fuzzer_util.cpp 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832
  1. // Copyright (c) 2019 Google LLC
  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/fuzz/fuzzer_util.h"
  15. #include <algorithm>
  16. #include <unordered_set>
  17. #include "source/opt/build_module.h"
  18. namespace spvtools {
  19. namespace fuzz {
  20. namespace fuzzerutil {
  21. namespace {
  22. uint32_t MaybeGetOpConstant(opt::IRContext* ir_context,
  23. const TransformationContext& transformation_context,
  24. const std::vector<uint32_t>& words,
  25. uint32_t type_id, bool is_irrelevant) {
  26. for (const auto& inst : ir_context->types_values()) {
  27. if (inst.opcode() == SpvOpConstant && inst.type_id() == type_id &&
  28. inst.GetInOperand(0).words == words &&
  29. transformation_context.GetFactManager()->IdIsIrrelevant(
  30. inst.result_id()) == is_irrelevant) {
  31. return inst.result_id();
  32. }
  33. }
  34. return 0;
  35. }
  36. } // namespace
  37. const spvtools::MessageConsumer kSilentMessageConsumer =
  38. [](spv_message_level_t, const char*, const spv_position_t&,
  39. const char*) -> void {};
  40. bool IsFreshId(opt::IRContext* context, uint32_t id) {
  41. return !context->get_def_use_mgr()->GetDef(id);
  42. }
  43. void UpdateModuleIdBound(opt::IRContext* context, uint32_t id) {
  44. // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/2541) consider the
  45. // case where the maximum id bound is reached.
  46. context->module()->SetIdBound(
  47. std::max(context->module()->id_bound(), id + 1));
  48. }
  49. opt::BasicBlock* MaybeFindBlock(opt::IRContext* context,
  50. uint32_t maybe_block_id) {
  51. auto inst = context->get_def_use_mgr()->GetDef(maybe_block_id);
  52. if (inst == nullptr) {
  53. // No instruction defining this id was found.
  54. return nullptr;
  55. }
  56. if (inst->opcode() != SpvOpLabel) {
  57. // The instruction defining the id is not a label, so it cannot be a block
  58. // id.
  59. return nullptr;
  60. }
  61. return context->cfg()->block(maybe_block_id);
  62. }
  63. bool PhiIdsOkForNewEdge(
  64. opt::IRContext* context, opt::BasicBlock* bb_from, opt::BasicBlock* bb_to,
  65. const google::protobuf::RepeatedField<google::protobuf::uint32>& phi_ids) {
  66. if (bb_from->IsSuccessor(bb_to)) {
  67. // There is already an edge from |from_block| to |to_block|, so there is
  68. // no need to extend OpPhi instructions. Do not allow phi ids to be
  69. // present. This might turn out to be too strict; perhaps it would be OK
  70. // just to ignore the ids in this case.
  71. return phi_ids.empty();
  72. }
  73. // The edge would add a previously non-existent edge from |from_block| to
  74. // |to_block|, so we go through the given phi ids and check that they exactly
  75. // match the OpPhi instructions in |to_block|.
  76. uint32_t phi_index = 0;
  77. // An explicit loop, rather than applying a lambda to each OpPhi in |bb_to|,
  78. // makes sense here because we need to increment |phi_index| for each OpPhi
  79. // instruction.
  80. for (auto& inst : *bb_to) {
  81. if (inst.opcode() != SpvOpPhi) {
  82. // The OpPhi instructions all occur at the start of the block; if we find
  83. // a non-OpPhi then we have seen them all.
  84. break;
  85. }
  86. if (phi_index == static_cast<uint32_t>(phi_ids.size())) {
  87. // Not enough phi ids have been provided to account for the OpPhi
  88. // instructions.
  89. return false;
  90. }
  91. // Look for an instruction defining the next phi id.
  92. opt::Instruction* phi_extension =
  93. context->get_def_use_mgr()->GetDef(phi_ids[phi_index]);
  94. if (!phi_extension) {
  95. // The id given to extend this OpPhi does not exist.
  96. return false;
  97. }
  98. if (phi_extension->type_id() != inst.type_id()) {
  99. // The instruction given to extend this OpPhi either does not have a type
  100. // or its type does not match that of the OpPhi.
  101. return false;
  102. }
  103. if (context->get_instr_block(phi_extension)) {
  104. // The instruction defining the phi id has an associated block (i.e., it
  105. // is not a global value). Check whether its definition dominates the
  106. // exit of |from_block|.
  107. auto dominator_analysis =
  108. context->GetDominatorAnalysis(bb_from->GetParent());
  109. if (!dominator_analysis->Dominates(phi_extension,
  110. bb_from->terminator())) {
  111. // The given id is no good as its definition does not dominate the exit
  112. // of |from_block|
  113. return false;
  114. }
  115. }
  116. phi_index++;
  117. }
  118. // We allow some of the ids provided for extending OpPhi instructions to be
  119. // unused. Their presence does no harm, and requiring a perfect match may
  120. // make transformations less likely to cleanly apply.
  121. return true;
  122. }
  123. void AddUnreachableEdgeAndUpdateOpPhis(
  124. opt::IRContext* context, opt::BasicBlock* bb_from, opt::BasicBlock* bb_to,
  125. uint32_t bool_id,
  126. const google::protobuf::RepeatedField<google::protobuf::uint32>& phi_ids) {
  127. assert(PhiIdsOkForNewEdge(context, bb_from, bb_to, phi_ids) &&
  128. "Precondition on phi_ids is not satisfied");
  129. assert(bb_from->terminator()->opcode() == SpvOpBranch &&
  130. "Precondition on terminator of bb_from is not satisfied");
  131. // Get the id of the boolean constant to be used as the condition.
  132. auto condition_inst = context->get_def_use_mgr()->GetDef(bool_id);
  133. assert(condition_inst &&
  134. (condition_inst->opcode() == SpvOpConstantTrue ||
  135. condition_inst->opcode() == SpvOpConstantFalse) &&
  136. "|bool_id| is invalid");
  137. auto condition_value = condition_inst->opcode() == SpvOpConstantTrue;
  138. const bool from_to_edge_already_exists = bb_from->IsSuccessor(bb_to);
  139. auto successor = bb_from->terminator()->GetSingleWordInOperand(0);
  140. // Add the dead branch, by turning OpBranch into OpBranchConditional, and
  141. // ordering the targets depending on whether the given boolean corresponds to
  142. // true or false.
  143. bb_from->terminator()->SetOpcode(SpvOpBranchConditional);
  144. bb_from->terminator()->SetInOperands(
  145. {{SPV_OPERAND_TYPE_ID, {bool_id}},
  146. {SPV_OPERAND_TYPE_ID, {condition_value ? successor : bb_to->id()}},
  147. {SPV_OPERAND_TYPE_ID, {condition_value ? bb_to->id() : successor}}});
  148. // Update OpPhi instructions in the target block if this branch adds a
  149. // previously non-existent edge from source to target.
  150. if (!from_to_edge_already_exists) {
  151. uint32_t phi_index = 0;
  152. for (auto& inst : *bb_to) {
  153. if (inst.opcode() != SpvOpPhi) {
  154. break;
  155. }
  156. assert(phi_index < static_cast<uint32_t>(phi_ids.size()) &&
  157. "There should be at least one phi id per OpPhi instruction.");
  158. inst.AddOperand({SPV_OPERAND_TYPE_ID, {phi_ids[phi_index]}});
  159. inst.AddOperand({SPV_OPERAND_TYPE_ID, {bb_from->id()}});
  160. phi_index++;
  161. }
  162. }
  163. }
  164. bool BlockIsBackEdge(opt::IRContext* context, uint32_t block_id,
  165. uint32_t loop_header_id) {
  166. auto block = context->cfg()->block(block_id);
  167. auto loop_header = context->cfg()->block(loop_header_id);
  168. // |block| and |loop_header| must be defined, |loop_header| must be in fact
  169. // loop header and |block| must branch to it.
  170. if (!(block && loop_header && loop_header->IsLoopHeader() &&
  171. block->IsSuccessor(loop_header))) {
  172. return false;
  173. }
  174. // |block_id| must be reachable and be dominated by |loop_header|.
  175. opt::DominatorAnalysis* dominator_analysis =
  176. context->GetDominatorAnalysis(loop_header->GetParent());
  177. return dominator_analysis->IsReachable(block_id) &&
  178. dominator_analysis->Dominates(loop_header_id, block_id);
  179. }
  180. bool BlockIsInLoopContinueConstruct(opt::IRContext* context, uint32_t block_id,
  181. uint32_t maybe_loop_header_id) {
  182. // We deem a block to be part of a loop's continue construct if the loop's
  183. // continue target dominates the block.
  184. auto containing_construct_block = context->cfg()->block(maybe_loop_header_id);
  185. if (containing_construct_block->IsLoopHeader()) {
  186. auto continue_target = containing_construct_block->ContinueBlockId();
  187. if (context->GetDominatorAnalysis(containing_construct_block->GetParent())
  188. ->Dominates(continue_target, block_id)) {
  189. return true;
  190. }
  191. }
  192. return false;
  193. }
  194. opt::BasicBlock::iterator GetIteratorForInstruction(
  195. opt::BasicBlock* block, const opt::Instruction* inst) {
  196. for (auto inst_it = block->begin(); inst_it != block->end(); ++inst_it) {
  197. if (inst == &*inst_it) {
  198. return inst_it;
  199. }
  200. }
  201. return block->end();
  202. }
  203. bool BlockIsReachableInItsFunction(opt::IRContext* context,
  204. opt::BasicBlock* bb) {
  205. auto enclosing_function = bb->GetParent();
  206. return context->GetDominatorAnalysis(enclosing_function)
  207. ->Dominates(enclosing_function->entry().get(), bb);
  208. }
  209. bool CanInsertOpcodeBeforeInstruction(
  210. SpvOp opcode, const opt::BasicBlock::iterator& instruction_in_block) {
  211. if (instruction_in_block->PreviousNode() &&
  212. (instruction_in_block->PreviousNode()->opcode() == SpvOpLoopMerge ||
  213. instruction_in_block->PreviousNode()->opcode() == SpvOpSelectionMerge)) {
  214. // We cannot insert directly after a merge instruction.
  215. return false;
  216. }
  217. if (opcode != SpvOpVariable &&
  218. instruction_in_block->opcode() == SpvOpVariable) {
  219. // We cannot insert a non-OpVariable instruction directly before a
  220. // variable; variables in a function must be contiguous in the entry block.
  221. return false;
  222. }
  223. // We cannot insert a non-OpPhi instruction directly before an OpPhi, because
  224. // OpPhi instructions need to be contiguous at the start of a block.
  225. return opcode == SpvOpPhi || instruction_in_block->opcode() != SpvOpPhi;
  226. }
  227. bool CanMakeSynonymOf(opt::IRContext* ir_context,
  228. const TransformationContext& transformation_context,
  229. opt::Instruction* inst) {
  230. if (inst->opcode() == SpvOpSampledImage) {
  231. // The SPIR-V data rules say that only very specific instructions may
  232. // may consume the result id of an OpSampledImage, and this excludes the
  233. // instructions that are used for making synonyms.
  234. return false;
  235. }
  236. if (!inst->HasResultId()) {
  237. // We can only make a synonym of an instruction that generates an id.
  238. return false;
  239. }
  240. if (transformation_context.GetFactManager()->IdIsIrrelevant(
  241. inst->result_id())) {
  242. // An irrelevant id can't be a synonym of anything.
  243. return false;
  244. }
  245. if (!inst->type_id()) {
  246. // We can only make a synonym of an instruction that has a type.
  247. return false;
  248. }
  249. auto type_inst = ir_context->get_def_use_mgr()->GetDef(inst->type_id());
  250. if (type_inst->opcode() == SpvOpTypeVoid) {
  251. // We only make synonyms of instructions that define objects, and an object
  252. // cannot have void type.
  253. return false;
  254. }
  255. if (type_inst->opcode() == SpvOpTypePointer) {
  256. switch (inst->opcode()) {
  257. case SpvOpConstantNull:
  258. case SpvOpUndef:
  259. // We disallow making synonyms of null or undefined pointers. This is
  260. // to provide the property that if the original shader exhibited no bad
  261. // pointer accesses, the transformed shader will not either.
  262. return false;
  263. default:
  264. break;
  265. }
  266. }
  267. // We do not make synonyms of objects that have decorations: if the synonym is
  268. // not decorated analogously, using the original object vs. its synonymous
  269. // form may not be equivalent.
  270. return ir_context->get_decoration_mgr()
  271. ->GetDecorationsFor(inst->result_id(), true)
  272. .empty();
  273. }
  274. bool IsCompositeType(const opt::analysis::Type* type) {
  275. return type && (type->AsArray() || type->AsMatrix() || type->AsStruct() ||
  276. type->AsVector());
  277. }
  278. std::vector<uint32_t> RepeatedFieldToVector(
  279. const google::protobuf::RepeatedField<uint32_t>& repeated_field) {
  280. std::vector<uint32_t> result;
  281. for (auto i : repeated_field) {
  282. result.push_back(i);
  283. }
  284. return result;
  285. }
  286. uint32_t WalkOneCompositeTypeIndex(opt::IRContext* context,
  287. uint32_t base_object_type_id,
  288. uint32_t index) {
  289. auto should_be_composite_type =
  290. context->get_def_use_mgr()->GetDef(base_object_type_id);
  291. assert(should_be_composite_type && "The type should exist.");
  292. switch (should_be_composite_type->opcode()) {
  293. case SpvOpTypeArray: {
  294. auto array_length = GetArraySize(*should_be_composite_type, context);
  295. if (array_length == 0 || index >= array_length) {
  296. return 0;
  297. }
  298. return should_be_composite_type->GetSingleWordInOperand(0);
  299. }
  300. case SpvOpTypeMatrix:
  301. case SpvOpTypeVector: {
  302. auto count = should_be_composite_type->GetSingleWordInOperand(1);
  303. if (index >= count) {
  304. return 0;
  305. }
  306. return should_be_composite_type->GetSingleWordInOperand(0);
  307. }
  308. case SpvOpTypeStruct: {
  309. if (index >= GetNumberOfStructMembers(*should_be_composite_type)) {
  310. return 0;
  311. }
  312. return should_be_composite_type->GetSingleWordInOperand(index);
  313. }
  314. default:
  315. return 0;
  316. }
  317. }
  318. uint32_t WalkCompositeTypeIndices(
  319. opt::IRContext* context, uint32_t base_object_type_id,
  320. const google::protobuf::RepeatedField<google::protobuf::uint32>& indices) {
  321. uint32_t sub_object_type_id = base_object_type_id;
  322. for (auto index : indices) {
  323. sub_object_type_id =
  324. WalkOneCompositeTypeIndex(context, sub_object_type_id, index);
  325. if (!sub_object_type_id) {
  326. return 0;
  327. }
  328. }
  329. return sub_object_type_id;
  330. }
  331. uint32_t GetNumberOfStructMembers(
  332. const opt::Instruction& struct_type_instruction) {
  333. assert(struct_type_instruction.opcode() == SpvOpTypeStruct &&
  334. "An OpTypeStruct instruction is required here.");
  335. return struct_type_instruction.NumInOperands();
  336. }
  337. uint32_t GetArraySize(const opt::Instruction& array_type_instruction,
  338. opt::IRContext* context) {
  339. auto array_length_constant =
  340. context->get_constant_mgr()
  341. ->GetConstantFromInst(context->get_def_use_mgr()->GetDef(
  342. array_type_instruction.GetSingleWordInOperand(1)))
  343. ->AsIntConstant();
  344. if (array_length_constant->words().size() != 1) {
  345. return 0;
  346. }
  347. return array_length_constant->GetU32();
  348. }
  349. uint32_t GetBoundForCompositeIndex(const opt::Instruction& composite_type_inst,
  350. opt::IRContext* ir_context) {
  351. switch (composite_type_inst.opcode()) {
  352. case SpvOpTypeArray:
  353. return fuzzerutil::GetArraySize(composite_type_inst, ir_context);
  354. case SpvOpTypeMatrix:
  355. case SpvOpTypeVector:
  356. return composite_type_inst.GetSingleWordInOperand(1);
  357. case SpvOpTypeStruct: {
  358. return fuzzerutil::GetNumberOfStructMembers(composite_type_inst);
  359. }
  360. case SpvOpTypeRuntimeArray:
  361. assert(false &&
  362. "GetBoundForCompositeIndex should not be invoked with an "
  363. "OpTypeRuntimeArray, which does not have a static bound.");
  364. return 0;
  365. default:
  366. assert(false && "Unknown composite type.");
  367. return 0;
  368. }
  369. }
  370. bool IsValid(const opt::IRContext* context,
  371. spv_validator_options validator_options,
  372. MessageConsumer consumer) {
  373. std::vector<uint32_t> binary;
  374. context->module()->ToBinary(&binary, false);
  375. SpirvTools tools(context->grammar().target_env());
  376. tools.SetMessageConsumer(consumer);
  377. return tools.Validate(binary.data(), binary.size(), validator_options);
  378. }
  379. bool IsValidAndWellFormed(const opt::IRContext* ir_context,
  380. spv_validator_options validator_options,
  381. MessageConsumer consumer) {
  382. if (!IsValid(ir_context, validator_options, consumer)) {
  383. // Expression to dump |ir_context| to /data/temp/shader.spv:
  384. // DumpShader(ir_context, "/data/temp/shader.spv")
  385. consumer(SPV_MSG_INFO, nullptr, {},
  386. "Module is invalid (set a breakpoint to inspect).");
  387. return false;
  388. }
  389. // Check that all blocks in the module have appropriate parent functions.
  390. for (auto& function : *ir_context->module()) {
  391. for (auto& block : function) {
  392. if (block.GetParent() == nullptr) {
  393. std::stringstream ss;
  394. ss << "Block " << block.id() << " has no parent; its parent should be "
  395. << function.result_id() << " (set a breakpoint to inspect).";
  396. consumer(SPV_MSG_INFO, nullptr, {}, ss.str().c_str());
  397. return false;
  398. }
  399. if (block.GetParent() != &function) {
  400. std::stringstream ss;
  401. ss << "Block " << block.id() << " should have parent "
  402. << function.result_id() << " but instead has parent "
  403. << block.GetParent() << " (set a breakpoint to inspect).";
  404. consumer(SPV_MSG_INFO, nullptr, {}, ss.str().c_str());
  405. return false;
  406. }
  407. }
  408. }
  409. // Check that all instructions have distinct unique ids. We map each unique
  410. // id to the first instruction it is observed to be associated with so that
  411. // if we encounter a duplicate we have access to the previous instruction -
  412. // this is a useful aid to debugging.
  413. std::unordered_map<uint32_t, opt::Instruction*> unique_ids;
  414. bool found_duplicate = false;
  415. ir_context->module()->ForEachInst([&consumer, &found_duplicate,
  416. &unique_ids](opt::Instruction* inst) {
  417. if (unique_ids.count(inst->unique_id()) != 0) {
  418. consumer(SPV_MSG_INFO, nullptr, {},
  419. "Two instructions have the same unique id (set a breakpoint to "
  420. "inspect).");
  421. found_duplicate = true;
  422. }
  423. unique_ids.insert({inst->unique_id(), inst});
  424. });
  425. return !found_duplicate;
  426. }
  427. std::unique_ptr<opt::IRContext> CloneIRContext(opt::IRContext* context) {
  428. std::vector<uint32_t> binary;
  429. context->module()->ToBinary(&binary, false);
  430. return BuildModule(context->grammar().target_env(), nullptr, binary.data(),
  431. binary.size());
  432. }
  433. bool IsNonFunctionTypeId(opt::IRContext* ir_context, uint32_t id) {
  434. auto type = ir_context->get_type_mgr()->GetType(id);
  435. return type && !type->AsFunction();
  436. }
  437. bool IsMergeOrContinue(opt::IRContext* ir_context, uint32_t block_id) {
  438. bool result = false;
  439. ir_context->get_def_use_mgr()->WhileEachUse(
  440. block_id,
  441. [&result](const opt::Instruction* use_instruction,
  442. uint32_t /*unused*/) -> bool {
  443. switch (use_instruction->opcode()) {
  444. case SpvOpLoopMerge:
  445. case SpvOpSelectionMerge:
  446. result = true;
  447. return false;
  448. default:
  449. return true;
  450. }
  451. });
  452. return result;
  453. }
  454. uint32_t GetLoopFromMergeBlock(opt::IRContext* ir_context,
  455. uint32_t merge_block_id) {
  456. uint32_t result = 0;
  457. ir_context->get_def_use_mgr()->WhileEachUse(
  458. merge_block_id,
  459. [ir_context, &result](opt::Instruction* use_instruction,
  460. uint32_t use_index) -> bool {
  461. switch (use_instruction->opcode()) {
  462. case SpvOpLoopMerge:
  463. // The merge block operand is the first operand in OpLoopMerge.
  464. if (use_index == 0) {
  465. result = ir_context->get_instr_block(use_instruction)->id();
  466. return false;
  467. }
  468. return true;
  469. default:
  470. return true;
  471. }
  472. });
  473. return result;
  474. }
  475. uint32_t FindFunctionType(opt::IRContext* ir_context,
  476. const std::vector<uint32_t>& type_ids) {
  477. // Look through the existing types for a match.
  478. for (auto& type_or_value : ir_context->types_values()) {
  479. if (type_or_value.opcode() != SpvOpTypeFunction) {
  480. // We are only interested in function types.
  481. continue;
  482. }
  483. if (type_or_value.NumInOperands() != type_ids.size()) {
  484. // Not a match: different numbers of arguments.
  485. continue;
  486. }
  487. // Check whether the return type and argument types match.
  488. bool input_operands_match = true;
  489. for (uint32_t i = 0; i < type_or_value.NumInOperands(); i++) {
  490. if (type_ids[i] != type_or_value.GetSingleWordInOperand(i)) {
  491. input_operands_match = false;
  492. break;
  493. }
  494. }
  495. if (input_operands_match) {
  496. // Everything matches.
  497. return type_or_value.result_id();
  498. }
  499. }
  500. // No match was found.
  501. return 0;
  502. }
  503. opt::Instruction* GetFunctionType(opt::IRContext* context,
  504. const opt::Function* function) {
  505. uint32_t type_id = function->DefInst().GetSingleWordInOperand(1);
  506. return context->get_def_use_mgr()->GetDef(type_id);
  507. }
  508. opt::Function* FindFunction(opt::IRContext* ir_context, uint32_t function_id) {
  509. for (auto& function : *ir_context->module()) {
  510. if (function.result_id() == function_id) {
  511. return &function;
  512. }
  513. }
  514. return nullptr;
  515. }
  516. bool FunctionContainsOpKillOrUnreachable(const opt::Function& function) {
  517. for (auto& block : function) {
  518. if (block.terminator()->opcode() == SpvOpKill ||
  519. block.terminator()->opcode() == SpvOpUnreachable) {
  520. return true;
  521. }
  522. }
  523. return false;
  524. }
  525. bool FunctionIsEntryPoint(opt::IRContext* context, uint32_t function_id) {
  526. for (auto& entry_point : context->module()->entry_points()) {
  527. if (entry_point.GetSingleWordInOperand(1) == function_id) {
  528. return true;
  529. }
  530. }
  531. return false;
  532. }
  533. bool IdIsAvailableAtUse(opt::IRContext* context,
  534. opt::Instruction* use_instruction,
  535. uint32_t use_input_operand_index, uint32_t id) {
  536. assert(context->get_instr_block(use_instruction) &&
  537. "|use_instruction| must be in a basic block");
  538. auto defining_instruction = context->get_def_use_mgr()->GetDef(id);
  539. auto enclosing_function =
  540. context->get_instr_block(use_instruction)->GetParent();
  541. // If the id a function parameter, it needs to be associated with the
  542. // function containing the use.
  543. if (defining_instruction->opcode() == SpvOpFunctionParameter) {
  544. return InstructionIsFunctionParameter(defining_instruction,
  545. enclosing_function);
  546. }
  547. if (!context->get_instr_block(id)) {
  548. // The id must be at global scope.
  549. return true;
  550. }
  551. if (defining_instruction == use_instruction) {
  552. // It is not OK for a definition to use itself.
  553. return false;
  554. }
  555. auto dominator_analysis = context->GetDominatorAnalysis(enclosing_function);
  556. if (!dominator_analysis->IsReachable(
  557. context->get_instr_block(use_instruction)) ||
  558. !dominator_analysis->IsReachable(context->get_instr_block(id))) {
  559. // Skip unreachable blocks.
  560. return false;
  561. }
  562. if (use_instruction->opcode() == SpvOpPhi) {
  563. // In the case where the use is an operand to OpPhi, it is actually the
  564. // *parent* block associated with the operand that must be dominated by
  565. // the synonym.
  566. auto parent_block =
  567. use_instruction->GetSingleWordInOperand(use_input_operand_index + 1);
  568. return dominator_analysis->Dominates(
  569. context->get_instr_block(defining_instruction)->id(), parent_block);
  570. }
  571. return dominator_analysis->Dominates(defining_instruction, use_instruction);
  572. }
  573. bool IdIsAvailableBeforeInstruction(opt::IRContext* context,
  574. opt::Instruction* instruction,
  575. uint32_t id) {
  576. assert(context->get_instr_block(instruction) &&
  577. "|instruction| must be in a basic block");
  578. auto id_definition = context->get_def_use_mgr()->GetDef(id);
  579. auto function_enclosing_instruction =
  580. context->get_instr_block(instruction)->GetParent();
  581. // If the id a function parameter, it needs to be associated with the
  582. // function containing the instruction.
  583. if (id_definition->opcode() == SpvOpFunctionParameter) {
  584. return InstructionIsFunctionParameter(id_definition,
  585. function_enclosing_instruction);
  586. }
  587. if (!context->get_instr_block(id)) {
  588. // The id is at global scope.
  589. return true;
  590. }
  591. if (id_definition == instruction) {
  592. // The instruction is not available right before its own definition.
  593. return false;
  594. }
  595. const auto* dominator_analysis =
  596. context->GetDominatorAnalysis(function_enclosing_instruction);
  597. if (dominator_analysis->IsReachable(context->get_instr_block(instruction)) &&
  598. dominator_analysis->IsReachable(context->get_instr_block(id)) &&
  599. dominator_analysis->Dominates(id_definition, instruction)) {
  600. // The id's definition dominates the instruction, and both the definition
  601. // and the instruction are in reachable blocks, thus the id is available at
  602. // the instruction.
  603. return true;
  604. }
  605. if (id_definition->opcode() == SpvOpVariable &&
  606. function_enclosing_instruction ==
  607. context->get_instr_block(id)->GetParent()) {
  608. assert(!dominator_analysis->IsReachable(
  609. context->get_instr_block(instruction)) &&
  610. "If the instruction were in a reachable block we should already "
  611. "have returned true.");
  612. // The id is a variable and it is in the same function as |instruction|.
  613. // This is OK despite |instruction| being unreachable.
  614. return true;
  615. }
  616. return false;
  617. }
  618. bool InstructionIsFunctionParameter(opt::Instruction* instruction,
  619. opt::Function* function) {
  620. if (instruction->opcode() != SpvOpFunctionParameter) {
  621. return false;
  622. }
  623. bool found_parameter = false;
  624. function->ForEachParam(
  625. [instruction, &found_parameter](opt::Instruction* param) {
  626. if (param == instruction) {
  627. found_parameter = true;
  628. }
  629. });
  630. return found_parameter;
  631. }
  632. uint32_t GetTypeId(opt::IRContext* context, uint32_t result_id) {
  633. const auto* inst = context->get_def_use_mgr()->GetDef(result_id);
  634. assert(inst && "|result_id| is invalid");
  635. return inst->type_id();
  636. }
  637. uint32_t GetPointeeTypeIdFromPointerType(opt::Instruction* pointer_type_inst) {
  638. assert(pointer_type_inst && pointer_type_inst->opcode() == SpvOpTypePointer &&
  639. "Precondition: |pointer_type_inst| must be OpTypePointer.");
  640. return pointer_type_inst->GetSingleWordInOperand(1);
  641. }
  642. uint32_t GetPointeeTypeIdFromPointerType(opt::IRContext* context,
  643. uint32_t pointer_type_id) {
  644. return GetPointeeTypeIdFromPointerType(
  645. context->get_def_use_mgr()->GetDef(pointer_type_id));
  646. }
  647. SpvStorageClass GetStorageClassFromPointerType(
  648. opt::Instruction* pointer_type_inst) {
  649. assert(pointer_type_inst && pointer_type_inst->opcode() == SpvOpTypePointer &&
  650. "Precondition: |pointer_type_inst| must be OpTypePointer.");
  651. return static_cast<SpvStorageClass>(
  652. pointer_type_inst->GetSingleWordInOperand(0));
  653. }
  654. SpvStorageClass GetStorageClassFromPointerType(opt::IRContext* context,
  655. uint32_t pointer_type_id) {
  656. return GetStorageClassFromPointerType(
  657. context->get_def_use_mgr()->GetDef(pointer_type_id));
  658. }
  659. uint32_t MaybeGetPointerType(opt::IRContext* context, uint32_t pointee_type_id,
  660. SpvStorageClass storage_class) {
  661. for (auto& inst : context->types_values()) {
  662. switch (inst.opcode()) {
  663. case SpvOpTypePointer:
  664. if (inst.GetSingleWordInOperand(0) == storage_class &&
  665. inst.GetSingleWordInOperand(1) == pointee_type_id) {
  666. return inst.result_id();
  667. }
  668. break;
  669. default:
  670. break;
  671. }
  672. }
  673. return 0;
  674. }
  675. uint32_t InOperandIndexFromOperandIndex(const opt::Instruction& inst,
  676. uint32_t absolute_index) {
  677. // Subtract the number of non-input operands from the index
  678. return absolute_index - inst.NumOperands() + inst.NumInOperands();
  679. }
  680. bool IsNullConstantSupported(const opt::analysis::Type& type) {
  681. return type.AsBool() || type.AsInteger() || type.AsFloat() ||
  682. type.AsMatrix() || type.AsVector() || type.AsArray() ||
  683. type.AsStruct() || type.AsPointer() || type.AsEvent() ||
  684. type.AsDeviceEvent() || type.AsReserveId() || type.AsQueue();
  685. }
  686. bool GlobalVariablesMustBeDeclaredInEntryPointInterfaces(
  687. const opt::IRContext* ir_context) {
  688. // TODO(afd): We capture the universal environments for which this requirement
  689. // holds. The check should be refined on demand for other target
  690. // environments.
  691. switch (ir_context->grammar().target_env()) {
  692. case SPV_ENV_UNIVERSAL_1_0:
  693. case SPV_ENV_UNIVERSAL_1_1:
  694. case SPV_ENV_UNIVERSAL_1_2:
  695. case SPV_ENV_UNIVERSAL_1_3:
  696. return false;
  697. default:
  698. return true;
  699. }
  700. }
  701. void AddVariableIdToEntryPointInterfaces(opt::IRContext* context, uint32_t id) {
  702. if (GlobalVariablesMustBeDeclaredInEntryPointInterfaces(context)) {
  703. // Conservatively add this global to the interface of every entry point in
  704. // the module. This means that the global is available for other
  705. // transformations to use.
  706. //
  707. // A downside of this is that the global will be in the interface even if it
  708. // ends up never being used.
  709. //
  710. // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/3111) revisit
  711. // this if a more thorough approach to entry point interfaces is taken.
  712. for (auto& entry_point : context->module()->entry_points()) {
  713. entry_point.AddOperand({SPV_OPERAND_TYPE_ID, {id}});
  714. }
  715. }
  716. }
  717. void AddGlobalVariable(opt::IRContext* context, uint32_t result_id,
  718. uint32_t type_id, SpvStorageClass storage_class,
  719. uint32_t initializer_id) {
  720. // Check various preconditions.
  721. assert(result_id != 0 && "Result id can't be 0");
  722. assert((storage_class == SpvStorageClassPrivate ||
  723. storage_class == SpvStorageClassWorkgroup) &&
  724. "Variable's storage class must be either Private or Workgroup");
  725. auto* type_inst = context->get_def_use_mgr()->GetDef(type_id);
  726. (void)type_inst; // Variable becomes unused in release mode.
  727. assert(type_inst && type_inst->opcode() == SpvOpTypePointer &&
  728. GetStorageClassFromPointerType(type_inst) == storage_class &&
  729. "Variable's type is invalid");
  730. if (storage_class == SpvStorageClassWorkgroup) {
  731. assert(initializer_id == 0);
  732. }
  733. if (initializer_id != 0) {
  734. const auto* constant_inst =
  735. context->get_def_use_mgr()->GetDef(initializer_id);
  736. (void)constant_inst; // Variable becomes unused in release mode.
  737. assert(constant_inst && spvOpcodeIsConstant(constant_inst->opcode()) &&
  738. GetPointeeTypeIdFromPointerType(type_inst) ==
  739. constant_inst->type_id() &&
  740. "Initializer is invalid");
  741. }
  742. opt::Instruction::OperandList operands = {
  743. {SPV_OPERAND_TYPE_STORAGE_CLASS, {static_cast<uint32_t>(storage_class)}}};
  744. if (initializer_id) {
  745. operands.push_back({SPV_OPERAND_TYPE_ID, {initializer_id}});
  746. }
  747. context->module()->AddGlobalValue(MakeUnique<opt::Instruction>(
  748. context, SpvOpVariable, type_id, result_id, std::move(operands)));
  749. AddVariableIdToEntryPointInterfaces(context, result_id);
  750. UpdateModuleIdBound(context, result_id);
  751. }
  752. void AddLocalVariable(opt::IRContext* context, uint32_t result_id,
  753. uint32_t type_id, uint32_t function_id,
  754. uint32_t initializer_id) {
  755. // Check various preconditions.
  756. assert(result_id != 0 && "Result id can't be 0");
  757. auto* type_inst = context->get_def_use_mgr()->GetDef(type_id);
  758. (void)type_inst; // Variable becomes unused in release mode.
  759. assert(type_inst && type_inst->opcode() == SpvOpTypePointer &&
  760. GetStorageClassFromPointerType(type_inst) == SpvStorageClassFunction &&
  761. "Variable's type is invalid");
  762. const auto* constant_inst =
  763. context->get_def_use_mgr()->GetDef(initializer_id);
  764. (void)constant_inst; // Variable becomes unused in release mode.
  765. assert(constant_inst && spvOpcodeIsConstant(constant_inst->opcode()) &&
  766. GetPointeeTypeIdFromPointerType(type_inst) ==
  767. constant_inst->type_id() &&
  768. "Initializer is invalid");
  769. auto* function = FindFunction(context, function_id);
  770. assert(function && "Function id is invalid");
  771. function->begin()->begin()->InsertBefore(MakeUnique<opt::Instruction>(
  772. context, SpvOpVariable, type_id, result_id,
  773. opt::Instruction::OperandList{
  774. {SPV_OPERAND_TYPE_STORAGE_CLASS, {SpvStorageClassFunction}},
  775. {SPV_OPERAND_TYPE_ID, {initializer_id}}}));
  776. UpdateModuleIdBound(context, result_id);
  777. }
  778. bool HasDuplicates(const std::vector<uint32_t>& arr) {
  779. return std::unordered_set<uint32_t>(arr.begin(), arr.end()).size() !=
  780. arr.size();
  781. }
  782. bool IsPermutationOfRange(const std::vector<uint32_t>& arr, uint32_t lo,
  783. uint32_t hi) {
  784. if (arr.empty()) {
  785. return lo > hi;
  786. }
  787. if (HasDuplicates(arr)) {
  788. return false;
  789. }
  790. auto min_max = std::minmax_element(arr.begin(), arr.end());
  791. return arr.size() == hi - lo + 1 && *min_max.first == lo &&
  792. *min_max.second == hi;
  793. }
  794. std::vector<opt::Instruction*> GetParameters(opt::IRContext* ir_context,
  795. uint32_t function_id) {
  796. auto* function = FindFunction(ir_context, function_id);
  797. assert(function && "|function_id| is invalid");
  798. std::vector<opt::Instruction*> result;
  799. function->ForEachParam(
  800. [&result](opt::Instruction* inst) { result.push_back(inst); });
  801. return result;
  802. }
  803. void RemoveParameter(opt::IRContext* ir_context, uint32_t parameter_id) {
  804. auto* function = GetFunctionFromParameterId(ir_context, parameter_id);
  805. assert(function && "|parameter_id| is invalid");
  806. assert(!FunctionIsEntryPoint(ir_context, function->result_id()) &&
  807. "Can't remove parameter from an entry point function");
  808. function->RemoveParameter(parameter_id);
  809. // We've just removed parameters from the function and cleared their memory.
  810. // Make sure analyses have no dangling pointers.
  811. ir_context->InvalidateAnalysesExceptFor(
  812. opt::IRContext::Analysis::kAnalysisNone);
  813. }
  814. std::vector<opt::Instruction*> GetCallers(opt::IRContext* ir_context,
  815. uint32_t function_id) {
  816. assert(FindFunction(ir_context, function_id) &&
  817. "|function_id| is not a result id of a function");
  818. std::vector<opt::Instruction*> result;
  819. ir_context->get_def_use_mgr()->ForEachUser(
  820. function_id, [&result, function_id](opt::Instruction* inst) {
  821. if (inst->opcode() == SpvOpFunctionCall &&
  822. inst->GetSingleWordInOperand(0) == function_id) {
  823. result.push_back(inst);
  824. }
  825. });
  826. return result;
  827. }
  828. opt::Function* GetFunctionFromParameterId(opt::IRContext* ir_context,
  829. uint32_t param_id) {
  830. auto* param_inst = ir_context->get_def_use_mgr()->GetDef(param_id);
  831. assert(param_inst && "Parameter id is invalid");
  832. for (auto& function : *ir_context->module()) {
  833. if (InstructionIsFunctionParameter(param_inst, &function)) {
  834. return &function;
  835. }
  836. }
  837. return nullptr;
  838. }
  839. uint32_t UpdateFunctionType(opt::IRContext* ir_context, uint32_t function_id,
  840. uint32_t new_function_type_result_id,
  841. uint32_t return_type_id,
  842. const std::vector<uint32_t>& parameter_type_ids) {
  843. // Check some initial constraints.
  844. assert(ir_context->get_type_mgr()->GetType(return_type_id) &&
  845. "Return type is invalid");
  846. for (auto id : parameter_type_ids) {
  847. const auto* type = ir_context->get_type_mgr()->GetType(id);
  848. (void)type; // Make compilers happy in release mode.
  849. // Parameters can't be OpTypeVoid.
  850. assert(type && !type->AsVoid() && "Parameter has invalid type");
  851. }
  852. auto* function = FindFunction(ir_context, function_id);
  853. assert(function && "|function_id| is invalid");
  854. auto* old_function_type = GetFunctionType(ir_context, function);
  855. assert(old_function_type && "Function has invalid type");
  856. std::vector<uint32_t> operand_ids = {return_type_id};
  857. operand_ids.insert(operand_ids.end(), parameter_type_ids.begin(),
  858. parameter_type_ids.end());
  859. // A trivial case - we change nothing.
  860. if (FindFunctionType(ir_context, operand_ids) ==
  861. old_function_type->result_id()) {
  862. return old_function_type->result_id();
  863. }
  864. if (ir_context->get_def_use_mgr()->NumUsers(old_function_type) == 1 &&
  865. FindFunctionType(ir_context, operand_ids) == 0) {
  866. // We can change |old_function_type| only if it's used once in the module
  867. // and we are certain we won't create a duplicate as a result of the change.
  868. // Update |old_function_type| in-place.
  869. opt::Instruction::OperandList operands;
  870. for (auto id : operand_ids) {
  871. operands.push_back({SPV_OPERAND_TYPE_ID, {id}});
  872. }
  873. old_function_type->SetInOperands(std::move(operands));
  874. // |operands| may depend on result ids defined below the |old_function_type|
  875. // in the module.
  876. old_function_type->RemoveFromList();
  877. ir_context->AddType(std::unique_ptr<opt::Instruction>(old_function_type));
  878. return old_function_type->result_id();
  879. } else {
  880. // We can't modify the |old_function_type| so we have to either use an
  881. // existing one or create a new one.
  882. auto type_id = FindOrCreateFunctionType(
  883. ir_context, new_function_type_result_id, operand_ids);
  884. assert(type_id != old_function_type->result_id() &&
  885. "We should've handled this case above");
  886. function->DefInst().SetInOperand(1, {type_id});
  887. // DefUseManager hasn't been updated yet, so if the following condition is
  888. // true, then |old_function_type| will have no users when this function
  889. // returns. We might as well remove it.
  890. if (ir_context->get_def_use_mgr()->NumUsers(old_function_type) == 1) {
  891. ir_context->KillInst(old_function_type);
  892. }
  893. return type_id;
  894. }
  895. }
  896. void AddFunctionType(opt::IRContext* ir_context, uint32_t result_id,
  897. const std::vector<uint32_t>& type_ids) {
  898. assert(result_id != 0 && "Result id can't be 0");
  899. assert(!type_ids.empty() &&
  900. "OpTypeFunction always has at least one operand - function's return "
  901. "type");
  902. assert(IsNonFunctionTypeId(ir_context, type_ids[0]) &&
  903. "Return type must not be a function");
  904. for (size_t i = 1; i < type_ids.size(); ++i) {
  905. const auto* param_type = ir_context->get_type_mgr()->GetType(type_ids[i]);
  906. (void)param_type; // Make compiler happy in release mode.
  907. assert(param_type && !param_type->AsVoid() && !param_type->AsFunction() &&
  908. "Function parameter can't have a function or void type");
  909. }
  910. opt::Instruction::OperandList operands;
  911. operands.reserve(type_ids.size());
  912. for (auto id : type_ids) {
  913. operands.push_back({SPV_OPERAND_TYPE_ID, {id}});
  914. }
  915. ir_context->AddType(MakeUnique<opt::Instruction>(
  916. ir_context, SpvOpTypeFunction, 0, result_id, std::move(operands)));
  917. UpdateModuleIdBound(ir_context, result_id);
  918. }
  919. uint32_t FindOrCreateFunctionType(opt::IRContext* ir_context,
  920. uint32_t result_id,
  921. const std::vector<uint32_t>& type_ids) {
  922. if (auto existing_id = FindFunctionType(ir_context, type_ids)) {
  923. return existing_id;
  924. }
  925. AddFunctionType(ir_context, result_id, type_ids);
  926. return result_id;
  927. }
  928. uint32_t MaybeGetIntegerType(opt::IRContext* ir_context, uint32_t width,
  929. bool is_signed) {
  930. opt::analysis::Integer type(width, is_signed);
  931. return ir_context->get_type_mgr()->GetId(&type);
  932. }
  933. uint32_t MaybeGetFloatType(opt::IRContext* ir_context, uint32_t width) {
  934. opt::analysis::Float type(width);
  935. return ir_context->get_type_mgr()->GetId(&type);
  936. }
  937. uint32_t MaybeGetBoolType(opt::IRContext* ir_context) {
  938. opt::analysis::Bool type;
  939. return ir_context->get_type_mgr()->GetId(&type);
  940. }
  941. uint32_t MaybeGetVectorType(opt::IRContext* ir_context,
  942. uint32_t component_type_id,
  943. uint32_t element_count) {
  944. const auto* component_type =
  945. ir_context->get_type_mgr()->GetType(component_type_id);
  946. assert(component_type &&
  947. (component_type->AsInteger() || component_type->AsFloat() ||
  948. component_type->AsBool()) &&
  949. "|component_type_id| is invalid");
  950. assert(element_count >= 2 && element_count <= 4 &&
  951. "Precondition: component count must be in range [2, 4].");
  952. opt::analysis::Vector type(component_type, element_count);
  953. return ir_context->get_type_mgr()->GetId(&type);
  954. }
  955. uint32_t MaybeGetStructType(opt::IRContext* ir_context,
  956. const std::vector<uint32_t>& component_type_ids) {
  957. for (auto& type_or_value : ir_context->types_values()) {
  958. if (type_or_value.opcode() != SpvOpTypeStruct ||
  959. type_or_value.NumInOperands() !=
  960. static_cast<uint32_t>(component_type_ids.size())) {
  961. continue;
  962. }
  963. bool all_components_match = true;
  964. for (uint32_t i = 0; i < component_type_ids.size(); i++) {
  965. if (type_or_value.GetSingleWordInOperand(i) != component_type_ids[i]) {
  966. all_components_match = false;
  967. break;
  968. }
  969. }
  970. if (all_components_match) {
  971. return type_or_value.result_id();
  972. }
  973. }
  974. return 0;
  975. }
  976. uint32_t MaybeGetVoidType(opt::IRContext* ir_context) {
  977. opt::analysis::Void type;
  978. return ir_context->get_type_mgr()->GetId(&type);
  979. }
  980. uint32_t MaybeGetZeroConstant(
  981. opt::IRContext* ir_context,
  982. const TransformationContext& transformation_context,
  983. uint32_t scalar_or_composite_type_id, bool is_irrelevant) {
  984. const auto* type_inst =
  985. ir_context->get_def_use_mgr()->GetDef(scalar_or_composite_type_id);
  986. assert(type_inst && "|scalar_or_composite_type_id| is invalid");
  987. switch (type_inst->opcode()) {
  988. case SpvOpTypeBool:
  989. return MaybeGetBoolConstant(ir_context, transformation_context, false,
  990. is_irrelevant);
  991. case SpvOpTypeFloat:
  992. case SpvOpTypeInt: {
  993. const auto width = type_inst->GetSingleWordInOperand(0);
  994. std::vector<uint32_t> words = {0};
  995. if (width > 32) {
  996. words.push_back(0);
  997. }
  998. return MaybeGetScalarConstant(ir_context, transformation_context, words,
  999. scalar_or_composite_type_id, is_irrelevant);
  1000. }
  1001. case SpvOpTypeStruct: {
  1002. std::vector<uint32_t> component_ids;
  1003. for (uint32_t i = 0; i < type_inst->NumInOperands(); ++i) {
  1004. const auto component_type_id = type_inst->GetSingleWordInOperand(i);
  1005. auto component_id =
  1006. MaybeGetZeroConstant(ir_context, transformation_context,
  1007. component_type_id, is_irrelevant);
  1008. if (component_id == 0 && is_irrelevant) {
  1009. // Irrelevant constants can use either relevant or irrelevant
  1010. // constituents.
  1011. component_id = MaybeGetZeroConstant(
  1012. ir_context, transformation_context, component_type_id, false);
  1013. }
  1014. if (component_id == 0) {
  1015. return 0;
  1016. }
  1017. component_ids.push_back(component_id);
  1018. }
  1019. return MaybeGetCompositeConstant(
  1020. ir_context, transformation_context, component_ids,
  1021. scalar_or_composite_type_id, is_irrelevant);
  1022. }
  1023. case SpvOpTypeMatrix:
  1024. case SpvOpTypeVector: {
  1025. const auto component_type_id = type_inst->GetSingleWordInOperand(0);
  1026. auto component_id = MaybeGetZeroConstant(
  1027. ir_context, transformation_context, component_type_id, is_irrelevant);
  1028. if (component_id == 0 && is_irrelevant) {
  1029. // Irrelevant constants can use either relevant or irrelevant
  1030. // constituents.
  1031. component_id = MaybeGetZeroConstant(ir_context, transformation_context,
  1032. component_type_id, false);
  1033. }
  1034. if (component_id == 0) {
  1035. return 0;
  1036. }
  1037. const auto component_count = type_inst->GetSingleWordInOperand(1);
  1038. return MaybeGetCompositeConstant(
  1039. ir_context, transformation_context,
  1040. std::vector<uint32_t>(component_count, component_id),
  1041. scalar_or_composite_type_id, is_irrelevant);
  1042. }
  1043. case SpvOpTypeArray: {
  1044. const auto component_type_id = type_inst->GetSingleWordInOperand(0);
  1045. auto component_id = MaybeGetZeroConstant(
  1046. ir_context, transformation_context, component_type_id, is_irrelevant);
  1047. if (component_id == 0 && is_irrelevant) {
  1048. // Irrelevant constants can use either relevant or irrelevant
  1049. // constituents.
  1050. component_id = MaybeGetZeroConstant(ir_context, transformation_context,
  1051. component_type_id, false);
  1052. }
  1053. if (component_id == 0) {
  1054. return 0;
  1055. }
  1056. return MaybeGetCompositeConstant(
  1057. ir_context, transformation_context,
  1058. std::vector<uint32_t>(GetArraySize(*type_inst, ir_context),
  1059. component_id),
  1060. scalar_or_composite_type_id, is_irrelevant);
  1061. }
  1062. default:
  1063. assert(false && "Type is not supported");
  1064. return 0;
  1065. }
  1066. }
  1067. bool CanCreateConstant(opt::IRContext* ir_context, uint32_t type_id) {
  1068. opt::Instruction* type_instr = ir_context->get_def_use_mgr()->GetDef(type_id);
  1069. assert(type_instr != nullptr && "The type must exist.");
  1070. assert(spvOpcodeGeneratesType(type_instr->opcode()) &&
  1071. "A type-generating opcode was expected.");
  1072. switch (type_instr->opcode()) {
  1073. case SpvOpTypeBool:
  1074. case SpvOpTypeInt:
  1075. case SpvOpTypeFloat:
  1076. case SpvOpTypeMatrix:
  1077. case SpvOpTypeVector:
  1078. return true;
  1079. case SpvOpTypeArray:
  1080. return CanCreateConstant(ir_context,
  1081. type_instr->GetSingleWordInOperand(0));
  1082. case SpvOpTypeStruct:
  1083. if (HasBlockOrBufferBlockDecoration(ir_context, type_id)) {
  1084. return false;
  1085. }
  1086. for (uint32_t index = 0; index < type_instr->NumInOperands(); index++) {
  1087. if (!CanCreateConstant(ir_context,
  1088. type_instr->GetSingleWordInOperand(index))) {
  1089. return false;
  1090. }
  1091. }
  1092. return true;
  1093. default:
  1094. return false;
  1095. }
  1096. }
  1097. uint32_t MaybeGetScalarConstant(
  1098. opt::IRContext* ir_context,
  1099. const TransformationContext& transformation_context,
  1100. const std::vector<uint32_t>& words, uint32_t scalar_type_id,
  1101. bool is_irrelevant) {
  1102. const auto* type = ir_context->get_type_mgr()->GetType(scalar_type_id);
  1103. assert(type && "|scalar_type_id| is invalid");
  1104. if (const auto* int_type = type->AsInteger()) {
  1105. return MaybeGetIntegerConstant(ir_context, transformation_context, words,
  1106. int_type->width(), int_type->IsSigned(),
  1107. is_irrelevant);
  1108. } else if (const auto* float_type = type->AsFloat()) {
  1109. return MaybeGetFloatConstant(ir_context, transformation_context, words,
  1110. float_type->width(), is_irrelevant);
  1111. } else {
  1112. assert(type->AsBool() && words.size() == 1 &&
  1113. "|scalar_type_id| doesn't represent a scalar type");
  1114. return MaybeGetBoolConstant(ir_context, transformation_context, words[0],
  1115. is_irrelevant);
  1116. }
  1117. }
  1118. uint32_t MaybeGetCompositeConstant(
  1119. opt::IRContext* ir_context,
  1120. const TransformationContext& transformation_context,
  1121. const std::vector<uint32_t>& component_ids, uint32_t composite_type_id,
  1122. bool is_irrelevant) {
  1123. const auto* type = ir_context->get_type_mgr()->GetType(composite_type_id);
  1124. (void)type; // Make compilers happy in release mode.
  1125. assert(IsCompositeType(type) && "|composite_type_id| is invalid");
  1126. for (const auto& inst : ir_context->types_values()) {
  1127. if (inst.opcode() == SpvOpConstantComposite &&
  1128. inst.type_id() == composite_type_id &&
  1129. transformation_context.GetFactManager()->IdIsIrrelevant(
  1130. inst.result_id()) == is_irrelevant &&
  1131. inst.NumInOperands() == component_ids.size()) {
  1132. bool is_match = true;
  1133. for (uint32_t i = 0; i < inst.NumInOperands(); ++i) {
  1134. if (inst.GetSingleWordInOperand(i) != component_ids[i]) {
  1135. is_match = false;
  1136. break;
  1137. }
  1138. }
  1139. if (is_match) {
  1140. return inst.result_id();
  1141. }
  1142. }
  1143. }
  1144. return 0;
  1145. }
  1146. uint32_t MaybeGetIntegerConstant(
  1147. opt::IRContext* ir_context,
  1148. const TransformationContext& transformation_context,
  1149. const std::vector<uint32_t>& words, uint32_t width, bool is_signed,
  1150. bool is_irrelevant) {
  1151. if (auto type_id = MaybeGetIntegerType(ir_context, width, is_signed)) {
  1152. return MaybeGetOpConstant(ir_context, transformation_context, words,
  1153. type_id, is_irrelevant);
  1154. }
  1155. return 0;
  1156. }
  1157. uint32_t MaybeGetIntegerConstantFromValueAndType(opt::IRContext* ir_context,
  1158. uint32_t value,
  1159. uint32_t int_type_id) {
  1160. auto int_type_inst = ir_context->get_def_use_mgr()->GetDef(int_type_id);
  1161. assert(int_type_inst && "The given type id must exist.");
  1162. auto int_type = ir_context->get_type_mgr()
  1163. ->GetType(int_type_inst->result_id())
  1164. ->AsInteger();
  1165. assert(int_type && int_type->width() == 32 &&
  1166. "The given type id must correspond to an 32-bit integer type.");
  1167. opt::analysis::IntConstant constant(int_type, {value});
  1168. // Check that the constant exists in the module.
  1169. if (!ir_context->get_constant_mgr()->FindConstant(&constant)) {
  1170. return 0;
  1171. }
  1172. return ir_context->get_constant_mgr()
  1173. ->GetDefiningInstruction(&constant)
  1174. ->result_id();
  1175. }
  1176. uint32_t MaybeGetFloatConstant(
  1177. opt::IRContext* ir_context,
  1178. const TransformationContext& transformation_context,
  1179. const std::vector<uint32_t>& words, uint32_t width, bool is_irrelevant) {
  1180. if (auto type_id = MaybeGetFloatType(ir_context, width)) {
  1181. return MaybeGetOpConstant(ir_context, transformation_context, words,
  1182. type_id, is_irrelevant);
  1183. }
  1184. return 0;
  1185. }
  1186. uint32_t MaybeGetBoolConstant(
  1187. opt::IRContext* ir_context,
  1188. const TransformationContext& transformation_context, bool value,
  1189. bool is_irrelevant) {
  1190. if (auto type_id = MaybeGetBoolType(ir_context)) {
  1191. for (const auto& inst : ir_context->types_values()) {
  1192. if (inst.opcode() == (value ? SpvOpConstantTrue : SpvOpConstantFalse) &&
  1193. inst.type_id() == type_id &&
  1194. transformation_context.GetFactManager()->IdIsIrrelevant(
  1195. inst.result_id()) == is_irrelevant) {
  1196. return inst.result_id();
  1197. }
  1198. }
  1199. }
  1200. return 0;
  1201. }
  1202. void AddIntegerType(opt::IRContext* ir_context, uint32_t result_id,
  1203. uint32_t width, bool is_signed) {
  1204. ir_context->module()->AddType(MakeUnique<opt::Instruction>(
  1205. ir_context, SpvOpTypeInt, 0, result_id,
  1206. opt::Instruction::OperandList{
  1207. {SPV_OPERAND_TYPE_LITERAL_INTEGER, {width}},
  1208. {SPV_OPERAND_TYPE_LITERAL_INTEGER, {is_signed ? 1u : 0u}}}));
  1209. UpdateModuleIdBound(ir_context, result_id);
  1210. }
  1211. void AddFloatType(opt::IRContext* ir_context, uint32_t result_id,
  1212. uint32_t width) {
  1213. ir_context->module()->AddType(MakeUnique<opt::Instruction>(
  1214. ir_context, SpvOpTypeFloat, 0, result_id,
  1215. opt::Instruction::OperandList{
  1216. {SPV_OPERAND_TYPE_LITERAL_INTEGER, {width}}}));
  1217. UpdateModuleIdBound(ir_context, result_id);
  1218. }
  1219. void AddVectorType(opt::IRContext* ir_context, uint32_t result_id,
  1220. uint32_t component_type_id, uint32_t element_count) {
  1221. const auto* component_type =
  1222. ir_context->get_type_mgr()->GetType(component_type_id);
  1223. (void)component_type; // Make compiler happy in release mode.
  1224. assert(component_type &&
  1225. (component_type->AsInteger() || component_type->AsFloat() ||
  1226. component_type->AsBool()) &&
  1227. "|component_type_id| is invalid");
  1228. assert(element_count >= 2 && element_count <= 4 &&
  1229. "Precondition: component count must be in range [2, 4].");
  1230. ir_context->module()->AddType(MakeUnique<opt::Instruction>(
  1231. ir_context, SpvOpTypeVector, 0, result_id,
  1232. opt::Instruction::OperandList{
  1233. {SPV_OPERAND_TYPE_ID, {component_type_id}},
  1234. {SPV_OPERAND_TYPE_LITERAL_INTEGER, {element_count}}}));
  1235. UpdateModuleIdBound(ir_context, result_id);
  1236. }
  1237. void AddStructType(opt::IRContext* ir_context, uint32_t result_id,
  1238. const std::vector<uint32_t>& component_type_ids) {
  1239. opt::Instruction::OperandList operands;
  1240. operands.reserve(component_type_ids.size());
  1241. for (auto type_id : component_type_ids) {
  1242. const auto* type = ir_context->get_type_mgr()->GetType(type_id);
  1243. (void)type; // Make compiler happy in release mode.
  1244. assert(type && !type->AsFunction() && "Component's type id is invalid");
  1245. if (type->AsStruct()) {
  1246. // From the spec for the BuiltIn decoration:
  1247. // - When applied to a structure-type member, that structure type cannot
  1248. // be contained as a member of another structure type.
  1249. assert(!MembersHaveBuiltInDecoration(ir_context, type_id) &&
  1250. "A member struct has BuiltIn members");
  1251. }
  1252. operands.push_back({SPV_OPERAND_TYPE_ID, {type_id}});
  1253. }
  1254. ir_context->AddType(MakeUnique<opt::Instruction>(
  1255. ir_context, SpvOpTypeStruct, 0, result_id, std::move(operands)));
  1256. UpdateModuleIdBound(ir_context, result_id);
  1257. }
  1258. std::vector<uint32_t> IntToWords(uint64_t value, uint32_t width,
  1259. bool is_signed) {
  1260. assert(width <= 64 && "The bit width should not be more than 64 bits");
  1261. // Sign-extend or zero-extend the last |width| bits of |value|, depending on
  1262. // |is_signed|.
  1263. if (is_signed) {
  1264. // Sign-extend by shifting left and then shifting right, interpreting the
  1265. // integer as signed.
  1266. value = static_cast<int64_t>(value << (64 - width)) >> (64 - width);
  1267. } else {
  1268. // Zero-extend by shifting left and then shifting right, interpreting the
  1269. // integer as unsigned.
  1270. value = (value << (64 - width)) >> (64 - width);
  1271. }
  1272. std::vector<uint32_t> result;
  1273. result.push_back(static_cast<uint32_t>(value));
  1274. if (width > 32) {
  1275. result.push_back(static_cast<uint32_t>(value >> 32));
  1276. }
  1277. return result;
  1278. }
  1279. bool TypesAreEqualUpToSign(opt::IRContext* ir_context, uint32_t type1_id,
  1280. uint32_t type2_id) {
  1281. if (type1_id == type2_id) {
  1282. return true;
  1283. }
  1284. auto type1 = ir_context->get_type_mgr()->GetType(type1_id);
  1285. auto type2 = ir_context->get_type_mgr()->GetType(type2_id);
  1286. // Integer scalar types must have the same width
  1287. if (type1->AsInteger() && type2->AsInteger()) {
  1288. return type1->AsInteger()->width() == type2->AsInteger()->width();
  1289. }
  1290. // Integer vector types must have the same number of components and their
  1291. // component types must be integers with the same width.
  1292. if (type1->AsVector() && type2->AsVector()) {
  1293. auto component_type1 = type1->AsVector()->element_type()->AsInteger();
  1294. auto component_type2 = type2->AsVector()->element_type()->AsInteger();
  1295. // Only check the component count and width if they are integer.
  1296. if (component_type1 && component_type2) {
  1297. return type1->AsVector()->element_count() ==
  1298. type2->AsVector()->element_count() &&
  1299. component_type1->width() == component_type2->width();
  1300. }
  1301. }
  1302. // In all other cases, the types cannot be considered equal.
  1303. return false;
  1304. }
  1305. std::map<uint32_t, uint32_t> RepeatedUInt32PairToMap(
  1306. const google::protobuf::RepeatedPtrField<protobufs::UInt32Pair>& data) {
  1307. std::map<uint32_t, uint32_t> result;
  1308. for (const auto& entry : data) {
  1309. result[entry.first()] = entry.second();
  1310. }
  1311. return result;
  1312. }
  1313. google::protobuf::RepeatedPtrField<protobufs::UInt32Pair>
  1314. MapToRepeatedUInt32Pair(const std::map<uint32_t, uint32_t>& data) {
  1315. google::protobuf::RepeatedPtrField<protobufs::UInt32Pair> result;
  1316. for (const auto& entry : data) {
  1317. protobufs::UInt32Pair pair;
  1318. pair.set_first(entry.first);
  1319. pair.set_second(entry.second);
  1320. *result.Add() = std::move(pair);
  1321. }
  1322. return result;
  1323. }
  1324. opt::Instruction* GetLastInsertBeforeInstruction(opt::IRContext* ir_context,
  1325. uint32_t block_id,
  1326. SpvOp opcode) {
  1327. // CFG::block uses std::map::at which throws an exception when |block_id| is
  1328. // invalid. The error message is unhelpful, though. Thus, we test that
  1329. // |block_id| is valid here.
  1330. const auto* label_inst = ir_context->get_def_use_mgr()->GetDef(block_id);
  1331. (void)label_inst; // Make compilers happy in release mode.
  1332. assert(label_inst && label_inst->opcode() == SpvOpLabel &&
  1333. "|block_id| is invalid");
  1334. auto* block = ir_context->cfg()->block(block_id);
  1335. auto it = block->rbegin();
  1336. assert(it != block->rend() && "Basic block can't be empty");
  1337. if (block->GetMergeInst()) {
  1338. ++it;
  1339. assert(it != block->rend() &&
  1340. "|block| must have at least two instructions:"
  1341. "terminator and a merge instruction");
  1342. }
  1343. return CanInsertOpcodeBeforeInstruction(opcode, &*it) ? &*it : nullptr;
  1344. }
  1345. bool IdUseCanBeReplaced(opt::IRContext* ir_context,
  1346. const TransformationContext& transformation_context,
  1347. opt::Instruction* use_instruction,
  1348. uint32_t use_in_operand_index) {
  1349. if (spvOpcodeIsAccessChain(use_instruction->opcode()) &&
  1350. use_in_operand_index > 0) {
  1351. // A replacement for an irrelevant index in OpAccessChain must be clamped
  1352. // first.
  1353. if (transformation_context.GetFactManager()->IdIsIrrelevant(
  1354. use_instruction->GetSingleWordInOperand(use_in_operand_index))) {
  1355. return false;
  1356. }
  1357. // This is an access chain index. If the (sub-)object being accessed by the
  1358. // given index has struct type then we cannot replace the use, as it needs
  1359. // to be an OpConstant.
  1360. // Get the top-level composite type that is being accessed.
  1361. auto object_being_accessed = ir_context->get_def_use_mgr()->GetDef(
  1362. use_instruction->GetSingleWordInOperand(0));
  1363. auto pointer_type =
  1364. ir_context->get_type_mgr()->GetType(object_being_accessed->type_id());
  1365. assert(pointer_type->AsPointer());
  1366. auto composite_type_being_accessed =
  1367. pointer_type->AsPointer()->pointee_type();
  1368. // Now walk the access chain, tracking the type of each sub-object of the
  1369. // composite that is traversed, until the index of interest is reached.
  1370. for (uint32_t index_in_operand = 1; index_in_operand < use_in_operand_index;
  1371. index_in_operand++) {
  1372. // For vectors, matrices and arrays, getting the type of the sub-object is
  1373. // trivial. For the struct case, the sub-object type is field-sensitive,
  1374. // and depends on the constant index that is used.
  1375. if (composite_type_being_accessed->AsVector()) {
  1376. composite_type_being_accessed =
  1377. composite_type_being_accessed->AsVector()->element_type();
  1378. } else if (composite_type_being_accessed->AsMatrix()) {
  1379. composite_type_being_accessed =
  1380. composite_type_being_accessed->AsMatrix()->element_type();
  1381. } else if (composite_type_being_accessed->AsArray()) {
  1382. composite_type_being_accessed =
  1383. composite_type_being_accessed->AsArray()->element_type();
  1384. } else if (composite_type_being_accessed->AsRuntimeArray()) {
  1385. composite_type_being_accessed =
  1386. composite_type_being_accessed->AsRuntimeArray()->element_type();
  1387. } else {
  1388. assert(composite_type_being_accessed->AsStruct());
  1389. auto constant_index_instruction = ir_context->get_def_use_mgr()->GetDef(
  1390. use_instruction->GetSingleWordInOperand(index_in_operand));
  1391. assert(constant_index_instruction->opcode() == SpvOpConstant);
  1392. uint32_t member_index =
  1393. constant_index_instruction->GetSingleWordInOperand(0);
  1394. composite_type_being_accessed =
  1395. composite_type_being_accessed->AsStruct()
  1396. ->element_types()[member_index];
  1397. }
  1398. }
  1399. // We have found the composite type being accessed by the index we are
  1400. // considering replacing. If it is a struct, then we cannot do the
  1401. // replacement as struct indices must be constants.
  1402. if (composite_type_being_accessed->AsStruct()) {
  1403. return false;
  1404. }
  1405. }
  1406. if (use_instruction->opcode() == SpvOpFunctionCall &&
  1407. use_in_operand_index > 0) {
  1408. // This is a function call argument. It is not allowed to have pointer
  1409. // type.
  1410. // Get the definition of the function being called.
  1411. auto function = ir_context->get_def_use_mgr()->GetDef(
  1412. use_instruction->GetSingleWordInOperand(0));
  1413. // From the function definition, get the function type.
  1414. auto function_type = ir_context->get_def_use_mgr()->GetDef(
  1415. function->GetSingleWordInOperand(1));
  1416. // OpTypeFunction's 0-th input operand is the function return type, and the
  1417. // function argument types follow. Because the arguments to OpFunctionCall
  1418. // start from input operand 1, we can use |use_in_operand_index| to get the
  1419. // type associated with this function argument.
  1420. auto parameter_type = ir_context->get_type_mgr()->GetType(
  1421. function_type->GetSingleWordInOperand(use_in_operand_index));
  1422. if (parameter_type->AsPointer()) {
  1423. return false;
  1424. }
  1425. }
  1426. if (use_instruction->opcode() == SpvOpImageTexelPointer &&
  1427. use_in_operand_index == 2) {
  1428. // The OpImageTexelPointer instruction has a Sample parameter that in some
  1429. // situations must be an id for the value 0. To guard against disrupting
  1430. // that requirement, we do not replace this argument to that instruction.
  1431. return false;
  1432. }
  1433. return true;
  1434. }
  1435. bool MembersHaveBuiltInDecoration(opt::IRContext* ir_context,
  1436. uint32_t struct_type_id) {
  1437. const auto* type_inst = ir_context->get_def_use_mgr()->GetDef(struct_type_id);
  1438. assert(type_inst && type_inst->opcode() == SpvOpTypeStruct &&
  1439. "|struct_type_id| is not a result id of an OpTypeStruct");
  1440. uint32_t builtin_count = 0;
  1441. ir_context->get_def_use_mgr()->ForEachUser(
  1442. type_inst,
  1443. [struct_type_id, &builtin_count](const opt::Instruction* user) {
  1444. if (user->opcode() == SpvOpMemberDecorate &&
  1445. user->GetSingleWordInOperand(0) == struct_type_id &&
  1446. static_cast<SpvDecoration>(user->GetSingleWordInOperand(2)) ==
  1447. SpvDecorationBuiltIn) {
  1448. ++builtin_count;
  1449. }
  1450. });
  1451. assert((builtin_count == 0 || builtin_count == type_inst->NumInOperands()) &&
  1452. "The module is invalid: either none or all of the members of "
  1453. "|struct_type_id| may be builtin");
  1454. return builtin_count != 0;
  1455. }
  1456. bool HasBlockOrBufferBlockDecoration(opt::IRContext* ir_context, uint32_t id) {
  1457. for (auto decoration : {SpvDecorationBlock, SpvDecorationBufferBlock}) {
  1458. if (!ir_context->get_decoration_mgr()->WhileEachDecoration(
  1459. id, decoration, [](const opt::Instruction & /*unused*/) -> bool {
  1460. return false;
  1461. })) {
  1462. return true;
  1463. }
  1464. }
  1465. return false;
  1466. }
  1467. bool SplittingBeforeInstructionSeparatesOpSampledImageDefinitionFromUse(
  1468. opt::BasicBlock* block_to_split, opt::Instruction* split_before) {
  1469. std::set<uint32_t> sampled_image_result_ids;
  1470. bool before_split = true;
  1471. // Check all the instructions in the block to split.
  1472. for (auto& instruction : *block_to_split) {
  1473. if (&instruction == &*split_before) {
  1474. before_split = false;
  1475. }
  1476. if (before_split) {
  1477. // If the instruction comes before the split and its opcode is
  1478. // OpSampledImage, record its result id.
  1479. if (instruction.opcode() == SpvOpSampledImage) {
  1480. sampled_image_result_ids.insert(instruction.result_id());
  1481. }
  1482. } else {
  1483. // If the instruction comes after the split, check if ids
  1484. // corresponding to OpSampledImage instructions defined before the split
  1485. // are used, and return true if they are.
  1486. if (!instruction.WhileEachInId(
  1487. [&sampled_image_result_ids](uint32_t* id) -> bool {
  1488. return !sampled_image_result_ids.count(*id);
  1489. })) {
  1490. return true;
  1491. }
  1492. }
  1493. }
  1494. // No usage that would be separated from the definition has been found.
  1495. return false;
  1496. }
  1497. bool InstructionHasNoSideEffects(const opt::Instruction& instruction) {
  1498. switch (instruction.opcode()) {
  1499. case SpvOpUndef:
  1500. case SpvOpAccessChain:
  1501. case SpvOpInBoundsAccessChain:
  1502. case SpvOpArrayLength:
  1503. case SpvOpVectorExtractDynamic:
  1504. case SpvOpVectorInsertDynamic:
  1505. case SpvOpVectorShuffle:
  1506. case SpvOpCompositeConstruct:
  1507. case SpvOpCompositeExtract:
  1508. case SpvOpCompositeInsert:
  1509. case SpvOpCopyObject:
  1510. case SpvOpTranspose:
  1511. case SpvOpConvertFToU:
  1512. case SpvOpConvertFToS:
  1513. case SpvOpConvertSToF:
  1514. case SpvOpConvertUToF:
  1515. case SpvOpUConvert:
  1516. case SpvOpSConvert:
  1517. case SpvOpFConvert:
  1518. case SpvOpQuantizeToF16:
  1519. case SpvOpSatConvertSToU:
  1520. case SpvOpSatConvertUToS:
  1521. case SpvOpBitcast:
  1522. case SpvOpSNegate:
  1523. case SpvOpFNegate:
  1524. case SpvOpIAdd:
  1525. case SpvOpFAdd:
  1526. case SpvOpISub:
  1527. case SpvOpFSub:
  1528. case SpvOpIMul:
  1529. case SpvOpFMul:
  1530. case SpvOpUDiv:
  1531. case SpvOpSDiv:
  1532. case SpvOpFDiv:
  1533. case SpvOpUMod:
  1534. case SpvOpSRem:
  1535. case SpvOpSMod:
  1536. case SpvOpFRem:
  1537. case SpvOpFMod:
  1538. case SpvOpVectorTimesScalar:
  1539. case SpvOpMatrixTimesScalar:
  1540. case SpvOpVectorTimesMatrix:
  1541. case SpvOpMatrixTimesVector:
  1542. case SpvOpMatrixTimesMatrix:
  1543. case SpvOpOuterProduct:
  1544. case SpvOpDot:
  1545. case SpvOpIAddCarry:
  1546. case SpvOpISubBorrow:
  1547. case SpvOpUMulExtended:
  1548. case SpvOpSMulExtended:
  1549. case SpvOpAny:
  1550. case SpvOpAll:
  1551. case SpvOpIsNan:
  1552. case SpvOpIsInf:
  1553. case SpvOpIsFinite:
  1554. case SpvOpIsNormal:
  1555. case SpvOpSignBitSet:
  1556. case SpvOpLessOrGreater:
  1557. case SpvOpOrdered:
  1558. case SpvOpUnordered:
  1559. case SpvOpLogicalEqual:
  1560. case SpvOpLogicalNotEqual:
  1561. case SpvOpLogicalOr:
  1562. case SpvOpLogicalAnd:
  1563. case SpvOpLogicalNot:
  1564. case SpvOpSelect:
  1565. case SpvOpIEqual:
  1566. case SpvOpINotEqual:
  1567. case SpvOpUGreaterThan:
  1568. case SpvOpSGreaterThan:
  1569. case SpvOpUGreaterThanEqual:
  1570. case SpvOpSGreaterThanEqual:
  1571. case SpvOpULessThan:
  1572. case SpvOpSLessThan:
  1573. case SpvOpULessThanEqual:
  1574. case SpvOpSLessThanEqual:
  1575. case SpvOpFOrdEqual:
  1576. case SpvOpFUnordEqual:
  1577. case SpvOpFOrdNotEqual:
  1578. case SpvOpFUnordNotEqual:
  1579. case SpvOpFOrdLessThan:
  1580. case SpvOpFUnordLessThan:
  1581. case SpvOpFOrdGreaterThan:
  1582. case SpvOpFUnordGreaterThan:
  1583. case SpvOpFOrdLessThanEqual:
  1584. case SpvOpFUnordLessThanEqual:
  1585. case SpvOpFOrdGreaterThanEqual:
  1586. case SpvOpFUnordGreaterThanEqual:
  1587. case SpvOpShiftRightLogical:
  1588. case SpvOpShiftRightArithmetic:
  1589. case SpvOpShiftLeftLogical:
  1590. case SpvOpBitwiseOr:
  1591. case SpvOpBitwiseXor:
  1592. case SpvOpBitwiseAnd:
  1593. case SpvOpNot:
  1594. case SpvOpBitFieldInsert:
  1595. case SpvOpBitFieldSExtract:
  1596. case SpvOpBitFieldUExtract:
  1597. case SpvOpBitReverse:
  1598. case SpvOpBitCount:
  1599. case SpvOpCopyLogical:
  1600. case SpvOpPhi:
  1601. case SpvOpPtrEqual:
  1602. case SpvOpPtrNotEqual:
  1603. return true;
  1604. default:
  1605. return false;
  1606. }
  1607. }
  1608. std::set<uint32_t> GetReachableReturnBlocks(opt::IRContext* ir_context,
  1609. uint32_t function_id) {
  1610. auto function = ir_context->GetFunction(function_id);
  1611. assert(function && "The function |function_id| must exist.");
  1612. std::set<uint32_t> result;
  1613. ir_context->cfg()->ForEachBlockInPostOrder(function->entry().get(),
  1614. [&result](opt::BasicBlock* block) {
  1615. if (block->IsReturn()) {
  1616. result.emplace(block->id());
  1617. }
  1618. });
  1619. return result;
  1620. }
  1621. } // namespace fuzzerutil
  1622. } // namespace fuzz
  1623. } // namespace spvtools