transformation_replace_params_with_struct.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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_params_with_struct.h"
  15. #include <vector>
  16. #include "source/fuzz/fuzzer_util.h"
  17. namespace spvtools {
  18. namespace fuzz {
  19. TransformationReplaceParamsWithStruct::TransformationReplaceParamsWithStruct(
  20. const protobufs::TransformationReplaceParamsWithStruct& message)
  21. : message_(message) {}
  22. TransformationReplaceParamsWithStruct::TransformationReplaceParamsWithStruct(
  23. const std::vector<uint32_t>& parameter_id, uint32_t fresh_function_type_id,
  24. uint32_t fresh_parameter_id,
  25. const std::unordered_map<uint32_t, uint32_t>&
  26. caller_id_to_fresh_composite_id) {
  27. message_.set_fresh_function_type_id(fresh_function_type_id);
  28. message_.set_fresh_parameter_id(fresh_parameter_id);
  29. for (auto id : parameter_id) {
  30. message_.add_parameter_id(id);
  31. }
  32. message_.mutable_caller_id_to_fresh_composite_id()->insert(
  33. caller_id_to_fresh_composite_id.begin(),
  34. caller_id_to_fresh_composite_id.end());
  35. }
  36. bool TransformationReplaceParamsWithStruct::IsApplicable(
  37. opt::IRContext* ir_context, const TransformationContext& /*unused*/) const {
  38. std::vector<uint32_t> parameter_id(message_.parameter_id().begin(),
  39. message_.parameter_id().end());
  40. // Check that |parameter_id| is neither empty nor it has duplicates.
  41. if (parameter_id.empty() || fuzzerutil::HasDuplicates(parameter_id)) {
  42. return false;
  43. }
  44. // All ids must correspond to valid parameters of the same function.
  45. // The function can't be an entry-point function.
  46. // fuzzerutil::GetFunctionFromParameterId requires a valid id.
  47. if (!ir_context->get_def_use_mgr()->GetDef(parameter_id[0])) {
  48. return false;
  49. }
  50. const auto* function =
  51. fuzzerutil::GetFunctionFromParameterId(ir_context, parameter_id[0]);
  52. if (!function ||
  53. fuzzerutil::FunctionIsEntryPoint(ir_context, function->result_id())) {
  54. return false;
  55. }
  56. // Compute all ids of the function's parameters.
  57. std::unordered_set<uint32_t> all_parameter_ids;
  58. for (const auto* param :
  59. fuzzerutil::GetParameters(ir_context, function->result_id())) {
  60. all_parameter_ids.insert(param->result_id());
  61. }
  62. // Check that all elements in |parameter_id| are valid.
  63. for (auto id : parameter_id) {
  64. // fuzzerutil::GetFunctionFromParameterId requires a valid id.
  65. if (!ir_context->get_def_use_mgr()->GetDef(id)) {
  66. return false;
  67. }
  68. // Check that |id| is a result id of one of the |function|'s parameters.
  69. if (!all_parameter_ids.count(id)) {
  70. return false;
  71. }
  72. // Check that the parameter with result id |id| has supported type.
  73. const auto* type = ir_context->get_type_mgr()->GetType(
  74. fuzzerutil::GetTypeId(ir_context, id));
  75. assert(type && "Parameter has invalid type");
  76. if (!IsParameterTypeSupported(*type)) {
  77. return false;
  78. }
  79. }
  80. // We already know that the function has at least |parameter_id.size()|
  81. // parameters.
  82. // Check that a relevant OpTypeStruct exists in the module.
  83. if (!MaybeGetRequiredStructType(ir_context)) {
  84. return false;
  85. }
  86. // Check that |callee_id_to_fresh_composite_id| is valid.
  87. for (const auto* inst :
  88. fuzzerutil::GetCallers(ir_context, function->result_id())) {
  89. // Check that the callee is present in the map. It's ok if the map contains
  90. // more ids that there are callees (those ids will not be used).
  91. if (!message_.caller_id_to_fresh_composite_id().contains(
  92. inst->result_id())) {
  93. return false;
  94. }
  95. }
  96. // Check that all fresh ids are unique and fresh.
  97. std::vector<uint32_t> fresh_ids = {message_.fresh_function_type_id(),
  98. message_.fresh_parameter_id()};
  99. for (const auto& entry : message_.caller_id_to_fresh_composite_id()) {
  100. fresh_ids.push_back(entry.second);
  101. }
  102. return !fuzzerutil::HasDuplicates(fresh_ids) &&
  103. std::all_of(fresh_ids.begin(), fresh_ids.end(),
  104. [ir_context](uint32_t id) {
  105. return fuzzerutil::IsFreshId(ir_context, id);
  106. });
  107. }
  108. void TransformationReplaceParamsWithStruct::Apply(
  109. opt::IRContext* ir_context, TransformationContext* /*unused*/) const {
  110. auto* function = fuzzerutil::GetFunctionFromParameterId(
  111. ir_context, message_.parameter_id(0));
  112. assert(function &&
  113. "All parameters' ids should've been checked in the IsApplicable");
  114. // Get a type id of the OpTypeStruct used as a type id of the new parameter.
  115. auto struct_type_id = MaybeGetRequiredStructType(ir_context);
  116. assert(struct_type_id &&
  117. "IsApplicable should've guaranteed that this value isn't equal to 0");
  118. // Add new parameter to the function.
  119. function->AddParameter(MakeUnique<opt::Instruction>(
  120. ir_context, SpvOpFunctionParameter, struct_type_id,
  121. message_.fresh_parameter_id(), opt::Instruction::OperandList()));
  122. fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_parameter_id());
  123. // Compute indices of replaced parameters. This will be used to adjust
  124. // OpFunctionCall instructions and create OpCompositeConstruct instructions at
  125. // every call site.
  126. std::vector<uint32_t> indices_of_replaced_params;
  127. {
  128. // We want to destroy |params| after the loop because it will contain
  129. // dangling pointers when we remove parameters from the function.
  130. auto params = fuzzerutil::GetParameters(ir_context, function->result_id());
  131. for (auto id : message_.parameter_id()) {
  132. auto it = std::find_if(params.begin(), params.end(),
  133. [id](const opt::Instruction* param) {
  134. return param->result_id() == id;
  135. });
  136. assert(it != params.end() && "Parameter's id is invalid");
  137. indices_of_replaced_params.push_back(
  138. static_cast<uint32_t>(it - params.begin()));
  139. }
  140. }
  141. // Update all function calls.
  142. for (auto* inst : fuzzerutil::GetCallers(ir_context, function->result_id())) {
  143. // Create a list of operands for the OpCompositeConstruct instruction.
  144. opt::Instruction::OperandList composite_components;
  145. for (auto index : indices_of_replaced_params) {
  146. // +1 since the first in operand to OpFunctionCall is the result id of
  147. // the function.
  148. composite_components.emplace_back(
  149. std::move(inst->GetInOperand(index + 1)));
  150. }
  151. // Remove arguments from the function call. We do it in a separate loop
  152. // and in reverse order to make sure we have removed correct operands.
  153. for (auto it = indices_of_replaced_params.rbegin();
  154. it != indices_of_replaced_params.rend(); ++it) {
  155. // +1 since the first in operand to OpFunctionCall is the result id of
  156. // the function.
  157. inst->RemoveInOperand(*it + 1);
  158. }
  159. // Insert OpCompositeConstruct before the function call.
  160. auto fresh_composite_id =
  161. message_.caller_id_to_fresh_composite_id().at(inst->result_id());
  162. inst->InsertBefore(MakeUnique<opt::Instruction>(
  163. ir_context, SpvOpCompositeConstruct, struct_type_id, fresh_composite_id,
  164. std::move(composite_components)));
  165. // Add a new operand to the OpFunctionCall instruction.
  166. inst->AddOperand({SPV_OPERAND_TYPE_ID, {fresh_composite_id}});
  167. fuzzerutil::UpdateModuleIdBound(ir_context, fresh_composite_id);
  168. }
  169. // Insert OpCompositeExtract instructions into the entry point block of the
  170. // function and remove replaced parameters.
  171. for (int i = 0; i < message_.parameter_id_size(); ++i) {
  172. const auto* param_inst =
  173. ir_context->get_def_use_mgr()->GetDef(message_.parameter_id(i));
  174. assert(param_inst && "Parameter id is invalid");
  175. // Skip all OpVariable instructions.
  176. auto iter = function->begin()->begin();
  177. while (iter != function->begin()->end() &&
  178. !fuzzerutil::CanInsertOpcodeBeforeInstruction(SpvOpCompositeExtract,
  179. iter)) {
  180. ++iter;
  181. }
  182. assert(fuzzerutil::CanInsertOpcodeBeforeInstruction(SpvOpCompositeExtract,
  183. iter) &&
  184. "Can't extract parameter's value from the structure");
  185. // Insert OpCompositeExtract instructions to unpack parameters' values from
  186. // the struct type.
  187. iter.InsertBefore(MakeUnique<opt::Instruction>(
  188. ir_context, SpvOpCompositeExtract, param_inst->type_id(),
  189. param_inst->result_id(),
  190. opt::Instruction::OperandList{
  191. {SPV_OPERAND_TYPE_ID, {message_.fresh_parameter_id()}},
  192. {SPV_OPERAND_TYPE_LITERAL_INTEGER, {static_cast<uint32_t>(i)}}}));
  193. function->RemoveParameter(param_inst->result_id());
  194. }
  195. // Update function's type.
  196. {
  197. // We use a separate scope here since |old_function_type| might become a
  198. // dangling pointer after the call to the fuzzerutil::UpdateFunctionType.
  199. auto* old_function_type = fuzzerutil::GetFunctionType(ir_context, function);
  200. assert(old_function_type && "Function has invalid type");
  201. // +1 since the first in operand to OpTypeFunction is the result type id
  202. // of the function.
  203. std::vector<uint32_t> parameter_type_ids;
  204. for (uint32_t i = 1; i < old_function_type->NumInOperands(); ++i) {
  205. if (std::find(indices_of_replaced_params.begin(),
  206. indices_of_replaced_params.end(),
  207. i - 1) == indices_of_replaced_params.end()) {
  208. parameter_type_ids.push_back(
  209. old_function_type->GetSingleWordInOperand(i));
  210. }
  211. }
  212. parameter_type_ids.push_back(struct_type_id);
  213. fuzzerutil::UpdateFunctionType(
  214. ir_context, function->result_id(), message_.fresh_function_type_id(),
  215. old_function_type->GetSingleWordInOperand(0), parameter_type_ids);
  216. }
  217. // Make sure our changes are analyzed
  218. ir_context->InvalidateAnalysesExceptFor(
  219. opt::IRContext::Analysis::kAnalysisNone);
  220. }
  221. protobufs::Transformation TransformationReplaceParamsWithStruct::ToMessage()
  222. const {
  223. protobufs::Transformation result;
  224. *result.mutable_replace_params_with_struct() = message_;
  225. return result;
  226. }
  227. bool TransformationReplaceParamsWithStruct::IsParameterTypeSupported(
  228. const opt::analysis::Type& param_type) {
  229. // TODO(https://github.com/KhronosGroup/SPIRV-Tools/issues/3403):
  230. // Consider adding support for more types of parameters.
  231. switch (param_type.kind()) {
  232. case opt::analysis::Type::kBool:
  233. case opt::analysis::Type::kInteger:
  234. case opt::analysis::Type::kFloat:
  235. case opt::analysis::Type::kArray:
  236. case opt::analysis::Type::kVector:
  237. case opt::analysis::Type::kMatrix:
  238. return true;
  239. case opt::analysis::Type::kStruct:
  240. return std::all_of(param_type.AsStruct()->element_types().begin(),
  241. param_type.AsStruct()->element_types().end(),
  242. [](const opt::analysis::Type* type) {
  243. return IsParameterTypeSupported(*type);
  244. });
  245. default:
  246. return false;
  247. }
  248. }
  249. uint32_t TransformationReplaceParamsWithStruct::MaybeGetRequiredStructType(
  250. opt::IRContext* ir_context) const {
  251. std::vector<uint32_t> component_type_ids;
  252. for (auto id : message_.parameter_id()) {
  253. component_type_ids.push_back(fuzzerutil::GetTypeId(ir_context, id));
  254. }
  255. return fuzzerutil::MaybeGetStructType(ir_context, component_type_ids);
  256. }
  257. } // namespace fuzz
  258. } // namespace spvtools