fuzzer_pass.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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_pass.h"
  15. #include <set>
  16. #include "source/fuzz/fuzzer_util.h"
  17. #include "source/fuzz/instruction_descriptor.h"
  18. #include "source/fuzz/transformation_add_constant_boolean.h"
  19. #include "source/fuzz/transformation_add_constant_composite.h"
  20. #include "source/fuzz/transformation_add_constant_scalar.h"
  21. #include "source/fuzz/transformation_add_global_undef.h"
  22. #include "source/fuzz/transformation_add_type_boolean.h"
  23. #include "source/fuzz/transformation_add_type_float.h"
  24. #include "source/fuzz/transformation_add_type_function.h"
  25. #include "source/fuzz/transformation_add_type_int.h"
  26. #include "source/fuzz/transformation_add_type_matrix.h"
  27. #include "source/fuzz/transformation_add_type_pointer.h"
  28. #include "source/fuzz/transformation_add_type_struct.h"
  29. #include "source/fuzz/transformation_add_type_vector.h"
  30. namespace spvtools {
  31. namespace fuzz {
  32. FuzzerPass::FuzzerPass(opt::IRContext* ir_context,
  33. TransformationContext* transformation_context,
  34. FuzzerContext* fuzzer_context,
  35. protobufs::TransformationSequence* transformations)
  36. : ir_context_(ir_context),
  37. transformation_context_(transformation_context),
  38. fuzzer_context_(fuzzer_context),
  39. transformations_(transformations) {}
  40. FuzzerPass::~FuzzerPass() = default;
  41. std::vector<opt::Instruction*> FuzzerPass::FindAvailableInstructions(
  42. opt::Function* function, opt::BasicBlock* block,
  43. const opt::BasicBlock::iterator& inst_it,
  44. std::function<bool(opt::IRContext*, opt::Instruction*)>
  45. instruction_is_relevant) const {
  46. // TODO(afd) The following is (relatively) simple, but may end up being
  47. // prohibitively inefficient, as it walks the whole dominator tree for
  48. // every instruction that is considered.
  49. std::vector<opt::Instruction*> result;
  50. // Consider all global declarations
  51. for (auto& global : GetIRContext()->module()->types_values()) {
  52. if (instruction_is_relevant(GetIRContext(), &global)) {
  53. result.push_back(&global);
  54. }
  55. }
  56. // Consider all function parameters
  57. function->ForEachParam(
  58. [this, &instruction_is_relevant, &result](opt::Instruction* param) {
  59. if (instruction_is_relevant(GetIRContext(), param)) {
  60. result.push_back(param);
  61. }
  62. });
  63. // Consider all previous instructions in this block
  64. for (auto prev_inst_it = block->begin(); prev_inst_it != inst_it;
  65. ++prev_inst_it) {
  66. if (instruction_is_relevant(GetIRContext(), &*prev_inst_it)) {
  67. result.push_back(&*prev_inst_it);
  68. }
  69. }
  70. // Walk the dominator tree to consider all instructions from dominating
  71. // blocks
  72. auto dominator_analysis = GetIRContext()->GetDominatorAnalysis(function);
  73. for (auto next_dominator = dominator_analysis->ImmediateDominator(block);
  74. next_dominator != nullptr;
  75. next_dominator =
  76. dominator_analysis->ImmediateDominator(next_dominator)) {
  77. for (auto& dominating_inst : *next_dominator) {
  78. if (instruction_is_relevant(GetIRContext(), &dominating_inst)) {
  79. result.push_back(&dominating_inst);
  80. }
  81. }
  82. }
  83. return result;
  84. }
  85. void FuzzerPass::ForEachInstructionWithInstructionDescriptor(
  86. std::function<
  87. void(opt::Function* function, opt::BasicBlock* block,
  88. opt::BasicBlock::iterator inst_it,
  89. const protobufs::InstructionDescriptor& instruction_descriptor)>
  90. action) {
  91. // Consider every block in every function.
  92. for (auto& function : *GetIRContext()->module()) {
  93. for (auto& block : function) {
  94. // We now consider every instruction in the block, randomly deciding
  95. // whether to apply a transformation before it.
  96. // In order for transformations to insert new instructions, they need to
  97. // be able to identify the instruction to insert before. We describe an
  98. // instruction via its opcode, 'opc', a base instruction 'base' that has a
  99. // result id, and the number of instructions with opcode 'opc' that we
  100. // should skip when searching from 'base' for the desired instruction.
  101. // (An instruction that has a result id is represented by its own opcode,
  102. // itself as 'base', and a skip-count of 0.)
  103. std::vector<std::tuple<uint32_t, SpvOp, uint32_t>>
  104. base_opcode_skip_triples;
  105. // The initial base instruction is the block label.
  106. uint32_t base = block.id();
  107. // Counts the number of times we have seen each opcode since we reset the
  108. // base instruction.
  109. std::map<SpvOp, uint32_t> skip_count;
  110. // Consider every instruction in the block. The label is excluded: it is
  111. // only necessary to consider it as a base in case the first instruction
  112. // in the block does not have a result id.
  113. for (auto inst_it = block.begin(); inst_it != block.end(); ++inst_it) {
  114. if (inst_it->HasResultId()) {
  115. // In the case that the instruction has a result id, we use the
  116. // instruction as its own base, and clear the skip counts we have
  117. // collected.
  118. base = inst_it->result_id();
  119. skip_count.clear();
  120. }
  121. const SpvOp opcode = inst_it->opcode();
  122. // Invoke the provided function, which might apply a transformation.
  123. action(&function, &block, inst_it,
  124. MakeInstructionDescriptor(
  125. base, opcode,
  126. skip_count.count(opcode) ? skip_count.at(opcode) : 0));
  127. if (!inst_it->HasResultId()) {
  128. skip_count[opcode] =
  129. skip_count.count(opcode) ? skip_count.at(opcode) + 1 : 1;
  130. }
  131. }
  132. }
  133. }
  134. }
  135. uint32_t FuzzerPass::FindOrCreateBoolType() {
  136. opt::analysis::Bool bool_type;
  137. auto existing_id = GetIRContext()->get_type_mgr()->GetId(&bool_type);
  138. if (existing_id) {
  139. return existing_id;
  140. }
  141. auto result = GetFuzzerContext()->GetFreshId();
  142. ApplyTransformation(TransformationAddTypeBoolean(result));
  143. return result;
  144. }
  145. uint32_t FuzzerPass::FindOrCreateIntegerType(uint32_t width, bool is_signed) {
  146. if (auto existing_id =
  147. fuzzerutil::MaybeGetIntegerType(GetIRContext(), width, is_signed)) {
  148. return existing_id;
  149. }
  150. auto result = GetFuzzerContext()->GetFreshId();
  151. ApplyTransformation(TransformationAddTypeInt(result, width, is_signed));
  152. return result;
  153. }
  154. uint32_t FuzzerPass::FindOrCreateFloatType(uint32_t width) {
  155. if (auto existing_id = fuzzerutil::MaybeGetFloatType(GetIRContext(), width)) {
  156. return existing_id;
  157. }
  158. auto result = GetFuzzerContext()->GetFreshId();
  159. ApplyTransformation(TransformationAddTypeFloat(result, width));
  160. return result;
  161. }
  162. uint32_t FuzzerPass::FindOrCreateFunctionType(
  163. uint32_t return_type_id, const std::vector<uint32_t>& argument_id) {
  164. // FindFunctionType has a sigle argument for OpTypeFunction operands
  165. // so we will have to copy them all in this vector
  166. std::vector<uint32_t> type_ids(argument_id.size() + 1);
  167. type_ids[0] = return_type_id;
  168. std::copy(argument_id.begin(), argument_id.end(), type_ids.begin() + 1);
  169. // Check if type exists
  170. auto existing_id = fuzzerutil::FindFunctionType(GetIRContext(), type_ids);
  171. if (existing_id) {
  172. return existing_id;
  173. }
  174. auto result = GetFuzzerContext()->GetFreshId();
  175. ApplyTransformation(
  176. TransformationAddTypeFunction(result, return_type_id, argument_id));
  177. return result;
  178. }
  179. uint32_t FuzzerPass::FindOrCreateVectorType(uint32_t component_type_id,
  180. uint32_t component_count) {
  181. if (auto existing_id = fuzzerutil::MaybeGetVectorType(
  182. GetIRContext(), component_type_id, component_count)) {
  183. return existing_id;
  184. }
  185. auto result = GetFuzzerContext()->GetFreshId();
  186. ApplyTransformation(
  187. TransformationAddTypeVector(result, component_type_id, component_count));
  188. return result;
  189. }
  190. uint32_t FuzzerPass::FindOrCreateMatrixType(uint32_t column_count,
  191. uint32_t row_count) {
  192. assert(column_count >= 2 && column_count <= 4 &&
  193. "Precondition: column count must be in range [2, 4].");
  194. assert(row_count >= 2 && row_count <= 4 &&
  195. "Precondition: row count must be in range [2, 4].");
  196. uint32_t column_type_id =
  197. FindOrCreateVectorType(FindOrCreateFloatType(32), row_count);
  198. opt::analysis::Type* column_type =
  199. GetIRContext()->get_type_mgr()->GetType(column_type_id);
  200. opt::analysis::Matrix matrix_type(column_type, column_count);
  201. auto existing_id = GetIRContext()->get_type_mgr()->GetId(&matrix_type);
  202. if (existing_id) {
  203. return existing_id;
  204. }
  205. auto result = GetFuzzerContext()->GetFreshId();
  206. ApplyTransformation(
  207. TransformationAddTypeMatrix(result, column_type_id, column_count));
  208. return result;
  209. }
  210. uint32_t FuzzerPass::FindOrCreateStructType(
  211. const std::vector<uint32_t>& component_type_ids) {
  212. if (auto existing_id =
  213. fuzzerutil::MaybeGetStructType(GetIRContext(), component_type_ids)) {
  214. return existing_id;
  215. }
  216. auto new_id = GetFuzzerContext()->GetFreshId();
  217. ApplyTransformation(TransformationAddTypeStruct(new_id, component_type_ids));
  218. return new_id;
  219. }
  220. uint32_t FuzzerPass::FindOrCreatePointerType(uint32_t base_type_id,
  221. SpvStorageClass storage_class) {
  222. // We do not use the type manager here, due to problems related to isomorphic
  223. // but distinct structs not being regarded as different.
  224. auto existing_id = fuzzerutil::MaybeGetPointerType(
  225. GetIRContext(), base_type_id, storage_class);
  226. if (existing_id) {
  227. return existing_id;
  228. }
  229. auto result = GetFuzzerContext()->GetFreshId();
  230. ApplyTransformation(
  231. TransformationAddTypePointer(result, storage_class, base_type_id));
  232. return result;
  233. }
  234. uint32_t FuzzerPass::FindOrCreatePointerToIntegerType(
  235. uint32_t width, bool is_signed, SpvStorageClass storage_class) {
  236. return FindOrCreatePointerType(FindOrCreateIntegerType(width, is_signed),
  237. storage_class);
  238. }
  239. uint32_t FuzzerPass::FindOrCreateIntegerConstant(
  240. const std::vector<uint32_t>& words, uint32_t width, bool is_signed) {
  241. auto int_type_id = FindOrCreateIntegerType(width, is_signed);
  242. opt::analysis::IntConstant int_constant(
  243. GetIRContext()->get_type_mgr()->GetType(int_type_id)->AsInteger(), words);
  244. auto existing_constant =
  245. GetIRContext()->get_constant_mgr()->FindConstant(&int_constant);
  246. if (existing_constant) {
  247. return GetIRContext()
  248. ->get_constant_mgr()
  249. ->GetDefiningInstruction(existing_constant)
  250. ->result_id();
  251. }
  252. auto result = GetFuzzerContext()->GetFreshId();
  253. ApplyTransformation(
  254. TransformationAddConstantScalar(result, int_type_id, words));
  255. return result;
  256. }
  257. uint32_t FuzzerPass::FindOrCreateFloatConstant(
  258. const std::vector<uint32_t>& words, uint32_t width) {
  259. auto float_type_id = FindOrCreateFloatType(width);
  260. opt::analysis::FloatConstant float_constant(
  261. GetIRContext()->get_type_mgr()->GetType(float_type_id)->AsFloat(), words);
  262. auto existing_constant =
  263. GetIRContext()->get_constant_mgr()->FindConstant(&float_constant);
  264. if (existing_constant) {
  265. return GetIRContext()
  266. ->get_constant_mgr()
  267. ->GetDefiningInstruction(existing_constant)
  268. ->result_id();
  269. }
  270. auto result = GetFuzzerContext()->GetFreshId();
  271. ApplyTransformation(
  272. TransformationAddConstantScalar(result, float_type_id, words));
  273. return result;
  274. }
  275. uint32_t FuzzerPass::FindOrCreateBoolConstant(bool value) {
  276. auto bool_type_id = FindOrCreateBoolType();
  277. opt::analysis::BoolConstant bool_constant(
  278. GetIRContext()->get_type_mgr()->GetType(bool_type_id)->AsBool(), value);
  279. auto existing_constant =
  280. GetIRContext()->get_constant_mgr()->FindConstant(&bool_constant);
  281. if (existing_constant) {
  282. return GetIRContext()
  283. ->get_constant_mgr()
  284. ->GetDefiningInstruction(existing_constant)
  285. ->result_id();
  286. }
  287. auto result = GetFuzzerContext()->GetFreshId();
  288. ApplyTransformation(TransformationAddConstantBoolean(result, value));
  289. return result;
  290. }
  291. uint32_t FuzzerPass::FindOrCreateConstant(const std::vector<uint32_t>& words,
  292. uint32_t type_id) {
  293. assert(type_id && "Constant's type id can't be 0.");
  294. const auto* type = GetIRContext()->get_type_mgr()->GetType(type_id);
  295. assert(type && "Type does not exist.");
  296. if (type->AsBool()) {
  297. assert(words.size() == 1);
  298. return FindOrCreateBoolConstant(words[0]);
  299. } else if (const auto* integer = type->AsInteger()) {
  300. return FindOrCreateIntegerConstant(words, integer->width(),
  301. integer->IsSigned());
  302. } else if (const auto* floating = type->AsFloat()) {
  303. return FindOrCreateFloatConstant(words, floating->width());
  304. }
  305. // This assertion will fail in debug build but not in release build
  306. // so we return 0 to make compiler happy.
  307. assert(false && "Constant type is not supported");
  308. return 0;
  309. }
  310. uint32_t FuzzerPass::FindOrCreateGlobalUndef(uint32_t type_id) {
  311. for (auto& inst : GetIRContext()->types_values()) {
  312. if (inst.opcode() == SpvOpUndef && inst.type_id() == type_id) {
  313. return inst.result_id();
  314. }
  315. }
  316. auto result = GetFuzzerContext()->GetFreshId();
  317. ApplyTransformation(TransformationAddGlobalUndef(result, type_id));
  318. return result;
  319. }
  320. std::pair<std::vector<uint32_t>, std::map<uint32_t, std::vector<uint32_t>>>
  321. FuzzerPass::GetAvailableBasicTypesAndPointers(
  322. SpvStorageClass storage_class) const {
  323. // Records all of the basic types available in the module.
  324. std::set<uint32_t> basic_types;
  325. // For each basic type, records all the associated pointer types that target
  326. // the basic type and that have |storage_class| as their storage class.
  327. std::map<uint32_t, std::vector<uint32_t>> basic_type_to_pointers;
  328. for (auto& inst : GetIRContext()->types_values()) {
  329. // For each basic type that we come across, record type, and the fact that
  330. // we cannot yet have seen any pointers that use the basic type as its
  331. // pointee type.
  332. //
  333. // For pointer types with basic pointee types, associate the pointer type
  334. // with the basic type.
  335. switch (inst.opcode()) {
  336. case SpvOpTypeBool:
  337. case SpvOpTypeFloat:
  338. case SpvOpTypeInt:
  339. case SpvOpTypeMatrix:
  340. case SpvOpTypeVector:
  341. // These are all basic types.
  342. basic_types.insert(inst.result_id());
  343. basic_type_to_pointers.insert({inst.result_id(), {}});
  344. break;
  345. case SpvOpTypeArray:
  346. // An array type is basic if its base type is basic.
  347. if (basic_types.count(inst.GetSingleWordInOperand(0))) {
  348. basic_types.insert(inst.result_id());
  349. basic_type_to_pointers.insert({inst.result_id(), {}});
  350. }
  351. break;
  352. case SpvOpTypeStruct: {
  353. // A struct type is basic if all of its members are basic.
  354. bool all_members_are_basic_types = true;
  355. for (uint32_t i = 0; i < inst.NumInOperands(); i++) {
  356. if (!basic_types.count(inst.GetSingleWordInOperand(i))) {
  357. all_members_are_basic_types = false;
  358. break;
  359. }
  360. }
  361. if (all_members_are_basic_types) {
  362. basic_types.insert(inst.result_id());
  363. basic_type_to_pointers.insert({inst.result_id(), {}});
  364. }
  365. break;
  366. }
  367. case SpvOpTypePointer: {
  368. // We are interested in the pointer if its pointee type is basic and it
  369. // has the right storage class.
  370. auto pointee_type = inst.GetSingleWordInOperand(1);
  371. if (inst.GetSingleWordInOperand(0) == storage_class &&
  372. basic_types.count(pointee_type)) {
  373. // The pointer has the desired storage class, and its pointee type is
  374. // a basic type, so we are interested in it. Associate it with its
  375. // basic type.
  376. basic_type_to_pointers.at(pointee_type).push_back(inst.result_id());
  377. }
  378. break;
  379. }
  380. default:
  381. break;
  382. }
  383. }
  384. return {{basic_types.begin(), basic_types.end()}, basic_type_to_pointers};
  385. }
  386. uint32_t FuzzerPass::FindOrCreateZeroConstant(
  387. uint32_t scalar_or_composite_type_id) {
  388. auto type_instruction =
  389. GetIRContext()->get_def_use_mgr()->GetDef(scalar_or_composite_type_id);
  390. assert(type_instruction && "The type instruction must exist.");
  391. switch (type_instruction->opcode()) {
  392. case SpvOpTypeBool:
  393. return FindOrCreateBoolConstant(false);
  394. case SpvOpTypeFloat: {
  395. auto width = type_instruction->GetSingleWordInOperand(0);
  396. auto num_words = (width + 32 - 1) / 32;
  397. return FindOrCreateFloatConstant(std::vector<uint32_t>(num_words, 0),
  398. width);
  399. }
  400. case SpvOpTypeInt: {
  401. auto width = type_instruction->GetSingleWordInOperand(0);
  402. auto num_words = (width + 32 - 1) / 32;
  403. return FindOrCreateIntegerConstant(
  404. std::vector<uint32_t>(num_words, 0), width,
  405. type_instruction->GetSingleWordInOperand(1));
  406. }
  407. case SpvOpTypeArray: {
  408. return GetZeroConstantForHomogeneousComposite(
  409. *type_instruction, type_instruction->GetSingleWordInOperand(0),
  410. fuzzerutil::GetArraySize(*type_instruction, GetIRContext()));
  411. }
  412. case SpvOpTypeMatrix:
  413. case SpvOpTypeVector: {
  414. return GetZeroConstantForHomogeneousComposite(
  415. *type_instruction, type_instruction->GetSingleWordInOperand(0),
  416. type_instruction->GetSingleWordInOperand(1));
  417. }
  418. case SpvOpTypeStruct: {
  419. std::vector<const opt::analysis::Constant*> field_zero_constants;
  420. std::vector<uint32_t> field_zero_ids;
  421. for (uint32_t index = 0; index < type_instruction->NumInOperands();
  422. index++) {
  423. uint32_t field_constant_id = FindOrCreateZeroConstant(
  424. type_instruction->GetSingleWordInOperand(index));
  425. field_zero_ids.push_back(field_constant_id);
  426. field_zero_constants.push_back(
  427. GetIRContext()->get_constant_mgr()->FindDeclaredConstant(
  428. field_constant_id));
  429. }
  430. return FindOrCreateCompositeConstant(
  431. *type_instruction, field_zero_constants, field_zero_ids);
  432. }
  433. default:
  434. assert(false && "Unknown type.");
  435. return 0;
  436. }
  437. }
  438. uint32_t FuzzerPass::FindOrCreateCompositeConstant(
  439. const opt::Instruction& composite_type_instruction,
  440. const std::vector<const opt::analysis::Constant*>& constants,
  441. const std::vector<uint32_t>& constant_ids) {
  442. assert(constants.size() == constant_ids.size() &&
  443. "Precondition: |constants| and |constant_ids| must be in "
  444. "correspondence.");
  445. opt::analysis::Type* composite_type = GetIRContext()->get_type_mgr()->GetType(
  446. composite_type_instruction.result_id());
  447. std::unique_ptr<opt::analysis::Constant> composite_constant;
  448. if (composite_type->AsArray()) {
  449. composite_constant = MakeUnique<opt::analysis::ArrayConstant>(
  450. composite_type->AsArray(), constants);
  451. } else if (composite_type->AsMatrix()) {
  452. composite_constant = MakeUnique<opt::analysis::MatrixConstant>(
  453. composite_type->AsMatrix(), constants);
  454. } else if (composite_type->AsStruct()) {
  455. composite_constant = MakeUnique<opt::analysis::StructConstant>(
  456. composite_type->AsStruct(), constants);
  457. } else if (composite_type->AsVector()) {
  458. composite_constant = MakeUnique<opt::analysis::VectorConstant>(
  459. composite_type->AsVector(), constants);
  460. } else {
  461. assert(false &&
  462. "Precondition: |composite_type| must declare a composite type.");
  463. return 0;
  464. }
  465. uint32_t existing_constant =
  466. GetIRContext()->get_constant_mgr()->FindDeclaredConstant(
  467. composite_constant.get(), composite_type_instruction.result_id());
  468. if (existing_constant) {
  469. return existing_constant;
  470. }
  471. uint32_t result = GetFuzzerContext()->GetFreshId();
  472. ApplyTransformation(TransformationAddConstantComposite(
  473. result, composite_type_instruction.result_id(), constant_ids));
  474. return result;
  475. }
  476. uint32_t FuzzerPass::GetZeroConstantForHomogeneousComposite(
  477. const opt::Instruction& composite_type_instruction,
  478. uint32_t component_type_id, uint32_t num_components) {
  479. std::vector<const opt::analysis::Constant*> zero_constants;
  480. std::vector<uint32_t> zero_ids;
  481. uint32_t zero_component = FindOrCreateZeroConstant(component_type_id);
  482. const opt::analysis::Constant* registered_zero_component =
  483. GetIRContext()->get_constant_mgr()->FindDeclaredConstant(zero_component);
  484. for (uint32_t i = 0; i < num_components; i++) {
  485. zero_constants.push_back(registered_zero_component);
  486. zero_ids.push_back(zero_component);
  487. }
  488. return FindOrCreateCompositeConstant(composite_type_instruction,
  489. zero_constants, zero_ids);
  490. }
  491. } // namespace fuzz
  492. } // namespace spvtools