• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2020 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 
15 #include "source/fuzz/fuzzer_pass_flatten_conditional_branches.h"
16 
17 #include "source/fuzz/comparator_deep_blocks_first.h"
18 #include "source/fuzz/instruction_descriptor.h"
19 #include "source/fuzz/transformation_flatten_conditional_branch.h"
20 
21 namespace spvtools {
22 namespace fuzz {
23 
24 // A fuzzer pass that randomly selects conditional branches to flatten and
25 // flattens them, if possible.
FuzzerPassFlattenConditionalBranches(opt::IRContext * ir_context,TransformationContext * transformation_context,FuzzerContext * fuzzer_context,protobufs::TransformationSequence * transformations)26 FuzzerPassFlattenConditionalBranches::FuzzerPassFlattenConditionalBranches(
27     opt::IRContext* ir_context, TransformationContext* transformation_context,
28     FuzzerContext* fuzzer_context,
29     protobufs::TransformationSequence* transformations)
30     : FuzzerPass(ir_context, transformation_context, fuzzer_context,
31                  transformations) {}
32 
Apply()33 void FuzzerPassFlattenConditionalBranches::Apply() {
34   for (auto& function : *GetIRContext()->module()) {
35     // Get all the selection headers that we want to flatten. We need to collect
36     // all of them first, because, since we are changing the structure of the
37     // module, it's not safe to modify them while iterating.
38     std::vector<opt::BasicBlock*> selection_headers;
39 
40     for (auto& block : function) {
41       // Randomly decide whether to consider this block.
42       if (!GetFuzzerContext()->ChoosePercentage(
43               GetFuzzerContext()->GetChanceOfFlatteningConditionalBranch())) {
44         continue;
45       }
46 
47       // Only consider this block if it is the header of a conditional, with a
48       // non-irrelevant condition.
49       if (block.GetMergeInst() &&
50           block.GetMergeInst()->opcode() == SpvOpSelectionMerge &&
51           block.terminator()->opcode() == SpvOpBranchConditional &&
52           !GetTransformationContext()->GetFactManager()->IdIsIrrelevant(
53               block.terminator()->GetSingleWordInOperand(0))) {
54         selection_headers.emplace_back(&block);
55       }
56     }
57 
58     // Sort the headers so that those that are more deeply nested are considered
59     // first, possibly enabling outer conditionals to be flattened.
60     std::sort(selection_headers.begin(), selection_headers.end(),
61               ComparatorDeepBlocksFirst(GetIRContext()));
62 
63     // Apply the transformation to the headers which can be flattened.
64     for (auto header : selection_headers) {
65       // Make a set to keep track of the instructions that need fresh ids.
66       std::set<opt::Instruction*> instructions_that_need_ids;
67 
68       // Do not consider this header if the conditional cannot be flattened.
69       if (!TransformationFlattenConditionalBranch::
70               GetProblematicInstructionsIfConditionalCanBeFlattened(
71                   GetIRContext(), header, *GetTransformationContext(),
72                   &instructions_that_need_ids)) {
73         continue;
74       }
75 
76       uint32_t convergence_block_id =
77           TransformationFlattenConditionalBranch::FindConvergenceBlock(
78               GetIRContext(), *header);
79 
80       // If the SPIR-V version is restricted so that OpSelect can only work on
81       // scalar, pointer and vector types then we cannot apply this
82       // transformation to a header whose convergence block features OpPhi
83       // instructions on different types, as we cannot convert such instructions
84       // to OpSelect instructions.
85       if (TransformationFlattenConditionalBranch::
86               OpSelectArgumentsAreRestricted(GetIRContext())) {
87         if (!GetIRContext()
88                  ->cfg()
89                  ->block(convergence_block_id)
90                  ->WhileEachPhiInst(
91                      [this](opt::Instruction* phi_instruction) -> bool {
92                        switch (GetIRContext()
93                                    ->get_def_use_mgr()
94                                    ->GetDef(phi_instruction->type_id())
95                                    ->opcode()) {
96                          case SpvOpTypeBool:
97                          case SpvOpTypeInt:
98                          case SpvOpTypeFloat:
99                          case SpvOpTypePointer:
100                          case SpvOpTypeVector:
101                            return true;
102                          default:
103                            return false;
104                        }
105                      })) {
106           // An OpPhi is performed on a type not supported by OpSelect; we
107           // cannot flatten this selection.
108           continue;
109         }
110       }
111 
112       // If the construct's convergence block features OpPhi instructions with
113       // vector result types then we may be *forced*, by the SPIR-V version, to
114       // turn these into component-wise OpSelect instructions, or we might wish
115       // to do so anyway.  The following booleans capture whether we will opt
116       // to use a component-wise select even if we don't have to.
117       bool use_component_wise_2d_select_even_if_optional =
118           GetFuzzerContext()->ChooseEven();
119       bool use_component_wise_3d_select_even_if_optional =
120           GetFuzzerContext()->ChooseEven();
121       bool use_component_wise_4d_select_even_if_optional =
122           GetFuzzerContext()->ChooseEven();
123 
124       // If we do need to perform any component-wise selections, we will need a
125       // fresh id for a boolean vector representing the selection's condition
126       // repeated N times, where N is the vector dimension.
127       uint32_t fresh_id_for_bvec2_selector = 0;
128       uint32_t fresh_id_for_bvec3_selector = 0;
129       uint32_t fresh_id_for_bvec4_selector = 0;
130 
131       GetIRContext()
132           ->cfg()
133           ->block(convergence_block_id)
134           ->ForEachPhiInst([this, &fresh_id_for_bvec2_selector,
135                             &fresh_id_for_bvec3_selector,
136                             &fresh_id_for_bvec4_selector,
137                             use_component_wise_2d_select_even_if_optional,
138                             use_component_wise_3d_select_even_if_optional,
139                             use_component_wise_4d_select_even_if_optional](
140                                opt::Instruction* phi_instruction) {
141             opt::Instruction* type_instruction =
142                 GetIRContext()->get_def_use_mgr()->GetDef(
143                     phi_instruction->type_id());
144             switch (type_instruction->opcode()) {
145               case SpvOpTypeVector: {
146                 uint32_t dimension =
147                     type_instruction->GetSingleWordInOperand(1);
148                 switch (dimension) {
149                   case 2:
150                     PrepareForOpPhiOnVectors(
151                         dimension,
152                         use_component_wise_2d_select_even_if_optional,
153                         &fresh_id_for_bvec2_selector);
154                     break;
155                   case 3:
156                     PrepareForOpPhiOnVectors(
157                         dimension,
158                         use_component_wise_3d_select_even_if_optional,
159                         &fresh_id_for_bvec3_selector);
160                     break;
161                   case 4:
162                     PrepareForOpPhiOnVectors(
163                         dimension,
164                         use_component_wise_4d_select_even_if_optional,
165                         &fresh_id_for_bvec4_selector);
166                     break;
167                   default:
168                     assert(false && "Invalid vector dimension.");
169                 }
170                 break;
171               }
172               default:
173                 break;
174             }
175           });
176 
177       // Some instructions will require to be enclosed inside conditionals
178       // because they have side effects (for example, loads and stores). Some of
179       // this have no result id, so we require instruction descriptors to
180       // identify them. Each of them is associated with the necessary ids for it
181       // via a SideEffectWrapperInfo message.
182       std::vector<protobufs::SideEffectWrapperInfo> wrappers_info;
183 
184       for (auto instruction : instructions_that_need_ids) {
185         protobufs::SideEffectWrapperInfo wrapper_info;
186         *wrapper_info.mutable_instruction() =
187             MakeInstructionDescriptor(GetIRContext(), instruction);
188         wrapper_info.set_merge_block_id(GetFuzzerContext()->GetFreshId());
189         wrapper_info.set_execute_block_id(GetFuzzerContext()->GetFreshId());
190 
191         // If the instruction has a non-void result id, we need to define more
192         // fresh ids and provide an id of the suitable type whose value can be
193         // copied in order to create a placeholder id.
194         if (TransformationFlattenConditionalBranch::InstructionNeedsPlaceholder(
195                 GetIRContext(), *instruction)) {
196           wrapper_info.set_actual_result_id(GetFuzzerContext()->GetFreshId());
197           wrapper_info.set_alternative_block_id(
198               GetFuzzerContext()->GetFreshId());
199           wrapper_info.set_placeholder_result_id(
200               GetFuzzerContext()->GetFreshId());
201 
202           // The id will be a zero constant if the type allows it, and an
203           // OpUndef otherwise. We want to avoid using OpUndef, if possible, to
204           // avoid undefined behaviour in the module as much as possible.
205           if (fuzzerutil::CanCreateConstant(GetIRContext(),
206                                             instruction->type_id())) {
207             wrapper_info.set_value_to_copy_id(
208                 FindOrCreateZeroConstant(instruction->type_id(), true));
209           } else {
210             wrapper_info.set_value_to_copy_id(
211                 FindOrCreateGlobalUndef(instruction->type_id()));
212           }
213         }
214 
215         wrappers_info.push_back(std::move(wrapper_info));
216       }
217 
218       // Apply the transformation, evenly choosing whether to lay out the true
219       // branch or the false branch first.
220       ApplyTransformation(TransformationFlattenConditionalBranch(
221           header->id(), GetFuzzerContext()->ChooseEven(),
222           fresh_id_for_bvec2_selector, fresh_id_for_bvec3_selector,
223           fresh_id_for_bvec4_selector, wrappers_info));
224     }
225   }
226 }
227 
PrepareForOpPhiOnVectors(uint32_t vector_dimension,bool use_vector_select_if_optional,uint32_t * fresh_id_for_bvec_selector)228 void FuzzerPassFlattenConditionalBranches::PrepareForOpPhiOnVectors(
229     uint32_t vector_dimension, bool use_vector_select_if_optional,
230     uint32_t* fresh_id_for_bvec_selector) {
231   if (*fresh_id_for_bvec_selector != 0) {
232     // We already have a fresh id for a component-wise OpSelect of this
233     // dimension
234     return;
235   }
236   if (TransformationFlattenConditionalBranch::OpSelectArgumentsAreRestricted(
237           GetIRContext()) ||
238       use_vector_select_if_optional) {
239     // We either have to, or have chosen to, perform a component-wise select, so
240     // we ensure that the right boolean vector type is available, and grab a
241     // fresh id.
242     FindOrCreateVectorType(FindOrCreateBoolType(), vector_dimension);
243     *fresh_id_for_bvec_selector = GetFuzzerContext()->GetFreshId();
244   }
245 }
246 
247 }  // namespace fuzz
248 }  // namespace spvtools
249