• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2017 Pierre Moreau
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "source/opt/decoration_manager.h"
16 
17 #include <algorithm>
18 #include <memory>
19 #include <set>
20 #include <stack>
21 #include <utility>
22 
23 #include "source/opt/ir_context.h"
24 
25 namespace spvtools {
26 namespace opt {
27 namespace analysis {
28 namespace {
29 using InstructionVector = std::vector<const spvtools::opt::Instruction*>;
30 using DecorationSet = std::set<std::u32string>;
31 
32 // Returns true if |a| is a subet of |b|.
IsSubset(const DecorationSet & a,const DecorationSet & b)33 bool IsSubset(const DecorationSet& a, const DecorationSet& b) {
34   auto it1 = a.begin();
35   auto it2 = b.begin();
36 
37   while (it1 != a.end()) {
38     if (it2 == b.end() || *it1 < *it2) {
39       // |*it1| is in |a|, but not in |b|.
40       return false;
41     }
42     if (*it1 == *it2) {
43       // Found the element move to the next one.
44       it1++;
45       it2++;
46     } else /* *it1 > *it2 */ {
47       // Did not find |*it1| yet, check the next element in |b|.
48       it2++;
49     }
50   }
51   return true;
52 }
53 }  // namespace
54 
RemoveDecorationsFrom(uint32_t id,std::function<bool (const Instruction &)> pred)55 bool DecorationManager::RemoveDecorationsFrom(
56     uint32_t id, std::function<bool(const Instruction&)> pred) {
57   bool was_modified = false;
58   const auto ids_iter = id_to_decoration_insts_.find(id);
59   if (ids_iter == id_to_decoration_insts_.end()) {
60     return was_modified;
61   }
62 
63   TargetData& decorations_info = ids_iter->second;
64   auto context = module_->context();
65   std::vector<Instruction*> insts_to_kill;
66   const bool is_group = !decorations_info.decorate_insts.empty();
67 
68   // Schedule all direct decorations for removal if instructed as such by
69   // |pred|.
70   for (Instruction* inst : decorations_info.direct_decorations)
71     if (pred(*inst)) insts_to_kill.push_back(inst);
72 
73   // For all groups being directly applied to |id|, remove |id| (and the
74   // literal if |inst| is an OpGroupMemberDecorate) from the instruction
75   // applying the group.
76   std::unordered_set<const Instruction*> indirect_decorations_to_remove;
77   for (Instruction* inst : decorations_info.indirect_decorations) {
78     assert(inst->opcode() == spv::Op::OpGroupDecorate ||
79            inst->opcode() == spv::Op::OpGroupMemberDecorate);
80 
81     std::vector<Instruction*> group_decorations_to_keep;
82     const uint32_t group_id = inst->GetSingleWordInOperand(0u);
83     const auto group_iter = id_to_decoration_insts_.find(group_id);
84     assert(group_iter != id_to_decoration_insts_.end() &&
85            "Unknown decoration group");
86     const auto& group_decorations = group_iter->second.direct_decorations;
87     for (Instruction* decoration : group_decorations) {
88       if (!pred(*decoration)) group_decorations_to_keep.push_back(decoration);
89     }
90 
91     // If all decorations should be kept, then we can keep |id| part of the
92     // group.  However, if the group itself has no decorations, we should remove
93     // the id from the group.  This is needed to make |KillNameAndDecorate| work
94     // correctly when a decoration group has no decorations.
95     if (group_decorations_to_keep.size() == group_decorations.size() &&
96         group_decorations.size() != 0) {
97       continue;
98     }
99 
100     // Otherwise, remove |id| from the targets of |group_id|
101     const uint32_t stride =
102         inst->opcode() == spv::Op::OpGroupDecorate ? 1u : 2u;
103     for (uint32_t i = 1u; i < inst->NumInOperands();) {
104       if (inst->GetSingleWordInOperand(i) != id) {
105         i += stride;
106         continue;
107       }
108 
109       const uint32_t last_operand_index = inst->NumInOperands() - stride;
110       if (i < last_operand_index)
111         inst->GetInOperand(i) = inst->GetInOperand(last_operand_index);
112       // Remove the associated literal, if it exists.
113       if (stride == 2u) {
114         if (i < last_operand_index)
115           inst->GetInOperand(i + 1u) =
116               inst->GetInOperand(last_operand_index + 1u);
117         inst->RemoveInOperand(last_operand_index + 1u);
118       }
119       inst->RemoveInOperand(last_operand_index);
120       was_modified = true;
121     }
122 
123     // If the instruction has no targets left, remove the instruction
124     // altogether.
125     if (inst->NumInOperands() == 1u) {
126       indirect_decorations_to_remove.emplace(inst);
127       insts_to_kill.push_back(inst);
128     } else if (was_modified) {
129       context->ForgetUses(inst);
130       indirect_decorations_to_remove.emplace(inst);
131       context->AnalyzeUses(inst);
132     }
133 
134     // If only some of the decorations should be kept, clone them and apply
135     // them directly to |id|.
136     if (!group_decorations_to_keep.empty()) {
137       for (Instruction* decoration : group_decorations_to_keep) {
138         // simply clone decoration and change |group_id| to |id|
139         std::unique_ptr<Instruction> new_inst(
140             decoration->Clone(module_->context()));
141         new_inst->SetInOperand(0, {id});
142         module_->AddAnnotationInst(std::move(new_inst));
143         auto decoration_iter = --module_->annotation_end();
144         context->AnalyzeUses(&*decoration_iter);
145       }
146     }
147   }
148 
149   auto& indirect_decorations = decorations_info.indirect_decorations;
150   indirect_decorations.erase(
151       std::remove_if(
152           indirect_decorations.begin(), indirect_decorations.end(),
153           [&indirect_decorations_to_remove](const Instruction* inst) {
154             return indirect_decorations_to_remove.count(inst);
155           }),
156       indirect_decorations.end());
157 
158   was_modified |= !insts_to_kill.empty();
159   for (Instruction* inst : insts_to_kill) context->KillInst(inst);
160   insts_to_kill.clear();
161 
162   // Schedule all instructions applying the group for removal if this group no
163   // longer applies decorations, either directly or indirectly.
164   if (is_group && decorations_info.direct_decorations.empty() &&
165       decorations_info.indirect_decorations.empty()) {
166     for (Instruction* inst : decorations_info.decorate_insts)
167       insts_to_kill.push_back(inst);
168   }
169   was_modified |= !insts_to_kill.empty();
170   for (Instruction* inst : insts_to_kill) context->KillInst(inst);
171 
172   if (decorations_info.direct_decorations.empty() &&
173       decorations_info.indirect_decorations.empty() &&
174       decorations_info.decorate_insts.empty()) {
175     id_to_decoration_insts_.erase(ids_iter);
176   }
177   return was_modified;
178 }
179 
GetDecorationsFor(uint32_t id,bool include_linkage)180 std::vector<Instruction*> DecorationManager::GetDecorationsFor(
181     uint32_t id, bool include_linkage) {
182   return InternalGetDecorationsFor<Instruction*>(id, include_linkage);
183 }
184 
GetDecorationsFor(uint32_t id,bool include_linkage) const185 std::vector<const Instruction*> DecorationManager::GetDecorationsFor(
186     uint32_t id, bool include_linkage) const {
187   return const_cast<DecorationManager*>(this)
188       ->InternalGetDecorationsFor<const Instruction*>(id, include_linkage);
189 }
190 
HaveTheSameDecorations(uint32_t id1,uint32_t id2) const191 bool DecorationManager::HaveTheSameDecorations(uint32_t id1,
192                                                uint32_t id2) const {
193   const InstructionVector decorations_for1 = GetDecorationsFor(id1, false);
194   const InstructionVector decorations_for2 = GetDecorationsFor(id2, false);
195 
196   // This function splits the decoration instructions into different sets,
197   // based on their opcode; only OpDecorate, OpDecorateId,
198   // OpDecorateStringGOOGLE, and OpMemberDecorate are considered, the other
199   // opcodes are ignored.
200   const auto fillDecorationSets =
201       [](const InstructionVector& decoration_list, DecorationSet* decorate_set,
202          DecorationSet* decorate_id_set, DecorationSet* decorate_string_set,
203          DecorationSet* member_decorate_set) {
204         for (const Instruction* inst : decoration_list) {
205           std::u32string decoration_payload;
206           // Ignore the opcode and the target as we do not want them to be
207           // compared.
208           for (uint32_t i = 1u; i < inst->NumInOperands(); ++i) {
209             for (uint32_t word : inst->GetInOperand(i).words) {
210               decoration_payload.push_back(word);
211             }
212           }
213 
214           switch (inst->opcode()) {
215             case spv::Op::OpDecorate:
216               decorate_set->emplace(std::move(decoration_payload));
217               break;
218             case spv::Op::OpMemberDecorate:
219               member_decorate_set->emplace(std::move(decoration_payload));
220               break;
221             case spv::Op::OpDecorateId:
222               decorate_id_set->emplace(std::move(decoration_payload));
223               break;
224             case spv::Op::OpDecorateStringGOOGLE:
225               decorate_string_set->emplace(std::move(decoration_payload));
226               break;
227             default:
228               break;
229           }
230         }
231       };
232 
233   DecorationSet decorate_set_for1;
234   DecorationSet decorate_id_set_for1;
235   DecorationSet decorate_string_set_for1;
236   DecorationSet member_decorate_set_for1;
237   fillDecorationSets(decorations_for1, &decorate_set_for1,
238                      &decorate_id_set_for1, &decorate_string_set_for1,
239                      &member_decorate_set_for1);
240 
241   DecorationSet decorate_set_for2;
242   DecorationSet decorate_id_set_for2;
243   DecorationSet decorate_string_set_for2;
244   DecorationSet member_decorate_set_for2;
245   fillDecorationSets(decorations_for2, &decorate_set_for2,
246                      &decorate_id_set_for2, &decorate_string_set_for2,
247                      &member_decorate_set_for2);
248 
249   const bool result = decorate_set_for1 == decorate_set_for2 &&
250                       decorate_id_set_for1 == decorate_id_set_for2 &&
251                       member_decorate_set_for1 == member_decorate_set_for2 &&
252                       // Compare string sets last in case the strings are long.
253                       decorate_string_set_for1 == decorate_string_set_for2;
254   return result;
255 }
256 
HaveSubsetOfDecorations(uint32_t id1,uint32_t id2) const257 bool DecorationManager::HaveSubsetOfDecorations(uint32_t id1,
258                                                 uint32_t id2) const {
259   const InstructionVector decorations_for1 = GetDecorationsFor(id1, false);
260   const InstructionVector decorations_for2 = GetDecorationsFor(id2, false);
261 
262   // This function splits the decoration instructions into different sets,
263   // based on their opcode; only OpDecorate, OpDecorateId,
264   // OpDecorateStringGOOGLE, and OpMemberDecorate are considered, the other
265   // opcodes are ignored.
266   const auto fillDecorationSets =
267       [](const InstructionVector& decoration_list, DecorationSet* decorate_set,
268          DecorationSet* decorate_id_set, DecorationSet* decorate_string_set,
269          DecorationSet* member_decorate_set) {
270         for (const Instruction* inst : decoration_list) {
271           std::u32string decoration_payload;
272           // Ignore the opcode and the target as we do not want them to be
273           // compared.
274           for (uint32_t i = 1u; i < inst->NumInOperands(); ++i) {
275             for (uint32_t word : inst->GetInOperand(i).words) {
276               decoration_payload.push_back(word);
277             }
278           }
279 
280           switch (inst->opcode()) {
281             case spv::Op::OpDecorate:
282               decorate_set->emplace(std::move(decoration_payload));
283               break;
284             case spv::Op::OpMemberDecorate:
285               member_decorate_set->emplace(std::move(decoration_payload));
286               break;
287             case spv::Op::OpDecorateId:
288               decorate_id_set->emplace(std::move(decoration_payload));
289               break;
290             case spv::Op::OpDecorateStringGOOGLE:
291               decorate_string_set->emplace(std::move(decoration_payload));
292               break;
293             default:
294               break;
295           }
296         }
297       };
298 
299   DecorationSet decorate_set_for1;
300   DecorationSet decorate_id_set_for1;
301   DecorationSet decorate_string_set_for1;
302   DecorationSet member_decorate_set_for1;
303   fillDecorationSets(decorations_for1, &decorate_set_for1,
304                      &decorate_id_set_for1, &decorate_string_set_for1,
305                      &member_decorate_set_for1);
306 
307   DecorationSet decorate_set_for2;
308   DecorationSet decorate_id_set_for2;
309   DecorationSet decorate_string_set_for2;
310   DecorationSet member_decorate_set_for2;
311   fillDecorationSets(decorations_for2, &decorate_set_for2,
312                      &decorate_id_set_for2, &decorate_string_set_for2,
313                      &member_decorate_set_for2);
314 
315   const bool result =
316       IsSubset(decorate_set_for1, decorate_set_for2) &&
317       IsSubset(decorate_id_set_for1, decorate_id_set_for2) &&
318       IsSubset(member_decorate_set_for1, member_decorate_set_for2) &&
319       // Compare string sets last in case the strings are long.
320       IsSubset(decorate_string_set_for1, decorate_string_set_for2);
321   return result;
322 }
323 
324 // TODO(pierremoreau): If OpDecorateId is referencing an OpConstant, one could
325 //                     check that the constants are the same rather than just
326 //                     looking at the constant ID.
AreDecorationsTheSame(const Instruction * inst1,const Instruction * inst2,bool ignore_target) const327 bool DecorationManager::AreDecorationsTheSame(const Instruction* inst1,
328                                               const Instruction* inst2,
329                                               bool ignore_target) const {
330   switch (inst1->opcode()) {
331     case spv::Op::OpDecorate:
332     case spv::Op::OpMemberDecorate:
333     case spv::Op::OpDecorateId:
334     case spv::Op::OpDecorateStringGOOGLE:
335       break;
336     default:
337       return false;
338   }
339 
340   if (inst1->opcode() != inst2->opcode() ||
341       inst1->NumInOperands() != inst2->NumInOperands())
342     return false;
343 
344   for (uint32_t i = ignore_target ? 1u : 0u; i < inst1->NumInOperands(); ++i)
345     if (inst1->GetInOperand(i) != inst2->GetInOperand(i)) return false;
346 
347   return true;
348 }
349 
AnalyzeDecorations()350 void DecorationManager::AnalyzeDecorations() {
351   if (!module_) return;
352 
353   // For each group and instruction, collect all their decoration instructions.
354   for (Instruction& inst : module_->annotations()) {
355     AddDecoration(&inst);
356   }
357 }
358 
AddDecoration(Instruction * inst)359 void DecorationManager::AddDecoration(Instruction* inst) {
360   switch (inst->opcode()) {
361     case spv::Op::OpDecorate:
362     case spv::Op::OpDecorateId:
363     case spv::Op::OpDecorateStringGOOGLE:
364     case spv::Op::OpMemberDecorate: {
365       const auto target_id = inst->GetSingleWordInOperand(0u);
366       id_to_decoration_insts_[target_id].direct_decorations.push_back(inst);
367       break;
368     }
369     case spv::Op::OpGroupDecorate:
370     case spv::Op::OpGroupMemberDecorate: {
371       const uint32_t start =
372           inst->opcode() == spv::Op::OpGroupDecorate ? 1u : 2u;
373       const uint32_t stride = start;
374       for (uint32_t i = start; i < inst->NumInOperands(); i += stride) {
375         const auto target_id = inst->GetSingleWordInOperand(i);
376         TargetData& target_data = id_to_decoration_insts_[target_id];
377         target_data.indirect_decorations.push_back(inst);
378       }
379       const auto target_id = inst->GetSingleWordInOperand(0u);
380       id_to_decoration_insts_[target_id].decorate_insts.push_back(inst);
381       break;
382     }
383     default:
384       break;
385   }
386 }
387 
AddDecoration(spv::Op opcode,std::vector<Operand> opnds)388 void DecorationManager::AddDecoration(spv::Op opcode,
389                                       std::vector<Operand> opnds) {
390   IRContext* ctx = module_->context();
391   std::unique_ptr<Instruction> newDecoOp(
392       new Instruction(ctx, opcode, 0, 0, opnds));
393   ctx->AddAnnotationInst(std::move(newDecoOp));
394 }
395 
AddDecoration(uint32_t inst_id,uint32_t decoration)396 void DecorationManager::AddDecoration(uint32_t inst_id, uint32_t decoration) {
397   AddDecoration(
398       spv::Op::OpDecorate,
399       {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {inst_id}},
400        {spv_operand_type_t::SPV_OPERAND_TYPE_LITERAL_INTEGER, {decoration}}});
401 }
402 
AddDecorationVal(uint32_t inst_id,uint32_t decoration,uint32_t decoration_value)403 void DecorationManager::AddDecorationVal(uint32_t inst_id, uint32_t decoration,
404                                          uint32_t decoration_value) {
405   AddDecoration(
406       spv::Op::OpDecorate,
407       {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {inst_id}},
408        {spv_operand_type_t::SPV_OPERAND_TYPE_LITERAL_INTEGER, {decoration}},
409        {spv_operand_type_t::SPV_OPERAND_TYPE_LITERAL_INTEGER,
410         {decoration_value}}});
411 }
412 
AddMemberDecoration(uint32_t inst_id,uint32_t member,uint32_t decoration,uint32_t decoration_value)413 void DecorationManager::AddMemberDecoration(uint32_t inst_id, uint32_t member,
414                                             uint32_t decoration,
415                                             uint32_t decoration_value) {
416   AddDecoration(
417       spv::Op::OpMemberDecorate,
418       {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {inst_id}},
419        {spv_operand_type_t::SPV_OPERAND_TYPE_LITERAL_INTEGER, {member}},
420        {spv_operand_type_t::SPV_OPERAND_TYPE_LITERAL_INTEGER, {decoration}},
421        {spv_operand_type_t::SPV_OPERAND_TYPE_LITERAL_INTEGER,
422         {decoration_value}}});
423 }
424 
425 template <typename T>
InternalGetDecorationsFor(uint32_t id,bool include_linkage)426 std::vector<T> DecorationManager::InternalGetDecorationsFor(
427     uint32_t id, bool include_linkage) {
428   std::vector<T> decorations;
429 
430   const auto ids_iter = id_to_decoration_insts_.find(id);
431   // |id| has no decorations
432   if (ids_iter == id_to_decoration_insts_.end()) return decorations;
433 
434   const TargetData& target_data = ids_iter->second;
435 
436   const auto process_direct_decorations =
437       [include_linkage,
438        &decorations](const std::vector<Instruction*>& direct_decorations) {
439         for (Instruction* inst : direct_decorations) {
440           const bool is_linkage =
441               inst->opcode() == spv::Op::OpDecorate &&
442               spv::Decoration(inst->GetSingleWordInOperand(1u)) ==
443                   spv::Decoration::LinkageAttributes;
444           if (include_linkage || !is_linkage) decorations.push_back(inst);
445         }
446       };
447 
448   // Process |id|'s decorations.
449   process_direct_decorations(ids_iter->second.direct_decorations);
450 
451   // Process the decorations of all groups applied to |id|.
452   for (const Instruction* inst : target_data.indirect_decorations) {
453     const uint32_t group_id = inst->GetSingleWordInOperand(0u);
454     const auto group_iter = id_to_decoration_insts_.find(group_id);
455     assert(group_iter != id_to_decoration_insts_.end() && "Unknown group ID");
456     process_direct_decorations(group_iter->second.direct_decorations);
457   }
458 
459   return decorations;
460 }
461 
WhileEachDecoration(uint32_t id,uint32_t decoration,std::function<bool (const Instruction &)> f) const462 bool DecorationManager::WhileEachDecoration(
463     uint32_t id, uint32_t decoration,
464     std::function<bool(const Instruction&)> f) const {
465   for (const Instruction* inst : GetDecorationsFor(id, true)) {
466     switch (inst->opcode()) {
467       case spv::Op::OpMemberDecorate:
468         if (inst->GetSingleWordInOperand(2) == decoration) {
469           if (!f(*inst)) return false;
470         }
471         break;
472       case spv::Op::OpDecorate:
473       case spv::Op::OpDecorateId:
474       case spv::Op::OpDecorateStringGOOGLE:
475         if (inst->GetSingleWordInOperand(1) == decoration) {
476           if (!f(*inst)) return false;
477         }
478         break;
479       default:
480         assert(false && "Unexpected decoration instruction");
481     }
482   }
483   return true;
484 }
485 
ForEachDecoration(uint32_t id,uint32_t decoration,std::function<void (const Instruction &)> f) const486 void DecorationManager::ForEachDecoration(
487     uint32_t id, uint32_t decoration,
488     std::function<void(const Instruction&)> f) const {
489   WhileEachDecoration(id, decoration, [&f](const Instruction& inst) {
490     f(inst);
491     return true;
492   });
493 }
494 
HasDecoration(uint32_t id,spv::Decoration decoration) const495 bool DecorationManager::HasDecoration(uint32_t id,
496                                       spv::Decoration decoration) const {
497   return HasDecoration(id, static_cast<uint32_t>(decoration));
498 }
499 
HasDecoration(uint32_t id,uint32_t decoration) const500 bool DecorationManager::HasDecoration(uint32_t id, uint32_t decoration) const {
501   bool has_decoration = false;
502   ForEachDecoration(id, decoration, [&has_decoration](const Instruction&) {
503     has_decoration = true;
504   });
505   return has_decoration;
506 }
507 
FindDecoration(uint32_t id,uint32_t decoration,std::function<bool (const Instruction &)> f)508 bool DecorationManager::FindDecoration(
509     uint32_t id, uint32_t decoration,
510     std::function<bool(const Instruction&)> f) {
511   return !WhileEachDecoration(
512       id, decoration, [&f](const Instruction& inst) { return !f(inst); });
513 }
514 
CloneDecorations(uint32_t from,uint32_t to)515 void DecorationManager::CloneDecorations(uint32_t from, uint32_t to) {
516   const auto decoration_list = id_to_decoration_insts_.find(from);
517   if (decoration_list == id_to_decoration_insts_.end()) return;
518   auto context = module_->context();
519   for (Instruction* inst : decoration_list->second.direct_decorations) {
520     // simply clone decoration and change |target-id| to |to|
521     std::unique_ptr<Instruction> new_inst(inst->Clone(module_->context()));
522     new_inst->SetInOperand(0, {to});
523     module_->AddAnnotationInst(std::move(new_inst));
524     auto decoration_iter = --module_->annotation_end();
525     context->AnalyzeUses(&*decoration_iter);
526   }
527   // We need to copy the list of instructions as ForgetUses and AnalyzeUses are
528   // going to modify it.
529   std::vector<Instruction*> indirect_decorations =
530       decoration_list->second.indirect_decorations;
531   for (Instruction* inst : indirect_decorations) {
532     switch (inst->opcode()) {
533       case spv::Op::OpGroupDecorate:
534         context->ForgetUses(inst);
535         // add |to| to list of decorated id's
536         inst->AddOperand(
537             Operand(spv_operand_type_t::SPV_OPERAND_TYPE_ID, {to}));
538         context->AnalyzeUses(inst);
539         break;
540       case spv::Op::OpGroupMemberDecorate: {
541         context->ForgetUses(inst);
542         // for each (id == from), add (to, literal) as operands
543         const uint32_t num_operands = inst->NumOperands();
544         for (uint32_t i = 1; i < num_operands; i += 2) {
545           Operand op = inst->GetOperand(i);
546           if (op.words[0] == from) {  // add new pair of operands: (to, literal)
547             inst->AddOperand(
548                 Operand(spv_operand_type_t::SPV_OPERAND_TYPE_ID, {to}));
549             op = inst->GetOperand(i + 1);
550             inst->AddOperand(std::move(op));
551           }
552         }
553         context->AnalyzeUses(inst);
554         break;
555       }
556       default:
557         assert(false && "Unexpected decoration instruction");
558     }
559   }
560 }
561 
CloneDecorations(uint32_t from,uint32_t to,const std::vector<spv::Decoration> & decorations_to_copy)562 void DecorationManager::CloneDecorations(
563     uint32_t from, uint32_t to,
564     const std::vector<spv::Decoration>& decorations_to_copy) {
565   const auto decoration_list = id_to_decoration_insts_.find(from);
566   if (decoration_list == id_to_decoration_insts_.end()) return;
567   auto context = module_->context();
568   for (Instruction* inst : decoration_list->second.direct_decorations) {
569     if (std::find(decorations_to_copy.begin(), decorations_to_copy.end(),
570                   spv::Decoration(inst->GetSingleWordInOperand(1))) ==
571         decorations_to_copy.end()) {
572       continue;
573     }
574 
575     // Clone decoration and change |target-id| to |to|.
576     std::unique_ptr<Instruction> new_inst(inst->Clone(module_->context()));
577     new_inst->SetInOperand(0, {to});
578     module_->AddAnnotationInst(std::move(new_inst));
579     auto decoration_iter = --module_->annotation_end();
580     context->AnalyzeUses(&*decoration_iter);
581   }
582 
583   // We need to copy the list of instructions as ForgetUses and AnalyzeUses are
584   // going to modify it.
585   std::vector<Instruction*> indirect_decorations =
586       decoration_list->second.indirect_decorations;
587   for (Instruction* inst : indirect_decorations) {
588     switch (inst->opcode()) {
589       case spv::Op::OpGroupDecorate:
590         CloneDecorations(inst->GetSingleWordInOperand(0), to,
591                          decorations_to_copy);
592         break;
593       case spv::Op::OpGroupMemberDecorate: {
594         assert(false && "The source id is not suppose to be a type.");
595         break;
596       }
597       default:
598         assert(false && "Unexpected decoration instruction");
599     }
600   }
601 }
602 
RemoveDecoration(Instruction * inst)603 void DecorationManager::RemoveDecoration(Instruction* inst) {
604   const auto remove_from_container = [inst](std::vector<Instruction*>& v) {
605     v.erase(std::remove(v.begin(), v.end(), inst), v.end());
606   };
607 
608   switch (inst->opcode()) {
609     case spv::Op::OpDecorate:
610     case spv::Op::OpDecorateId:
611     case spv::Op::OpDecorateStringGOOGLE:
612     case spv::Op::OpMemberDecorate: {
613       const auto target_id = inst->GetSingleWordInOperand(0u);
614       auto const iter = id_to_decoration_insts_.find(target_id);
615       if (iter == id_to_decoration_insts_.end()) return;
616       remove_from_container(iter->second.direct_decorations);
617     } break;
618     case spv::Op::OpGroupDecorate:
619     case spv::Op::OpGroupMemberDecorate: {
620       const uint32_t stride =
621           inst->opcode() == spv::Op::OpGroupDecorate ? 1u : 2u;
622       for (uint32_t i = 1u; i < inst->NumInOperands(); i += stride) {
623         const auto target_id = inst->GetSingleWordInOperand(i);
624         auto const iter = id_to_decoration_insts_.find(target_id);
625         if (iter == id_to_decoration_insts_.end()) continue;
626         remove_from_container(iter->second.indirect_decorations);
627       }
628       const auto group_id = inst->GetSingleWordInOperand(0u);
629       auto const iter = id_to_decoration_insts_.find(group_id);
630       if (iter == id_to_decoration_insts_.end()) return;
631       remove_from_container(iter->second.decorate_insts);
632     } break;
633     default:
634       break;
635   }
636 }
637 
operator ==(const DecorationManager & lhs,const DecorationManager & rhs)638 bool operator==(const DecorationManager& lhs, const DecorationManager& rhs) {
639   return lhs.id_to_decoration_insts_ == rhs.id_to_decoration_insts_;
640 }
641 
642 }  // namespace analysis
643 }  // namespace opt
644 }  // namespace spvtools
645