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() != spv::Op::OpFunctionParameter) {
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 spv::StorageClass::Private)) {
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 spv::StorageClass::Private),
95 spv::StorageClass::Private,
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(spv::Op::OpLoad, it)) {
107 ++it;
108 }
109
110 assert(fuzzerutil::CanInsertOpcodeBeforeInstruction(spv::Op::OpLoad, 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, spv::Op::OpLoad, param_inst->type_id(),
116 param_inst->result_id(),
117 opt::Instruction::OperandList{
118 {SPV_OPERAND_TYPE_ID, {message_.global_variable_fresh_id()}}}));
119
120 // Calculate the index of the replaced parameter (we need to know this to
121 // remove operands from the OpFunctionCall).
122 auto params = fuzzerutil::GetParameters(ir_context, function->result_id());
123 auto parameter_index = static_cast<uint32_t>(params.size());
124 for (uint32_t i = 0, n = static_cast<uint32_t>(params.size()); i < n; ++i) {
125 if (params[i]->result_id() == message_.parameter_id()) {
126 parameter_index = i;
127 break;
128 }
129 }
130
131 assert(parameter_index != params.size() &&
132 "Parameter must exist in the function");
133
134 // Update all relevant OpFunctionCall instructions.
135 for (auto* inst : fuzzerutil::GetCallers(ir_context, function->result_id())) {
136 assert(
137 fuzzerutil::CanInsertOpcodeBeforeInstruction(spv::Op::OpStore, inst) &&
138 "Can't insert OpStore right before the function call");
139
140 // Insert an OpStore before the OpFunctionCall. +1 since the first
141 // operand of OpFunctionCall is an id of the function.
142 inst->InsertBefore(MakeUnique<opt::Instruction>(
143 ir_context, spv::Op::OpStore, 0, 0,
144 opt::Instruction::OperandList{
145 {SPV_OPERAND_TYPE_ID, {message_.global_variable_fresh_id()}},
146 {SPV_OPERAND_TYPE_ID,
147 {inst->GetSingleWordInOperand(parameter_index + 1)}}}));
148
149 // +1 since the first operand of OpFunctionCall is an id of the
150 // function.
151 inst->RemoveInOperand(parameter_index + 1);
152 }
153
154 // Remove the parameter from the function.
155 fuzzerutil::RemoveParameter(ir_context, message_.parameter_id());
156
157 // Update function's type.
158 {
159 // We use a separate scope here since |old_function_type| might become a
160 // dangling pointer after the call to the fuzzerutil::UpdateFunctionType.
161
162 auto* old_function_type = fuzzerutil::GetFunctionType(ir_context, function);
163 assert(old_function_type && "Function has invalid type");
164
165 // +1 and -1 since the first operand is the return type id.
166 std::vector<uint32_t> parameter_type_ids;
167 for (uint32_t i = 1; i < old_function_type->NumInOperands(); ++i) {
168 if (i - 1 != parameter_index) {
169 parameter_type_ids.push_back(
170 old_function_type->GetSingleWordInOperand(i));
171 }
172 }
173
174 fuzzerutil::UpdateFunctionType(
175 ir_context, function->result_id(), message_.function_type_fresh_id(),
176 old_function_type->GetSingleWordInOperand(0), parameter_type_ids);
177 }
178
179 // Make sure our changes are analyzed
180 ir_context->InvalidateAnalysesExceptFor(
181 opt::IRContext::Analysis::kAnalysisNone);
182
183 // Mark the pointee of the global variable storing the parameter's value as
184 // irrelevant if replaced parameter is irrelevant.
185 if (transformation_context->GetFactManager()->IdIsIrrelevant(
186 message_.parameter_id())) {
187 transformation_context->GetFactManager()->AddFactValueOfPointeeIsIrrelevant(
188 message_.global_variable_fresh_id());
189 }
190 }
191
ToMessage() const192 protobufs::Transformation TransformationReplaceParameterWithGlobal::ToMessage()
193 const {
194 protobufs::Transformation result;
195 *result.mutable_replace_parameter_with_global() = message_;
196 return result;
197 }
198
IsParameterTypeSupported(opt::IRContext * ir_context,uint32_t param_type_id)199 bool TransformationReplaceParameterWithGlobal::IsParameterTypeSupported(
200 opt::IRContext* ir_context, uint32_t param_type_id) {
201 // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/3403):
202 // Think about other type instructions we can add here.
203 return fuzzerutil::CanCreateConstant(ir_context, param_type_id);
204 }
205
206 std::unordered_set<uint32_t>
GetFreshIds() const207 TransformationReplaceParameterWithGlobal::GetFreshIds() const {
208 return {message_.function_type_fresh_id(),
209 message_.global_variable_fresh_id()};
210 }
211
212 } // namespace fuzz
213 } // namespace spvtools
214