• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2019 Google LLC
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/desc_sroa.h"
16 
17 #include "source/opt/desc_sroa_util.h"
18 #include "source/util/string_utils.h"
19 
20 namespace spvtools {
21 namespace opt {
22 namespace {
23 
IsDecorationBinding(Instruction * inst)24 bool IsDecorationBinding(Instruction* inst) {
25   if (inst->opcode() != spv::Op::OpDecorate) return false;
26   return spv::Decoration(inst->GetSingleWordInOperand(1u)) ==
27          spv::Decoration::Binding;
28 }
29 
30 }  // namespace
31 
Process()32 Pass::Status DescriptorScalarReplacement::Process() {
33   bool modified = false;
34 
35   std::vector<Instruction*> vars_to_kill;
36 
37   for (Instruction& var : context()->types_values()) {
38     if (descsroautil::IsDescriptorArray(context(), &var)) {
39       modified = true;
40       if (!ReplaceCandidate(&var)) {
41         return Status::Failure;
42       }
43       vars_to_kill.push_back(&var);
44     }
45   }
46 
47   for (Instruction* var : vars_to_kill) {
48     context()->KillInst(var);
49   }
50 
51   return (modified ? Status::SuccessWithChange : Status::SuccessWithoutChange);
52 }
53 
ReplaceCandidate(Instruction * var)54 bool DescriptorScalarReplacement::ReplaceCandidate(Instruction* var) {
55   std::vector<Instruction*> access_chain_work_list;
56   std::vector<Instruction*> load_work_list;
57   bool failed = !get_def_use_mgr()->WhileEachUser(
58       var->result_id(),
59       [this, &access_chain_work_list, &load_work_list](Instruction* use) {
60         if (use->opcode() == spv::Op::OpName) {
61           return true;
62         }
63 
64         if (use->IsDecoration()) {
65           return true;
66         }
67 
68         switch (use->opcode()) {
69           case spv::Op::OpAccessChain:
70           case spv::Op::OpInBoundsAccessChain:
71             access_chain_work_list.push_back(use);
72             return true;
73           case spv::Op::OpLoad:
74             load_work_list.push_back(use);
75             return true;
76           default:
77             context()->EmitErrorMessage(
78                 "Variable cannot be replaced: invalid instruction", use);
79             return false;
80         }
81         return true;
82       });
83 
84   if (failed) {
85     return false;
86   }
87 
88   for (Instruction* use : access_chain_work_list) {
89     if (!ReplaceAccessChain(var, use)) {
90       return false;
91     }
92   }
93   for (Instruction* use : load_work_list) {
94     if (!ReplaceLoadedValue(var, use)) {
95       return false;
96     }
97   }
98   return true;
99 }
100 
ReplaceAccessChain(Instruction * var,Instruction * use)101 bool DescriptorScalarReplacement::ReplaceAccessChain(Instruction* var,
102                                                      Instruction* use) {
103   if (use->NumInOperands() <= 1) {
104     context()->EmitErrorMessage(
105         "Variable cannot be replaced: invalid instruction", use);
106     return false;
107   }
108 
109   const analysis::Constant* const_index =
110       descsroautil::GetAccessChainIndexAsConst(context(), use);
111   if (const_index == nullptr) {
112     context()->EmitErrorMessage("Variable cannot be replaced: invalid index",
113                                 use);
114     return false;
115   }
116 
117   uint32_t idx = const_index->GetU32();
118   uint32_t replacement_var = GetReplacementVariable(var, idx);
119 
120   if (use->NumInOperands() == 2) {
121     // We are not indexing into the replacement variable.  We can replaces the
122     // access chain with the replacement variable itself.
123     context()->ReplaceAllUsesWith(use->result_id(), replacement_var);
124     context()->KillInst(use);
125     return true;
126   }
127 
128   // We need to build a new access chain with the replacement variable as the
129   // base address.
130   Instruction::OperandList new_operands;
131 
132   // Same result id and result type.
133   new_operands.emplace_back(use->GetOperand(0));
134   new_operands.emplace_back(use->GetOperand(1));
135 
136   // Use the replacement variable as the base address.
137   new_operands.push_back({SPV_OPERAND_TYPE_ID, {replacement_var}});
138 
139   // Drop the first index because it is consumed by the replacement, and copy
140   // the rest.
141   for (uint32_t i = 4; i < use->NumOperands(); i++) {
142     new_operands.emplace_back(use->GetOperand(i));
143   }
144 
145   use->ReplaceOperands(new_operands);
146   context()->UpdateDefUse(use);
147   return true;
148 }
149 
GetReplacementVariable(Instruction * var,uint32_t idx)150 uint32_t DescriptorScalarReplacement::GetReplacementVariable(Instruction* var,
151                                                              uint32_t idx) {
152   auto replacement_vars = replacement_variables_.find(var);
153   if (replacement_vars == replacement_variables_.end()) {
154     uint32_t number_of_elements =
155         descsroautil::GetNumberOfElementsForArrayOrStruct(context(), var);
156     replacement_vars =
157         replacement_variables_
158             .insert({var, std::vector<uint32_t>(number_of_elements, 0)})
159             .first;
160   }
161 
162   if (replacement_vars->second[idx] == 0) {
163     replacement_vars->second[idx] = CreateReplacementVariable(var, idx);
164   }
165 
166   return replacement_vars->second[idx];
167 }
168 
CopyDecorationsForNewVariable(Instruction * old_var,uint32_t index,uint32_t new_var_id,uint32_t new_var_ptr_type_id,const bool is_old_var_array,const bool is_old_var_struct,Instruction * old_var_type)169 void DescriptorScalarReplacement::CopyDecorationsForNewVariable(
170     Instruction* old_var, uint32_t index, uint32_t new_var_id,
171     uint32_t new_var_ptr_type_id, const bool is_old_var_array,
172     const bool is_old_var_struct, Instruction* old_var_type) {
173   // Handle OpDecorate and OpDecorateString instructions.
174   for (auto old_decoration :
175        get_decoration_mgr()->GetDecorationsFor(old_var->result_id(), true)) {
176     uint32_t new_binding = 0;
177     if (IsDecorationBinding(old_decoration)) {
178       new_binding = GetNewBindingForElement(
179           old_decoration->GetSingleWordInOperand(2), index, new_var_ptr_type_id,
180           is_old_var_array, is_old_var_struct, old_var_type);
181     }
182     CreateNewDecorationForNewVariable(old_decoration, new_var_id, new_binding);
183   }
184 
185   // Handle OpMemberDecorate instructions.
186   for (auto old_decoration : get_decoration_mgr()->GetDecorationsFor(
187            old_var_type->result_id(), true)) {
188     assert(old_decoration->opcode() == spv::Op::OpMemberDecorate);
189     if (old_decoration->GetSingleWordInOperand(1u) != index) continue;
190     CreateNewDecorationForMemberDecorate(old_decoration, new_var_id);
191   }
192 }
193 
GetNewBindingForElement(uint32_t old_binding,uint32_t index,uint32_t new_var_ptr_type_id,const bool is_old_var_array,const bool is_old_var_struct,Instruction * old_var_type)194 uint32_t DescriptorScalarReplacement::GetNewBindingForElement(
195     uint32_t old_binding, uint32_t index, uint32_t new_var_ptr_type_id,
196     const bool is_old_var_array, const bool is_old_var_struct,
197     Instruction* old_var_type) {
198   if (is_old_var_array) {
199     return old_binding + index * GetNumBindingsUsedByType(new_var_ptr_type_id);
200   }
201   if (is_old_var_struct) {
202     // The binding offset that should be added is the sum of binding
203     // numbers used by previous members of the current struct.
204     uint32_t new_binding = old_binding;
205     for (uint32_t i = 0; i < index; ++i) {
206       new_binding +=
207           GetNumBindingsUsedByType(old_var_type->GetSingleWordInOperand(i));
208     }
209     return new_binding;
210   }
211   return old_binding;
212 }
213 
CreateNewDecorationForNewVariable(Instruction * old_decoration,uint32_t new_var_id,uint32_t new_binding)214 void DescriptorScalarReplacement::CreateNewDecorationForNewVariable(
215     Instruction* old_decoration, uint32_t new_var_id, uint32_t new_binding) {
216   assert(old_decoration->opcode() == spv::Op::OpDecorate ||
217          old_decoration->opcode() == spv::Op::OpDecorateString);
218   std::unique_ptr<Instruction> new_decoration(old_decoration->Clone(context()));
219   new_decoration->SetInOperand(0, {new_var_id});
220 
221   if (IsDecorationBinding(new_decoration.get())) {
222     new_decoration->SetInOperand(2, {new_binding});
223   }
224   context()->AddAnnotationInst(std::move(new_decoration));
225 }
226 
CreateNewDecorationForMemberDecorate(Instruction * old_member_decoration,uint32_t new_var_id)227 void DescriptorScalarReplacement::CreateNewDecorationForMemberDecorate(
228     Instruction* old_member_decoration, uint32_t new_var_id) {
229   std::vector<Operand> operands(
230       {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {new_var_id}}});
231   auto new_decorate_operand_begin = old_member_decoration->begin() + 2u;
232   auto new_decorate_operand_end = old_member_decoration->end();
233   operands.insert(operands.end(), new_decorate_operand_begin,
234                   new_decorate_operand_end);
235   get_decoration_mgr()->AddDecoration(spv::Op::OpDecorate, std::move(operands));
236 }
237 
CreateReplacementVariable(Instruction * var,uint32_t idx)238 uint32_t DescriptorScalarReplacement::CreateReplacementVariable(
239     Instruction* var, uint32_t idx) {
240   // The storage class for the new variable is the same as the original.
241   spv::StorageClass storage_class =
242       static_cast<spv::StorageClass>(var->GetSingleWordInOperand(0));
243 
244   // The type for the new variable will be a pointer to type of the elements of
245   // the array.
246   uint32_t ptr_type_id = var->type_id();
247   Instruction* ptr_type_inst = get_def_use_mgr()->GetDef(ptr_type_id);
248   assert(ptr_type_inst->opcode() == spv::Op::OpTypePointer &&
249          "Variable should be a pointer to an array or structure.");
250   uint32_t pointee_type_id = ptr_type_inst->GetSingleWordInOperand(1);
251   Instruction* pointee_type_inst = get_def_use_mgr()->GetDef(pointee_type_id);
252   const bool is_array = pointee_type_inst->opcode() == spv::Op::OpTypeArray;
253   const bool is_struct = pointee_type_inst->opcode() == spv::Op::OpTypeStruct;
254   assert((is_array || is_struct) &&
255          "Variable should be a pointer to an array or structure.");
256 
257   uint32_t element_type_id =
258       is_array ? pointee_type_inst->GetSingleWordInOperand(0)
259                : pointee_type_inst->GetSingleWordInOperand(idx);
260 
261   uint32_t ptr_element_type_id = context()->get_type_mgr()->FindPointerToType(
262       element_type_id, storage_class);
263 
264   // Create the variable.
265   uint32_t id = TakeNextId();
266   std::unique_ptr<Instruction> variable(
267       new Instruction(context(), spv::Op::OpVariable, ptr_element_type_id, id,
268                       std::initializer_list<Operand>{
269                           {SPV_OPERAND_TYPE_STORAGE_CLASS,
270                            {static_cast<uint32_t>(storage_class)}}}));
271   context()->AddGlobalValue(std::move(variable));
272 
273   CopyDecorationsForNewVariable(var, idx, id, ptr_element_type_id, is_array,
274                                 is_struct, pointee_type_inst);
275 
276   // Create a new OpName for the replacement variable.
277   std::vector<std::unique_ptr<Instruction>> names_to_add;
278   for (auto p : context()->GetNames(var->result_id())) {
279     Instruction* name_inst = p.second;
280     std::string name_str = utils::MakeString(name_inst->GetOperand(1).words);
281     if (is_array) {
282       name_str += "[" + utils::ToString(idx) + "]";
283     }
284     if (is_struct) {
285       Instruction* member_name_inst =
286           context()->GetMemberName(pointee_type_inst->result_id(), idx);
287       name_str += ".";
288       if (member_name_inst)
289         name_str += utils::MakeString(member_name_inst->GetOperand(2).words);
290       else
291         // In case the member does not have a name assigned to it, use the
292         // member index.
293         name_str += utils::ToString(idx);
294     }
295 
296     std::unique_ptr<Instruction> new_name(new Instruction(
297         context(), spv::Op::OpName, 0, 0,
298         std::initializer_list<Operand>{
299             {SPV_OPERAND_TYPE_ID, {id}},
300             {SPV_OPERAND_TYPE_LITERAL_STRING, utils::MakeVector(name_str)}}));
301     Instruction* new_name_inst = new_name.get();
302     get_def_use_mgr()->AnalyzeInstDefUse(new_name_inst);
303     names_to_add.push_back(std::move(new_name));
304   }
305 
306   // We shouldn't add the new names when we are iterating over name ranges
307   // above. We can add all the new names now.
308   for (auto& new_name : names_to_add)
309     context()->AddDebug2Inst(std::move(new_name));
310 
311   return id;
312 }
313 
GetNumBindingsUsedByType(uint32_t type_id)314 uint32_t DescriptorScalarReplacement::GetNumBindingsUsedByType(
315     uint32_t type_id) {
316   Instruction* type_inst = get_def_use_mgr()->GetDef(type_id);
317 
318   // If it's a pointer, look at the underlying type.
319   if (type_inst->opcode() == spv::Op::OpTypePointer) {
320     type_id = type_inst->GetSingleWordInOperand(1);
321     type_inst = get_def_use_mgr()->GetDef(type_id);
322   }
323 
324   // Arrays consume N*M binding numbers where N is the array length, and M is
325   // the number of bindings used by each array element.
326   if (type_inst->opcode() == spv::Op::OpTypeArray) {
327     uint32_t element_type_id = type_inst->GetSingleWordInOperand(0);
328     uint32_t length_id = type_inst->GetSingleWordInOperand(1);
329     const analysis::Constant* length_const =
330         context()->get_constant_mgr()->FindDeclaredConstant(length_id);
331     // OpTypeArray's length must always be a constant
332     assert(length_const != nullptr);
333     uint32_t num_elems = length_const->GetU32();
334     return num_elems * GetNumBindingsUsedByType(element_type_id);
335   }
336 
337   // The number of bindings consumed by a structure is the sum of the bindings
338   // used by its members.
339   if (type_inst->opcode() == spv::Op::OpTypeStruct &&
340       !descsroautil::IsTypeOfStructuredBuffer(context(), type_inst)) {
341     uint32_t sum = 0;
342     for (uint32_t i = 0; i < type_inst->NumInOperands(); i++)
343       sum += GetNumBindingsUsedByType(type_inst->GetSingleWordInOperand(i));
344     return sum;
345   }
346 
347   // All other types are considered to take up 1 binding number.
348   return 1;
349 }
350 
ReplaceLoadedValue(Instruction * var,Instruction * value)351 bool DescriptorScalarReplacement::ReplaceLoadedValue(Instruction* var,
352                                                      Instruction* value) {
353   // |var| is the global variable that has to be eliminated (OpVariable).
354   // |value| is the OpLoad instruction that has loaded |var|.
355   // The function expects all users of |value| to be OpCompositeExtract
356   // instructions. Otherwise the function returns false with an error message.
357   assert(value->opcode() == spv::Op::OpLoad);
358   assert(value->GetSingleWordInOperand(0) == var->result_id());
359   std::vector<Instruction*> work_list;
360   bool failed = !get_def_use_mgr()->WhileEachUser(
361       value->result_id(), [this, &work_list](Instruction* use) {
362         if (use->opcode() != spv::Op::OpCompositeExtract) {
363           context()->EmitErrorMessage(
364               "Variable cannot be replaced: invalid instruction", use);
365           return false;
366         }
367         work_list.push_back(use);
368         return true;
369       });
370 
371   if (failed) {
372     return false;
373   }
374 
375   for (Instruction* use : work_list) {
376     if (!ReplaceCompositeExtract(var, use)) {
377       return false;
378     }
379   }
380 
381   // All usages of the loaded value have been killed. We can kill the OpLoad.
382   context()->KillInst(value);
383   return true;
384 }
385 
ReplaceCompositeExtract(Instruction * var,Instruction * extract)386 bool DescriptorScalarReplacement::ReplaceCompositeExtract(
387     Instruction* var, Instruction* extract) {
388   assert(extract->opcode() == spv::Op::OpCompositeExtract);
389   // We're currently only supporting extractions of one index at a time. If we
390   // need to, we can handle cases with multiple indexes in the future.
391   if (extract->NumInOperands() != 2) {
392     context()->EmitErrorMessage(
393         "Variable cannot be replaced: invalid instruction", extract);
394     return false;
395   }
396 
397   uint32_t replacement_var =
398       GetReplacementVariable(var, extract->GetSingleWordInOperand(1));
399 
400   // The result type of the OpLoad is the same as the result type of the
401   // OpCompositeExtract.
402   uint32_t load_id = TakeNextId();
403   std::unique_ptr<Instruction> load(
404       new Instruction(context(), spv::Op::OpLoad, extract->type_id(), load_id,
405                       std::initializer_list<Operand>{
406                           {SPV_OPERAND_TYPE_ID, {replacement_var}}}));
407   Instruction* load_instr = load.get();
408   get_def_use_mgr()->AnalyzeInstDefUse(load_instr);
409   context()->set_instr_block(load_instr, context()->get_instr_block(extract));
410   extract->InsertBefore(std::move(load));
411   context()->ReplaceAllUsesWith(extract->result_id(), load_id);
412   context()->KillInst(extract);
413   return true;
414 }
415 
416 }  // namespace opt
417 }  // namespace spvtools
418