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_replace_irrelevant_ids.h"
16
17 #include "source/fuzz/fuzzer_util.h"
18 #include "source/fuzz/id_use_descriptor.h"
19 #include "source/fuzz/transformation_replace_irrelevant_id.h"
20
21 namespace spvtools {
22 namespace fuzz {
23
24 // A fuzzer pass that, for every use of an id that has been recorded as
25 // irrelevant, randomly decides whether to replace it with another id of the
26 // same type.
FuzzerPassReplaceIrrelevantIds(opt::IRContext * ir_context,TransformationContext * transformation_context,FuzzerContext * fuzzer_context,protobufs::TransformationSequence * transformations,bool ignore_inapplicable_transformations)27 FuzzerPassReplaceIrrelevantIds::FuzzerPassReplaceIrrelevantIds(
28 opt::IRContext* ir_context, TransformationContext* transformation_context,
29 FuzzerContext* fuzzer_context,
30 protobufs::TransformationSequence* transformations,
31 bool ignore_inapplicable_transformations)
32 : FuzzerPass(ir_context, transformation_context, fuzzer_context,
33 transformations, ignore_inapplicable_transformations) {}
34
Apply()35 void FuzzerPassReplaceIrrelevantIds::Apply() {
36 // Keep track of the irrelevant ids. This includes all the ids that are
37 // irrelevant according to the fact manager and that are still present in the
38 // module (some of them may have been removed by previously-run
39 // transformations).
40 std::vector<uint32_t> irrelevant_ids;
41
42 // Keep a map from the type ids of irrelevant ids to all the ids with that
43 // type.
44 std::unordered_map<uint32_t, std::vector<uint32_t>> types_to_ids;
45
46 // Find all the irrelevant ids that still exist in the module and all the
47 // types for which irrelevant ids exist.
48 for (auto id :
49 GetTransformationContext()->GetFactManager()->GetIrrelevantIds()) {
50 // Check that the id still exists in the module.
51 auto declaration = GetIRContext()->get_def_use_mgr()->GetDef(id);
52 if (!declaration) {
53 continue;
54 }
55
56 irrelevant_ids.push_back(id);
57
58 // If the type of this id has not been seen before, add a mapping from this
59 // type id to an empty list in |types_to_ids|. The list will be filled later
60 // on.
61 if (types_to_ids.count(declaration->type_id()) == 0) {
62 types_to_ids.insert({declaration->type_id(), {}});
63 }
64 }
65
66 // If no irrelevant ids were found, return.
67 if (irrelevant_ids.empty()) {
68 return;
69 }
70
71 // For every type for which we have at least one irrelevant id, record all ids
72 // in the module which have that type. Skip ids of OpFunction instructions as
73 // we cannot use these as replacements.
74 for (const auto& pair : GetIRContext()->get_def_use_mgr()->id_to_defs()) {
75 uint32_t type_id = pair.second->type_id();
76 if (pair.second->opcode() != SpvOpFunction && type_id &&
77 types_to_ids.count(type_id)) {
78 types_to_ids[type_id].push_back(pair.first);
79 }
80 }
81
82 // Keep a list of all the transformations to perform. We avoid applying the
83 // transformations while traversing the uses since applying the transformation
84 // invalidates all analyses, and we want to avoid invalidating and recomputing
85 // them every time.
86 std::vector<TransformationReplaceIrrelevantId> transformations_to_apply;
87
88 // Loop through all the uses of irrelevant ids, check that the id can be
89 // replaced and randomly decide whether to apply the transformation.
90 for (auto irrelevant_id : irrelevant_ids) {
91 uint32_t type_id =
92 GetIRContext()->get_def_use_mgr()->GetDef(irrelevant_id)->type_id();
93
94 GetIRContext()->get_def_use_mgr()->ForEachUse(
95 irrelevant_id, [this, &irrelevant_id, &type_id, &types_to_ids,
96 &transformations_to_apply](opt::Instruction* use_inst,
97 uint32_t use_index) {
98 // Randomly decide whether to consider this use.
99 if (!GetFuzzerContext()->ChoosePercentage(
100 GetFuzzerContext()->GetChanceOfReplacingIrrelevantId())) {
101 return;
102 }
103
104 // The id must be used as an input operand.
105 if (use_index < use_inst->NumOperands() - use_inst->NumInOperands()) {
106 // The id is used as an output operand, so we cannot replace this
107 // usage.
108 return;
109 }
110
111 // Get the input operand index for this use, from the absolute operand
112 // index.
113 uint32_t in_index =
114 fuzzerutil::InOperandIndexFromOperandIndex(*use_inst, use_index);
115
116 // Only go ahead if this id use can be replaced in principle.
117 if (!fuzzerutil::IdUseCanBeReplaced(GetIRContext(),
118 *GetTransformationContext(),
119 use_inst, in_index)) {
120 return;
121 }
122
123 // Find out which ids could be used to replace this use.
124 std::vector<uint32_t> available_replacement_ids;
125
126 for (auto replacement_id : types_to_ids[type_id]) {
127 // It would be pointless to replace an id with itself.
128 if (replacement_id == irrelevant_id) {
129 continue;
130 }
131
132 // We cannot replace a variable initializer with a non-constant.
133 if (TransformationReplaceIrrelevantId::
134 AttemptsToReplaceVariableInitializerWithNonConstant(
135 *use_inst, *GetIRContext()->get_def_use_mgr()->GetDef(
136 replacement_id))) {
137 continue;
138 }
139
140 // Only consider this replacement if the use point is within a basic
141 // block and the id is available at the use point.
142 //
143 // There might be opportunities for replacing a non-block use of an
144 // irrelevant id - such as the initializer of a global variable -
145 // with another id, but it would require some care (e.g. to ensure
146 // that the replacement id is defined earlier) and does not seem
147 // worth doing.
148 if (GetIRContext()->get_instr_block(use_inst) &&
149 fuzzerutil::IdIsAvailableAtUse(GetIRContext(), use_inst,
150 in_index, replacement_id)) {
151 available_replacement_ids.push_back(replacement_id);
152 }
153 }
154
155 // Only go ahead if there is at least one id with which this use can
156 // be replaced.
157 if (available_replacement_ids.empty()) {
158 return;
159 }
160
161 // Choose the replacement id randomly.
162 uint32_t replacement_id =
163 available_replacement_ids[GetFuzzerContext()->RandomIndex(
164 available_replacement_ids)];
165
166 // Add this replacement to the list of transformations to apply.
167 transformations_to_apply.emplace_back(
168 TransformationReplaceIrrelevantId(
169 MakeIdUseDescriptorFromUse(GetIRContext(), use_inst,
170 in_index),
171 replacement_id));
172 });
173 }
174
175 // Apply all the transformations.
176 for (const auto& transformation : transformations_to_apply) {
177 ApplyTransformation(transformation);
178 }
179 }
180
181 } // namespace fuzz
182 } // namespace spvtools
183