transformation_replace_parameter_with_global.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. #include "source/fuzz/transformation_replace_parameter_with_global.h"
  15. #include <vector>
  16. #include "source/fuzz/fuzzer_util.h"
  17. namespace spvtools {
  18. namespace fuzz {
  19. namespace {
  20. opt::Function* GetFunctionFromParameterId(opt::IRContext* ir_context,
  21. uint32_t param_id) {
  22. auto* param_inst = ir_context->get_def_use_mgr()->GetDef(param_id);
  23. assert(param_inst && "Parameter id is invalid");
  24. for (auto& function : *ir_context->module()) {
  25. if (fuzzerutil::InstructionIsFunctionParameter(param_inst, &function)) {
  26. return &function;
  27. }
  28. }
  29. return nullptr;
  30. }
  31. } // namespace
  32. TransformationReplaceParameterWithGlobal::
  33. TransformationReplaceParameterWithGlobal(
  34. const protobufs::TransformationReplaceParameterWithGlobal& message)
  35. : message_(message) {}
  36. TransformationReplaceParameterWithGlobal::
  37. TransformationReplaceParameterWithGlobal(
  38. uint32_t function_type_fresh_id, uint32_t parameter_id,
  39. uint32_t global_variable_fresh_id) {
  40. message_.set_function_type_fresh_id(function_type_fresh_id);
  41. message_.set_parameter_id(parameter_id);
  42. message_.set_global_variable_fresh_id(global_variable_fresh_id);
  43. }
  44. bool TransformationReplaceParameterWithGlobal::IsApplicable(
  45. opt::IRContext* ir_context, const TransformationContext& /*unused*/) const {
  46. // Check that |parameter_id| is valid.
  47. const auto* param_inst =
  48. ir_context->get_def_use_mgr()->GetDef(message_.parameter_id());
  49. if (!param_inst || param_inst->opcode() != SpvOpFunctionParameter) {
  50. return false;
  51. }
  52. // Check that function exists and is not an entry point.
  53. const auto* function =
  54. GetFunctionFromParameterId(ir_context, message_.parameter_id());
  55. if (!function ||
  56. fuzzerutil::FunctionIsEntryPoint(ir_context, function->result_id())) {
  57. return false;
  58. }
  59. // We already know that the function has at least one parameter -
  60. // |parameter_id|.
  61. // Check that replaced parameter has valid type.
  62. const auto* param_type =
  63. ir_context->get_type_mgr()->GetType(param_inst->type_id());
  64. assert(param_type && "Parameter has invalid type");
  65. if (!CanReplaceFunctionParameterType(*param_type)) {
  66. return false;
  67. }
  68. // Check that initializer for the global variable exists in the module.
  69. if (fuzzerutil::MaybeGetZeroConstant(ir_context, param_inst->type_id()) ==
  70. 0) {
  71. return false;
  72. }
  73. // Check that pointer type for the global variable exists in the module.
  74. if (!fuzzerutil::MaybeGetPointerType(ir_context, param_inst->type_id(),
  75. SpvStorageClassPrivate)) {
  76. return false;
  77. }
  78. return fuzzerutil::IsFreshId(ir_context, message_.function_type_fresh_id()) &&
  79. fuzzerutil::IsFreshId(ir_context,
  80. message_.global_variable_fresh_id()) &&
  81. message_.function_type_fresh_id() !=
  82. message_.global_variable_fresh_id();
  83. }
  84. void TransformationReplaceParameterWithGlobal::Apply(
  85. opt::IRContext* ir_context, TransformationContext* /*unused*/) 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. // Create global variable to store parameter's value.
  90. //
  91. // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/3177):
  92. // Mark the global variable's pointee as irrelevant if replaced parameter is
  93. // irrelevant.
  94. fuzzerutil::AddGlobalVariable(
  95. ir_context, message_.global_variable_fresh_id(),
  96. fuzzerutil::MaybeGetPointerType(ir_context, param_inst->type_id(),
  97. SpvStorageClassPrivate),
  98. SpvStorageClassPrivate,
  99. fuzzerutil::MaybeGetZeroConstant(ir_context, param_inst->type_id()));
  100. auto* function =
  101. GetFunctionFromParameterId(ir_context, message_.parameter_id());
  102. assert(function && "Function must exist");
  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. assert(fuzzerutil::CanInsertOpcodeBeforeInstruction(SpvOpLoad, it) &&
  110. "Can't insert OpLoad or OpCopyMemory into the first basic block of "
  111. "the function");
  112. it.InsertBefore(MakeUnique<opt::Instruction>(
  113. ir_context, SpvOpLoad, param_inst->type_id(), param_inst->result_id(),
  114. opt::Instruction::OperandList{
  115. {SPV_OPERAND_TYPE_ID, {message_.global_variable_fresh_id()}}}));
  116. // Calculate the index of the replaced parameter (we need to know this to
  117. // remove operands from the OpFunctionCall).
  118. auto params = fuzzerutil::GetParameters(ir_context, function->result_id());
  119. auto parameter_index = static_cast<uint32_t>(params.size());
  120. for (uint32_t i = 0, n = static_cast<uint32_t>(params.size()); i < n; ++i) {
  121. if (params[i]->result_id() == message_.parameter_id()) {
  122. parameter_index = i;
  123. break;
  124. }
  125. }
  126. assert(parameter_index != params.size() &&
  127. "Parameter must exist in the function");
  128. // Update all relevant OpFunctionCall instructions.
  129. ir_context->get_def_use_mgr()->ForEachUser(
  130. function->result_id(),
  131. [ir_context, parameter_index, this](opt::Instruction* inst) {
  132. if (inst->opcode() != SpvOpFunctionCall) {
  133. return;
  134. }
  135. assert(fuzzerutil::CanInsertOpcodeBeforeInstruction(SpvOpStore, inst) &&
  136. "Can't insert OpStore right before the function call");
  137. // Insert an OpStore before the OpFunctionCall. +1 since the first
  138. // operand of OpFunctionCall is an id of the function.
  139. inst->InsertBefore(MakeUnique<opt::Instruction>(
  140. ir_context, SpvOpStore, 0, 0,
  141. opt::Instruction::OperandList{
  142. {SPV_OPERAND_TYPE_ID, {message_.global_variable_fresh_id()}},
  143. {SPV_OPERAND_TYPE_ID,
  144. {inst->GetSingleWordInOperand(parameter_index + 1)}}}));
  145. // +1 since the first operand of OpFunctionCall is an id of the
  146. // function.
  147. inst->RemoveInOperand(parameter_index + 1);
  148. });
  149. // Remove the parameter from the function.
  150. function->RemoveParameter(message_.parameter_id());
  151. // Update function's type.
  152. auto* old_function_type = fuzzerutil::GetFunctionType(ir_context, function);
  153. assert(old_function_type && "Function has invalid type");
  154. // Preemptively add function's return type id.
  155. std::vector<uint32_t> type_ids = {
  156. old_function_type->GetSingleWordInOperand(0)};
  157. // +1 and -1 since the first operand is the return type id.
  158. for (uint32_t i = 1; i < old_function_type->NumInOperands(); ++i) {
  159. if (i - 1 != parameter_index) {
  160. type_ids.push_back(old_function_type->GetSingleWordInOperand(i));
  161. }
  162. }
  163. if (ir_context->get_def_use_mgr()->NumUsers(old_function_type) == 1) {
  164. // Change the old type in place. +1 since the first operand is the result
  165. // type id of the function.
  166. old_function_type->RemoveInOperand(parameter_index + 1);
  167. } else {
  168. // Find an existing or create a new function type.
  169. function->DefInst().SetInOperand(
  170. 1, {fuzzerutil::FindOrCreateFunctionType(
  171. ir_context, message_.function_type_fresh_id(), type_ids)});
  172. }
  173. // Make sure our changes are analyzed
  174. ir_context->InvalidateAnalysesExceptFor(
  175. opt::IRContext::Analysis::kAnalysisNone);
  176. }
  177. protobufs::Transformation TransformationReplaceParameterWithGlobal::ToMessage()
  178. const {
  179. protobufs::Transformation result;
  180. *result.mutable_replace_parameter_with_global() = message_;
  181. return result;
  182. }
  183. bool TransformationReplaceParameterWithGlobal::CanReplaceFunctionParameterType(
  184. const opt::analysis::Type& type) {
  185. // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/3403):
  186. // Think about other type instructions we can add here.
  187. switch (type.kind()) {
  188. case opt::analysis::Type::kBool:
  189. case opt::analysis::Type::kInteger:
  190. case opt::analysis::Type::kFloat:
  191. case opt::analysis::Type::kArray:
  192. case opt::analysis::Type::kMatrix:
  193. case opt::analysis::Type::kVector:
  194. return true;
  195. case opt::analysis::Type::kStruct:
  196. return std::all_of(
  197. type.AsStruct()->element_types().begin(),
  198. type.AsStruct()->element_types().end(),
  199. [](const opt::analysis::Type* element_type) {
  200. return CanReplaceFunctionParameterType(*element_type);
  201. });
  202. default:
  203. return false;
  204. }
  205. }
  206. } // namespace fuzz
  207. } // namespace spvtools