ir_context.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  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/ir_context.h"
  15. #include <cstring>
  16. #include "OpenCLDebugInfo100.h"
  17. #include "source/latest_version_glsl_std_450_header.h"
  18. #include "source/opt/log.h"
  19. #include "source/opt/mem_pass.h"
  20. #include "source/opt/reflect.h"
  21. namespace {
  22. static const int kSpvDecorateTargetIdInIdx = 0;
  23. static const int kSpvDecorateDecorationInIdx = 1;
  24. static const int kSpvDecorateBuiltinInIdx = 2;
  25. static const int kEntryPointInterfaceInIdx = 3;
  26. static const int kEntryPointFunctionIdInIdx = 1;
  27. // Constants for OpenCL.DebugInfo.100 / NonSemantic.Shader.DebugInfo.100
  28. // extension instructions.
  29. static const uint32_t kDebugFunctionOperandFunctionIndex = 13;
  30. static const uint32_t kDebugGlobalVariableOperandVariableIndex = 11;
  31. } // anonymous namespace
  32. namespace spvtools {
  33. namespace opt {
  34. void IRContext::BuildInvalidAnalyses(IRContext::Analysis set) {
  35. set = Analysis(set & ~valid_analyses_);
  36. if (set & kAnalysisDefUse) {
  37. BuildDefUseManager();
  38. }
  39. if (set & kAnalysisInstrToBlockMapping) {
  40. BuildInstrToBlockMapping();
  41. }
  42. if (set & kAnalysisDecorations) {
  43. BuildDecorationManager();
  44. }
  45. if (set & kAnalysisCFG) {
  46. BuildCFG();
  47. }
  48. if (set & kAnalysisDominatorAnalysis) {
  49. ResetDominatorAnalysis();
  50. }
  51. if (set & kAnalysisLoopAnalysis) {
  52. ResetLoopAnalysis();
  53. }
  54. if (set & kAnalysisBuiltinVarId) {
  55. ResetBuiltinAnalysis();
  56. }
  57. if (set & kAnalysisNameMap) {
  58. BuildIdToNameMap();
  59. }
  60. if (set & kAnalysisScalarEvolution) {
  61. BuildScalarEvolutionAnalysis();
  62. }
  63. if (set & kAnalysisRegisterPressure) {
  64. BuildRegPressureAnalysis();
  65. }
  66. if (set & kAnalysisValueNumberTable) {
  67. BuildValueNumberTable();
  68. }
  69. if (set & kAnalysisStructuredCFG) {
  70. BuildStructuredCFGAnalysis();
  71. }
  72. if (set & kAnalysisIdToFuncMapping) {
  73. BuildIdToFuncMapping();
  74. }
  75. if (set & kAnalysisConstants) {
  76. BuildConstantManager();
  77. }
  78. if (set & kAnalysisTypes) {
  79. BuildTypeManager();
  80. }
  81. if (set & kAnalysisDebugInfo) {
  82. BuildDebugInfoManager();
  83. }
  84. }
  85. void IRContext::InvalidateAnalysesExceptFor(
  86. IRContext::Analysis preserved_analyses) {
  87. uint32_t analyses_to_invalidate = valid_analyses_ & (~preserved_analyses);
  88. InvalidateAnalyses(static_cast<IRContext::Analysis>(analyses_to_invalidate));
  89. }
  90. void IRContext::InvalidateAnalyses(IRContext::Analysis analyses_to_invalidate) {
  91. // The ConstantManager and DebugInfoManager contain Type pointers. If the
  92. // TypeManager goes away, the ConstantManager and DebugInfoManager have to
  93. // go away.
  94. if (analyses_to_invalidate & kAnalysisTypes) {
  95. analyses_to_invalidate |= kAnalysisConstants;
  96. analyses_to_invalidate |= kAnalysisDebugInfo;
  97. }
  98. // The dominator analysis hold the pseudo entry and exit nodes from the CFG.
  99. // Also if the CFG change the dominators many changed as well, so the
  100. // dominator analysis should be invalidated as well.
  101. if (analyses_to_invalidate & kAnalysisCFG) {
  102. analyses_to_invalidate |= kAnalysisDominatorAnalysis;
  103. }
  104. if (analyses_to_invalidate & kAnalysisDefUse) {
  105. def_use_mgr_.reset(nullptr);
  106. }
  107. if (analyses_to_invalidate & kAnalysisInstrToBlockMapping) {
  108. instr_to_block_.clear();
  109. }
  110. if (analyses_to_invalidate & kAnalysisDecorations) {
  111. decoration_mgr_.reset(nullptr);
  112. }
  113. if (analyses_to_invalidate & kAnalysisCombinators) {
  114. combinator_ops_.clear();
  115. }
  116. if (analyses_to_invalidate & kAnalysisBuiltinVarId) {
  117. builtin_var_id_map_.clear();
  118. }
  119. if (analyses_to_invalidate & kAnalysisCFG) {
  120. cfg_.reset(nullptr);
  121. }
  122. if (analyses_to_invalidate & kAnalysisDominatorAnalysis) {
  123. dominator_trees_.clear();
  124. post_dominator_trees_.clear();
  125. }
  126. if (analyses_to_invalidate & kAnalysisNameMap) {
  127. id_to_name_.reset(nullptr);
  128. }
  129. if (analyses_to_invalidate & kAnalysisValueNumberTable) {
  130. vn_table_.reset(nullptr);
  131. }
  132. if (analyses_to_invalidate & kAnalysisStructuredCFG) {
  133. struct_cfg_analysis_.reset(nullptr);
  134. }
  135. if (analyses_to_invalidate & kAnalysisIdToFuncMapping) {
  136. id_to_func_.clear();
  137. }
  138. if (analyses_to_invalidate & kAnalysisConstants) {
  139. constant_mgr_.reset(nullptr);
  140. }
  141. if (analyses_to_invalidate & kAnalysisTypes) {
  142. type_mgr_.reset(nullptr);
  143. }
  144. if (analyses_to_invalidate & kAnalysisDebugInfo) {
  145. debug_info_mgr_.reset(nullptr);
  146. }
  147. valid_analyses_ = Analysis(valid_analyses_ & ~analyses_to_invalidate);
  148. }
  149. Instruction* IRContext::KillInst(Instruction* inst) {
  150. if (!inst) {
  151. return nullptr;
  152. }
  153. KillNamesAndDecorates(inst);
  154. KillOperandFromDebugInstructions(inst);
  155. if (AreAnalysesValid(kAnalysisDefUse)) {
  156. analysis::DefUseManager* def_use_mgr = get_def_use_mgr();
  157. def_use_mgr->ClearInst(inst);
  158. for (auto& l_inst : inst->dbg_line_insts()) def_use_mgr->ClearInst(&l_inst);
  159. }
  160. if (AreAnalysesValid(kAnalysisInstrToBlockMapping)) {
  161. instr_to_block_.erase(inst);
  162. }
  163. if (AreAnalysesValid(kAnalysisDecorations)) {
  164. if (inst->IsDecoration()) {
  165. decoration_mgr_->RemoveDecoration(inst);
  166. }
  167. }
  168. if (AreAnalysesValid(kAnalysisDebugInfo)) {
  169. get_debug_info_mgr()->ClearDebugScopeAndInlinedAtUses(inst);
  170. get_debug_info_mgr()->ClearDebugInfo(inst);
  171. }
  172. if (type_mgr_ && IsTypeInst(inst->opcode())) {
  173. type_mgr_->RemoveId(inst->result_id());
  174. }
  175. if (constant_mgr_ && IsConstantInst(inst->opcode())) {
  176. constant_mgr_->RemoveId(inst->result_id());
  177. }
  178. if (inst->opcode() == SpvOpCapability || inst->opcode() == SpvOpExtension) {
  179. // We reset the feature manager, instead of updating it, because it is just
  180. // as much work. We would have to remove all capabilities implied by this
  181. // capability that are not also implied by the remaining OpCapability
  182. // instructions. We could update extensions, but we will see if it is
  183. // needed.
  184. ResetFeatureManager();
  185. }
  186. RemoveFromIdToName(inst);
  187. Instruction* next_instruction = nullptr;
  188. if (inst->IsInAList()) {
  189. next_instruction = inst->NextNode();
  190. inst->RemoveFromList();
  191. delete inst;
  192. } else {
  193. // Needed for instructions that are not part of a list like OpLabels,
  194. // OpFunction, OpFunctionEnd, etc..
  195. inst->ToNop();
  196. }
  197. return next_instruction;
  198. }
  199. void IRContext::CollectNonSemanticTree(
  200. Instruction* inst, std::unordered_set<Instruction*>* to_kill) {
  201. if (!inst->HasResultId()) return;
  202. // Debug[No]Line result id is not used, so we are done
  203. if (inst->IsDebugLineInst()) return;
  204. std::vector<Instruction*> work_list;
  205. std::unordered_set<Instruction*> seen;
  206. work_list.push_back(inst);
  207. while (!work_list.empty()) {
  208. auto* i = work_list.back();
  209. work_list.pop_back();
  210. get_def_use_mgr()->ForEachUser(
  211. i, [&work_list, to_kill, &seen](Instruction* user) {
  212. if (user->IsNonSemanticInstruction() && seen.insert(user).second) {
  213. work_list.push_back(user);
  214. to_kill->insert(user);
  215. }
  216. });
  217. }
  218. }
  219. bool IRContext::KillDef(uint32_t id) {
  220. Instruction* def = get_def_use_mgr()->GetDef(id);
  221. if (def != nullptr) {
  222. KillInst(def);
  223. return true;
  224. }
  225. return false;
  226. }
  227. bool IRContext::ReplaceAllUsesWith(uint32_t before, uint32_t after) {
  228. return ReplaceAllUsesWithPredicate(before, after,
  229. [](Instruction*) { return true; });
  230. }
  231. bool IRContext::ReplaceAllUsesWithPredicate(
  232. uint32_t before, uint32_t after,
  233. const std::function<bool(Instruction*)>& predicate) {
  234. if (before == after) return false;
  235. if (AreAnalysesValid(kAnalysisDebugInfo)) {
  236. get_debug_info_mgr()->ReplaceAllUsesInDebugScopeWithPredicate(before, after,
  237. predicate);
  238. }
  239. // Ensure that |after| has been registered as def.
  240. assert(get_def_use_mgr()->GetDef(after) &&
  241. "'after' is not a registered def.");
  242. std::vector<std::pair<Instruction*, uint32_t>> uses_to_update;
  243. get_def_use_mgr()->ForEachUse(
  244. before, [&predicate, &uses_to_update](Instruction* user, uint32_t index) {
  245. if (predicate(user)) {
  246. uses_to_update.emplace_back(user, index);
  247. }
  248. });
  249. Instruction* prev = nullptr;
  250. for (auto p : uses_to_update) {
  251. Instruction* user = p.first;
  252. uint32_t index = p.second;
  253. if (prev == nullptr || prev != user) {
  254. ForgetUses(user);
  255. prev = user;
  256. }
  257. const uint32_t type_result_id_count =
  258. (user->result_id() != 0) + (user->type_id() != 0);
  259. if (index < type_result_id_count) {
  260. // Update the type_id. Note that result id is immutable so it should
  261. // never be updated.
  262. if (user->type_id() != 0 && index == 0) {
  263. user->SetResultType(after);
  264. } else if (user->type_id() == 0) {
  265. SPIRV_ASSERT(consumer_, false,
  266. "Result type id considered as use while the instruction "
  267. "doesn't have a result type id.");
  268. (void)consumer_; // Makes the compiler happy for release build.
  269. } else {
  270. SPIRV_ASSERT(consumer_, false,
  271. "Trying setting the immutable result id.");
  272. }
  273. } else {
  274. // Update an in-operand.
  275. uint32_t in_operand_pos = index - type_result_id_count;
  276. // Make the modification in the instruction.
  277. user->SetInOperand(in_operand_pos, {after});
  278. }
  279. AnalyzeUses(user);
  280. }
  281. return true;
  282. }
  283. bool IRContext::IsConsistent() {
  284. #ifndef SPIRV_CHECK_CONTEXT
  285. return true;
  286. #else
  287. if (AreAnalysesValid(kAnalysisDefUse)) {
  288. analysis::DefUseManager new_def_use(module());
  289. if (!CompareAndPrintDifferences(*get_def_use_mgr(), new_def_use)) {
  290. return false;
  291. }
  292. }
  293. if (AreAnalysesValid(kAnalysisIdToFuncMapping)) {
  294. for (auto& fn : *module_) {
  295. if (id_to_func_[fn.result_id()] != &fn) {
  296. return false;
  297. }
  298. }
  299. }
  300. if (AreAnalysesValid(kAnalysisInstrToBlockMapping)) {
  301. for (auto& func : *module()) {
  302. for (auto& block : func) {
  303. if (!block.WhileEachInst([this, &block](Instruction* inst) {
  304. if (get_instr_block(inst) != &block) {
  305. return false;
  306. }
  307. return true;
  308. }))
  309. return false;
  310. }
  311. }
  312. }
  313. if (!CheckCFG()) {
  314. return false;
  315. }
  316. if (AreAnalysesValid(kAnalysisDecorations)) {
  317. analysis::DecorationManager* dec_mgr = get_decoration_mgr();
  318. analysis::DecorationManager current(module());
  319. if (*dec_mgr != current) {
  320. return false;
  321. }
  322. }
  323. if (feature_mgr_ != nullptr) {
  324. FeatureManager current(grammar_);
  325. current.Analyze(module());
  326. if (current != *feature_mgr_) {
  327. return false;
  328. }
  329. }
  330. return true;
  331. #endif
  332. }
  333. void IRContext::ForgetUses(Instruction* inst) {
  334. if (AreAnalysesValid(kAnalysisDefUse)) {
  335. get_def_use_mgr()->EraseUseRecordsOfOperandIds(inst);
  336. }
  337. if (AreAnalysesValid(kAnalysisDecorations)) {
  338. if (inst->IsDecoration()) {
  339. get_decoration_mgr()->RemoveDecoration(inst);
  340. }
  341. }
  342. if (AreAnalysesValid(kAnalysisDebugInfo)) {
  343. get_debug_info_mgr()->ClearDebugInfo(inst);
  344. }
  345. RemoveFromIdToName(inst);
  346. }
  347. void IRContext::AnalyzeUses(Instruction* inst) {
  348. if (AreAnalysesValid(kAnalysisDefUse)) {
  349. get_def_use_mgr()->AnalyzeInstUse(inst);
  350. }
  351. if (AreAnalysesValid(kAnalysisDecorations)) {
  352. if (inst->IsDecoration()) {
  353. get_decoration_mgr()->AddDecoration(inst);
  354. }
  355. }
  356. if (AreAnalysesValid(kAnalysisDebugInfo)) {
  357. get_debug_info_mgr()->AnalyzeDebugInst(inst);
  358. }
  359. if (id_to_name_ &&
  360. (inst->opcode() == SpvOpName || inst->opcode() == SpvOpMemberName)) {
  361. id_to_name_->insert({inst->GetSingleWordInOperand(0), inst});
  362. }
  363. }
  364. void IRContext::KillNamesAndDecorates(uint32_t id) {
  365. analysis::DecorationManager* dec_mgr = get_decoration_mgr();
  366. dec_mgr->RemoveDecorationsFrom(id);
  367. std::vector<Instruction*> name_to_kill;
  368. for (auto name : GetNames(id)) {
  369. name_to_kill.push_back(name.second);
  370. }
  371. for (Instruction* name_inst : name_to_kill) {
  372. KillInst(name_inst);
  373. }
  374. }
  375. void IRContext::KillNamesAndDecorates(Instruction* inst) {
  376. const uint32_t rId = inst->result_id();
  377. if (rId == 0) return;
  378. KillNamesAndDecorates(rId);
  379. }
  380. void IRContext::KillOperandFromDebugInstructions(Instruction* inst) {
  381. const auto opcode = inst->opcode();
  382. const uint32_t id = inst->result_id();
  383. // Kill id of OpFunction from DebugFunction.
  384. if (opcode == SpvOpFunction) {
  385. for (auto it = module()->ext_inst_debuginfo_begin();
  386. it != module()->ext_inst_debuginfo_end(); ++it) {
  387. if (it->GetOpenCL100DebugOpcode() != OpenCLDebugInfo100DebugFunction)
  388. continue;
  389. auto& operand = it->GetOperand(kDebugFunctionOperandFunctionIndex);
  390. if (operand.words[0] == id) {
  391. operand.words[0] =
  392. get_debug_info_mgr()->GetDebugInfoNone()->result_id();
  393. get_def_use_mgr()->AnalyzeInstUse(&*it);
  394. }
  395. }
  396. }
  397. // Kill id of OpVariable for global variable from DebugGlobalVariable.
  398. if (opcode == SpvOpVariable || IsConstantInst(opcode)) {
  399. for (auto it = module()->ext_inst_debuginfo_begin();
  400. it != module()->ext_inst_debuginfo_end(); ++it) {
  401. if (it->GetCommonDebugOpcode() != CommonDebugInfoDebugGlobalVariable)
  402. continue;
  403. auto& operand = it->GetOperand(kDebugGlobalVariableOperandVariableIndex);
  404. if (operand.words[0] == id) {
  405. operand.words[0] =
  406. get_debug_info_mgr()->GetDebugInfoNone()->result_id();
  407. get_def_use_mgr()->AnalyzeInstUse(&*it);
  408. }
  409. }
  410. }
  411. }
  412. void IRContext::AddCombinatorsForCapability(uint32_t capability) {
  413. if (capability == SpvCapabilityShader) {
  414. combinator_ops_[0].insert({SpvOpNop,
  415. SpvOpUndef,
  416. SpvOpConstant,
  417. SpvOpConstantTrue,
  418. SpvOpConstantFalse,
  419. SpvOpConstantComposite,
  420. SpvOpConstantSampler,
  421. SpvOpConstantNull,
  422. SpvOpTypeVoid,
  423. SpvOpTypeBool,
  424. SpvOpTypeInt,
  425. SpvOpTypeFloat,
  426. SpvOpTypeVector,
  427. SpvOpTypeMatrix,
  428. SpvOpTypeImage,
  429. SpvOpTypeSampler,
  430. SpvOpTypeSampledImage,
  431. SpvOpTypeAccelerationStructureNV,
  432. SpvOpTypeAccelerationStructureKHR,
  433. SpvOpTypeRayQueryKHR,
  434. SpvOpTypeArray,
  435. SpvOpTypeRuntimeArray,
  436. SpvOpTypeStruct,
  437. SpvOpTypeOpaque,
  438. SpvOpTypePointer,
  439. SpvOpTypeFunction,
  440. SpvOpTypeEvent,
  441. SpvOpTypeDeviceEvent,
  442. SpvOpTypeReserveId,
  443. SpvOpTypeQueue,
  444. SpvOpTypePipe,
  445. SpvOpTypeForwardPointer,
  446. SpvOpVariable,
  447. SpvOpImageTexelPointer,
  448. SpvOpLoad,
  449. SpvOpAccessChain,
  450. SpvOpInBoundsAccessChain,
  451. SpvOpArrayLength,
  452. SpvOpVectorExtractDynamic,
  453. SpvOpVectorInsertDynamic,
  454. SpvOpVectorShuffle,
  455. SpvOpCompositeConstruct,
  456. SpvOpCompositeExtract,
  457. SpvOpCompositeInsert,
  458. SpvOpCopyObject,
  459. SpvOpTranspose,
  460. SpvOpSampledImage,
  461. SpvOpImageSampleImplicitLod,
  462. SpvOpImageSampleExplicitLod,
  463. SpvOpImageSampleDrefImplicitLod,
  464. SpvOpImageSampleDrefExplicitLod,
  465. SpvOpImageSampleProjImplicitLod,
  466. SpvOpImageSampleProjExplicitLod,
  467. SpvOpImageSampleProjDrefImplicitLod,
  468. SpvOpImageSampleProjDrefExplicitLod,
  469. SpvOpImageFetch,
  470. SpvOpImageGather,
  471. SpvOpImageDrefGather,
  472. SpvOpImageRead,
  473. SpvOpImage,
  474. SpvOpImageQueryFormat,
  475. SpvOpImageQueryOrder,
  476. SpvOpImageQuerySizeLod,
  477. SpvOpImageQuerySize,
  478. SpvOpImageQueryLevels,
  479. SpvOpImageQuerySamples,
  480. SpvOpConvertFToU,
  481. SpvOpConvertFToS,
  482. SpvOpConvertSToF,
  483. SpvOpConvertUToF,
  484. SpvOpUConvert,
  485. SpvOpSConvert,
  486. SpvOpFConvert,
  487. SpvOpQuantizeToF16,
  488. SpvOpBitcast,
  489. SpvOpSNegate,
  490. SpvOpFNegate,
  491. SpvOpIAdd,
  492. SpvOpFAdd,
  493. SpvOpISub,
  494. SpvOpFSub,
  495. SpvOpIMul,
  496. SpvOpFMul,
  497. SpvOpUDiv,
  498. SpvOpSDiv,
  499. SpvOpFDiv,
  500. SpvOpUMod,
  501. SpvOpSRem,
  502. SpvOpSMod,
  503. SpvOpFRem,
  504. SpvOpFMod,
  505. SpvOpVectorTimesScalar,
  506. SpvOpMatrixTimesScalar,
  507. SpvOpVectorTimesMatrix,
  508. SpvOpMatrixTimesVector,
  509. SpvOpMatrixTimesMatrix,
  510. SpvOpOuterProduct,
  511. SpvOpDot,
  512. SpvOpIAddCarry,
  513. SpvOpISubBorrow,
  514. SpvOpUMulExtended,
  515. SpvOpSMulExtended,
  516. SpvOpAny,
  517. SpvOpAll,
  518. SpvOpIsNan,
  519. SpvOpIsInf,
  520. SpvOpLogicalEqual,
  521. SpvOpLogicalNotEqual,
  522. SpvOpLogicalOr,
  523. SpvOpLogicalAnd,
  524. SpvOpLogicalNot,
  525. SpvOpSelect,
  526. SpvOpIEqual,
  527. SpvOpINotEqual,
  528. SpvOpUGreaterThan,
  529. SpvOpSGreaterThan,
  530. SpvOpUGreaterThanEqual,
  531. SpvOpSGreaterThanEqual,
  532. SpvOpULessThan,
  533. SpvOpSLessThan,
  534. SpvOpULessThanEqual,
  535. SpvOpSLessThanEqual,
  536. SpvOpFOrdEqual,
  537. SpvOpFUnordEqual,
  538. SpvOpFOrdNotEqual,
  539. SpvOpFUnordNotEqual,
  540. SpvOpFOrdLessThan,
  541. SpvOpFUnordLessThan,
  542. SpvOpFOrdGreaterThan,
  543. SpvOpFUnordGreaterThan,
  544. SpvOpFOrdLessThanEqual,
  545. SpvOpFUnordLessThanEqual,
  546. SpvOpFOrdGreaterThanEqual,
  547. SpvOpFUnordGreaterThanEqual,
  548. SpvOpShiftRightLogical,
  549. SpvOpShiftRightArithmetic,
  550. SpvOpShiftLeftLogical,
  551. SpvOpBitwiseOr,
  552. SpvOpBitwiseXor,
  553. SpvOpBitwiseAnd,
  554. SpvOpNot,
  555. SpvOpBitFieldInsert,
  556. SpvOpBitFieldSExtract,
  557. SpvOpBitFieldUExtract,
  558. SpvOpBitReverse,
  559. SpvOpBitCount,
  560. SpvOpPhi,
  561. SpvOpImageSparseSampleImplicitLod,
  562. SpvOpImageSparseSampleExplicitLod,
  563. SpvOpImageSparseSampleDrefImplicitLod,
  564. SpvOpImageSparseSampleDrefExplicitLod,
  565. SpvOpImageSparseSampleProjImplicitLod,
  566. SpvOpImageSparseSampleProjExplicitLod,
  567. SpvOpImageSparseSampleProjDrefImplicitLod,
  568. SpvOpImageSparseSampleProjDrefExplicitLod,
  569. SpvOpImageSparseFetch,
  570. SpvOpImageSparseGather,
  571. SpvOpImageSparseDrefGather,
  572. SpvOpImageSparseTexelsResident,
  573. SpvOpImageSparseRead,
  574. SpvOpSizeOf});
  575. }
  576. }
  577. void IRContext::AddCombinatorsForExtension(Instruction* extension) {
  578. assert(extension->opcode() == SpvOpExtInstImport &&
  579. "Expecting an import of an extension's instruction set.");
  580. const std::string extension_name = extension->GetInOperand(0).AsString();
  581. if (extension_name == "GLSL.std.450") {
  582. combinator_ops_[extension->result_id()] = {GLSLstd450Round,
  583. GLSLstd450RoundEven,
  584. GLSLstd450Trunc,
  585. GLSLstd450FAbs,
  586. GLSLstd450SAbs,
  587. GLSLstd450FSign,
  588. GLSLstd450SSign,
  589. GLSLstd450Floor,
  590. GLSLstd450Ceil,
  591. GLSLstd450Fract,
  592. GLSLstd450Radians,
  593. GLSLstd450Degrees,
  594. GLSLstd450Sin,
  595. GLSLstd450Cos,
  596. GLSLstd450Tan,
  597. GLSLstd450Asin,
  598. GLSLstd450Acos,
  599. GLSLstd450Atan,
  600. GLSLstd450Sinh,
  601. GLSLstd450Cosh,
  602. GLSLstd450Tanh,
  603. GLSLstd450Asinh,
  604. GLSLstd450Acosh,
  605. GLSLstd450Atanh,
  606. GLSLstd450Atan2,
  607. GLSLstd450Pow,
  608. GLSLstd450Exp,
  609. GLSLstd450Log,
  610. GLSLstd450Exp2,
  611. GLSLstd450Log2,
  612. GLSLstd450Sqrt,
  613. GLSLstd450InverseSqrt,
  614. GLSLstd450Determinant,
  615. GLSLstd450MatrixInverse,
  616. GLSLstd450ModfStruct,
  617. GLSLstd450FMin,
  618. GLSLstd450UMin,
  619. GLSLstd450SMin,
  620. GLSLstd450FMax,
  621. GLSLstd450UMax,
  622. GLSLstd450SMax,
  623. GLSLstd450FClamp,
  624. GLSLstd450UClamp,
  625. GLSLstd450SClamp,
  626. GLSLstd450FMix,
  627. GLSLstd450IMix,
  628. GLSLstd450Step,
  629. GLSLstd450SmoothStep,
  630. GLSLstd450Fma,
  631. GLSLstd450FrexpStruct,
  632. GLSLstd450Ldexp,
  633. GLSLstd450PackSnorm4x8,
  634. GLSLstd450PackUnorm4x8,
  635. GLSLstd450PackSnorm2x16,
  636. GLSLstd450PackUnorm2x16,
  637. GLSLstd450PackHalf2x16,
  638. GLSLstd450PackDouble2x32,
  639. GLSLstd450UnpackSnorm2x16,
  640. GLSLstd450UnpackUnorm2x16,
  641. GLSLstd450UnpackHalf2x16,
  642. GLSLstd450UnpackSnorm4x8,
  643. GLSLstd450UnpackUnorm4x8,
  644. GLSLstd450UnpackDouble2x32,
  645. GLSLstd450Length,
  646. GLSLstd450Distance,
  647. GLSLstd450Cross,
  648. GLSLstd450Normalize,
  649. GLSLstd450FaceForward,
  650. GLSLstd450Reflect,
  651. GLSLstd450Refract,
  652. GLSLstd450FindILsb,
  653. GLSLstd450FindSMsb,
  654. GLSLstd450FindUMsb,
  655. GLSLstd450InterpolateAtCentroid,
  656. GLSLstd450InterpolateAtSample,
  657. GLSLstd450InterpolateAtOffset,
  658. GLSLstd450NMin,
  659. GLSLstd450NMax,
  660. GLSLstd450NClamp};
  661. } else {
  662. // Map the result id to the empty set.
  663. combinator_ops_[extension->result_id()];
  664. }
  665. }
  666. void IRContext::InitializeCombinators() {
  667. get_feature_mgr()->GetCapabilities()->ForEach(
  668. [this](SpvCapability cap) { AddCombinatorsForCapability(cap); });
  669. for (auto& extension : module()->ext_inst_imports()) {
  670. AddCombinatorsForExtension(&extension);
  671. }
  672. valid_analyses_ |= kAnalysisCombinators;
  673. }
  674. void IRContext::RemoveFromIdToName(const Instruction* inst) {
  675. if (id_to_name_ &&
  676. (inst->opcode() == SpvOpName || inst->opcode() == SpvOpMemberName)) {
  677. auto range = id_to_name_->equal_range(inst->GetSingleWordInOperand(0));
  678. for (auto it = range.first; it != range.second; ++it) {
  679. if (it->second == inst) {
  680. id_to_name_->erase(it);
  681. break;
  682. }
  683. }
  684. }
  685. }
  686. LoopDescriptor* IRContext::GetLoopDescriptor(const Function* f) {
  687. if (!AreAnalysesValid(kAnalysisLoopAnalysis)) {
  688. ResetLoopAnalysis();
  689. }
  690. std::unordered_map<const Function*, LoopDescriptor>::iterator it =
  691. loop_descriptors_.find(f);
  692. if (it == loop_descriptors_.end()) {
  693. return &loop_descriptors_
  694. .emplace(std::make_pair(f, LoopDescriptor(this, f)))
  695. .first->second;
  696. }
  697. return &it->second;
  698. }
  699. uint32_t IRContext::FindBuiltinInputVar(uint32_t builtin) {
  700. for (auto& a : module_->annotations()) {
  701. if (a.opcode() != SpvOpDecorate) continue;
  702. if (a.GetSingleWordInOperand(kSpvDecorateDecorationInIdx) !=
  703. SpvDecorationBuiltIn)
  704. continue;
  705. if (a.GetSingleWordInOperand(kSpvDecorateBuiltinInIdx) != builtin) continue;
  706. uint32_t target_id = a.GetSingleWordInOperand(kSpvDecorateTargetIdInIdx);
  707. Instruction* b_var = get_def_use_mgr()->GetDef(target_id);
  708. if (b_var->opcode() != SpvOpVariable) continue;
  709. if (b_var->GetSingleWordInOperand(0) != SpvStorageClassInput) continue;
  710. return target_id;
  711. }
  712. return 0;
  713. }
  714. void IRContext::AddVarToEntryPoints(uint32_t var_id) {
  715. uint32_t ocnt = 0;
  716. for (auto& e : module()->entry_points()) {
  717. bool found = false;
  718. e.ForEachInOperand([&ocnt, &found, &var_id](const uint32_t* idp) {
  719. if (ocnt >= kEntryPointInterfaceInIdx) {
  720. if (*idp == var_id) found = true;
  721. }
  722. ++ocnt;
  723. });
  724. if (!found) {
  725. e.AddOperand({SPV_OPERAND_TYPE_ID, {var_id}});
  726. get_def_use_mgr()->AnalyzeInstDefUse(&e);
  727. }
  728. }
  729. }
  730. uint32_t IRContext::GetBuiltinInputVarId(uint32_t builtin) {
  731. if (!AreAnalysesValid(kAnalysisBuiltinVarId)) ResetBuiltinAnalysis();
  732. // If cached, return it.
  733. std::unordered_map<uint32_t, uint32_t>::iterator it =
  734. builtin_var_id_map_.find(builtin);
  735. if (it != builtin_var_id_map_.end()) return it->second;
  736. // Look for one in shader
  737. uint32_t var_id = FindBuiltinInputVar(builtin);
  738. if (var_id == 0) {
  739. // If not found, create it
  740. // TODO(greg-lunarg): Add support for all builtins
  741. analysis::TypeManager* type_mgr = get_type_mgr();
  742. analysis::Type* reg_type;
  743. switch (builtin) {
  744. case SpvBuiltInFragCoord: {
  745. analysis::Float float_ty(32);
  746. analysis::Type* reg_float_ty = type_mgr->GetRegisteredType(&float_ty);
  747. analysis::Vector v4float_ty(reg_float_ty, 4);
  748. reg_type = type_mgr->GetRegisteredType(&v4float_ty);
  749. break;
  750. }
  751. case SpvBuiltInVertexIndex:
  752. case SpvBuiltInInstanceIndex:
  753. case SpvBuiltInPrimitiveId:
  754. case SpvBuiltInInvocationId:
  755. case SpvBuiltInSubgroupLocalInvocationId: {
  756. analysis::Integer uint_ty(32, false);
  757. reg_type = type_mgr->GetRegisteredType(&uint_ty);
  758. break;
  759. }
  760. case SpvBuiltInGlobalInvocationId:
  761. case SpvBuiltInLaunchIdNV: {
  762. analysis::Integer uint_ty(32, false);
  763. analysis::Type* reg_uint_ty = type_mgr->GetRegisteredType(&uint_ty);
  764. analysis::Vector v3uint_ty(reg_uint_ty, 3);
  765. reg_type = type_mgr->GetRegisteredType(&v3uint_ty);
  766. break;
  767. }
  768. case SpvBuiltInTessCoord: {
  769. analysis::Float float_ty(32);
  770. analysis::Type* reg_float_ty = type_mgr->GetRegisteredType(&float_ty);
  771. analysis::Vector v3float_ty(reg_float_ty, 3);
  772. reg_type = type_mgr->GetRegisteredType(&v3float_ty);
  773. break;
  774. }
  775. case SpvBuiltInSubgroupLtMask: {
  776. analysis::Integer uint_ty(32, false);
  777. analysis::Type* reg_uint_ty = type_mgr->GetRegisteredType(&uint_ty);
  778. analysis::Vector v4uint_ty(reg_uint_ty, 4);
  779. reg_type = type_mgr->GetRegisteredType(&v4uint_ty);
  780. break;
  781. }
  782. default: {
  783. assert(false && "unhandled builtin");
  784. return 0;
  785. }
  786. }
  787. uint32_t type_id = type_mgr->GetTypeInstruction(reg_type);
  788. uint32_t varTyPtrId =
  789. type_mgr->FindPointerToType(type_id, SpvStorageClassInput);
  790. // TODO(1841): Handle id overflow.
  791. var_id = TakeNextId();
  792. std::unique_ptr<Instruction> newVarOp(
  793. new Instruction(this, SpvOpVariable, varTyPtrId, var_id,
  794. {{spv_operand_type_t::SPV_OPERAND_TYPE_LITERAL_INTEGER,
  795. {SpvStorageClassInput}}}));
  796. get_def_use_mgr()->AnalyzeInstDefUse(&*newVarOp);
  797. module()->AddGlobalValue(std::move(newVarOp));
  798. get_decoration_mgr()->AddDecorationVal(var_id, SpvDecorationBuiltIn,
  799. builtin);
  800. AddVarToEntryPoints(var_id);
  801. }
  802. builtin_var_id_map_[builtin] = var_id;
  803. return var_id;
  804. }
  805. void IRContext::AddCalls(const Function* func, std::queue<uint32_t>* todo) {
  806. for (auto bi = func->begin(); bi != func->end(); ++bi)
  807. for (auto ii = bi->begin(); ii != bi->end(); ++ii)
  808. if (ii->opcode() == SpvOpFunctionCall)
  809. todo->push(ii->GetSingleWordInOperand(0));
  810. }
  811. bool IRContext::ProcessEntryPointCallTree(ProcessFunction& pfn) {
  812. // Collect all of the entry points as the roots.
  813. std::queue<uint32_t> roots;
  814. for (auto& e : module()->entry_points()) {
  815. roots.push(e.GetSingleWordInOperand(kEntryPointFunctionIdInIdx));
  816. }
  817. return ProcessCallTreeFromRoots(pfn, &roots);
  818. }
  819. bool IRContext::ProcessReachableCallTree(ProcessFunction& pfn) {
  820. std::queue<uint32_t> roots;
  821. // Add all entry points since they can be reached from outside the module.
  822. for (auto& e : module()->entry_points())
  823. roots.push(e.GetSingleWordInOperand(kEntryPointFunctionIdInIdx));
  824. // Add all exported functions since they can be reached from outside the
  825. // module.
  826. for (auto& a : annotations()) {
  827. // TODO: Handle group decorations as well. Currently not generate by any
  828. // front-end, but could be coming.
  829. if (a.opcode() == SpvOp::SpvOpDecorate) {
  830. if (a.GetSingleWordOperand(1) ==
  831. SpvDecoration::SpvDecorationLinkageAttributes) {
  832. uint32_t lastOperand = a.NumOperands() - 1;
  833. if (a.GetSingleWordOperand(lastOperand) ==
  834. SpvLinkageType::SpvLinkageTypeExport) {
  835. uint32_t id = a.GetSingleWordOperand(0);
  836. if (GetFunction(id)) {
  837. roots.push(id);
  838. }
  839. }
  840. }
  841. }
  842. }
  843. return ProcessCallTreeFromRoots(pfn, &roots);
  844. }
  845. bool IRContext::ProcessCallTreeFromRoots(ProcessFunction& pfn,
  846. std::queue<uint32_t>* roots) {
  847. // Process call tree
  848. bool modified = false;
  849. std::unordered_set<uint32_t> done;
  850. while (!roots->empty()) {
  851. const uint32_t fi = roots->front();
  852. roots->pop();
  853. if (done.insert(fi).second) {
  854. Function* fn = GetFunction(fi);
  855. assert(fn && "Trying to process a function that does not exist.");
  856. modified = pfn(fn) || modified;
  857. AddCalls(fn, roots);
  858. }
  859. }
  860. return modified;
  861. }
  862. void IRContext::CollectCallTreeFromRoots(unsigned entryId,
  863. std::unordered_set<uint32_t>* funcs) {
  864. std::queue<uint32_t> roots;
  865. roots.push(entryId);
  866. while (!roots.empty()) {
  867. const uint32_t fi = roots.front();
  868. roots.pop();
  869. funcs->insert(fi);
  870. Function* fn = GetFunction(fi);
  871. AddCalls(fn, &roots);
  872. }
  873. }
  874. void IRContext::EmitErrorMessage(std::string message, Instruction* inst) {
  875. if (!consumer()) {
  876. return;
  877. }
  878. Instruction* line_inst = inst;
  879. while (line_inst != nullptr) { // Stop at the beginning of the basic block.
  880. if (!line_inst->dbg_line_insts().empty()) {
  881. line_inst = &line_inst->dbg_line_insts().back();
  882. if (line_inst->IsNoLine()) {
  883. line_inst = nullptr;
  884. }
  885. break;
  886. }
  887. line_inst = line_inst->PreviousNode();
  888. }
  889. uint32_t line_number = 0;
  890. uint32_t col_number = 0;
  891. std::string source;
  892. if (line_inst != nullptr) {
  893. Instruction* file_name =
  894. get_def_use_mgr()->GetDef(line_inst->GetSingleWordInOperand(0));
  895. source = file_name->GetInOperand(0).AsString();
  896. // Get the line number and column number.
  897. line_number = line_inst->GetSingleWordInOperand(1);
  898. col_number = line_inst->GetSingleWordInOperand(2);
  899. }
  900. message +=
  901. "\n " + inst->PrettyPrint(SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES);
  902. consumer()(SPV_MSG_ERROR, source.c_str(), {line_number, col_number, 0},
  903. message.c_str());
  904. }
  905. // Gets the dominator analysis for function |f|.
  906. DominatorAnalysis* IRContext::GetDominatorAnalysis(const Function* f) {
  907. if (!AreAnalysesValid(kAnalysisDominatorAnalysis)) {
  908. ResetDominatorAnalysis();
  909. }
  910. if (dominator_trees_.find(f) == dominator_trees_.end()) {
  911. dominator_trees_[f].InitializeTree(*cfg(), f);
  912. }
  913. return &dominator_trees_[f];
  914. }
  915. // Gets the postdominator analysis for function |f|.
  916. PostDominatorAnalysis* IRContext::GetPostDominatorAnalysis(const Function* f) {
  917. if (!AreAnalysesValid(kAnalysisDominatorAnalysis)) {
  918. ResetDominatorAnalysis();
  919. }
  920. if (post_dominator_trees_.find(f) == post_dominator_trees_.end()) {
  921. post_dominator_trees_[f].InitializeTree(*cfg(), f);
  922. }
  923. return &post_dominator_trees_[f];
  924. }
  925. bool IRContext::CheckCFG() {
  926. std::unordered_map<uint32_t, std::vector<uint32_t>> real_preds;
  927. if (!AreAnalysesValid(kAnalysisCFG)) {
  928. return true;
  929. }
  930. for (Function& function : *module()) {
  931. for (const auto& bb : function) {
  932. bb.ForEachSuccessorLabel([&bb, &real_preds](const uint32_t lab_id) {
  933. real_preds[lab_id].push_back(bb.id());
  934. });
  935. }
  936. for (auto& bb : function) {
  937. std::vector<uint32_t> preds = cfg()->preds(bb.id());
  938. std::vector<uint32_t> real = real_preds[bb.id()];
  939. std::sort(preds.begin(), preds.end());
  940. std::sort(real.begin(), real.end());
  941. bool same = true;
  942. if (preds.size() != real.size()) {
  943. same = false;
  944. }
  945. for (size_t i = 0; i < real.size() && same; i++) {
  946. if (preds[i] != real[i]) {
  947. same = false;
  948. }
  949. }
  950. if (!same) {
  951. std::cerr << "Predecessors for " << bb.id() << " are different:\n";
  952. std::cerr << "Real:";
  953. for (uint32_t i : real) {
  954. std::cerr << ' ' << i;
  955. }
  956. std::cerr << std::endl;
  957. std::cerr << "Recorded:";
  958. for (uint32_t i : preds) {
  959. std::cerr << ' ' << i;
  960. }
  961. std::cerr << std::endl;
  962. }
  963. if (!same) return false;
  964. }
  965. }
  966. return true;
  967. }
  968. bool IRContext::IsReachable(const opt::BasicBlock& bb) {
  969. auto enclosing_function = bb.GetParent();
  970. return GetDominatorAnalysis(enclosing_function)
  971. ->Dominates(enclosing_function->entry().get(), &bb);
  972. }
  973. } // namespace opt
  974. } // namespace spvtools