desc_sroa.cpp 17 KB

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