desc_sroa.cpp 16 KB

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