transformation_replace_params_with_struct.cpp 12 KB

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