scalar_replacement_pass.cpp 34 KB

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