• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2020 André Perez Maselco
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 
15 #include "source/fuzz/fuzzer_pass_push_ids_through_variables.h"
16 
17 #include "source/fuzz/fuzzer_util.h"
18 #include "source/fuzz/instruction_descriptor.h"
19 #include "source/fuzz/transformation_push_id_through_variable.h"
20 
21 namespace spvtools {
22 namespace fuzz {
23 
FuzzerPassPushIdsThroughVariables(opt::IRContext * ir_context,TransformationContext * transformation_context,FuzzerContext * fuzzer_context,protobufs::TransformationSequence * transformations,bool ignore_inapplicable_transformations)24 FuzzerPassPushIdsThroughVariables::FuzzerPassPushIdsThroughVariables(
25     opt::IRContext* ir_context, TransformationContext* transformation_context,
26     FuzzerContext* fuzzer_context,
27     protobufs::TransformationSequence* transformations,
28     bool ignore_inapplicable_transformations)
29     : FuzzerPass(ir_context, transformation_context, fuzzer_context,
30                  transformations, ignore_inapplicable_transformations) {}
31 
Apply()32 void FuzzerPassPushIdsThroughVariables::Apply() {
33   ForEachInstructionWithInstructionDescriptor(
34       [this](opt::Function* function, opt::BasicBlock* block,
35              opt::BasicBlock::iterator instruction_iterator,
36              const protobufs::InstructionDescriptor& instruction_descriptor)
37           -> void {
38         assert(instruction_iterator->opcode() ==
39                    instruction_descriptor.target_instruction_opcode() &&
40                "The opcode of the instruction we might insert before must be "
41                "the same as the opcode in the descriptor for the instruction");
42 
43         // Randomly decide whether to try pushing an id through a variable.
44         if (!GetFuzzerContext()->ChoosePercentage(
45                 GetFuzzerContext()->GetChanceOfPushingIdThroughVariable())) {
46           return;
47         }
48 
49         // The block containing the instruction we are going to insert before
50         // must be reachable.
51         if (!GetIRContext()->IsReachable(*block)) {
52           return;
53         }
54 
55         // It must be valid to insert OpStore and OpLoad instructions
56         // before the instruction to insert before.
57         if (!fuzzerutil::CanInsertOpcodeBeforeInstruction(
58                 SpvOpStore, instruction_iterator) ||
59             !fuzzerutil::CanInsertOpcodeBeforeInstruction(
60                 SpvOpLoad, instruction_iterator)) {
61           return;
62         }
63 
64         // Randomly decides whether a global or local variable will be added.
65         auto variable_storage_class = GetFuzzerContext()->ChooseEven()
66                                           ? SpvStorageClassPrivate
67                                           : SpvStorageClassFunction;
68 
69         // Gets the available basic and pointer types.
70         auto basic_type_ids_and_pointers =
71             GetAvailableBasicTypesAndPointers(variable_storage_class);
72         auto& basic_types = basic_type_ids_and_pointers.first;
73 
74         // There must be at least some basic types.
75         if (basic_types.empty()) {
76           return;
77         }
78 
79         uint32_t basic_type_id =
80             basic_types[GetFuzzerContext()->RandomIndex(basic_types)];
81 
82         // Looks for ids that we might wish to consider pushing through a
83         // variable.
84         std::vector<opt::Instruction*> value_instructions =
85             FindAvailableInstructions(
86                 function, block, instruction_iterator,
87                 [this, basic_type_id, instruction_descriptor](
88                     opt::IRContext* ir_context,
89                     opt::Instruction* instruction) -> bool {
90                   if (!instruction->result_id() || !instruction->type_id()) {
91                     return false;
92                   }
93 
94                   if (instruction->type_id() != basic_type_id) {
95                     return false;
96                   }
97 
98                   // If the id is irrelevant, we can use it since it will not
99                   // participate in DataSynonym fact. Otherwise, we should be
100                   // able to produce a synonym out of the id.
101                   if (!GetTransformationContext()
102                            ->GetFactManager()
103                            ->IdIsIrrelevant(instruction->result_id()) &&
104                       !fuzzerutil::CanMakeSynonymOf(ir_context,
105                                                     *GetTransformationContext(),
106                                                     *instruction)) {
107                     return false;
108                   }
109 
110                   return fuzzerutil::IdIsAvailableBeforeInstruction(
111                       ir_context,
112                       FindInstruction(instruction_descriptor, ir_context),
113                       instruction->result_id());
114                 });
115 
116         if (value_instructions.empty()) {
117           return;
118         }
119 
120         // If the pointer type does not exist, then create it.
121         FindOrCreatePointerType(basic_type_id, variable_storage_class);
122 
123         // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/3403):
124         //  type support here is limited by the FindOrCreateZeroConstant
125         //  function.
126         const auto* type_inst =
127             GetIRContext()->get_def_use_mgr()->GetDef(basic_type_id);
128         assert(type_inst);
129         switch (type_inst->opcode()) {
130           case SpvOpTypeBool:
131           case SpvOpTypeFloat:
132           case SpvOpTypeInt:
133           case SpvOpTypeArray:
134           case SpvOpTypeMatrix:
135           case SpvOpTypeVector:
136           case SpvOpTypeStruct:
137             break;
138           default:
139             return;
140         }
141 
142         // Create a constant to initialize the variable from. This might update
143         // module's id bound so it must be done before any fresh ids are
144         // computed.
145         auto initializer_id = FindOrCreateZeroConstant(basic_type_id, false);
146 
147         // Applies the push id through variable transformation.
148         ApplyTransformation(TransformationPushIdThroughVariable(
149             value_instructions[GetFuzzerContext()->RandomIndex(
150                                    value_instructions)]
151                 ->result_id(),
152             GetFuzzerContext()->GetFreshId(), GetFuzzerContext()->GetFreshId(),
153             variable_storage_class, initializer_id, instruction_descriptor));
154       });
155 }
156 
157 }  // namespace fuzz
158 }  // namespace spvtools
159