1 // Copyright (c) 2020 Vasyl Teliman
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/transformation_replace_parameter_with_global.h"
16
17 #include <vector>
18
19 #include "source/fuzz/fuzzer_util.h"
20
21 namespace spvtools {
22 namespace fuzz {
23
24 TransformationReplaceParameterWithGlobal::
TransformationReplaceParameterWithGlobal(protobufs::TransformationReplaceParameterWithGlobal message)25 TransformationReplaceParameterWithGlobal(
26 protobufs::TransformationReplaceParameterWithGlobal message)
27 : message_(std::move(message)) {}
28
29 TransformationReplaceParameterWithGlobal::
TransformationReplaceParameterWithGlobal(uint32_t function_type_fresh_id,uint32_t parameter_id,uint32_t global_variable_fresh_id)30 TransformationReplaceParameterWithGlobal(
31 uint32_t function_type_fresh_id, uint32_t parameter_id,
32 uint32_t global_variable_fresh_id) {
33 message_.set_function_type_fresh_id(function_type_fresh_id);
34 message_.set_parameter_id(parameter_id);
35 message_.set_global_variable_fresh_id(global_variable_fresh_id);
36 }
37
IsApplicable(opt::IRContext * ir_context,const TransformationContext & transformation_context) const38 bool TransformationReplaceParameterWithGlobal::IsApplicable(
39 opt::IRContext* ir_context,
40 const TransformationContext& transformation_context) const {
41 // Check that |parameter_id| is valid.
42 const auto* param_inst =
43 ir_context->get_def_use_mgr()->GetDef(message_.parameter_id());
44 if (!param_inst || param_inst->opcode() != SpvOpFunctionParameter) {
45 return false;
46 }
47
48 // Check that function exists and is not an entry point.
49 const auto* function = fuzzerutil::GetFunctionFromParameterId(
50 ir_context, message_.parameter_id());
51 if (!function ||
52 fuzzerutil::FunctionIsEntryPoint(ir_context, function->result_id())) {
53 return false;
54 }
55
56 // We already know that the function has at least one parameter -
57 // |parameter_id|.
58
59 // Check that replaced parameter has valid type.
60 if (!IsParameterTypeSupported(ir_context, param_inst->type_id())) {
61 return false;
62 }
63
64 // Check that initializer for the global variable exists in the module.
65 if (fuzzerutil::MaybeGetZeroConstant(ir_context, transformation_context,
66 param_inst->type_id(), false) == 0) {
67 return false;
68 }
69
70 // Check that pointer type for the global variable exists in the module.
71 if (!fuzzerutil::MaybeGetPointerType(ir_context, param_inst->type_id(),
72 SpvStorageClassPrivate)) {
73 return false;
74 }
75
76 return fuzzerutil::IsFreshId(ir_context, message_.function_type_fresh_id()) &&
77 fuzzerutil::IsFreshId(ir_context,
78 message_.global_variable_fresh_id()) &&
79 message_.function_type_fresh_id() !=
80 message_.global_variable_fresh_id();
81 }
82
Apply(opt::IRContext * ir_context,TransformationContext * transformation_context) const83 void TransformationReplaceParameterWithGlobal::Apply(
84 opt::IRContext* ir_context,
85 TransformationContext* transformation_context) const {
86 const auto* param_inst =
87 ir_context->get_def_use_mgr()->GetDef(message_.parameter_id());
88 assert(param_inst && "Parameter must exist");
89
90 // Create global variable to store parameter's value.
91 fuzzerutil::AddGlobalVariable(
92 ir_context, message_.global_variable_fresh_id(),
93 fuzzerutil::MaybeGetPointerType(ir_context, param_inst->type_id(),
94 SpvStorageClassPrivate),
95 SpvStorageClassPrivate,
96 fuzzerutil::MaybeGetZeroConstant(ir_context, *transformation_context,
97 param_inst->type_id(), false));
98
99 auto* function = fuzzerutil::GetFunctionFromParameterId(
100 ir_context, message_.parameter_id());
101 assert(function && "Function must exist");
102
103 // Insert an OpLoad instruction right after OpVariable instructions.
104 auto it = function->begin()->begin();
105 while (it != function->begin()->end() &&
106 !fuzzerutil::CanInsertOpcodeBeforeInstruction(SpvOpLoad, it)) {
107 ++it;
108 }
109
110 assert(fuzzerutil::CanInsertOpcodeBeforeInstruction(SpvOpLoad, it) &&
111 "Can't insert OpLoad or OpCopyMemory into the first basic block of "
112 "the function");
113
114 it.InsertBefore(MakeUnique<opt::Instruction>(
115 ir_context, SpvOpLoad, param_inst->type_id(), param_inst->result_id(),
116 opt::Instruction::OperandList{
117 {SPV_OPERAND_TYPE_ID, {message_.global_variable_fresh_id()}}}));
118
119 // Calculate the index of the replaced parameter (we need to know this to
120 // remove operands from the OpFunctionCall).
121 auto params = fuzzerutil::GetParameters(ir_context, function->result_id());
122 auto parameter_index = static_cast<uint32_t>(params.size());
123 for (uint32_t i = 0, n = static_cast<uint32_t>(params.size()); i < n; ++i) {
124 if (params[i]->result_id() == message_.parameter_id()) {
125 parameter_index = i;
126 break;
127 }
128 }
129
130 assert(parameter_index != params.size() &&
131 "Parameter must exist in the function");
132
133 // Update all relevant OpFunctionCall instructions.
134 for (auto* inst : fuzzerutil::GetCallers(ir_context, function->result_id())) {
135 assert(fuzzerutil::CanInsertOpcodeBeforeInstruction(SpvOpStore, inst) &&
136 "Can't insert OpStore right before the function call");
137
138 // Insert an OpStore before the OpFunctionCall. +1 since the first
139 // operand of OpFunctionCall is an id of the function.
140 inst->InsertBefore(MakeUnique<opt::Instruction>(
141 ir_context, SpvOpStore, 0, 0,
142 opt::Instruction::OperandList{
143 {SPV_OPERAND_TYPE_ID, {message_.global_variable_fresh_id()}},
144 {SPV_OPERAND_TYPE_ID,
145 {inst->GetSingleWordInOperand(parameter_index + 1)}}}));
146
147 // +1 since the first operand of OpFunctionCall is an id of the
148 // function.
149 inst->RemoveInOperand(parameter_index + 1);
150 }
151
152 // Remove the parameter from the function.
153 fuzzerutil::RemoveParameter(ir_context, message_.parameter_id());
154
155 // Update function's type.
156 {
157 // We use a separate scope here since |old_function_type| might become a
158 // dangling pointer after the call to the fuzzerutil::UpdateFunctionType.
159
160 auto* old_function_type = fuzzerutil::GetFunctionType(ir_context, function);
161 assert(old_function_type && "Function has invalid type");
162
163 // +1 and -1 since the first operand is the return type id.
164 std::vector<uint32_t> parameter_type_ids;
165 for (uint32_t i = 1; i < old_function_type->NumInOperands(); ++i) {
166 if (i - 1 != parameter_index) {
167 parameter_type_ids.push_back(
168 old_function_type->GetSingleWordInOperand(i));
169 }
170 }
171
172 fuzzerutil::UpdateFunctionType(
173 ir_context, function->result_id(), message_.function_type_fresh_id(),
174 old_function_type->GetSingleWordInOperand(0), parameter_type_ids);
175 }
176
177 // Make sure our changes are analyzed
178 ir_context->InvalidateAnalysesExceptFor(
179 opt::IRContext::Analysis::kAnalysisNone);
180
181 // Mark the pointee of the global variable storing the parameter's value as
182 // irrelevant if replaced parameter is irrelevant.
183 if (transformation_context->GetFactManager()->IdIsIrrelevant(
184 message_.parameter_id())) {
185 transformation_context->GetFactManager()->AddFactValueOfPointeeIsIrrelevant(
186 message_.global_variable_fresh_id());
187 }
188 }
189
ToMessage() const190 protobufs::Transformation TransformationReplaceParameterWithGlobal::ToMessage()
191 const {
192 protobufs::Transformation result;
193 *result.mutable_replace_parameter_with_global() = message_;
194 return result;
195 }
196
IsParameterTypeSupported(opt::IRContext * ir_context,uint32_t param_type_id)197 bool TransformationReplaceParameterWithGlobal::IsParameterTypeSupported(
198 opt::IRContext* ir_context, uint32_t param_type_id) {
199 // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/3403):
200 // Think about other type instructions we can add here.
201 return fuzzerutil::CanCreateConstant(ir_context, param_type_id);
202 }
203
204 std::unordered_set<uint32_t>
GetFreshIds() const205 TransformationReplaceParameterWithGlobal::GetFreshIds() const {
206 return {message_.function_type_fresh_id(),
207 message_.global_variable_fresh_id()};
208 }
209
210 } // namespace fuzz
211 } // namespace spvtools
212