ir_context.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  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 spvtools {
  22. namespace opt {
  23. namespace {
  24. constexpr int kSpvDecorateTargetIdInIdx = 0;
  25. constexpr int kSpvDecorateDecorationInIdx = 1;
  26. constexpr int kSpvDecorateBuiltinInIdx = 2;
  27. constexpr int kEntryPointInterfaceInIdx = 3;
  28. constexpr int kEntryPointFunctionIdInIdx = 1;
  29. constexpr int kEntryPointExecutionModelInIdx = 0;
  30. // Constants for OpenCL.DebugInfo.100 / NonSemantic.Shader.DebugInfo.100
  31. // extension instructions.
  32. constexpr uint32_t kDebugFunctionOperandFunctionIndex = 13;
  33. constexpr uint32_t kDebugGlobalVariableOperandVariableIndex = 11;
  34. } // namespace
  35. void IRContext::BuildInvalidAnalyses(IRContext::Analysis set) {
  36. set = Analysis(set & ~valid_analyses_);
  37. if (set & kAnalysisDefUse) {
  38. BuildDefUseManager();
  39. }
  40. if (set & kAnalysisInstrToBlockMapping) {
  41. BuildInstrToBlockMapping();
  42. }
  43. if (set & kAnalysisDecorations) {
  44. BuildDecorationManager();
  45. }
  46. if (set & kAnalysisCFG) {
  47. BuildCFG();
  48. }
  49. if (set & kAnalysisDominatorAnalysis) {
  50. ResetDominatorAnalysis();
  51. }
  52. if (set & kAnalysisLoopAnalysis) {
  53. ResetLoopAnalysis();
  54. }
  55. if (set & kAnalysisBuiltinVarId) {
  56. ResetBuiltinAnalysis();
  57. }
  58. if (set & kAnalysisNameMap) {
  59. BuildIdToNameMap();
  60. }
  61. if (set & kAnalysisScalarEvolution) {
  62. BuildScalarEvolutionAnalysis();
  63. }
  64. if (set & kAnalysisRegisterPressure) {
  65. BuildRegPressureAnalysis();
  66. }
  67. if (set & kAnalysisValueNumberTable) {
  68. BuildValueNumberTable();
  69. }
  70. if (set & kAnalysisStructuredCFG) {
  71. BuildStructuredCFGAnalysis();
  72. }
  73. if (set & kAnalysisIdToFuncMapping) {
  74. BuildIdToFuncMapping();
  75. }
  76. if (set & kAnalysisConstants) {
  77. BuildConstantManager();
  78. }
  79. if (set & kAnalysisTypes) {
  80. BuildTypeManager();
  81. }
  82. if (set & kAnalysisDebugInfo) {
  83. BuildDebugInfoManager();
  84. }
  85. }
  86. void IRContext::InvalidateAnalysesExceptFor(
  87. IRContext::Analysis preserved_analyses) {
  88. uint32_t analyses_to_invalidate = valid_analyses_ & (~preserved_analyses);
  89. InvalidateAnalyses(static_cast<IRContext::Analysis>(analyses_to_invalidate));
  90. }
  91. void IRContext::InvalidateAnalyses(IRContext::Analysis analyses_to_invalidate) {
  92. // The ConstantManager and DebugInfoManager contain Type pointers. If the
  93. // TypeManager goes away, the ConstantManager and DebugInfoManager have to
  94. // go away.
  95. if (analyses_to_invalidate & kAnalysisTypes) {
  96. analyses_to_invalidate |= kAnalysisConstants;
  97. analyses_to_invalidate |= kAnalysisDebugInfo;
  98. }
  99. // The dominator analysis hold the pseudo entry and exit nodes from the CFG.
  100. // Also if the CFG change the dominators many changed as well, so the
  101. // dominator analysis should be invalidated as well.
  102. if (analyses_to_invalidate & kAnalysisCFG) {
  103. analyses_to_invalidate |= kAnalysisDominatorAnalysis;
  104. }
  105. if (analyses_to_invalidate & kAnalysisDefUse) {
  106. def_use_mgr_.reset(nullptr);
  107. }
  108. if (analyses_to_invalidate & kAnalysisInstrToBlockMapping) {
  109. instr_to_block_.clear();
  110. }
  111. if (analyses_to_invalidate & kAnalysisDecorations) {
  112. decoration_mgr_.reset(nullptr);
  113. }
  114. if (analyses_to_invalidate & kAnalysisCombinators) {
  115. combinator_ops_.clear();
  116. }
  117. if (analyses_to_invalidate & kAnalysisBuiltinVarId) {
  118. builtin_var_id_map_.clear();
  119. }
  120. if (analyses_to_invalidate & kAnalysisCFG) {
  121. cfg_.reset(nullptr);
  122. }
  123. if (analyses_to_invalidate & kAnalysisDominatorAnalysis) {
  124. dominator_trees_.clear();
  125. post_dominator_trees_.clear();
  126. }
  127. if (analyses_to_invalidate & kAnalysisNameMap) {
  128. id_to_name_.reset(nullptr);
  129. }
  130. if (analyses_to_invalidate & kAnalysisValueNumberTable) {
  131. vn_table_.reset(nullptr);
  132. }
  133. if (analyses_to_invalidate & kAnalysisStructuredCFG) {
  134. struct_cfg_analysis_.reset(nullptr);
  135. }
  136. if (analyses_to_invalidate & kAnalysisIdToFuncMapping) {
  137. id_to_func_.clear();
  138. }
  139. if (analyses_to_invalidate & kAnalysisConstants) {
  140. constant_mgr_.reset(nullptr);
  141. }
  142. if (analyses_to_invalidate & kAnalysisLiveness) {
  143. liveness_mgr_.reset(nullptr);
  144. }
  145. if (analyses_to_invalidate & kAnalysisTypes) {
  146. type_mgr_.reset(nullptr);
  147. }
  148. if (analyses_to_invalidate & kAnalysisDebugInfo) {
  149. debug_info_mgr_.reset(nullptr);
  150. }
  151. valid_analyses_ = Analysis(valid_analyses_ & ~analyses_to_invalidate);
  152. }
  153. Instruction* IRContext::KillInst(Instruction* inst) {
  154. if (!inst) {
  155. return nullptr;
  156. }
  157. KillNamesAndDecorates(inst);
  158. KillOperandFromDebugInstructions(inst);
  159. if (AreAnalysesValid(kAnalysisDefUse)) {
  160. analysis::DefUseManager* def_use_mgr = get_def_use_mgr();
  161. def_use_mgr->ClearInst(inst);
  162. for (auto& l_inst : inst->dbg_line_insts()) def_use_mgr->ClearInst(&l_inst);
  163. }
  164. if (AreAnalysesValid(kAnalysisInstrToBlockMapping)) {
  165. instr_to_block_.erase(inst);
  166. }
  167. if (AreAnalysesValid(kAnalysisDecorations)) {
  168. if (inst->IsDecoration()) {
  169. decoration_mgr_->RemoveDecoration(inst);
  170. }
  171. }
  172. if (AreAnalysesValid(kAnalysisDebugInfo)) {
  173. get_debug_info_mgr()->ClearDebugScopeAndInlinedAtUses(inst);
  174. get_debug_info_mgr()->ClearDebugInfo(inst);
  175. }
  176. if (type_mgr_ && IsTypeInst(inst->opcode())) {
  177. type_mgr_->RemoveId(inst->result_id());
  178. }
  179. if (constant_mgr_ && IsConstantInst(inst->opcode())) {
  180. constant_mgr_->RemoveId(inst->result_id());
  181. }
  182. if (inst->opcode() == spv::Op::OpCapability ||
  183. inst->opcode() == spv::Op::OpExtension) {
  184. // We reset the feature manager, instead of updating it, because it is just
  185. // as much work. We would have to remove all capabilities implied by this
  186. // capability that are not also implied by the remaining OpCapability
  187. // instructions. We could update extensions, but we will see if it is
  188. // needed.
  189. ResetFeatureManager();
  190. }
  191. RemoveFromIdToName(inst);
  192. Instruction* next_instruction = nullptr;
  193. if (inst->IsInAList()) {
  194. next_instruction = inst->NextNode();
  195. inst->RemoveFromList();
  196. delete inst;
  197. } else {
  198. // Needed for instructions that are not part of a list like OpLabels,
  199. // OpFunction, OpFunctionEnd, etc..
  200. inst->ToNop();
  201. }
  202. return next_instruction;
  203. }
  204. void IRContext::CollectNonSemanticTree(
  205. Instruction* inst, std::unordered_set<Instruction*>* to_kill) {
  206. if (!inst->HasResultId()) return;
  207. // Debug[No]Line result id is not used, so we are done
  208. if (inst->IsDebugLineInst()) return;
  209. std::vector<Instruction*> work_list;
  210. std::unordered_set<Instruction*> seen;
  211. work_list.push_back(inst);
  212. while (!work_list.empty()) {
  213. auto* i = work_list.back();
  214. work_list.pop_back();
  215. get_def_use_mgr()->ForEachUser(
  216. i, [&work_list, to_kill, &seen](Instruction* user) {
  217. if (user->IsNonSemanticInstruction() && seen.insert(user).second) {
  218. work_list.push_back(user);
  219. to_kill->insert(user);
  220. }
  221. });
  222. }
  223. }
  224. bool IRContext::KillDef(uint32_t id) {
  225. Instruction* def = get_def_use_mgr()->GetDef(id);
  226. if (def != nullptr) {
  227. KillInst(def);
  228. return true;
  229. }
  230. return false;
  231. }
  232. bool IRContext::ReplaceAllUsesWith(uint32_t before, uint32_t after) {
  233. return ReplaceAllUsesWithPredicate(before, after,
  234. [](Instruction*) { return true; });
  235. }
  236. bool IRContext::ReplaceAllUsesWithPredicate(
  237. uint32_t before, uint32_t after,
  238. const std::function<bool(Instruction*)>& predicate) {
  239. if (before == after) return false;
  240. if (AreAnalysesValid(kAnalysisDebugInfo)) {
  241. get_debug_info_mgr()->ReplaceAllUsesInDebugScopeWithPredicate(before, after,
  242. predicate);
  243. }
  244. // Ensure that |after| has been registered as def.
  245. assert(get_def_use_mgr()->GetDef(after) &&
  246. "'after' is not a registered def.");
  247. std::vector<std::pair<Instruction*, uint32_t>> uses_to_update;
  248. get_def_use_mgr()->ForEachUse(
  249. before, [&predicate, &uses_to_update](Instruction* user, uint32_t index) {
  250. if (predicate(user)) {
  251. uses_to_update.emplace_back(user, index);
  252. }
  253. });
  254. Instruction* prev = nullptr;
  255. for (auto p : uses_to_update) {
  256. Instruction* user = p.first;
  257. uint32_t index = p.second;
  258. if (prev == nullptr || prev != user) {
  259. ForgetUses(user);
  260. prev = user;
  261. }
  262. const uint32_t type_result_id_count =
  263. (user->result_id() != 0) + (user->type_id() != 0);
  264. if (index < type_result_id_count) {
  265. // Update the type_id. Note that result id is immutable so it should
  266. // never be updated.
  267. if (user->type_id() != 0 && index == 0) {
  268. user->SetResultType(after);
  269. } else if (user->type_id() == 0) {
  270. SPIRV_ASSERT(consumer_, false,
  271. "Result type id considered as use while the instruction "
  272. "doesn't have a result type id.");
  273. (void)consumer_; // Makes the compiler happy for release build.
  274. } else {
  275. SPIRV_ASSERT(consumer_, false,
  276. "Trying setting the immutable result id.");
  277. }
  278. } else {
  279. // Update an in-operand.
  280. uint32_t in_operand_pos = index - type_result_id_count;
  281. // Make the modification in the instruction.
  282. user->SetInOperand(in_operand_pos, {after});
  283. }
  284. AnalyzeUses(user);
  285. }
  286. return true;
  287. }
  288. bool IRContext::IsConsistent() {
  289. #ifndef SPIRV_CHECK_CONTEXT
  290. return true;
  291. #else
  292. if (AreAnalysesValid(kAnalysisDefUse)) {
  293. analysis::DefUseManager new_def_use(module());
  294. if (!CompareAndPrintDifferences(*get_def_use_mgr(), new_def_use)) {
  295. return false;
  296. }
  297. }
  298. if (AreAnalysesValid(kAnalysisIdToFuncMapping)) {
  299. for (auto& fn : *module_) {
  300. if (id_to_func_[fn.result_id()] != &fn) {
  301. return false;
  302. }
  303. }
  304. }
  305. if (AreAnalysesValid(kAnalysisInstrToBlockMapping)) {
  306. for (auto& func : *module()) {
  307. for (auto& block : func) {
  308. if (!block.WhileEachInst([this, &block](Instruction* inst) {
  309. if (get_instr_block(inst) != &block) {
  310. return false;
  311. }
  312. return true;
  313. }))
  314. return false;
  315. }
  316. }
  317. }
  318. if (!CheckCFG()) {
  319. return false;
  320. }
  321. if (AreAnalysesValid(kAnalysisDecorations)) {
  322. analysis::DecorationManager* dec_mgr = get_decoration_mgr();
  323. analysis::DecorationManager current(module());
  324. if (*dec_mgr != current) {
  325. return false;
  326. }
  327. }
  328. if (feature_mgr_ != nullptr) {
  329. FeatureManager current(grammar_);
  330. current.Analyze(module());
  331. if (current != *feature_mgr_) {
  332. return false;
  333. }
  334. }
  335. return true;
  336. #endif
  337. }
  338. void IRContext::ForgetUses(Instruction* inst) {
  339. if (AreAnalysesValid(kAnalysisDefUse)) {
  340. get_def_use_mgr()->EraseUseRecordsOfOperandIds(inst);
  341. }
  342. if (AreAnalysesValid(kAnalysisDecorations)) {
  343. if (inst->IsDecoration()) {
  344. get_decoration_mgr()->RemoveDecoration(inst);
  345. }
  346. }
  347. if (AreAnalysesValid(kAnalysisDebugInfo)) {
  348. get_debug_info_mgr()->ClearDebugInfo(inst);
  349. }
  350. RemoveFromIdToName(inst);
  351. }
  352. void IRContext::AnalyzeUses(Instruction* inst) {
  353. if (AreAnalysesValid(kAnalysisDefUse)) {
  354. get_def_use_mgr()->AnalyzeInstUse(inst);
  355. }
  356. if (AreAnalysesValid(kAnalysisDecorations)) {
  357. if (inst->IsDecoration()) {
  358. get_decoration_mgr()->AddDecoration(inst);
  359. }
  360. }
  361. if (AreAnalysesValid(kAnalysisDebugInfo)) {
  362. get_debug_info_mgr()->AnalyzeDebugInst(inst);
  363. }
  364. if (id_to_name_ && (inst->opcode() == spv::Op::OpName ||
  365. inst->opcode() == spv::Op::OpMemberName)) {
  366. id_to_name_->insert({inst->GetSingleWordInOperand(0), inst});
  367. }
  368. }
  369. void IRContext::KillNamesAndDecorates(uint32_t id) {
  370. analysis::DecorationManager* dec_mgr = get_decoration_mgr();
  371. dec_mgr->RemoveDecorationsFrom(id);
  372. std::vector<Instruction*> name_to_kill;
  373. for (auto name : GetNames(id)) {
  374. name_to_kill.push_back(name.second);
  375. }
  376. for (Instruction* name_inst : name_to_kill) {
  377. KillInst(name_inst);
  378. }
  379. }
  380. void IRContext::KillNamesAndDecorates(Instruction* inst) {
  381. const uint32_t rId = inst->result_id();
  382. if (rId == 0) return;
  383. KillNamesAndDecorates(rId);
  384. }
  385. void IRContext::KillOperandFromDebugInstructions(Instruction* inst) {
  386. const auto opcode = inst->opcode();
  387. const uint32_t id = inst->result_id();
  388. // Kill id of OpFunction from DebugFunction.
  389. if (opcode == spv::Op::OpFunction) {
  390. for (auto it = module()->ext_inst_debuginfo_begin();
  391. it != module()->ext_inst_debuginfo_end(); ++it) {
  392. if (it->GetOpenCL100DebugOpcode() != OpenCLDebugInfo100DebugFunction)
  393. continue;
  394. auto& operand = it->GetOperand(kDebugFunctionOperandFunctionIndex);
  395. if (operand.words[0] == id) {
  396. operand.words[0] =
  397. get_debug_info_mgr()->GetDebugInfoNone()->result_id();
  398. get_def_use_mgr()->AnalyzeInstUse(&*it);
  399. }
  400. }
  401. }
  402. // Kill id of OpVariable for global variable from DebugGlobalVariable.
  403. if (opcode == spv::Op::OpVariable || IsConstantInst(opcode)) {
  404. for (auto it = module()->ext_inst_debuginfo_begin();
  405. it != module()->ext_inst_debuginfo_end(); ++it) {
  406. if (it->GetCommonDebugOpcode() != CommonDebugInfoDebugGlobalVariable)
  407. continue;
  408. auto& operand = it->GetOperand(kDebugGlobalVariableOperandVariableIndex);
  409. if (operand.words[0] == id) {
  410. operand.words[0] =
  411. get_debug_info_mgr()->GetDebugInfoNone()->result_id();
  412. get_def_use_mgr()->AnalyzeInstUse(&*it);
  413. }
  414. }
  415. }
  416. }
  417. void IRContext::AddCombinatorsForCapability(uint32_t capability) {
  418. spv::Capability cap = spv::Capability(capability);
  419. if (cap == spv::Capability::Shader) {
  420. combinator_ops_[0].insert(
  421. {(uint32_t)spv::Op::OpNop,
  422. (uint32_t)spv::Op::OpUndef,
  423. (uint32_t)spv::Op::OpConstant,
  424. (uint32_t)spv::Op::OpConstantTrue,
  425. (uint32_t)spv::Op::OpConstantFalse,
  426. (uint32_t)spv::Op::OpConstantComposite,
  427. (uint32_t)spv::Op::OpConstantSampler,
  428. (uint32_t)spv::Op::OpConstantNull,
  429. (uint32_t)spv::Op::OpTypeVoid,
  430. (uint32_t)spv::Op::OpTypeBool,
  431. (uint32_t)spv::Op::OpTypeInt,
  432. (uint32_t)spv::Op::OpTypeFloat,
  433. (uint32_t)spv::Op::OpTypeVector,
  434. (uint32_t)spv::Op::OpTypeMatrix,
  435. (uint32_t)spv::Op::OpTypeImage,
  436. (uint32_t)spv::Op::OpTypeSampler,
  437. (uint32_t)spv::Op::OpTypeSampledImage,
  438. (uint32_t)spv::Op::OpTypeAccelerationStructureNV,
  439. (uint32_t)spv::Op::OpTypeAccelerationStructureKHR,
  440. (uint32_t)spv::Op::OpTypeRayQueryKHR,
  441. (uint32_t)spv::Op::OpTypeHitObjectNV,
  442. (uint32_t)spv::Op::OpTypeArray,
  443. (uint32_t)spv::Op::OpTypeRuntimeArray,
  444. (uint32_t)spv::Op::OpTypeStruct,
  445. (uint32_t)spv::Op::OpTypeOpaque,
  446. (uint32_t)spv::Op::OpTypePointer,
  447. (uint32_t)spv::Op::OpTypeFunction,
  448. (uint32_t)spv::Op::OpTypeEvent,
  449. (uint32_t)spv::Op::OpTypeDeviceEvent,
  450. (uint32_t)spv::Op::OpTypeReserveId,
  451. (uint32_t)spv::Op::OpTypeQueue,
  452. (uint32_t)spv::Op::OpTypePipe,
  453. (uint32_t)spv::Op::OpTypeForwardPointer,
  454. (uint32_t)spv::Op::OpVariable,
  455. (uint32_t)spv::Op::OpImageTexelPointer,
  456. (uint32_t)spv::Op::OpLoad,
  457. (uint32_t)spv::Op::OpAccessChain,
  458. (uint32_t)spv::Op::OpInBoundsAccessChain,
  459. (uint32_t)spv::Op::OpArrayLength,
  460. (uint32_t)spv::Op::OpVectorExtractDynamic,
  461. (uint32_t)spv::Op::OpVectorInsertDynamic,
  462. (uint32_t)spv::Op::OpVectorShuffle,
  463. (uint32_t)spv::Op::OpCompositeConstruct,
  464. (uint32_t)spv::Op::OpCompositeExtract,
  465. (uint32_t)spv::Op::OpCompositeInsert,
  466. (uint32_t)spv::Op::OpCopyObject,
  467. (uint32_t)spv::Op::OpTranspose,
  468. (uint32_t)spv::Op::OpSampledImage,
  469. (uint32_t)spv::Op::OpImageSampleImplicitLod,
  470. (uint32_t)spv::Op::OpImageSampleExplicitLod,
  471. (uint32_t)spv::Op::OpImageSampleDrefImplicitLod,
  472. (uint32_t)spv::Op::OpImageSampleDrefExplicitLod,
  473. (uint32_t)spv::Op::OpImageSampleProjImplicitLod,
  474. (uint32_t)spv::Op::OpImageSampleProjExplicitLod,
  475. (uint32_t)spv::Op::OpImageSampleProjDrefImplicitLod,
  476. (uint32_t)spv::Op::OpImageSampleProjDrefExplicitLod,
  477. (uint32_t)spv::Op::OpImageFetch,
  478. (uint32_t)spv::Op::OpImageGather,
  479. (uint32_t)spv::Op::OpImageDrefGather,
  480. (uint32_t)spv::Op::OpImageRead,
  481. (uint32_t)spv::Op::OpImage,
  482. (uint32_t)spv::Op::OpImageQueryFormat,
  483. (uint32_t)spv::Op::OpImageQueryOrder,
  484. (uint32_t)spv::Op::OpImageQuerySizeLod,
  485. (uint32_t)spv::Op::OpImageQuerySize,
  486. (uint32_t)spv::Op::OpImageQueryLevels,
  487. (uint32_t)spv::Op::OpImageQuerySamples,
  488. (uint32_t)spv::Op::OpConvertFToU,
  489. (uint32_t)spv::Op::OpConvertFToS,
  490. (uint32_t)spv::Op::OpConvertSToF,
  491. (uint32_t)spv::Op::OpConvertUToF,
  492. (uint32_t)spv::Op::OpUConvert,
  493. (uint32_t)spv::Op::OpSConvert,
  494. (uint32_t)spv::Op::OpFConvert,
  495. (uint32_t)spv::Op::OpQuantizeToF16,
  496. (uint32_t)spv::Op::OpBitcast,
  497. (uint32_t)spv::Op::OpSNegate,
  498. (uint32_t)spv::Op::OpFNegate,
  499. (uint32_t)spv::Op::OpIAdd,
  500. (uint32_t)spv::Op::OpFAdd,
  501. (uint32_t)spv::Op::OpISub,
  502. (uint32_t)spv::Op::OpFSub,
  503. (uint32_t)spv::Op::OpIMul,
  504. (uint32_t)spv::Op::OpFMul,
  505. (uint32_t)spv::Op::OpUDiv,
  506. (uint32_t)spv::Op::OpSDiv,
  507. (uint32_t)spv::Op::OpFDiv,
  508. (uint32_t)spv::Op::OpUMod,
  509. (uint32_t)spv::Op::OpSRem,
  510. (uint32_t)spv::Op::OpSMod,
  511. (uint32_t)spv::Op::OpFRem,
  512. (uint32_t)spv::Op::OpFMod,
  513. (uint32_t)spv::Op::OpVectorTimesScalar,
  514. (uint32_t)spv::Op::OpMatrixTimesScalar,
  515. (uint32_t)spv::Op::OpVectorTimesMatrix,
  516. (uint32_t)spv::Op::OpMatrixTimesVector,
  517. (uint32_t)spv::Op::OpMatrixTimesMatrix,
  518. (uint32_t)spv::Op::OpOuterProduct,
  519. (uint32_t)spv::Op::OpDot,
  520. (uint32_t)spv::Op::OpIAddCarry,
  521. (uint32_t)spv::Op::OpISubBorrow,
  522. (uint32_t)spv::Op::OpUMulExtended,
  523. (uint32_t)spv::Op::OpSMulExtended,
  524. (uint32_t)spv::Op::OpAny,
  525. (uint32_t)spv::Op::OpAll,
  526. (uint32_t)spv::Op::OpIsNan,
  527. (uint32_t)spv::Op::OpIsInf,
  528. (uint32_t)spv::Op::OpLogicalEqual,
  529. (uint32_t)spv::Op::OpLogicalNotEqual,
  530. (uint32_t)spv::Op::OpLogicalOr,
  531. (uint32_t)spv::Op::OpLogicalAnd,
  532. (uint32_t)spv::Op::OpLogicalNot,
  533. (uint32_t)spv::Op::OpSelect,
  534. (uint32_t)spv::Op::OpIEqual,
  535. (uint32_t)spv::Op::OpINotEqual,
  536. (uint32_t)spv::Op::OpUGreaterThan,
  537. (uint32_t)spv::Op::OpSGreaterThan,
  538. (uint32_t)spv::Op::OpUGreaterThanEqual,
  539. (uint32_t)spv::Op::OpSGreaterThanEqual,
  540. (uint32_t)spv::Op::OpULessThan,
  541. (uint32_t)spv::Op::OpSLessThan,
  542. (uint32_t)spv::Op::OpULessThanEqual,
  543. (uint32_t)spv::Op::OpSLessThanEqual,
  544. (uint32_t)spv::Op::OpFOrdEqual,
  545. (uint32_t)spv::Op::OpFUnordEqual,
  546. (uint32_t)spv::Op::OpFOrdNotEqual,
  547. (uint32_t)spv::Op::OpFUnordNotEqual,
  548. (uint32_t)spv::Op::OpFOrdLessThan,
  549. (uint32_t)spv::Op::OpFUnordLessThan,
  550. (uint32_t)spv::Op::OpFOrdGreaterThan,
  551. (uint32_t)spv::Op::OpFUnordGreaterThan,
  552. (uint32_t)spv::Op::OpFOrdLessThanEqual,
  553. (uint32_t)spv::Op::OpFUnordLessThanEqual,
  554. (uint32_t)spv::Op::OpFOrdGreaterThanEqual,
  555. (uint32_t)spv::Op::OpFUnordGreaterThanEqual,
  556. (uint32_t)spv::Op::OpShiftRightLogical,
  557. (uint32_t)spv::Op::OpShiftRightArithmetic,
  558. (uint32_t)spv::Op::OpShiftLeftLogical,
  559. (uint32_t)spv::Op::OpBitwiseOr,
  560. (uint32_t)spv::Op::OpBitwiseXor,
  561. (uint32_t)spv::Op::OpBitwiseAnd,
  562. (uint32_t)spv::Op::OpNot,
  563. (uint32_t)spv::Op::OpBitFieldInsert,
  564. (uint32_t)spv::Op::OpBitFieldSExtract,
  565. (uint32_t)spv::Op::OpBitFieldUExtract,
  566. (uint32_t)spv::Op::OpBitReverse,
  567. (uint32_t)spv::Op::OpBitCount,
  568. (uint32_t)spv::Op::OpPhi,
  569. (uint32_t)spv::Op::OpImageSparseSampleImplicitLod,
  570. (uint32_t)spv::Op::OpImageSparseSampleExplicitLod,
  571. (uint32_t)spv::Op::OpImageSparseSampleDrefImplicitLod,
  572. (uint32_t)spv::Op::OpImageSparseSampleDrefExplicitLod,
  573. (uint32_t)spv::Op::OpImageSparseSampleProjImplicitLod,
  574. (uint32_t)spv::Op::OpImageSparseSampleProjExplicitLod,
  575. (uint32_t)spv::Op::OpImageSparseSampleProjDrefImplicitLod,
  576. (uint32_t)spv::Op::OpImageSparseSampleProjDrefExplicitLod,
  577. (uint32_t)spv::Op::OpImageSparseFetch,
  578. (uint32_t)spv::Op::OpImageSparseGather,
  579. (uint32_t)spv::Op::OpImageSparseDrefGather,
  580. (uint32_t)spv::Op::OpImageSparseTexelsResident,
  581. (uint32_t)spv::Op::OpImageSparseRead,
  582. (uint32_t)spv::Op::OpSizeOf});
  583. }
  584. }
  585. void IRContext::AddCombinatorsForExtension(Instruction* extension) {
  586. assert(extension->opcode() == spv::Op::OpExtInstImport &&
  587. "Expecting an import of an extension's instruction set.");
  588. const std::string extension_name = extension->GetInOperand(0).AsString();
  589. if (extension_name == "GLSL.std.450") {
  590. combinator_ops_[extension->result_id()] = {
  591. (uint32_t)GLSLstd450Round,
  592. (uint32_t)GLSLstd450RoundEven,
  593. (uint32_t)GLSLstd450Trunc,
  594. (uint32_t)GLSLstd450FAbs,
  595. (uint32_t)GLSLstd450SAbs,
  596. (uint32_t)GLSLstd450FSign,
  597. (uint32_t)GLSLstd450SSign,
  598. (uint32_t)GLSLstd450Floor,
  599. (uint32_t)GLSLstd450Ceil,
  600. (uint32_t)GLSLstd450Fract,
  601. (uint32_t)GLSLstd450Radians,
  602. (uint32_t)GLSLstd450Degrees,
  603. (uint32_t)GLSLstd450Sin,
  604. (uint32_t)GLSLstd450Cos,
  605. (uint32_t)GLSLstd450Tan,
  606. (uint32_t)GLSLstd450Asin,
  607. (uint32_t)GLSLstd450Acos,
  608. (uint32_t)GLSLstd450Atan,
  609. (uint32_t)GLSLstd450Sinh,
  610. (uint32_t)GLSLstd450Cosh,
  611. (uint32_t)GLSLstd450Tanh,
  612. (uint32_t)GLSLstd450Asinh,
  613. (uint32_t)GLSLstd450Acosh,
  614. (uint32_t)GLSLstd450Atanh,
  615. (uint32_t)GLSLstd450Atan2,
  616. (uint32_t)GLSLstd450Pow,
  617. (uint32_t)GLSLstd450Exp,
  618. (uint32_t)GLSLstd450Log,
  619. (uint32_t)GLSLstd450Exp2,
  620. (uint32_t)GLSLstd450Log2,
  621. (uint32_t)GLSLstd450Sqrt,
  622. (uint32_t)GLSLstd450InverseSqrt,
  623. (uint32_t)GLSLstd450Determinant,
  624. (uint32_t)GLSLstd450MatrixInverse,
  625. (uint32_t)GLSLstd450ModfStruct,
  626. (uint32_t)GLSLstd450FMin,
  627. (uint32_t)GLSLstd450UMin,
  628. (uint32_t)GLSLstd450SMin,
  629. (uint32_t)GLSLstd450FMax,
  630. (uint32_t)GLSLstd450UMax,
  631. (uint32_t)GLSLstd450SMax,
  632. (uint32_t)GLSLstd450FClamp,
  633. (uint32_t)GLSLstd450UClamp,
  634. (uint32_t)GLSLstd450SClamp,
  635. (uint32_t)GLSLstd450FMix,
  636. (uint32_t)GLSLstd450IMix,
  637. (uint32_t)GLSLstd450Step,
  638. (uint32_t)GLSLstd450SmoothStep,
  639. (uint32_t)GLSLstd450Fma,
  640. (uint32_t)GLSLstd450FrexpStruct,
  641. (uint32_t)GLSLstd450Ldexp,
  642. (uint32_t)GLSLstd450PackSnorm4x8,
  643. (uint32_t)GLSLstd450PackUnorm4x8,
  644. (uint32_t)GLSLstd450PackSnorm2x16,
  645. (uint32_t)GLSLstd450PackUnorm2x16,
  646. (uint32_t)GLSLstd450PackHalf2x16,
  647. (uint32_t)GLSLstd450PackDouble2x32,
  648. (uint32_t)GLSLstd450UnpackSnorm2x16,
  649. (uint32_t)GLSLstd450UnpackUnorm2x16,
  650. (uint32_t)GLSLstd450UnpackHalf2x16,
  651. (uint32_t)GLSLstd450UnpackSnorm4x8,
  652. (uint32_t)GLSLstd450UnpackUnorm4x8,
  653. (uint32_t)GLSLstd450UnpackDouble2x32,
  654. (uint32_t)GLSLstd450Length,
  655. (uint32_t)GLSLstd450Distance,
  656. (uint32_t)GLSLstd450Cross,
  657. (uint32_t)GLSLstd450Normalize,
  658. (uint32_t)GLSLstd450FaceForward,
  659. (uint32_t)GLSLstd450Reflect,
  660. (uint32_t)GLSLstd450Refract,
  661. (uint32_t)GLSLstd450FindILsb,
  662. (uint32_t)GLSLstd450FindSMsb,
  663. (uint32_t)GLSLstd450FindUMsb,
  664. (uint32_t)GLSLstd450InterpolateAtCentroid,
  665. (uint32_t)GLSLstd450InterpolateAtSample,
  666. (uint32_t)GLSLstd450InterpolateAtOffset,
  667. (uint32_t)GLSLstd450NMin,
  668. (uint32_t)GLSLstd450NMax,
  669. (uint32_t)GLSLstd450NClamp};
  670. } else {
  671. // Map the result id to the empty set.
  672. combinator_ops_[extension->result_id()];
  673. }
  674. }
  675. void IRContext::InitializeCombinators() {
  676. get_feature_mgr()->GetCapabilities()->ForEach([this](spv::Capability cap) {
  677. AddCombinatorsForCapability(uint32_t(cap));
  678. });
  679. for (auto& extension : module()->ext_inst_imports()) {
  680. AddCombinatorsForExtension(&extension);
  681. }
  682. valid_analyses_ |= kAnalysisCombinators;
  683. }
  684. void IRContext::RemoveFromIdToName(const Instruction* inst) {
  685. if (id_to_name_ && (inst->opcode() == spv::Op::OpName ||
  686. inst->opcode() == spv::Op::OpMemberName)) {
  687. auto range = id_to_name_->equal_range(inst->GetSingleWordInOperand(0));
  688. for (auto it = range.first; it != range.second; ++it) {
  689. if (it->second == inst) {
  690. id_to_name_->erase(it);
  691. break;
  692. }
  693. }
  694. }
  695. }
  696. LoopDescriptor* IRContext::GetLoopDescriptor(const Function* f) {
  697. if (!AreAnalysesValid(kAnalysisLoopAnalysis)) {
  698. ResetLoopAnalysis();
  699. }
  700. std::unordered_map<const Function*, LoopDescriptor>::iterator it =
  701. loop_descriptors_.find(f);
  702. if (it == loop_descriptors_.end()) {
  703. return &loop_descriptors_
  704. .emplace(std::make_pair(f, LoopDescriptor(this, f)))
  705. .first->second;
  706. }
  707. return &it->second;
  708. }
  709. uint32_t IRContext::FindBuiltinInputVar(uint32_t builtin) {
  710. for (auto& a : module_->annotations()) {
  711. if (spv::Op(a.opcode()) != spv::Op::OpDecorate) continue;
  712. if (spv::Decoration(a.GetSingleWordInOperand(
  713. kSpvDecorateDecorationInIdx)) != spv::Decoration::BuiltIn)
  714. continue;
  715. if (a.GetSingleWordInOperand(kSpvDecorateBuiltinInIdx) != builtin) continue;
  716. uint32_t target_id = a.GetSingleWordInOperand(kSpvDecorateTargetIdInIdx);
  717. Instruction* b_var = get_def_use_mgr()->GetDef(target_id);
  718. if (b_var->opcode() != spv::Op::OpVariable) continue;
  719. if (spv::StorageClass(b_var->GetSingleWordInOperand(0)) !=
  720. spv::StorageClass::Input)
  721. continue;
  722. return target_id;
  723. }
  724. return 0;
  725. }
  726. void IRContext::AddVarToEntryPoints(uint32_t var_id) {
  727. uint32_t ocnt = 0;
  728. for (auto& e : module()->entry_points()) {
  729. bool found = false;
  730. e.ForEachInOperand([&ocnt, &found, &var_id](const uint32_t* idp) {
  731. if (ocnt >= kEntryPointInterfaceInIdx) {
  732. if (*idp == var_id) found = true;
  733. }
  734. ++ocnt;
  735. });
  736. if (!found) {
  737. e.AddOperand({SPV_OPERAND_TYPE_ID, {var_id}});
  738. get_def_use_mgr()->AnalyzeInstDefUse(&e);
  739. }
  740. }
  741. }
  742. uint32_t IRContext::GetBuiltinInputVarId(uint32_t builtin) {
  743. if (!AreAnalysesValid(kAnalysisBuiltinVarId)) ResetBuiltinAnalysis();
  744. // If cached, return it.
  745. std::unordered_map<uint32_t, uint32_t>::iterator it =
  746. builtin_var_id_map_.find(builtin);
  747. if (it != builtin_var_id_map_.end()) return it->second;
  748. // Look for one in shader
  749. uint32_t var_id = FindBuiltinInputVar(builtin);
  750. if (var_id == 0) {
  751. // If not found, create it
  752. // TODO(greg-lunarg): Add support for all builtins
  753. analysis::TypeManager* type_mgr = get_type_mgr();
  754. analysis::Type* reg_type;
  755. switch (spv::BuiltIn(builtin)) {
  756. case spv::BuiltIn::FragCoord: {
  757. analysis::Float float_ty(32);
  758. analysis::Type* reg_float_ty = type_mgr->GetRegisteredType(&float_ty);
  759. analysis::Vector v4float_ty(reg_float_ty, 4);
  760. reg_type = type_mgr->GetRegisteredType(&v4float_ty);
  761. break;
  762. }
  763. case spv::BuiltIn::VertexIndex:
  764. case spv::BuiltIn::InstanceIndex:
  765. case spv::BuiltIn::PrimitiveId:
  766. case spv::BuiltIn::InvocationId:
  767. case spv::BuiltIn::SubgroupLocalInvocationId: {
  768. analysis::Integer uint_ty(32, false);
  769. reg_type = type_mgr->GetRegisteredType(&uint_ty);
  770. break;
  771. }
  772. case spv::BuiltIn::GlobalInvocationId:
  773. case spv::BuiltIn::LaunchIdNV: {
  774. analysis::Integer uint_ty(32, false);
  775. analysis::Type* reg_uint_ty = type_mgr->GetRegisteredType(&uint_ty);
  776. analysis::Vector v3uint_ty(reg_uint_ty, 3);
  777. reg_type = type_mgr->GetRegisteredType(&v3uint_ty);
  778. break;
  779. }
  780. case spv::BuiltIn::TessCoord: {
  781. analysis::Float float_ty(32);
  782. analysis::Type* reg_float_ty = type_mgr->GetRegisteredType(&float_ty);
  783. analysis::Vector v3float_ty(reg_float_ty, 3);
  784. reg_type = type_mgr->GetRegisteredType(&v3float_ty);
  785. break;
  786. }
  787. case spv::BuiltIn::SubgroupLtMask: {
  788. analysis::Integer uint_ty(32, false);
  789. analysis::Type* reg_uint_ty = type_mgr->GetRegisteredType(&uint_ty);
  790. analysis::Vector v4uint_ty(reg_uint_ty, 4);
  791. reg_type = type_mgr->GetRegisteredType(&v4uint_ty);
  792. break;
  793. }
  794. default: {
  795. assert(false && "unhandled builtin");
  796. return 0;
  797. }
  798. }
  799. uint32_t type_id = type_mgr->GetTypeInstruction(reg_type);
  800. uint32_t varTyPtrId =
  801. type_mgr->FindPointerToType(type_id, spv::StorageClass::Input);
  802. // TODO(1841): Handle id overflow.
  803. var_id = TakeNextId();
  804. std::unique_ptr<Instruction> newVarOp(
  805. new Instruction(this, spv::Op::OpVariable, varTyPtrId, var_id,
  806. {{spv_operand_type_t::SPV_OPERAND_TYPE_LITERAL_INTEGER,
  807. {uint32_t(spv::StorageClass::Input)}}}));
  808. get_def_use_mgr()->AnalyzeInstDefUse(&*newVarOp);
  809. module()->AddGlobalValue(std::move(newVarOp));
  810. get_decoration_mgr()->AddDecorationVal(
  811. var_id, uint32_t(spv::Decoration::BuiltIn), builtin);
  812. AddVarToEntryPoints(var_id);
  813. }
  814. builtin_var_id_map_[builtin] = var_id;
  815. return var_id;
  816. }
  817. void IRContext::AddCalls(const Function* func, std::queue<uint32_t>* todo) {
  818. for (auto bi = func->begin(); bi != func->end(); ++bi)
  819. for (auto ii = bi->begin(); ii != bi->end(); ++ii)
  820. if (ii->opcode() == spv::Op::OpFunctionCall)
  821. todo->push(ii->GetSingleWordInOperand(0));
  822. }
  823. bool IRContext::ProcessEntryPointCallTree(ProcessFunction& pfn) {
  824. // Collect all of the entry points as the roots.
  825. std::queue<uint32_t> roots;
  826. for (auto& e : module()->entry_points()) {
  827. roots.push(e.GetSingleWordInOperand(kEntryPointFunctionIdInIdx));
  828. }
  829. return ProcessCallTreeFromRoots(pfn, &roots);
  830. }
  831. bool IRContext::ProcessReachableCallTree(ProcessFunction& pfn) {
  832. std::queue<uint32_t> roots;
  833. // Add all entry points since they can be reached from outside the module.
  834. for (auto& e : module()->entry_points())
  835. roots.push(e.GetSingleWordInOperand(kEntryPointFunctionIdInIdx));
  836. // Add all exported functions since they can be reached from outside the
  837. // module.
  838. for (auto& a : annotations()) {
  839. // TODO: Handle group decorations as well. Currently not generate by any
  840. // front-end, but could be coming.
  841. if (a.opcode() == spv::Op::OpDecorate) {
  842. if (spv::Decoration(a.GetSingleWordOperand(1)) ==
  843. spv::Decoration::LinkageAttributes) {
  844. uint32_t lastOperand = a.NumOperands() - 1;
  845. if (spv::LinkageType(a.GetSingleWordOperand(lastOperand)) ==
  846. spv::LinkageType::Export) {
  847. uint32_t id = a.GetSingleWordOperand(0);
  848. if (GetFunction(id)) {
  849. roots.push(id);
  850. }
  851. }
  852. }
  853. }
  854. }
  855. return ProcessCallTreeFromRoots(pfn, &roots);
  856. }
  857. bool IRContext::ProcessCallTreeFromRoots(ProcessFunction& pfn,
  858. std::queue<uint32_t>* roots) {
  859. // Process call tree
  860. bool modified = false;
  861. std::unordered_set<uint32_t> done;
  862. while (!roots->empty()) {
  863. const uint32_t fi = roots->front();
  864. roots->pop();
  865. if (done.insert(fi).second) {
  866. Function* fn = GetFunction(fi);
  867. assert(fn && "Trying to process a function that does not exist.");
  868. modified = pfn(fn) || modified;
  869. AddCalls(fn, roots);
  870. }
  871. }
  872. return modified;
  873. }
  874. void IRContext::CollectCallTreeFromRoots(unsigned entryId,
  875. std::unordered_set<uint32_t>* funcs) {
  876. std::queue<uint32_t> roots;
  877. roots.push(entryId);
  878. while (!roots.empty()) {
  879. const uint32_t fi = roots.front();
  880. roots.pop();
  881. funcs->insert(fi);
  882. Function* fn = GetFunction(fi);
  883. AddCalls(fn, &roots);
  884. }
  885. }
  886. void IRContext::EmitErrorMessage(std::string message, Instruction* inst) {
  887. if (!consumer()) {
  888. return;
  889. }
  890. Instruction* line_inst = inst;
  891. while (line_inst != nullptr) { // Stop at the beginning of the basic block.
  892. if (!line_inst->dbg_line_insts().empty()) {
  893. line_inst = &line_inst->dbg_line_insts().back();
  894. if (line_inst->IsNoLine()) {
  895. line_inst = nullptr;
  896. }
  897. break;
  898. }
  899. line_inst = line_inst->PreviousNode();
  900. }
  901. uint32_t line_number = 0;
  902. uint32_t col_number = 0;
  903. std::string source;
  904. if (line_inst != nullptr) {
  905. Instruction* file_name =
  906. get_def_use_mgr()->GetDef(line_inst->GetSingleWordInOperand(0));
  907. source = file_name->GetInOperand(0).AsString();
  908. // Get the line number and column number.
  909. line_number = line_inst->GetSingleWordInOperand(1);
  910. col_number = line_inst->GetSingleWordInOperand(2);
  911. }
  912. message +=
  913. "\n " + inst->PrettyPrint(SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES);
  914. consumer()(SPV_MSG_ERROR, source.c_str(), {line_number, col_number, 0},
  915. message.c_str());
  916. }
  917. // Gets the dominator analysis for function |f|.
  918. DominatorAnalysis* IRContext::GetDominatorAnalysis(const Function* f) {
  919. if (!AreAnalysesValid(kAnalysisDominatorAnalysis)) {
  920. ResetDominatorAnalysis();
  921. }
  922. if (dominator_trees_.find(f) == dominator_trees_.end()) {
  923. dominator_trees_[f].InitializeTree(*cfg(), f);
  924. }
  925. return &dominator_trees_[f];
  926. }
  927. // Gets the postdominator analysis for function |f|.
  928. PostDominatorAnalysis* IRContext::GetPostDominatorAnalysis(const Function* f) {
  929. if (!AreAnalysesValid(kAnalysisDominatorAnalysis)) {
  930. ResetDominatorAnalysis();
  931. }
  932. if (post_dominator_trees_.find(f) == post_dominator_trees_.end()) {
  933. post_dominator_trees_[f].InitializeTree(*cfg(), f);
  934. }
  935. return &post_dominator_trees_[f];
  936. }
  937. bool IRContext::CheckCFG() {
  938. std::unordered_map<uint32_t, std::vector<uint32_t>> real_preds;
  939. if (!AreAnalysesValid(kAnalysisCFG)) {
  940. return true;
  941. }
  942. for (Function& function : *module()) {
  943. for (const auto& bb : function) {
  944. bb.ForEachSuccessorLabel([&bb, &real_preds](const uint32_t lab_id) {
  945. real_preds[lab_id].push_back(bb.id());
  946. });
  947. }
  948. for (auto& bb : function) {
  949. std::vector<uint32_t> preds = cfg()->preds(bb.id());
  950. std::vector<uint32_t> real = real_preds[bb.id()];
  951. std::sort(preds.begin(), preds.end());
  952. std::sort(real.begin(), real.end());
  953. bool same = true;
  954. if (preds.size() != real.size()) {
  955. same = false;
  956. }
  957. for (size_t i = 0; i < real.size() && same; i++) {
  958. if (preds[i] != real[i]) {
  959. same = false;
  960. }
  961. }
  962. if (!same) {
  963. std::cerr << "Predecessors for " << bb.id() << " are different:\n";
  964. std::cerr << "Real:";
  965. for (uint32_t i : real) {
  966. std::cerr << ' ' << i;
  967. }
  968. std::cerr << std::endl;
  969. std::cerr << "Recorded:";
  970. for (uint32_t i : preds) {
  971. std::cerr << ' ' << i;
  972. }
  973. std::cerr << std::endl;
  974. }
  975. if (!same) return false;
  976. }
  977. }
  978. return true;
  979. }
  980. bool IRContext::IsReachable(const opt::BasicBlock& bb) {
  981. auto enclosing_function = bb.GetParent();
  982. return GetDominatorAnalysis(enclosing_function)
  983. ->Dominates(enclosing_function->entry().get(), &bb);
  984. }
  985. spv::ExecutionModel IRContext::GetStage() {
  986. const auto& entry_points = module()->entry_points();
  987. if (entry_points.empty()) {
  988. return spv::ExecutionModel::Max;
  989. }
  990. uint32_t stage = entry_points.begin()->GetSingleWordInOperand(
  991. kEntryPointExecutionModelInIdx);
  992. auto it = std::find_if(
  993. entry_points.begin(), entry_points.end(), [stage](const Instruction& x) {
  994. return x.GetSingleWordInOperand(kEntryPointExecutionModelInIdx) !=
  995. stage;
  996. });
  997. if (it != entry_points.end()) {
  998. EmitErrorMessage("Mixed stage shader module not supported", &(*it));
  999. }
  1000. return static_cast<spv::ExecutionModel>(stage);
  1001. }
  1002. } // namespace opt
  1003. } // namespace spvtools