fuzzer_util.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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 "source/opt/build_module.h"
  16. namespace spvtools {
  17. namespace fuzz {
  18. namespace fuzzerutil {
  19. bool IsFreshId(opt::IRContext* context, uint32_t id) {
  20. return !context->get_def_use_mgr()->GetDef(id);
  21. }
  22. void UpdateModuleIdBound(opt::IRContext* context, uint32_t id) {
  23. // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/2541) consider the
  24. // case where the maximum id bound is reached.
  25. context->module()->SetIdBound(
  26. std::max(context->module()->id_bound(), id + 1));
  27. }
  28. opt::BasicBlock* MaybeFindBlock(opt::IRContext* context,
  29. uint32_t maybe_block_id) {
  30. auto inst = context->get_def_use_mgr()->GetDef(maybe_block_id);
  31. if (inst == nullptr) {
  32. // No instruction defining this id was found.
  33. return nullptr;
  34. }
  35. if (inst->opcode() != SpvOpLabel) {
  36. // The instruction defining the id is not a label, so it cannot be a block
  37. // id.
  38. return nullptr;
  39. }
  40. return context->cfg()->block(maybe_block_id);
  41. }
  42. bool PhiIdsOkForNewEdge(
  43. opt::IRContext* context, opt::BasicBlock* bb_from, opt::BasicBlock* bb_to,
  44. const google::protobuf::RepeatedField<google::protobuf::uint32>& phi_ids) {
  45. if (bb_from->IsSuccessor(bb_to)) {
  46. // There is already an edge from |from_block| to |to_block|, so there is
  47. // no need to extend OpPhi instructions. Do not allow phi ids to be
  48. // present. This might turn out to be too strict; perhaps it would be OK
  49. // just to ignore the ids in this case.
  50. return phi_ids.empty();
  51. }
  52. // The edge would add a previously non-existent edge from |from_block| to
  53. // |to_block|, so we go through the given phi ids and check that they exactly
  54. // match the OpPhi instructions in |to_block|.
  55. uint32_t phi_index = 0;
  56. // An explicit loop, rather than applying a lambda to each OpPhi in |bb_to|,
  57. // makes sense here because we need to increment |phi_index| for each OpPhi
  58. // instruction.
  59. for (auto& inst : *bb_to) {
  60. if (inst.opcode() != SpvOpPhi) {
  61. // The OpPhi instructions all occur at the start of the block; if we find
  62. // a non-OpPhi then we have seen them all.
  63. break;
  64. }
  65. if (phi_index == static_cast<uint32_t>(phi_ids.size())) {
  66. // Not enough phi ids have been provided to account for the OpPhi
  67. // instructions.
  68. return false;
  69. }
  70. // Look for an instruction defining the next phi id.
  71. opt::Instruction* phi_extension =
  72. context->get_def_use_mgr()->GetDef(phi_ids[phi_index]);
  73. if (!phi_extension) {
  74. // The id given to extend this OpPhi does not exist.
  75. return false;
  76. }
  77. if (phi_extension->type_id() != inst.type_id()) {
  78. // The instruction given to extend this OpPhi either does not have a type
  79. // or its type does not match that of the OpPhi.
  80. return false;
  81. }
  82. if (context->get_instr_block(phi_extension)) {
  83. // The instruction defining the phi id has an associated block (i.e., it
  84. // is not a global value). Check whether its definition dominates the
  85. // exit of |from_block|.
  86. auto dominator_analysis =
  87. context->GetDominatorAnalysis(bb_from->GetParent());
  88. if (!dominator_analysis->Dominates(phi_extension,
  89. bb_from->terminator())) {
  90. // The given id is no good as its definition does not dominate the exit
  91. // of |from_block|
  92. return false;
  93. }
  94. }
  95. phi_index++;
  96. }
  97. // We allow some of the ids provided for extending OpPhi instructions to be
  98. // unused. Their presence does no harm, and requiring a perfect match may
  99. // make transformations less likely to cleanly apply.
  100. return true;
  101. }
  102. uint32_t MaybeGetBoolConstantId(opt::IRContext* context, bool value) {
  103. opt::analysis::Bool bool_type;
  104. auto registered_bool_type =
  105. context->get_type_mgr()->GetRegisteredType(&bool_type);
  106. if (!registered_bool_type) {
  107. return 0;
  108. }
  109. opt::analysis::BoolConstant bool_constant(registered_bool_type->AsBool(),
  110. value);
  111. return context->get_constant_mgr()->FindDeclaredConstant(
  112. &bool_constant, context->get_type_mgr()->GetId(&bool_type));
  113. }
  114. void AddUnreachableEdgeAndUpdateOpPhis(
  115. opt::IRContext* context, opt::BasicBlock* bb_from, opt::BasicBlock* bb_to,
  116. bool condition_value,
  117. const google::protobuf::RepeatedField<google::protobuf::uint32>& phi_ids) {
  118. assert(PhiIdsOkForNewEdge(context, bb_from, bb_to, phi_ids) &&
  119. "Precondition on phi_ids is not satisfied");
  120. assert(bb_from->terminator()->opcode() == SpvOpBranch &&
  121. "Precondition on terminator of bb_from is not satisfied");
  122. // Get the id of the boolean constant to be used as the condition.
  123. uint32_t bool_id = MaybeGetBoolConstantId(context, condition_value);
  124. assert(
  125. bool_id &&
  126. "Precondition that condition value must be available is not satisfied");
  127. const bool from_to_edge_already_exists = bb_from->IsSuccessor(bb_to);
  128. auto successor = bb_from->terminator()->GetSingleWordInOperand(0);
  129. // Add the dead branch, by turning OpBranch into OpBranchConditional, and
  130. // ordering the targets depending on whether the given boolean corresponds to
  131. // true or false.
  132. bb_from->terminator()->SetOpcode(SpvOpBranchConditional);
  133. bb_from->terminator()->SetInOperands(
  134. {{SPV_OPERAND_TYPE_ID, {bool_id}},
  135. {SPV_OPERAND_TYPE_ID, {condition_value ? successor : bb_to->id()}},
  136. {SPV_OPERAND_TYPE_ID, {condition_value ? bb_to->id() : successor}}});
  137. // Update OpPhi instructions in the target block if this branch adds a
  138. // previously non-existent edge from source to target.
  139. if (!from_to_edge_already_exists) {
  140. uint32_t phi_index = 0;
  141. for (auto& inst : *bb_to) {
  142. if (inst.opcode() != SpvOpPhi) {
  143. break;
  144. }
  145. assert(phi_index < static_cast<uint32_t>(phi_ids.size()) &&
  146. "There should be at least one phi id per OpPhi instruction.");
  147. inst.AddOperand({SPV_OPERAND_TYPE_ID, {phi_ids[phi_index]}});
  148. inst.AddOperand({SPV_OPERAND_TYPE_ID, {bb_from->id()}});
  149. phi_index++;
  150. }
  151. }
  152. }
  153. bool BlockIsInLoopContinueConstruct(opt::IRContext* context, uint32_t block_id,
  154. uint32_t maybe_loop_header_id) {
  155. // We deem a block to be part of a loop's continue construct if the loop's
  156. // continue target dominates the block.
  157. auto containing_construct_block = context->cfg()->block(maybe_loop_header_id);
  158. if (containing_construct_block->IsLoopHeader()) {
  159. auto continue_target = containing_construct_block->ContinueBlockId();
  160. if (context->GetDominatorAnalysis(containing_construct_block->GetParent())
  161. ->Dominates(continue_target, block_id)) {
  162. return true;
  163. }
  164. }
  165. return false;
  166. }
  167. opt::BasicBlock::iterator GetIteratorForInstruction(
  168. opt::BasicBlock* block, const opt::Instruction* inst) {
  169. for (auto inst_it = block->begin(); inst_it != block->end(); ++inst_it) {
  170. if (inst == &*inst_it) {
  171. return inst_it;
  172. }
  173. }
  174. return block->end();
  175. }
  176. bool BlockIsReachableInItsFunction(opt::IRContext* context,
  177. opt::BasicBlock* bb) {
  178. auto enclosing_function = bb->GetParent();
  179. return context->GetDominatorAnalysis(enclosing_function)
  180. ->Dominates(enclosing_function->entry().get(), bb);
  181. }
  182. bool CanInsertOpcodeBeforeInstruction(
  183. SpvOp opcode, const opt::BasicBlock::iterator& instruction_in_block) {
  184. if (instruction_in_block->PreviousNode() &&
  185. (instruction_in_block->PreviousNode()->opcode() == SpvOpLoopMerge ||
  186. instruction_in_block->PreviousNode()->opcode() == SpvOpSelectionMerge)) {
  187. // We cannot insert directly after a merge instruction.
  188. return false;
  189. }
  190. if (opcode != SpvOpVariable &&
  191. instruction_in_block->opcode() == SpvOpVariable) {
  192. // We cannot insert a non-OpVariable instruction directly before a
  193. // variable; variables in a function must be contiguous in the entry block.
  194. return false;
  195. }
  196. // We cannot insert a non-OpPhi instruction directly before an OpPhi, because
  197. // OpPhi instructions need to be contiguous at the start of a block.
  198. return opcode == SpvOpPhi || instruction_in_block->opcode() != SpvOpPhi;
  199. }
  200. bool CanMakeSynonymOf(opt::IRContext* ir_context, opt::Instruction* inst) {
  201. if (!inst->HasResultId()) {
  202. // We can only make a synonym of an instruction that generates an id.
  203. return false;
  204. }
  205. if (!inst->type_id()) {
  206. // We can only make a synonym of an instruction that has a type.
  207. return false;
  208. }
  209. auto type_inst = ir_context->get_def_use_mgr()->GetDef(inst->type_id());
  210. if (type_inst->opcode() == SpvOpTypePointer) {
  211. switch (inst->opcode()) {
  212. case SpvOpConstantNull:
  213. case SpvOpUndef:
  214. // We disallow making synonyms of null or undefined pointers. This is
  215. // to provide the property that if the original shader exhibited no bad
  216. // pointer accesses, the transformed shader will not either.
  217. return false;
  218. default:
  219. break;
  220. }
  221. }
  222. // We do not make synonyms of objects that have decorations: if the synonym is
  223. // not decorated analogously, using the original object vs. its synonymous
  224. // form may not be equivalent.
  225. return ir_context->get_decoration_mgr()
  226. ->GetDecorationsFor(inst->result_id(), true)
  227. .empty();
  228. }
  229. bool IsCompositeType(const opt::analysis::Type* type) {
  230. return type && (type->AsArray() || type->AsMatrix() || type->AsStruct() ||
  231. type->AsVector());
  232. }
  233. std::vector<uint32_t> RepeatedFieldToVector(
  234. const google::protobuf::RepeatedField<uint32_t>& repeated_field) {
  235. std::vector<uint32_t> result;
  236. for (auto i : repeated_field) {
  237. result.push_back(i);
  238. }
  239. return result;
  240. }
  241. uint32_t WalkOneCompositeTypeIndex(opt::IRContext* context,
  242. uint32_t base_object_type_id,
  243. uint32_t index) {
  244. auto should_be_composite_type =
  245. context->get_def_use_mgr()->GetDef(base_object_type_id);
  246. assert(should_be_composite_type && "The type should exist.");
  247. switch (should_be_composite_type->opcode()) {
  248. case SpvOpTypeArray: {
  249. auto array_length = GetArraySize(*should_be_composite_type, context);
  250. if (array_length == 0 || index >= array_length) {
  251. return 0;
  252. }
  253. return should_be_composite_type->GetSingleWordInOperand(0);
  254. }
  255. case SpvOpTypeMatrix:
  256. case SpvOpTypeVector: {
  257. auto count = should_be_composite_type->GetSingleWordInOperand(1);
  258. if (index >= count) {
  259. return 0;
  260. }
  261. return should_be_composite_type->GetSingleWordInOperand(0);
  262. }
  263. case SpvOpTypeStruct: {
  264. if (index >= GetNumberOfStructMembers(*should_be_composite_type)) {
  265. return 0;
  266. }
  267. return should_be_composite_type->GetSingleWordInOperand(index);
  268. }
  269. default:
  270. return 0;
  271. }
  272. }
  273. uint32_t WalkCompositeTypeIndices(
  274. opt::IRContext* context, uint32_t base_object_type_id,
  275. const google::protobuf::RepeatedField<google::protobuf::uint32>& indices) {
  276. uint32_t sub_object_type_id = base_object_type_id;
  277. for (auto index : indices) {
  278. sub_object_type_id =
  279. WalkOneCompositeTypeIndex(context, sub_object_type_id, index);
  280. if (!sub_object_type_id) {
  281. return 0;
  282. }
  283. }
  284. return sub_object_type_id;
  285. }
  286. uint32_t GetNumberOfStructMembers(
  287. const opt::Instruction& struct_type_instruction) {
  288. assert(struct_type_instruction.opcode() == SpvOpTypeStruct &&
  289. "An OpTypeStruct instruction is required here.");
  290. return struct_type_instruction.NumInOperands();
  291. }
  292. uint32_t GetArraySize(const opt::Instruction& array_type_instruction,
  293. opt::IRContext* context) {
  294. auto array_length_constant =
  295. context->get_constant_mgr()
  296. ->GetConstantFromInst(context->get_def_use_mgr()->GetDef(
  297. array_type_instruction.GetSingleWordInOperand(1)))
  298. ->AsIntConstant();
  299. if (array_length_constant->words().size() != 1) {
  300. return 0;
  301. }
  302. return array_length_constant->GetU32();
  303. }
  304. bool IsValid(opt::IRContext* context) {
  305. std::vector<uint32_t> binary;
  306. context->module()->ToBinary(&binary, false);
  307. SpirvTools tools(context->grammar().target_env());
  308. return tools.Validate(binary);
  309. }
  310. std::unique_ptr<opt::IRContext> CloneIRContext(opt::IRContext* context) {
  311. std::vector<uint32_t> binary;
  312. context->module()->ToBinary(&binary, false);
  313. return BuildModule(context->grammar().target_env(), nullptr, binary.data(),
  314. binary.size());
  315. }
  316. bool IsNonFunctionTypeId(opt::IRContext* ir_context, uint32_t id) {
  317. auto type = ir_context->get_type_mgr()->GetType(id);
  318. return type && !type->AsFunction();
  319. }
  320. bool IsMergeOrContinue(opt::IRContext* ir_context, uint32_t block_id) {
  321. bool result = false;
  322. ir_context->get_def_use_mgr()->WhileEachUse(
  323. block_id,
  324. [&result](const opt::Instruction* use_instruction,
  325. uint32_t /*unused*/) -> bool {
  326. switch (use_instruction->opcode()) {
  327. case SpvOpLoopMerge:
  328. case SpvOpSelectionMerge:
  329. result = true;
  330. return false;
  331. default:
  332. return true;
  333. }
  334. });
  335. return result;
  336. }
  337. uint32_t FindFunctionType(opt::IRContext* ir_context,
  338. const std::vector<uint32_t>& type_ids) {
  339. // Look through the existing types for a match.
  340. for (auto& type_or_value : ir_context->types_values()) {
  341. if (type_or_value.opcode() != SpvOpTypeFunction) {
  342. // We are only interested in function types.
  343. continue;
  344. }
  345. if (type_or_value.NumInOperands() != type_ids.size()) {
  346. // Not a match: different numbers of arguments.
  347. continue;
  348. }
  349. // Check whether the return type and argument types match.
  350. bool input_operands_match = true;
  351. for (uint32_t i = 0; i < type_or_value.NumInOperands(); i++) {
  352. if (type_ids[i] != type_or_value.GetSingleWordInOperand(i)) {
  353. input_operands_match = false;
  354. break;
  355. }
  356. }
  357. if (input_operands_match) {
  358. // Everything matches.
  359. return type_or_value.result_id();
  360. }
  361. }
  362. // No match was found.
  363. return 0;
  364. }
  365. opt::Instruction* GetFunctionType(opt::IRContext* context,
  366. const opt::Function* function) {
  367. uint32_t type_id = function->DefInst().GetSingleWordInOperand(1);
  368. return context->get_def_use_mgr()->GetDef(type_id);
  369. }
  370. opt::Function* FindFunction(opt::IRContext* ir_context, uint32_t function_id) {
  371. for (auto& function : *ir_context->module()) {
  372. if (function.result_id() == function_id) {
  373. return &function;
  374. }
  375. }
  376. return nullptr;
  377. }
  378. bool FunctionIsEntryPoint(opt::IRContext* context, uint32_t function_id) {
  379. for (auto& entry_point : context->module()->entry_points()) {
  380. if (entry_point.GetSingleWordInOperand(1) == function_id) {
  381. return true;
  382. }
  383. }
  384. return false;
  385. }
  386. bool IdIsAvailableAtUse(opt::IRContext* context,
  387. opt::Instruction* use_instruction,
  388. uint32_t use_input_operand_index, uint32_t id) {
  389. auto defining_instruction = context->get_def_use_mgr()->GetDef(id);
  390. auto enclosing_function =
  391. context->get_instr_block(use_instruction)->GetParent();
  392. // If the id a function parameter, it needs to be associated with the
  393. // function containing the use.
  394. if (defining_instruction->opcode() == SpvOpFunctionParameter) {
  395. return InstructionIsFunctionParameter(defining_instruction,
  396. enclosing_function);
  397. }
  398. if (!context->get_instr_block(id)) {
  399. // The id must be at global scope.
  400. return true;
  401. }
  402. if (defining_instruction == use_instruction) {
  403. // It is not OK for a definition to use itself.
  404. return false;
  405. }
  406. auto dominator_analysis = context->GetDominatorAnalysis(enclosing_function);
  407. if (use_instruction->opcode() == SpvOpPhi) {
  408. // In the case where the use is an operand to OpPhi, it is actually the
  409. // *parent* block associated with the operand that must be dominated by
  410. // the synonym.
  411. auto parent_block =
  412. use_instruction->GetSingleWordInOperand(use_input_operand_index + 1);
  413. return dominator_analysis->Dominates(
  414. context->get_instr_block(defining_instruction)->id(), parent_block);
  415. }
  416. return dominator_analysis->Dominates(defining_instruction, use_instruction);
  417. }
  418. bool IdIsAvailableBeforeInstruction(opt::IRContext* context,
  419. opt::Instruction* instruction,
  420. uint32_t id) {
  421. auto defining_instruction = context->get_def_use_mgr()->GetDef(id);
  422. auto enclosing_function = context->get_instr_block(instruction)->GetParent();
  423. // If the id a function parameter, it needs to be associated with the
  424. // function containing the instruction.
  425. if (defining_instruction->opcode() == SpvOpFunctionParameter) {
  426. return InstructionIsFunctionParameter(defining_instruction,
  427. enclosing_function);
  428. }
  429. if (!context->get_instr_block(id)) {
  430. // The id is at global scope.
  431. return true;
  432. }
  433. if (defining_instruction == instruction) {
  434. // The instruction is not available right before its own definition.
  435. return false;
  436. }
  437. return context->GetDominatorAnalysis(enclosing_function)
  438. ->Dominates(defining_instruction, instruction);
  439. }
  440. bool InstructionIsFunctionParameter(opt::Instruction* instruction,
  441. opt::Function* function) {
  442. if (instruction->opcode() != SpvOpFunctionParameter) {
  443. return false;
  444. }
  445. bool found_parameter = false;
  446. function->ForEachParam(
  447. [instruction, &found_parameter](opt::Instruction* param) {
  448. if (param == instruction) {
  449. found_parameter = true;
  450. }
  451. });
  452. return found_parameter;
  453. }
  454. uint32_t GetTypeId(opt::IRContext* context, uint32_t result_id) {
  455. return context->get_def_use_mgr()->GetDef(result_id)->type_id();
  456. }
  457. uint32_t GetPointeeTypeIdFromPointerType(opt::Instruction* pointer_type_inst) {
  458. assert(pointer_type_inst && pointer_type_inst->opcode() == SpvOpTypePointer &&
  459. "Precondition: |pointer_type_inst| must be OpTypePointer.");
  460. return pointer_type_inst->GetSingleWordInOperand(1);
  461. }
  462. uint32_t GetPointeeTypeIdFromPointerType(opt::IRContext* context,
  463. uint32_t pointer_type_id) {
  464. return GetPointeeTypeIdFromPointerType(
  465. context->get_def_use_mgr()->GetDef(pointer_type_id));
  466. }
  467. SpvStorageClass GetStorageClassFromPointerType(
  468. opt::Instruction* pointer_type_inst) {
  469. assert(pointer_type_inst && pointer_type_inst->opcode() == SpvOpTypePointer &&
  470. "Precondition: |pointer_type_inst| must be OpTypePointer.");
  471. return static_cast<SpvStorageClass>(
  472. pointer_type_inst->GetSingleWordInOperand(0));
  473. }
  474. SpvStorageClass GetStorageClassFromPointerType(opt::IRContext* context,
  475. uint32_t pointer_type_id) {
  476. return GetStorageClassFromPointerType(
  477. context->get_def_use_mgr()->GetDef(pointer_type_id));
  478. }
  479. uint32_t MaybeGetPointerType(opt::IRContext* context, uint32_t pointee_type_id,
  480. SpvStorageClass storage_class) {
  481. for (auto& inst : context->types_values()) {
  482. switch (inst.opcode()) {
  483. case SpvOpTypePointer:
  484. if (inst.GetSingleWordInOperand(0) == storage_class &&
  485. inst.GetSingleWordInOperand(1) == pointee_type_id) {
  486. return inst.result_id();
  487. }
  488. break;
  489. default:
  490. break;
  491. }
  492. }
  493. return 0;
  494. }
  495. } // namespace fuzzerutil
  496. } // namespace fuzz
  497. } // namespace spvtools