desc_sroa.cpp 15 KB

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