desc_sroa.cpp 15 KB

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