force_render_red.cpp 16 KB

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