scalar_replacement_pass.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  1. // Copyright (c) 2017 Google Inc.
  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/scalar_replacement_pass.h"
  15. #include <algorithm>
  16. #include <queue>
  17. #include <tuple>
  18. #include <utility>
  19. #include "source/enum_string_mapping.h"
  20. #include "source/extensions.h"
  21. #include "source/opt/reflect.h"
  22. #include "source/opt/types.h"
  23. #include "source/util/make_unique.h"
  24. #include "types.h"
  25. namespace spvtools {
  26. namespace opt {
  27. namespace {
  28. constexpr uint32_t kDebugValueOperandValueIndex = 5;
  29. constexpr uint32_t kDebugValueOperandExpressionIndex = 6;
  30. constexpr uint32_t kDebugDeclareOperandVariableIndex = 5;
  31. } // namespace
  32. Pass::Status ScalarReplacementPass::Process() {
  33. Status status = Status::SuccessWithoutChange;
  34. for (auto& f : *get_module()) {
  35. if (f.IsDeclaration()) {
  36. continue;
  37. }
  38. Status functionStatus = ProcessFunction(&f);
  39. if (functionStatus == Status::Failure)
  40. return functionStatus;
  41. else if (functionStatus == Status::SuccessWithChange)
  42. status = functionStatus;
  43. }
  44. return status;
  45. }
  46. Pass::Status ScalarReplacementPass::ProcessFunction(Function* function) {
  47. std::queue<Instruction*> worklist;
  48. BasicBlock& entry = *function->begin();
  49. for (auto iter = entry.begin(); iter != entry.end(); ++iter) {
  50. // Function storage class OpVariables must appear as the first instructions
  51. // of the entry block.
  52. if (iter->opcode() != spv::Op::OpVariable) break;
  53. Instruction* varInst = &*iter;
  54. if (CanReplaceVariable(varInst)) {
  55. worklist.push(varInst);
  56. }
  57. }
  58. Status status = Status::SuccessWithoutChange;
  59. while (!worklist.empty()) {
  60. Instruction* varInst = worklist.front();
  61. worklist.pop();
  62. Status var_status = ReplaceVariable(varInst, &worklist);
  63. if (var_status == Status::Failure)
  64. return var_status;
  65. else if (var_status == Status::SuccessWithChange)
  66. status = var_status;
  67. }
  68. return status;
  69. }
  70. Pass::Status ScalarReplacementPass::ReplaceVariable(
  71. Instruction* inst, std::queue<Instruction*>* worklist) {
  72. std::vector<Instruction*> replacements;
  73. if (!CreateReplacementVariables(inst, &replacements)) {
  74. return Status::Failure;
  75. }
  76. std::vector<Instruction*> dead;
  77. bool replaced_all_uses = get_def_use_mgr()->WhileEachUser(
  78. inst, [this, &replacements, &dead](Instruction* user) {
  79. if (user->GetCommonDebugOpcode() == CommonDebugInfoDebugDeclare) {
  80. if (ReplaceWholeDebugDeclare(user, replacements)) {
  81. dead.push_back(user);
  82. return true;
  83. }
  84. return false;
  85. }
  86. if (user->GetCommonDebugOpcode() == CommonDebugInfoDebugValue) {
  87. if (ReplaceWholeDebugValue(user, replacements)) {
  88. dead.push_back(user);
  89. return true;
  90. }
  91. return false;
  92. }
  93. if (!IsAnnotationInst(user->opcode())) {
  94. switch (user->opcode()) {
  95. case spv::Op::OpLoad:
  96. if (ReplaceWholeLoad(user, replacements)) {
  97. dead.push_back(user);
  98. } else {
  99. return false;
  100. }
  101. break;
  102. case spv::Op::OpStore:
  103. if (ReplaceWholeStore(user, replacements)) {
  104. dead.push_back(user);
  105. } else {
  106. return false;
  107. }
  108. break;
  109. case spv::Op::OpAccessChain:
  110. case spv::Op::OpInBoundsAccessChain:
  111. if (ReplaceAccessChain(user, replacements))
  112. dead.push_back(user);
  113. else
  114. return false;
  115. break;
  116. case spv::Op::OpName:
  117. case spv::Op::OpMemberName:
  118. break;
  119. default:
  120. assert(false && "Unexpected opcode");
  121. break;
  122. }
  123. }
  124. return true;
  125. });
  126. if (replaced_all_uses) {
  127. dead.push_back(inst);
  128. } else {
  129. return Status::Failure;
  130. }
  131. // If there are no dead instructions to clean up, return with no changes.
  132. if (dead.empty()) return Status::SuccessWithoutChange;
  133. // Clean up some dead code.
  134. while (!dead.empty()) {
  135. Instruction* toKill = dead.back();
  136. dead.pop_back();
  137. context()->KillInst(toKill);
  138. }
  139. // Attempt to further scalarize.
  140. for (auto var : replacements) {
  141. if (var->opcode() == spv::Op::OpVariable) {
  142. if (get_def_use_mgr()->NumUsers(var) == 0) {
  143. context()->KillInst(var);
  144. } else if (CanReplaceVariable(var)) {
  145. worklist->push(var);
  146. }
  147. }
  148. }
  149. return Status::SuccessWithChange;
  150. }
  151. bool ScalarReplacementPass::ReplaceWholeDebugDeclare(
  152. Instruction* dbg_decl, const std::vector<Instruction*>& replacements) {
  153. // Insert Deref operation to the front of the operation list of |dbg_decl|.
  154. Instruction* dbg_expr = context()->get_def_use_mgr()->GetDef(
  155. dbg_decl->GetSingleWordOperand(kDebugValueOperandExpressionIndex));
  156. auto* deref_expr =
  157. context()->get_debug_info_mgr()->DerefDebugExpression(dbg_expr);
  158. // Add DebugValue instruction with Indexes operand and Deref operation.
  159. int32_t idx = 0;
  160. for (const auto* var : replacements) {
  161. Instruction* insert_before = var->NextNode();
  162. while (insert_before->opcode() == spv::Op::OpVariable)
  163. insert_before = insert_before->NextNode();
  164. assert(insert_before != nullptr && "unexpected end of list");
  165. Instruction* added_dbg_value =
  166. context()->get_debug_info_mgr()->AddDebugValueForDecl(
  167. dbg_decl, /*value_id=*/var->result_id(),
  168. /*insert_before=*/insert_before, /*scope_and_line=*/dbg_decl);
  169. if (added_dbg_value == nullptr) return false;
  170. added_dbg_value->AddOperand(
  171. {SPV_OPERAND_TYPE_ID,
  172. {context()->get_constant_mgr()->GetSIntConstId(idx)}});
  173. added_dbg_value->SetOperand(kDebugValueOperandExpressionIndex,
  174. {deref_expr->result_id()});
  175. if (context()->AreAnalysesValid(IRContext::Analysis::kAnalysisDefUse)) {
  176. context()->get_def_use_mgr()->AnalyzeInstUse(added_dbg_value);
  177. }
  178. ++idx;
  179. }
  180. return true;
  181. }
  182. bool ScalarReplacementPass::ReplaceWholeDebugValue(
  183. Instruction* dbg_value, const std::vector<Instruction*>& replacements) {
  184. int32_t idx = 0;
  185. BasicBlock* block = context()->get_instr_block(dbg_value);
  186. for (auto var : replacements) {
  187. // Clone the DebugValue.
  188. std::unique_ptr<Instruction> new_dbg_value(dbg_value->Clone(context()));
  189. uint32_t new_id = TakeNextId();
  190. if (new_id == 0) return false;
  191. new_dbg_value->SetResultId(new_id);
  192. // Update 'Value' operand to the |replacements|.
  193. new_dbg_value->SetOperand(kDebugValueOperandValueIndex, {var->result_id()});
  194. // Append 'Indexes' operand.
  195. new_dbg_value->AddOperand(
  196. {SPV_OPERAND_TYPE_ID,
  197. {context()->get_constant_mgr()->GetSIntConstId(idx)}});
  198. // Insert the new DebugValue to the basic block.
  199. auto* added_instr = dbg_value->InsertBefore(std::move(new_dbg_value));
  200. get_def_use_mgr()->AnalyzeInstDefUse(added_instr);
  201. context()->set_instr_block(added_instr, block);
  202. ++idx;
  203. }
  204. return true;
  205. }
  206. bool ScalarReplacementPass::ReplaceWholeLoad(
  207. Instruction* load, const std::vector<Instruction*>& replacements) {
  208. // Replaces the load of the entire composite with a load from each replacement
  209. // variable followed by a composite construction.
  210. BasicBlock* block = context()->get_instr_block(load);
  211. std::vector<Instruction*> loads;
  212. loads.reserve(replacements.size());
  213. BasicBlock::iterator where(load);
  214. for (auto var : replacements) {
  215. // Create a load of each replacement variable.
  216. if (var->opcode() != spv::Op::OpVariable) {
  217. loads.push_back(var);
  218. continue;
  219. }
  220. Instruction* type = GetStorageType(var);
  221. uint32_t loadId = TakeNextId();
  222. if (loadId == 0) {
  223. return false;
  224. }
  225. std::unique_ptr<Instruction> newLoad(
  226. new Instruction(context(), spv::Op::OpLoad, type->result_id(), loadId,
  227. std::initializer_list<Operand>{
  228. {SPV_OPERAND_TYPE_ID, {var->result_id()}}}));
  229. // Copy memory access attributes which start at index 1. Index 0 is the
  230. // pointer to load.
  231. for (uint32_t i = 1; i < load->NumInOperands(); ++i) {
  232. Operand copy(load->GetInOperand(i));
  233. newLoad->AddOperand(std::move(copy));
  234. }
  235. where = where.InsertBefore(std::move(newLoad));
  236. get_def_use_mgr()->AnalyzeInstDefUse(&*where);
  237. context()->set_instr_block(&*where, block);
  238. where->UpdateDebugInfoFrom(load);
  239. loads.push_back(&*where);
  240. }
  241. // Construct a new composite.
  242. uint32_t compositeId = TakeNextId();
  243. if (compositeId == 0) {
  244. return false;
  245. }
  246. where = load;
  247. std::unique_ptr<Instruction> compositeConstruct(
  248. new Instruction(context(), spv::Op::OpCompositeConstruct, load->type_id(),
  249. compositeId, {}));
  250. for (auto l : loads) {
  251. Operand op(SPV_OPERAND_TYPE_ID,
  252. std::initializer_list<uint32_t>{l->result_id()});
  253. compositeConstruct->AddOperand(std::move(op));
  254. }
  255. where = where.InsertBefore(std::move(compositeConstruct));
  256. get_def_use_mgr()->AnalyzeInstDefUse(&*where);
  257. where->UpdateDebugInfoFrom(load);
  258. context()->set_instr_block(&*where, block);
  259. context()->ReplaceAllUsesWith(load->result_id(), compositeId);
  260. return true;
  261. }
  262. bool ScalarReplacementPass::ReplaceWholeStore(
  263. Instruction* store, const std::vector<Instruction*>& replacements) {
  264. // Replaces a store to the whole composite with a series of extract and stores
  265. // to each element.
  266. uint32_t storeInput = store->GetSingleWordInOperand(1u);
  267. BasicBlock* block = context()->get_instr_block(store);
  268. BasicBlock::iterator where(store);
  269. uint32_t elementIndex = 0;
  270. for (auto var : replacements) {
  271. // Create the extract.
  272. if (var->opcode() != spv::Op::OpVariable) {
  273. elementIndex++;
  274. continue;
  275. }
  276. Instruction* type = GetStorageType(var);
  277. uint32_t extractId = TakeNextId();
  278. if (extractId == 0) {
  279. return false;
  280. }
  281. std::unique_ptr<Instruction> extract(new Instruction(
  282. context(), spv::Op::OpCompositeExtract, type->result_id(), extractId,
  283. std::initializer_list<Operand>{
  284. {SPV_OPERAND_TYPE_ID, {storeInput}},
  285. {SPV_OPERAND_TYPE_LITERAL_INTEGER, {elementIndex++}}}));
  286. auto iter = where.InsertBefore(std::move(extract));
  287. iter->UpdateDebugInfoFrom(store);
  288. get_def_use_mgr()->AnalyzeInstDefUse(&*iter);
  289. context()->set_instr_block(&*iter, block);
  290. // Create the store.
  291. std::unique_ptr<Instruction> newStore(
  292. new Instruction(context(), spv::Op::OpStore, 0, 0,
  293. std::initializer_list<Operand>{
  294. {SPV_OPERAND_TYPE_ID, {var->result_id()}},
  295. {SPV_OPERAND_TYPE_ID, {extractId}}}));
  296. // Copy memory access attributes which start at index 2. Index 0 is the
  297. // pointer and index 1 is the data.
  298. for (uint32_t i = 2; i < store->NumInOperands(); ++i) {
  299. Operand copy(store->GetInOperand(i));
  300. newStore->AddOperand(std::move(copy));
  301. }
  302. iter = where.InsertBefore(std::move(newStore));
  303. iter->UpdateDebugInfoFrom(store);
  304. get_def_use_mgr()->AnalyzeInstDefUse(&*iter);
  305. context()->set_instr_block(&*iter, block);
  306. }
  307. return true;
  308. }
  309. bool ScalarReplacementPass::ReplaceAccessChain(
  310. Instruction* chain, const std::vector<Instruction*>& replacements) {
  311. // Replaces the access chain with either another access chain (with one fewer
  312. // indexes) or a direct use of the replacement variable.
  313. uint32_t indexId = chain->GetSingleWordInOperand(1u);
  314. const Instruction* index = get_def_use_mgr()->GetDef(indexId);
  315. int64_t indexValue = context()
  316. ->get_constant_mgr()
  317. ->GetConstantFromInst(index)
  318. ->GetSignExtendedValue();
  319. if (indexValue < 0 ||
  320. indexValue >= static_cast<int64_t>(replacements.size())) {
  321. // Out of bounds access, this is illegal IR. Notice that OpAccessChain
  322. // indexing is 0-based, so we should also reject index == size-of-array.
  323. return false;
  324. } else {
  325. const Instruction* var = replacements[static_cast<size_t>(indexValue)];
  326. if (chain->NumInOperands() > 2) {
  327. // Replace input access chain with another access chain.
  328. BasicBlock::iterator chainIter(chain);
  329. uint32_t replacementId = TakeNextId();
  330. if (replacementId == 0) {
  331. return false;
  332. }
  333. std::unique_ptr<Instruction> replacementChain(new Instruction(
  334. context(), chain->opcode(), chain->type_id(), replacementId,
  335. std::initializer_list<Operand>{
  336. {SPV_OPERAND_TYPE_ID, {var->result_id()}}}));
  337. // Add the remaining indexes.
  338. for (uint32_t i = 2; i < chain->NumInOperands(); ++i) {
  339. Operand copy(chain->GetInOperand(i));
  340. replacementChain->AddOperand(std::move(copy));
  341. }
  342. replacementChain->UpdateDebugInfoFrom(chain);
  343. auto iter = chainIter.InsertBefore(std::move(replacementChain));
  344. get_def_use_mgr()->AnalyzeInstDefUse(&*iter);
  345. context()->set_instr_block(&*iter, context()->get_instr_block(chain));
  346. context()->ReplaceAllUsesWith(chain->result_id(), replacementId);
  347. } else {
  348. // Replace with a use of the variable.
  349. context()->ReplaceAllUsesWith(chain->result_id(), var->result_id());
  350. }
  351. }
  352. return true;
  353. }
  354. bool ScalarReplacementPass::CreateReplacementVariables(
  355. Instruction* inst, std::vector<Instruction*>* replacements) {
  356. Instruction* type = GetStorageType(inst);
  357. std::unique_ptr<std::unordered_set<int64_t>> components_used =
  358. GetUsedComponents(inst);
  359. uint32_t elem = 0;
  360. switch (type->opcode()) {
  361. case spv::Op::OpTypeStruct:
  362. type->ForEachInOperand(
  363. [this, inst, &elem, replacements, &components_used](uint32_t* id) {
  364. if (!components_used || components_used->count(elem)) {
  365. CreateVariable(*id, inst, elem, replacements);
  366. } else {
  367. replacements->push_back(GetUndef(*id));
  368. }
  369. elem++;
  370. });
  371. break;
  372. case spv::Op::OpTypeArray:
  373. for (uint32_t i = 0; i != GetArrayLength(type); ++i) {
  374. if (!components_used || components_used->count(i)) {
  375. CreateVariable(type->GetSingleWordInOperand(0u), inst, i,
  376. replacements);
  377. } else {
  378. uint32_t element_type_id = type->GetSingleWordInOperand(0);
  379. replacements->push_back(GetUndef(element_type_id));
  380. }
  381. }
  382. break;
  383. case spv::Op::OpTypeMatrix:
  384. case spv::Op::OpTypeVector:
  385. for (uint32_t i = 0; i != GetNumElements(type); ++i) {
  386. CreateVariable(type->GetSingleWordInOperand(0u), inst, i, replacements);
  387. }
  388. break;
  389. default:
  390. assert(false && "Unexpected type.");
  391. break;
  392. }
  393. TransferAnnotations(inst, replacements);
  394. return std::find(replacements->begin(), replacements->end(), nullptr) ==
  395. replacements->end();
  396. }
  397. Instruction* ScalarReplacementPass::GetUndef(uint32_t type_id) {
  398. return get_def_use_mgr()->GetDef(Type2Undef(type_id));
  399. }
  400. void ScalarReplacementPass::TransferAnnotations(
  401. const Instruction* source, std::vector<Instruction*>* replacements) {
  402. // Only transfer invariant and restrict decorations on the variable. There are
  403. // no type or member decorations that are necessary to transfer.
  404. for (auto inst :
  405. get_decoration_mgr()->GetDecorationsFor(source->result_id(), false)) {
  406. assert(inst->opcode() == spv::Op::OpDecorate);
  407. auto decoration = spv::Decoration(inst->GetSingleWordInOperand(1u));
  408. if (decoration == spv::Decoration::Invariant ||
  409. decoration == spv::Decoration::Restrict) {
  410. for (auto var : *replacements) {
  411. if (var == nullptr) {
  412. continue;
  413. }
  414. std::unique_ptr<Instruction> annotation(new Instruction(
  415. context(), spv::Op::OpDecorate, 0, 0,
  416. std::initializer_list<Operand>{
  417. {SPV_OPERAND_TYPE_ID, {var->result_id()}},
  418. {SPV_OPERAND_TYPE_DECORATION, {uint32_t(decoration)}}}));
  419. for (uint32_t i = 2; i < inst->NumInOperands(); ++i) {
  420. Operand copy(inst->GetInOperand(i));
  421. annotation->AddOperand(std::move(copy));
  422. }
  423. context()->AddAnnotationInst(std::move(annotation));
  424. get_def_use_mgr()->AnalyzeInstUse(&*--context()->annotation_end());
  425. }
  426. }
  427. }
  428. }
  429. void ScalarReplacementPass::CreateVariable(
  430. uint32_t typeId, Instruction* varInst, uint32_t index,
  431. std::vector<Instruction*>* replacements) {
  432. uint32_t ptrId = GetOrCreatePointerType(typeId);
  433. uint32_t id = TakeNextId();
  434. if (id == 0) {
  435. replacements->push_back(nullptr);
  436. }
  437. std::unique_ptr<Instruction> variable(
  438. new Instruction(context(), spv::Op::OpVariable, ptrId, id,
  439. std::initializer_list<Operand>{
  440. {SPV_OPERAND_TYPE_STORAGE_CLASS,
  441. {uint32_t(spv::StorageClass::Function)}}}));
  442. BasicBlock* block = context()->get_instr_block(varInst);
  443. block->begin().InsertBefore(std::move(variable));
  444. Instruction* inst = &*block->begin();
  445. // If varInst was initialized, make sure to initialize its replacement.
  446. GetOrCreateInitialValue(varInst, index, inst);
  447. get_def_use_mgr()->AnalyzeInstDefUse(inst);
  448. context()->set_instr_block(inst, block);
  449. // Copy decorations from the member to the new variable.
  450. Instruction* typeInst = GetStorageType(varInst);
  451. for (auto dec_inst :
  452. get_decoration_mgr()->GetDecorationsFor(typeInst->result_id(), false)) {
  453. uint32_t decoration;
  454. if (dec_inst->opcode() != spv::Op::OpMemberDecorate) {
  455. continue;
  456. }
  457. if (dec_inst->GetSingleWordInOperand(1) != index) {
  458. continue;
  459. }
  460. decoration = dec_inst->GetSingleWordInOperand(2u);
  461. switch (spv::Decoration(decoration)) {
  462. case spv::Decoration::RelaxedPrecision: {
  463. std::unique_ptr<Instruction> new_dec_inst(
  464. new Instruction(context(), spv::Op::OpDecorate, 0, 0, {}));
  465. new_dec_inst->AddOperand(Operand(SPV_OPERAND_TYPE_ID, {id}));
  466. for (uint32_t i = 2; i < dec_inst->NumInOperandWords(); ++i) {
  467. new_dec_inst->AddOperand(Operand(dec_inst->GetInOperand(i)));
  468. }
  469. context()->AddAnnotationInst(std::move(new_dec_inst));
  470. } break;
  471. default:
  472. break;
  473. }
  474. }
  475. // Update the DebugInfo debug information.
  476. inst->UpdateDebugInfoFrom(varInst);
  477. replacements->push_back(inst);
  478. }
  479. uint32_t ScalarReplacementPass::GetOrCreatePointerType(uint32_t id) {
  480. auto iter = pointee_to_pointer_.find(id);
  481. if (iter != pointee_to_pointer_.end()) return iter->second;
  482. analysis::Type* pointeeTy;
  483. std::unique_ptr<analysis::Pointer> pointerTy;
  484. std::tie(pointeeTy, pointerTy) =
  485. context()->get_type_mgr()->GetTypeAndPointerType(
  486. id, spv::StorageClass::Function);
  487. uint32_t ptrId = 0;
  488. if (pointeeTy->IsUniqueType()) {
  489. // Non-ambiguous type, just ask the type manager for an id.
  490. ptrId = context()->get_type_mgr()->GetTypeInstruction(pointerTy.get());
  491. pointee_to_pointer_[id] = ptrId;
  492. return ptrId;
  493. }
  494. // Ambiguous type. We must perform a linear search to try and find the right
  495. // type.
  496. for (auto global : context()->types_values()) {
  497. if (global.opcode() == spv::Op::OpTypePointer &&
  498. spv::StorageClass(global.GetSingleWordInOperand(0u)) ==
  499. spv::StorageClass::Function &&
  500. global.GetSingleWordInOperand(1u) == id) {
  501. if (get_decoration_mgr()->GetDecorationsFor(id, false).empty()) {
  502. // Only reuse a decoration-less pointer of the correct type.
  503. ptrId = global.result_id();
  504. break;
  505. }
  506. }
  507. }
  508. if (ptrId != 0) {
  509. pointee_to_pointer_[id] = ptrId;
  510. return ptrId;
  511. }
  512. ptrId = TakeNextId();
  513. context()->AddType(MakeUnique<Instruction>(
  514. context(), spv::Op::OpTypePointer, 0, ptrId,
  515. std::initializer_list<Operand>{{SPV_OPERAND_TYPE_STORAGE_CLASS,
  516. {uint32_t(spv::StorageClass::Function)}},
  517. {SPV_OPERAND_TYPE_ID, {id}}}));
  518. Instruction* ptr = &*--context()->types_values_end();
  519. get_def_use_mgr()->AnalyzeInstDefUse(ptr);
  520. pointee_to_pointer_[id] = ptrId;
  521. // Register with the type manager if necessary.
  522. context()->get_type_mgr()->RegisterType(ptrId, *pointerTy);
  523. return ptrId;
  524. }
  525. void ScalarReplacementPass::GetOrCreateInitialValue(Instruction* source,
  526. uint32_t index,
  527. Instruction* newVar) {
  528. assert(source->opcode() == spv::Op::OpVariable);
  529. if (source->NumInOperands() < 2) return;
  530. uint32_t initId = source->GetSingleWordInOperand(1u);
  531. uint32_t storageId = GetStorageType(newVar)->result_id();
  532. Instruction* init = get_def_use_mgr()->GetDef(initId);
  533. uint32_t newInitId = 0;
  534. // TODO(dnovillo): Refactor this with constant propagation.
  535. if (init->opcode() == spv::Op::OpConstantNull) {
  536. // Initialize to appropriate NULL.
  537. auto iter = type_to_null_.find(storageId);
  538. if (iter == type_to_null_.end()) {
  539. newInitId = TakeNextId();
  540. type_to_null_[storageId] = newInitId;
  541. context()->AddGlobalValue(
  542. MakeUnique<Instruction>(context(), spv::Op::OpConstantNull, storageId,
  543. newInitId, std::initializer_list<Operand>{}));
  544. Instruction* newNull = &*--context()->types_values_end();
  545. get_def_use_mgr()->AnalyzeInstDefUse(newNull);
  546. } else {
  547. newInitId = iter->second;
  548. }
  549. } else if (IsSpecConstantInst(init->opcode())) {
  550. // Create a new constant extract.
  551. newInitId = TakeNextId();
  552. context()->AddGlobalValue(MakeUnique<Instruction>(
  553. context(), spv::Op::OpSpecConstantOp, storageId, newInitId,
  554. std::initializer_list<Operand>{
  555. {SPV_OPERAND_TYPE_SPEC_CONSTANT_OP_NUMBER,
  556. {uint32_t(spv::Op::OpCompositeExtract)}},
  557. {SPV_OPERAND_TYPE_ID, {init->result_id()}},
  558. {SPV_OPERAND_TYPE_LITERAL_INTEGER, {index}}}));
  559. Instruction* newSpecConst = &*--context()->types_values_end();
  560. get_def_use_mgr()->AnalyzeInstDefUse(newSpecConst);
  561. } else if (init->opcode() == spv::Op::OpConstantComposite) {
  562. // Get the appropriate index constant.
  563. newInitId = init->GetSingleWordInOperand(index);
  564. Instruction* element = get_def_use_mgr()->GetDef(newInitId);
  565. if (element->opcode() == spv::Op::OpUndef) {
  566. // Undef is not a valid initializer for a variable.
  567. newInitId = 0;
  568. }
  569. } else {
  570. assert(false);
  571. }
  572. if (newInitId != 0) {
  573. newVar->AddOperand({SPV_OPERAND_TYPE_ID, {newInitId}});
  574. }
  575. }
  576. uint64_t ScalarReplacementPass::GetArrayLength(
  577. const Instruction* arrayType) const {
  578. assert(arrayType->opcode() == spv::Op::OpTypeArray);
  579. const Instruction* length =
  580. get_def_use_mgr()->GetDef(arrayType->GetSingleWordInOperand(1u));
  581. return context()
  582. ->get_constant_mgr()
  583. ->GetConstantFromInst(length)
  584. ->GetZeroExtendedValue();
  585. }
  586. uint64_t ScalarReplacementPass::GetNumElements(const Instruction* type) const {
  587. assert(type->opcode() == spv::Op::OpTypeVector ||
  588. type->opcode() == spv::Op::OpTypeMatrix);
  589. const Operand& op = type->GetInOperand(1u);
  590. assert(op.words.size() <= 2);
  591. uint64_t len = 0;
  592. for (size_t i = 0; i != op.words.size(); ++i) {
  593. len |= (static_cast<uint64_t>(op.words[i]) << (32ull * i));
  594. }
  595. return len;
  596. }
  597. bool ScalarReplacementPass::IsSpecConstant(uint32_t id) const {
  598. const Instruction* inst = get_def_use_mgr()->GetDef(id);
  599. assert(inst);
  600. return spvOpcodeIsSpecConstant(inst->opcode());
  601. }
  602. Instruction* ScalarReplacementPass::GetStorageType(
  603. const Instruction* inst) const {
  604. assert(inst->opcode() == spv::Op::OpVariable);
  605. uint32_t ptrTypeId = inst->type_id();
  606. uint32_t typeId =
  607. get_def_use_mgr()->GetDef(ptrTypeId)->GetSingleWordInOperand(1u);
  608. return get_def_use_mgr()->GetDef(typeId);
  609. }
  610. bool ScalarReplacementPass::CanReplaceVariable(
  611. const Instruction* varInst) const {
  612. assert(varInst->opcode() == spv::Op::OpVariable);
  613. // Can only replace function scope variables.
  614. if (spv::StorageClass(varInst->GetSingleWordInOperand(0u)) !=
  615. spv::StorageClass::Function) {
  616. return false;
  617. }
  618. if (!CheckTypeAnnotations(get_def_use_mgr()->GetDef(varInst->type_id()))) {
  619. return false;
  620. }
  621. const Instruction* typeInst = GetStorageType(varInst);
  622. if (!CheckType(typeInst)) {
  623. return false;
  624. }
  625. if (!CheckAnnotations(varInst)) {
  626. return false;
  627. }
  628. if (!CheckUses(varInst)) {
  629. return false;
  630. }
  631. return true;
  632. }
  633. bool ScalarReplacementPass::CheckType(const Instruction* typeInst) const {
  634. if (!CheckTypeAnnotations(typeInst)) {
  635. return false;
  636. }
  637. switch (typeInst->opcode()) {
  638. case spv::Op::OpTypeStruct:
  639. // Don't bother with empty structs or very large structs.
  640. if (typeInst->NumInOperands() == 0 ||
  641. IsLargerThanSizeLimit(typeInst->NumInOperands())) {
  642. return false;
  643. }
  644. return true;
  645. case spv::Op::OpTypeArray:
  646. if (IsSpecConstant(typeInst->GetSingleWordInOperand(1u))) {
  647. return false;
  648. }
  649. if (IsLargerThanSizeLimit(GetArrayLength(typeInst))) {
  650. return false;
  651. }
  652. return true;
  653. // TODO(alanbaker): Develop some heuristics for when this should be
  654. // re-enabled.
  655. //// Specifically including matrix and vector in an attempt to reduce the
  656. //// number of vector registers required.
  657. // case spv::Op::OpTypeMatrix:
  658. // case spv::Op::OpTypeVector:
  659. // if (IsLargerThanSizeLimit(GetNumElements(typeInst))) return false;
  660. // return true;
  661. case spv::Op::OpTypeRuntimeArray:
  662. default:
  663. return false;
  664. }
  665. }
  666. bool ScalarReplacementPass::CheckTypeAnnotations(
  667. const Instruction* typeInst) const {
  668. for (auto inst :
  669. get_decoration_mgr()->GetDecorationsFor(typeInst->result_id(), false)) {
  670. uint32_t decoration;
  671. if (inst->opcode() == spv::Op::OpDecorate) {
  672. decoration = inst->GetSingleWordInOperand(1u);
  673. } else {
  674. assert(inst->opcode() == spv::Op::OpMemberDecorate);
  675. decoration = inst->GetSingleWordInOperand(2u);
  676. }
  677. switch (spv::Decoration(decoration)) {
  678. case spv::Decoration::RowMajor:
  679. case spv::Decoration::ColMajor:
  680. case spv::Decoration::ArrayStride:
  681. case spv::Decoration::MatrixStride:
  682. case spv::Decoration::CPacked:
  683. case spv::Decoration::Invariant:
  684. case spv::Decoration::Restrict:
  685. case spv::Decoration::Offset:
  686. case spv::Decoration::Alignment:
  687. case spv::Decoration::AlignmentId:
  688. case spv::Decoration::MaxByteOffset:
  689. case spv::Decoration::RelaxedPrecision:
  690. break;
  691. default:
  692. return false;
  693. }
  694. }
  695. return true;
  696. }
  697. bool ScalarReplacementPass::CheckAnnotations(const Instruction* varInst) const {
  698. for (auto inst :
  699. get_decoration_mgr()->GetDecorationsFor(varInst->result_id(), false)) {
  700. assert(inst->opcode() == spv::Op::OpDecorate);
  701. auto decoration = spv::Decoration(inst->GetSingleWordInOperand(1u));
  702. switch (decoration) {
  703. case spv::Decoration::Invariant:
  704. case spv::Decoration::Restrict:
  705. case spv::Decoration::Alignment:
  706. case spv::Decoration::AlignmentId:
  707. case spv::Decoration::MaxByteOffset:
  708. break;
  709. default:
  710. return false;
  711. }
  712. }
  713. return true;
  714. }
  715. bool ScalarReplacementPass::CheckUses(const Instruction* inst) const {
  716. VariableStats stats = {0, 0};
  717. bool ok = CheckUses(inst, &stats);
  718. // TODO(alanbaker/greg-lunarg): Add some meaningful heuristics about when
  719. // SRoA is costly, such as when the structure has many (unaccessed?)
  720. // members.
  721. return ok;
  722. }
  723. bool ScalarReplacementPass::CheckUses(const Instruction* inst,
  724. VariableStats* stats) const {
  725. uint64_t max_legal_index = GetMaxLegalIndex(inst);
  726. bool ok = true;
  727. get_def_use_mgr()->ForEachUse(inst, [this, max_legal_index, stats, &ok](
  728. const Instruction* user,
  729. uint32_t index) {
  730. if (user->GetCommonDebugOpcode() == CommonDebugInfoDebugDeclare ||
  731. user->GetCommonDebugOpcode() == CommonDebugInfoDebugValue) {
  732. // TODO: include num_partial_accesses if it uses Fragment operation or
  733. // DebugValue has Indexes operand.
  734. stats->num_full_accesses++;
  735. return;
  736. }
  737. // Annotations are check as a group separately.
  738. if (!IsAnnotationInst(user->opcode())) {
  739. switch (user->opcode()) {
  740. case spv::Op::OpAccessChain:
  741. case spv::Op::OpInBoundsAccessChain:
  742. if (index == 2u && user->NumInOperands() > 1) {
  743. uint32_t id = user->GetSingleWordInOperand(1u);
  744. const Instruction* opInst = get_def_use_mgr()->GetDef(id);
  745. const auto* constant =
  746. context()->get_constant_mgr()->GetConstantFromInst(opInst);
  747. if (!constant) {
  748. ok = false;
  749. } else if (constant->GetZeroExtendedValue() >= max_legal_index) {
  750. ok = false;
  751. } else {
  752. if (!CheckUsesRelaxed(user)) ok = false;
  753. }
  754. stats->num_partial_accesses++;
  755. } else {
  756. ok = false;
  757. }
  758. break;
  759. case spv::Op::OpLoad:
  760. if (!CheckLoad(user, index)) ok = false;
  761. stats->num_full_accesses++;
  762. break;
  763. case spv::Op::OpStore:
  764. if (!CheckStore(user, index)) ok = false;
  765. stats->num_full_accesses++;
  766. break;
  767. case spv::Op::OpName:
  768. case spv::Op::OpMemberName:
  769. break;
  770. default:
  771. ok = false;
  772. break;
  773. }
  774. }
  775. });
  776. return ok;
  777. }
  778. bool ScalarReplacementPass::CheckUsesRelaxed(const Instruction* inst) const {
  779. bool ok = true;
  780. get_def_use_mgr()->ForEachUse(
  781. inst, [this, &ok](const Instruction* user, uint32_t index) {
  782. switch (user->opcode()) {
  783. case spv::Op::OpAccessChain:
  784. case spv::Op::OpInBoundsAccessChain:
  785. if (index != 2u) {
  786. ok = false;
  787. } else {
  788. if (!CheckUsesRelaxed(user)) ok = false;
  789. }
  790. break;
  791. case spv::Op::OpLoad:
  792. if (!CheckLoad(user, index)) ok = false;
  793. break;
  794. case spv::Op::OpStore:
  795. if (!CheckStore(user, index)) ok = false;
  796. break;
  797. case spv::Op::OpImageTexelPointer:
  798. if (!CheckImageTexelPointer(index)) ok = false;
  799. break;
  800. case spv::Op::OpExtInst:
  801. if (user->GetCommonDebugOpcode() != CommonDebugInfoDebugDeclare ||
  802. !CheckDebugDeclare(index))
  803. ok = false;
  804. break;
  805. default:
  806. ok = false;
  807. break;
  808. }
  809. });
  810. return ok;
  811. }
  812. bool ScalarReplacementPass::CheckImageTexelPointer(uint32_t index) const {
  813. return index == 2u;
  814. }
  815. bool ScalarReplacementPass::CheckLoad(const Instruction* inst,
  816. uint32_t index) const {
  817. if (index != 2u) return false;
  818. if (inst->NumInOperands() >= 2 &&
  819. inst->GetSingleWordInOperand(1u) &
  820. uint32_t(spv::MemoryAccessMask::Volatile))
  821. return false;
  822. return true;
  823. }
  824. bool ScalarReplacementPass::CheckStore(const Instruction* inst,
  825. uint32_t index) const {
  826. if (index != 0u) return false;
  827. if (inst->NumInOperands() >= 3 &&
  828. inst->GetSingleWordInOperand(2u) &
  829. uint32_t(spv::MemoryAccessMask::Volatile))
  830. return false;
  831. return true;
  832. }
  833. bool ScalarReplacementPass::CheckDebugDeclare(uint32_t index) const {
  834. if (index != kDebugDeclareOperandVariableIndex) return false;
  835. return true;
  836. }
  837. bool ScalarReplacementPass::IsLargerThanSizeLimit(uint64_t length) const {
  838. if (max_num_elements_ == 0) {
  839. return false;
  840. }
  841. return length > max_num_elements_;
  842. }
  843. std::unique_ptr<std::unordered_set<int64_t>>
  844. ScalarReplacementPass::GetUsedComponents(Instruction* inst) {
  845. std::unique_ptr<std::unordered_set<int64_t>> result(
  846. new std::unordered_set<int64_t>());
  847. analysis::DefUseManager* def_use_mgr = context()->get_def_use_mgr();
  848. def_use_mgr->WhileEachUser(inst, [&result, def_use_mgr,
  849. this](Instruction* use) {
  850. switch (use->opcode()) {
  851. case spv::Op::OpLoad: {
  852. // Look for extract from the load.
  853. std::vector<uint32_t> t;
  854. if (def_use_mgr->WhileEachUser(use, [&t](Instruction* use2) {
  855. if (use2->opcode() != spv::Op::OpCompositeExtract ||
  856. use2->NumInOperands() <= 1) {
  857. return false;
  858. }
  859. t.push_back(use2->GetSingleWordInOperand(1));
  860. return true;
  861. })) {
  862. result->insert(t.begin(), t.end());
  863. return true;
  864. } else {
  865. result.reset(nullptr);
  866. return false;
  867. }
  868. }
  869. case spv::Op::OpName:
  870. case spv::Op::OpMemberName:
  871. case spv::Op::OpStore:
  872. // No components are used.
  873. return true;
  874. case spv::Op::OpAccessChain:
  875. case spv::Op::OpInBoundsAccessChain: {
  876. // Add the first index it if is a constant.
  877. // TODO: Could be improved by checking if the address is used in a load.
  878. analysis::ConstantManager* const_mgr = context()->get_constant_mgr();
  879. uint32_t index_id = use->GetSingleWordInOperand(1);
  880. const analysis::Constant* index_const =
  881. const_mgr->FindDeclaredConstant(index_id);
  882. if (index_const) {
  883. result->insert(index_const->GetSignExtendedValue());
  884. return true;
  885. } else {
  886. // Could be any element. Assuming all are used.
  887. result.reset(nullptr);
  888. return false;
  889. }
  890. }
  891. default:
  892. // We do not know what is happening. Have to assume the worst.
  893. result.reset(nullptr);
  894. return false;
  895. }
  896. });
  897. return result;
  898. }
  899. uint64_t ScalarReplacementPass::GetMaxLegalIndex(
  900. const Instruction* var_inst) const {
  901. assert(var_inst->opcode() == spv::Op::OpVariable &&
  902. "|var_inst| must be a variable instruction.");
  903. Instruction* type = GetStorageType(var_inst);
  904. switch (type->opcode()) {
  905. case spv::Op::OpTypeStruct:
  906. return type->NumInOperands();
  907. case spv::Op::OpTypeArray:
  908. return GetArrayLength(type);
  909. case spv::Op::OpTypeMatrix:
  910. case spv::Op::OpTypeVector:
  911. return GetNumElements(type);
  912. default:
  913. return 0;
  914. }
  915. return 0;
  916. }
  917. } // namespace opt
  918. } // namespace spvtools