force_render_red.cpp 16 KB

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