fuzzer_pass_construct_composites.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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_construct_composites.h"
  15. #include <cmath>
  16. #include <memory>
  17. #include "source/fuzz/fuzzer_util.h"
  18. #include "source/fuzz/transformation_composite_construct.h"
  19. #include "source/util/make_unique.h"
  20. namespace spvtools {
  21. namespace fuzz {
  22. FuzzerPassConstructComposites::FuzzerPassConstructComposites(
  23. opt::IRContext* ir_context, TransformationContext* transformation_context,
  24. FuzzerContext* fuzzer_context,
  25. protobufs::TransformationSequence* transformations)
  26. : FuzzerPass(ir_context, transformation_context, fuzzer_context,
  27. transformations) {}
  28. FuzzerPassConstructComposites::~FuzzerPassConstructComposites() = default;
  29. void FuzzerPassConstructComposites::Apply() {
  30. // Gather up the ids of all composite types.
  31. std::vector<uint32_t> composite_type_ids;
  32. for (auto& inst : GetIRContext()->types_values()) {
  33. if (fuzzerutil::IsCompositeType(
  34. GetIRContext()->get_type_mgr()->GetType(inst.result_id()))) {
  35. composite_type_ids.push_back(inst.result_id());
  36. }
  37. }
  38. ForEachInstructionWithInstructionDescriptor(
  39. [this, &composite_type_ids](
  40. opt::Function* function, opt::BasicBlock* block,
  41. opt::BasicBlock::iterator inst_it,
  42. const protobufs::InstructionDescriptor& instruction_descriptor)
  43. -> void {
  44. // Check whether it is legitimate to insert a composite construction
  45. // before the instruction.
  46. if (!fuzzerutil::CanInsertOpcodeBeforeInstruction(
  47. SpvOpCompositeConstruct, inst_it)) {
  48. return;
  49. }
  50. // Randomly decide whether to try inserting an object copy here.
  51. if (!GetFuzzerContext()->ChoosePercentage(
  52. GetFuzzerContext()->GetChanceOfConstructingComposite())) {
  53. return;
  54. }
  55. // For each instruction that is available at this program point (i.e. an
  56. // instruction that is global or whose definition strictly dominates the
  57. // program point) and suitable for making a synonym of, associate it
  58. // with the id of its result type.
  59. TypeIdToInstructions type_id_to_available_instructions;
  60. for (auto instruction : FindAvailableInstructions(
  61. function, block, inst_it, fuzzerutil::CanMakeSynonymOf)) {
  62. RecordAvailableInstruction(instruction,
  63. &type_id_to_available_instructions);
  64. }
  65. // At this point, |composite_type_ids| captures all the composite types
  66. // we could try to create, while |type_id_to_available_instructions|
  67. // captures all the available result ids we might use, organized by
  68. // type.
  69. // Now we try to find a composite that we can construct. We might not
  70. // manage, if there is a paucity of available ingredients in the module
  71. // (e.g. if our only available composite was a boolean vector and we had
  72. // no instructions generating boolean result types available).
  73. //
  74. // If we succeed, |chosen_composite_type| will end up being non-zero,
  75. // and |constructor_arguments| will end up giving us result ids suitable
  76. // for constructing a composite of that type. Otherwise these variables
  77. // will remain 0 and null respectively.
  78. uint32_t chosen_composite_type = 0;
  79. std::vector<uint32_t> constructor_arguments;
  80. // Initially, all composite type ids are available for us to try. Keep
  81. // trying until we run out of options.
  82. auto composites_to_try_constructing = composite_type_ids;
  83. while (!composites_to_try_constructing.empty()) {
  84. // Remove a composite type from the composite types left for us to
  85. // try.
  86. auto next_composite_to_try_constructing =
  87. GetFuzzerContext()->RemoveAtRandomIndex(
  88. &composites_to_try_constructing);
  89. // Now try to construct a composite of this type, using an appropriate
  90. // helper method depending on the kind of composite type.
  91. auto composite_type_inst = GetIRContext()->get_def_use_mgr()->GetDef(
  92. next_composite_to_try_constructing);
  93. switch (composite_type_inst->opcode()) {
  94. case SpvOpTypeArray:
  95. constructor_arguments = FindComponentsToConstructArray(
  96. *composite_type_inst, type_id_to_available_instructions);
  97. break;
  98. case SpvOpTypeMatrix:
  99. constructor_arguments = FindComponentsToConstructMatrix(
  100. *composite_type_inst, type_id_to_available_instructions);
  101. break;
  102. case SpvOpTypeStruct:
  103. constructor_arguments = FindComponentsToConstructStruct(
  104. *composite_type_inst, type_id_to_available_instructions);
  105. break;
  106. case SpvOpTypeVector:
  107. constructor_arguments = FindComponentsToConstructVector(
  108. *composite_type_inst, type_id_to_available_instructions);
  109. break;
  110. default:
  111. assert(false &&
  112. "The space of possible composite types should be covered "
  113. "by the above cases.");
  114. break;
  115. }
  116. if (!constructor_arguments.empty()) {
  117. // We succeeded! Note the composite type we finally settled on, and
  118. // exit from the loop.
  119. chosen_composite_type = next_composite_to_try_constructing;
  120. break;
  121. }
  122. }
  123. if (!chosen_composite_type) {
  124. // We did not manage to make a composite; return 0 to indicate that no
  125. // instructions were added.
  126. assert(constructor_arguments.empty());
  127. return;
  128. }
  129. assert(!constructor_arguments.empty());
  130. // Make and apply a transformation.
  131. ApplyTransformation(TransformationCompositeConstruct(
  132. chosen_composite_type, constructor_arguments,
  133. instruction_descriptor, GetFuzzerContext()->GetFreshId()));
  134. });
  135. }
  136. void FuzzerPassConstructComposites::RecordAvailableInstruction(
  137. opt::Instruction* inst,
  138. TypeIdToInstructions* type_id_to_available_instructions) {
  139. if (type_id_to_available_instructions->count(inst->type_id()) == 0) {
  140. (*type_id_to_available_instructions)[inst->type_id()] = {};
  141. }
  142. type_id_to_available_instructions->at(inst->type_id()).push_back(inst);
  143. }
  144. std::vector<uint32_t>
  145. FuzzerPassConstructComposites::FindComponentsToConstructArray(
  146. const opt::Instruction& array_type_instruction,
  147. const TypeIdToInstructions& type_id_to_available_instructions) {
  148. assert(array_type_instruction.opcode() == SpvOpTypeArray &&
  149. "Precondition: instruction must be an array type.");
  150. // Get the element type for the array.
  151. auto element_type_id = array_type_instruction.GetSingleWordInOperand(0);
  152. // Get all instructions at our disposal that compute something of this element
  153. // type.
  154. auto available_instructions =
  155. type_id_to_available_instructions.find(element_type_id);
  156. if (available_instructions == type_id_to_available_instructions.cend()) {
  157. // If there are not any instructions available that compute the element type
  158. // of the array then we are not in a position to construct a composite with
  159. // this array type.
  160. return {};
  161. }
  162. uint32_t array_length =
  163. GetIRContext()
  164. ->get_def_use_mgr()
  165. ->GetDef(array_type_instruction.GetSingleWordInOperand(1))
  166. ->GetSingleWordInOperand(0);
  167. std::vector<uint32_t> result;
  168. for (uint32_t index = 0; index < array_length; index++) {
  169. result.push_back(available_instructions
  170. ->second[GetFuzzerContext()->RandomIndex(
  171. available_instructions->second)]
  172. ->result_id());
  173. }
  174. return result;
  175. }
  176. std::vector<uint32_t>
  177. FuzzerPassConstructComposites::FindComponentsToConstructMatrix(
  178. const opt::Instruction& matrix_type_instruction,
  179. const TypeIdToInstructions& type_id_to_available_instructions) {
  180. assert(matrix_type_instruction.opcode() == SpvOpTypeMatrix &&
  181. "Precondition: instruction must be a matrix type.");
  182. // Get the element type for the matrix.
  183. auto element_type_id = matrix_type_instruction.GetSingleWordInOperand(0);
  184. // Get all instructions at our disposal that compute something of this element
  185. // type.
  186. auto available_instructions =
  187. type_id_to_available_instructions.find(element_type_id);
  188. if (available_instructions == type_id_to_available_instructions.cend()) {
  189. // If there are not any instructions available that compute the element type
  190. // of the matrix then we are not in a position to construct a composite with
  191. // this matrix type.
  192. return {};
  193. }
  194. std::vector<uint32_t> result;
  195. for (uint32_t index = 0;
  196. index < matrix_type_instruction.GetSingleWordInOperand(1); index++) {
  197. result.push_back(available_instructions
  198. ->second[GetFuzzerContext()->RandomIndex(
  199. available_instructions->second)]
  200. ->result_id());
  201. }
  202. return result;
  203. }
  204. std::vector<uint32_t>
  205. FuzzerPassConstructComposites::FindComponentsToConstructStruct(
  206. const opt::Instruction& struct_type_instruction,
  207. const TypeIdToInstructions& type_id_to_available_instructions) {
  208. assert(struct_type_instruction.opcode() == SpvOpTypeStruct &&
  209. "Precondition: instruction must be a struct type.");
  210. std::vector<uint32_t> result;
  211. // Consider the type of each field of the struct.
  212. for (uint32_t in_operand_index = 0;
  213. in_operand_index < struct_type_instruction.NumInOperands();
  214. in_operand_index++) {
  215. auto element_type_id =
  216. struct_type_instruction.GetSingleWordInOperand(in_operand_index);
  217. // Find the instructions at our disposal that compute something of the field
  218. // type.
  219. auto available_instructions =
  220. type_id_to_available_instructions.find(element_type_id);
  221. if (available_instructions == type_id_to_available_instructions.cend()) {
  222. // If there are no such instructions, we cannot construct a composite of
  223. // this struct type.
  224. return {};
  225. }
  226. result.push_back(available_instructions
  227. ->second[GetFuzzerContext()->RandomIndex(
  228. available_instructions->second)]
  229. ->result_id());
  230. }
  231. return result;
  232. }
  233. std::vector<uint32_t>
  234. FuzzerPassConstructComposites::FindComponentsToConstructVector(
  235. const opt::Instruction& vector_type_instruction,
  236. const TypeIdToInstructions& type_id_to_available_instructions) {
  237. assert(vector_type_instruction.opcode() == SpvOpTypeVector &&
  238. "Precondition: instruction must be a vector type.");
  239. // Get details of the type underlying the vector, and the width of the vector,
  240. // for convenience.
  241. auto element_type_id = vector_type_instruction.GetSingleWordInOperand(0);
  242. auto element_type = GetIRContext()->get_type_mgr()->GetType(element_type_id);
  243. auto element_count = vector_type_instruction.GetSingleWordInOperand(1);
  244. // Collect a mapping, from type id to width, for scalar/vector types that are
  245. // smaller in width than |vector_type|, but that have the same underlying
  246. // type. For example, if |vector_type| is vec4, the mapping will be:
  247. // { float -> 1, vec2 -> 2, vec3 -> 3 }
  248. // The mapping will have missing entries if some of these types do not exist.
  249. std::map<uint32_t, uint32_t> smaller_vector_type_id_to_width;
  250. // Add the underlying type. This id must exist, in order for |vector_type| to
  251. // exist.
  252. smaller_vector_type_id_to_width[element_type_id] = 1;
  253. // Now add every vector type with width at least 2, and less than the width of
  254. // |vector_type|.
  255. for (uint32_t width = 2; width < element_count; width++) {
  256. opt::analysis::Vector smaller_vector_type(element_type, width);
  257. auto smaller_vector_type_id =
  258. GetIRContext()->get_type_mgr()->GetId(&smaller_vector_type);
  259. // We might find that there is no declared type of this smaller width.
  260. // For example, a module can declare vec4 without having declared vec2 or
  261. // vec3.
  262. if (smaller_vector_type_id) {
  263. smaller_vector_type_id_to_width[smaller_vector_type_id] = width;
  264. }
  265. }
  266. // Now we know the types that are available to us, we set about populating a
  267. // vector of the right length. We do this by deciding, with no order in mind,
  268. // which instructions we will use to populate the vector, and subsequently
  269. // randomly choosing an order. This is to avoid biasing construction of
  270. // vectors with smaller vectors to the left and scalars to the right. That is
  271. // a concern because, e.g. in the case of populating a vec4, if we populate
  272. // the constructor instructions left-to-right, we can always choose a vec3 to
  273. // construct the first three elements, but can only choose a vec3 to construct
  274. // the last three elements if we chose a float to construct the first element
  275. // (otherwise there will not be space left for a vec3).
  276. uint32_t vector_slots_used = 0;
  277. // The instructions we will use to construct the vector, in no particular
  278. // order at this stage.
  279. std::vector<opt::Instruction*> instructions_to_use;
  280. while (vector_slots_used < element_count) {
  281. std::vector<opt::Instruction*> instructions_to_choose_from;
  282. for (auto& entry : smaller_vector_type_id_to_width) {
  283. if (entry.second >
  284. std::min(element_count - 1, element_count - vector_slots_used)) {
  285. continue;
  286. }
  287. auto available_instructions =
  288. type_id_to_available_instructions.find(entry.first);
  289. if (available_instructions == type_id_to_available_instructions.cend()) {
  290. continue;
  291. }
  292. instructions_to_choose_from.insert(instructions_to_choose_from.end(),
  293. available_instructions->second.begin(),
  294. available_instructions->second.end());
  295. }
  296. if (instructions_to_choose_from.empty()) {
  297. // We may get unlucky and find that there are not any instructions to
  298. // choose from. In this case we give up constructing a composite of this
  299. // vector type. It might be that we could construct the composite in
  300. // another manner, so we could opt to retry a few times here, but it is
  301. // simpler to just give up on the basis that this will not happen
  302. // frequently.
  303. return {};
  304. }
  305. auto instruction_to_use =
  306. instructions_to_choose_from[GetFuzzerContext()->RandomIndex(
  307. instructions_to_choose_from)];
  308. instructions_to_use.push_back(instruction_to_use);
  309. auto chosen_type =
  310. GetIRContext()->get_type_mgr()->GetType(instruction_to_use->type_id());
  311. if (chosen_type->AsVector()) {
  312. assert(chosen_type->AsVector()->element_type() == element_type);
  313. assert(chosen_type->AsVector()->element_count() < element_count);
  314. assert(chosen_type->AsVector()->element_count() <=
  315. element_count - vector_slots_used);
  316. vector_slots_used += chosen_type->AsVector()->element_count();
  317. } else {
  318. assert(chosen_type == element_type);
  319. vector_slots_used += 1;
  320. }
  321. }
  322. assert(vector_slots_used == element_count);
  323. std::vector<uint32_t> result;
  324. std::vector<uint32_t> operands;
  325. while (!instructions_to_use.empty()) {
  326. auto index = GetFuzzerContext()->RandomIndex(instructions_to_use);
  327. result.push_back(instructions_to_use[index]->result_id());
  328. instructions_to_use.erase(instructions_to_use.begin() + index);
  329. }
  330. assert(result.size() > 1);
  331. return result;
  332. }
  333. } // namespace fuzz
  334. } // namespace spvtools