ir_context.cpp 33 KB

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