1 // Copyright (c) 2019 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/force_render_red.h"
16 
17 #include "source/fuzz/fact_manager/fact_manager.h"
18 #include "source/fuzz/instruction_descriptor.h"
19 #include "source/fuzz/protobufs/spirvfuzz_protobufs.h"
20 #include "source/fuzz/transformation_context.h"
21 #include "source/fuzz/transformation_replace_constant_with_uniform.h"
22 #include "source/fuzz/uniform_buffer_element_descriptor.h"
23 #include "source/opt/build_module.h"
24 #include "source/opt/ir_context.h"
25 #include "source/opt/types.h"
26 #include "source/util/make_unique.h"
27 #include "tools/util/cli_consumer.h"
28 
29 namespace spvtools {
30 namespace fuzz {
31 
32 namespace {
33 
34 // Helper method to find the fragment shader entry point, complaining if there
35 // is no shader or if there is no fragment entry point.
FindFragmentShaderEntryPoint(opt::IRContext * ir_context,MessageConsumer message_consumer)36 opt::Function* FindFragmentShaderEntryPoint(opt::IRContext* ir_context,
37                                             MessageConsumer message_consumer) {
38   // Check that this is a fragment shader
39   bool found_capability_shader = false;
40   for (auto& capability : ir_context->capabilities()) {
41     assert(capability.opcode() == SpvOpCapability);
42     if (capability.GetSingleWordInOperand(0) == SpvCapabilityShader) {
43       found_capability_shader = true;
44       break;
45     }
46   }
47   if (!found_capability_shader) {
48     message_consumer(
49         SPV_MSG_ERROR, nullptr, {},
50         "Forcing of red rendering requires the Shader capability.");
51     return nullptr;
52   }
53 
54   opt::Instruction* fragment_entry_point = nullptr;
55   for (auto& entry_point : ir_context->module()->entry_points()) {
56     if (entry_point.GetSingleWordInOperand(0) == SpvExecutionModelFragment) {
57       fragment_entry_point = &entry_point;
58       break;
59     }
60   }
61   if (fragment_entry_point == nullptr) {
62     message_consumer(SPV_MSG_ERROR, nullptr, {},
63                      "Forcing of red rendering requires an entry point with "
64                      "the Fragment execution model.");
65     return nullptr;
66   }
67 
68   for (auto& function : *ir_context->module()) {
69     if (function.result_id() ==
70         fragment_entry_point->GetSingleWordInOperand(1)) {
71       return &function;
72     }
73   }
74   assert(
75       false &&
76       "A valid module must have a function associate with each entry point.");
77   return nullptr;
78 }
79 
80 // Helper method to check that there is a single vec4 output variable and get a
81 // pointer to it.
FindVec4OutputVariable(opt::IRContext * ir_context,MessageConsumer message_consumer)82 opt::Instruction* FindVec4OutputVariable(opt::IRContext* ir_context,
83                                          MessageConsumer message_consumer) {
84   opt::Instruction* output_variable = nullptr;
85   for (auto& inst : ir_context->types_values()) {
86     if (inst.opcode() == SpvOpVariable &&
87         inst.GetSingleWordInOperand(0) == SpvStorageClassOutput) {
88       if (output_variable != nullptr) {
89         message_consumer(SPV_MSG_ERROR, nullptr, {},
90                          "Only one output variable can be handled at present; "
91                          "found multiple.");
92         return nullptr;
93       }
94       output_variable = &inst;
95       // Do not break, as we want to check for multiple output variables.
96     }
97   }
98   if (output_variable == nullptr) {
99     message_consumer(SPV_MSG_ERROR, nullptr, {},
100                      "No output variable to which to write red was found.");
101     return nullptr;
102   }
103 
104   auto output_variable_base_type = ir_context->get_type_mgr()
105                                        ->GetType(output_variable->type_id())
106                                        ->AsPointer()
107                                        ->pointee_type()
108                                        ->AsVector();
109   if (!output_variable_base_type ||
110       output_variable_base_type->element_count() != 4 ||
111       !output_variable_base_type->element_type()->AsFloat()) {
112     message_consumer(SPV_MSG_ERROR, nullptr, {},
113                      "The output variable must have type vec4.");
114     return nullptr;
115   }
116 
117   return output_variable;
118 }
119 
120 // Helper to get the ids of float constants 0.0 and 1.0, creating them if
121 // necessary.
FindOrCreateFloatZeroAndOne(opt::IRContext * ir_context,opt::analysis::Float * float_type)122 std::pair<uint32_t, uint32_t> FindOrCreateFloatZeroAndOne(
123     opt::IRContext* ir_context, opt::analysis::Float* float_type) {
124   float one = 1.0;
125   uint32_t one_as_uint;
126   memcpy(&one_as_uint, &one, sizeof(float));
127   std::vector<uint32_t> zero_bytes = {0};
128   std::vector<uint32_t> one_bytes = {one_as_uint};
129   auto constant_zero = ir_context->get_constant_mgr()->RegisterConstant(
130       MakeUnique<opt::analysis::FloatConstant>(float_type, zero_bytes));
131   auto constant_one = ir_context->get_constant_mgr()->RegisterConstant(
132       MakeUnique<opt::analysis::FloatConstant>(float_type, one_bytes));
133   auto constant_zero_id = ir_context->get_constant_mgr()
134                               ->GetDefiningInstruction(constant_zero)
135                               ->result_id();
136   auto constant_one_id = ir_context->get_constant_mgr()
137                              ->GetDefiningInstruction(constant_one)
138                              ->result_id();
139   return std::pair<uint32_t, uint32_t>(constant_zero_id, constant_one_id);
140 }
141 
142 std::unique_ptr<TransformationReplaceConstantWithUniform>
MakeConstantUniformReplacement(opt::IRContext * ir_context,const FactManager & fact_manager,uint32_t constant_id,uint32_t greater_than_instruction,uint32_t in_operand_index)143 MakeConstantUniformReplacement(opt::IRContext* ir_context,
144                                const FactManager& fact_manager,
145                                uint32_t constant_id,
146                                uint32_t greater_than_instruction,
147                                uint32_t in_operand_index) {
148   return MakeUnique<TransformationReplaceConstantWithUniform>(
149       MakeIdUseDescriptor(constant_id,
150                           MakeInstructionDescriptor(greater_than_instruction,
151                                                     SpvOpFOrdGreaterThan, 0),
152                           in_operand_index),
153       fact_manager.GetUniformDescriptorsForConstant(constant_id)[0],
154       ir_context->TakeNextId(), ir_context->TakeNextId());
155 }
156 
157 }  // namespace
158 
ForceRenderRed(const spv_target_env & target_env,spv_validator_options validator_options,const std::vector<uint32_t> & binary_in,const spvtools::fuzz::protobufs::FactSequence & initial_facts,std::vector<uint32_t> * binary_out)159 bool ForceRenderRed(
160     const spv_target_env& target_env, spv_validator_options validator_options,
161     const std::vector<uint32_t>& binary_in,
162     const spvtools::fuzz::protobufs::FactSequence& initial_facts,
163     std::vector<uint32_t>* binary_out) {
164   auto message_consumer = spvtools::utils::CLIMessageConsumer;
165   spvtools::SpirvTools tools(target_env);
166   if (!tools.IsValid()) {
167     message_consumer(SPV_MSG_ERROR, nullptr, {},
168                      "Failed to create SPIRV-Tools interface; stopping.");
169     return false;
170   }
171 
172   // Initial binary should be valid.
173   if (!tools.Validate(&binary_in[0], binary_in.size(), validator_options)) {
174     message_consumer(SPV_MSG_ERROR, nullptr, {},
175                      "Initial binary is invalid; stopping.");
176     return false;
177   }
178 
179   // Build the module from the input binary.
180   std::unique_ptr<opt::IRContext> ir_context = BuildModule(
181       target_env, message_consumer, binary_in.data(), binary_in.size());
182   assert(ir_context);
183 
184   // Set up a fact manager with any given initial facts.
185   TransformationContext transformation_context(
186       MakeUnique<FactManager>(ir_context.get()), validator_options);
187   for (auto& fact : initial_facts.fact()) {
188     transformation_context.GetFactManager()->MaybeAddFact(fact);
189   }
190 
191   auto entry_point_function =
192       FindFragmentShaderEntryPoint(ir_context.get(), message_consumer);
193   auto output_variable =
194       FindVec4OutputVariable(ir_context.get(), message_consumer);
195   if (entry_point_function == nullptr || output_variable == nullptr) {
196     return false;
197   }
198 
199   opt::analysis::Float temp_float_type(32);
200   opt::analysis::Float* float_type = ir_context->get_type_mgr()
201                                          ->GetRegisteredType(&temp_float_type)
202                                          ->AsFloat();
203   std::pair<uint32_t, uint32_t> zero_one_float_ids =
204       FindOrCreateFloatZeroAndOne(ir_context.get(), float_type);
205 
206   // Make the new exit block
207   auto new_exit_block_id = ir_context->TakeNextId();
208   {
209     auto label = MakeUnique<opt::Instruction>(ir_context.get(), SpvOpLabel, 0,
210                                               new_exit_block_id,
211                                               opt::Instruction::OperandList());
212     auto new_exit_block = MakeUnique<opt::BasicBlock>(std::move(label));
213     new_exit_block->AddInstruction(MakeUnique<opt::Instruction>(
214         ir_context.get(), SpvOpReturn, 0, 0, opt::Instruction::OperandList()));
215     new_exit_block->SetParent(entry_point_function);
216     entry_point_function->AddBasicBlock(std::move(new_exit_block));
217   }
218 
219   // Make the new entry block
220   {
221     auto label = MakeUnique<opt::Instruction>(ir_context.get(), SpvOpLabel, 0,
222                                               ir_context->TakeNextId(),
223                                               opt::Instruction::OperandList());
224     auto new_entry_block = MakeUnique<opt::BasicBlock>(std::move(label));
225 
226     // Make an instruction to construct vec4(1.0, 0.0, 0.0, 1.0), representing
227     // the colour red.
228     opt::Operand zero_float = {SPV_OPERAND_TYPE_ID, {zero_one_float_ids.first}};
229     opt::Operand one_float = {SPV_OPERAND_TYPE_ID, {zero_one_float_ids.second}};
230     opt::Instruction::OperandList op_composite_construct_operands = {
231         one_float, zero_float, zero_float, one_float};
232     auto temp_vec4 = opt::analysis::Vector(float_type, 4);
233     auto vec4_id = ir_context->get_type_mgr()->GetId(&temp_vec4);
234     auto red = MakeUnique<opt::Instruction>(
235         ir_context.get(), SpvOpCompositeConstruct, vec4_id,
236         ir_context->TakeNextId(), op_composite_construct_operands);
237     auto red_id = red->result_id();
238     new_entry_block->AddInstruction(std::move(red));
239 
240     // Make an instruction to store red into the output color.
241     opt::Operand variable_to_store_into = {SPV_OPERAND_TYPE_ID,
242                                            {output_variable->result_id()}};
243     opt::Operand value_to_be_stored = {SPV_OPERAND_TYPE_ID, {red_id}};
244     opt::Instruction::OperandList op_store_operands = {variable_to_store_into,
245                                                        value_to_be_stored};
246     new_entry_block->AddInstruction(MakeUnique<opt::Instruction>(
247         ir_context.get(), SpvOpStore, 0, 0, op_store_operands));
248 
249     // We are going to attempt to construct 'false' as an expression of the form
250     // 'literal1 > literal2'. If we succeed, we will later replace each literal
251     // with a uniform of the same value - we can only do that replacement once
252     // we have added the entry block to the module.
253     std::unique_ptr<TransformationReplaceConstantWithUniform>
254         first_greater_then_operand_replacement = nullptr;
255     std::unique_ptr<TransformationReplaceConstantWithUniform>
256         second_greater_then_operand_replacement = nullptr;
257     uint32_t id_guaranteed_to_be_false = 0;
258 
259     opt::analysis::Bool temp_bool_type;
260     opt::analysis::Bool* registered_bool_type =
261         ir_context->get_type_mgr()
262             ->GetRegisteredType(&temp_bool_type)
263             ->AsBool();
264 
265     auto float_type_id = ir_context->get_type_mgr()->GetId(float_type);
266     auto types_for_which_uniforms_are_known =
267         transformation_context.GetFactManager()
268             ->GetTypesForWhichUniformValuesAreKnown();
269 
270     // Check whether we have any float uniforms.
271     if (std::find(types_for_which_uniforms_are_known.begin(),
272                   types_for_which_uniforms_are_known.end(),
273                   float_type_id) != types_for_which_uniforms_are_known.end()) {
274       // We have at least one float uniform; let's see whether we have at least
275       // two.
276       auto available_constants =
277           transformation_context.GetFactManager()
278               ->GetConstantsAvailableFromUniformsForType(float_type_id);
279       if (available_constants.size() > 1) {
280         // Grab the float constants associated with the first two known float
281         // uniforms.
282         auto first_constant =
283             ir_context->get_constant_mgr()
284                 ->GetConstantFromInst(ir_context->get_def_use_mgr()->GetDef(
285                     available_constants[0]))
286                 ->AsFloatConstant();
287         auto second_constant =
288             ir_context->get_constant_mgr()
289                 ->GetConstantFromInst(ir_context->get_def_use_mgr()->GetDef(
290                     available_constants[1]))
291                 ->AsFloatConstant();
292 
293         // Now work out which of the two constants is larger than the other.
294         uint32_t larger_constant_index = 0;
295         uint32_t smaller_constant_index = 0;
296         if (first_constant->GetFloat() > second_constant->GetFloat()) {
297           larger_constant_index = 0;
298           smaller_constant_index = 1;
299         } else if (first_constant->GetFloat() < second_constant->GetFloat()) {
300           larger_constant_index = 1;
301           smaller_constant_index = 0;
302         }
303 
304         // Only proceed with these constants if they have turned out to be
305         // distinct.
306         if (larger_constant_index != smaller_constant_index) {
307           // We are in a position to create 'false' as 'literal1 > literal2', so
308           // reserve an id for this computation; this id will end up being
309           // guaranteed to be 'false'.
310           id_guaranteed_to_be_false = ir_context->TakeNextId();
311 
312           auto smaller_constant = available_constants[smaller_constant_index];
313           auto larger_constant = available_constants[larger_constant_index];
314 
315           opt::Instruction::OperandList greater_than_operands = {
316               {SPV_OPERAND_TYPE_ID, {smaller_constant}},
317               {SPV_OPERAND_TYPE_ID, {larger_constant}}};
318           new_entry_block->AddInstruction(MakeUnique<opt::Instruction>(
319               ir_context.get(), SpvOpFOrdGreaterThan,
320               ir_context->get_type_mgr()->GetId(registered_bool_type),
321               id_guaranteed_to_be_false, greater_than_operands));
322 
323           first_greater_then_operand_replacement =
324               MakeConstantUniformReplacement(
325                   ir_context.get(), *transformation_context.GetFactManager(),
326                   smaller_constant, id_guaranteed_to_be_false, 0);
327           second_greater_then_operand_replacement =
328               MakeConstantUniformReplacement(
329                   ir_context.get(), *transformation_context.GetFactManager(),
330                   larger_constant, id_guaranteed_to_be_false, 1);
331         }
332       }
333     }
334 
335     if (id_guaranteed_to_be_false == 0) {
336       auto constant_false = ir_context->get_constant_mgr()->RegisterConstant(
337           MakeUnique<opt::analysis::BoolConstant>(registered_bool_type, false));
338       id_guaranteed_to_be_false = ir_context->get_constant_mgr()
339                                       ->GetDefiningInstruction(constant_false)
340                                       ->result_id();
341     }
342 
343     opt::Operand false_condition = {SPV_OPERAND_TYPE_ID,
344                                     {id_guaranteed_to_be_false}};
345     opt::Operand then_block = {SPV_OPERAND_TYPE_ID,
346                                {entry_point_function->entry()->id()}};
347     opt::Operand else_block = {SPV_OPERAND_TYPE_ID, {new_exit_block_id}};
348     opt::Instruction::OperandList op_branch_conditional_operands = {
349         false_condition, then_block, else_block};
350     new_entry_block->AddInstruction(
351         MakeUnique<opt::Instruction>(ir_context.get(), SpvOpBranchConditional,
352                                      0, 0, op_branch_conditional_operands));
353 
354     entry_point_function->InsertBasicBlockBefore(
355         std::move(new_entry_block), entry_point_function->entry().get());
356 
357     for (auto& replacement : {first_greater_then_operand_replacement.get(),
358                               second_greater_then_operand_replacement.get()}) {
359       if (replacement) {
360         assert(replacement->IsApplicable(ir_context.get(),
361                                          transformation_context));
362         replacement->Apply(ir_context.get(), &transformation_context);
363       }
364     }
365   }
366 
367   // Write out the module as a binary.
368   ir_context->module()->ToBinary(binary_out, false);
369   return true;
370 }
371 
372 }  // namespace fuzz
373 }  // namespace spvtools
374