transformation_outline_function.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  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/transformation_outline_function.h"
  15. #include <set>
  16. #include "source/fuzz/fuzzer_util.h"
  17. namespace spvtools {
  18. namespace fuzz {
  19. TransformationOutlineFunction::TransformationOutlineFunction(
  20. const spvtools::fuzz::protobufs::TransformationOutlineFunction& message)
  21. : message_(message) {}
  22. TransformationOutlineFunction::TransformationOutlineFunction(
  23. uint32_t entry_block, uint32_t exit_block,
  24. uint32_t new_function_struct_return_type_id, uint32_t new_function_type_id,
  25. uint32_t new_function_id, uint32_t new_function_region_entry_block,
  26. uint32_t new_caller_result_id, uint32_t new_callee_result_id,
  27. const std::map<uint32_t, uint32_t>& input_id_to_fresh_id,
  28. const std::map<uint32_t, uint32_t>& output_id_to_fresh_id) {
  29. message_.set_entry_block(entry_block);
  30. message_.set_exit_block(exit_block);
  31. message_.set_new_function_struct_return_type_id(
  32. new_function_struct_return_type_id);
  33. message_.set_new_function_type_id(new_function_type_id);
  34. message_.set_new_function_id(new_function_id);
  35. message_.set_new_function_region_entry_block(new_function_region_entry_block);
  36. message_.set_new_caller_result_id(new_caller_result_id);
  37. message_.set_new_callee_result_id(new_callee_result_id);
  38. *message_.mutable_input_id_to_fresh_id() =
  39. fuzzerutil::MapToRepeatedUInt32Pair(input_id_to_fresh_id);
  40. *message_.mutable_output_id_to_fresh_id() =
  41. fuzzerutil::MapToRepeatedUInt32Pair(output_id_to_fresh_id);
  42. }
  43. bool TransformationOutlineFunction::IsApplicable(
  44. opt::IRContext* ir_context,
  45. const TransformationContext& transformation_context) const {
  46. std::set<uint32_t> ids_used_by_this_transformation;
  47. // The various new ids used by the transformation must be fresh and distinct.
  48. if (!CheckIdIsFreshAndNotUsedByThisTransformation(
  49. message_.new_function_struct_return_type_id(), ir_context,
  50. &ids_used_by_this_transformation)) {
  51. return false;
  52. }
  53. if (!CheckIdIsFreshAndNotUsedByThisTransformation(
  54. message_.new_function_type_id(), ir_context,
  55. &ids_used_by_this_transformation)) {
  56. return false;
  57. }
  58. if (!CheckIdIsFreshAndNotUsedByThisTransformation(
  59. message_.new_function_id(), ir_context,
  60. &ids_used_by_this_transformation)) {
  61. return false;
  62. }
  63. if (!CheckIdIsFreshAndNotUsedByThisTransformation(
  64. message_.new_function_region_entry_block(), ir_context,
  65. &ids_used_by_this_transformation)) {
  66. return false;
  67. }
  68. if (!CheckIdIsFreshAndNotUsedByThisTransformation(
  69. message_.new_caller_result_id(), ir_context,
  70. &ids_used_by_this_transformation)) {
  71. return false;
  72. }
  73. if (!CheckIdIsFreshAndNotUsedByThisTransformation(
  74. message_.new_callee_result_id(), ir_context,
  75. &ids_used_by_this_transformation)) {
  76. return false;
  77. }
  78. for (auto& pair : message_.input_id_to_fresh_id()) {
  79. if (!CheckIdIsFreshAndNotUsedByThisTransformation(
  80. pair.second(), ir_context, &ids_used_by_this_transformation)) {
  81. return false;
  82. }
  83. }
  84. for (auto& pair : message_.output_id_to_fresh_id()) {
  85. if (!CheckIdIsFreshAndNotUsedByThisTransformation(
  86. pair.second(), ir_context, &ids_used_by_this_transformation)) {
  87. return false;
  88. }
  89. }
  90. // The entry and exit block ids must indeed refer to blocks.
  91. for (auto block_id : {message_.entry_block(), message_.exit_block()}) {
  92. auto block_label = ir_context->get_def_use_mgr()->GetDef(block_id);
  93. if (!block_label || block_label->opcode() != SpvOpLabel) {
  94. return false;
  95. }
  96. }
  97. auto entry_block = ir_context->cfg()->block(message_.entry_block());
  98. auto exit_block = ir_context->cfg()->block(message_.exit_block());
  99. // The entry block cannot start with OpVariable - this would mean that
  100. // outlining would remove a variable from the function containing the region
  101. // being outlined.
  102. if (entry_block->begin()->opcode() == SpvOpVariable) {
  103. return false;
  104. }
  105. // For simplicity, we do not allow the entry block to be a loop header.
  106. if (entry_block->GetLoopMergeInst()) {
  107. return false;
  108. }
  109. // For simplicity, we do not allow the exit block to be a merge block or
  110. // continue target.
  111. if (fuzzerutil::IsMergeOrContinue(ir_context, exit_block->id())) {
  112. return false;
  113. }
  114. // The entry block cannot start with OpPhi. This is to keep the
  115. // transformation logic simple. (Another transformation to split the OpPhis
  116. // from a block could be applied to avoid this scenario.)
  117. if (entry_block->begin()->opcode() == SpvOpPhi) {
  118. return false;
  119. }
  120. // The block must be in the same function.
  121. if (entry_block->GetParent() != exit_block->GetParent()) {
  122. return false;
  123. }
  124. // The entry block must dominate the exit block.
  125. auto dominator_analysis =
  126. ir_context->GetDominatorAnalysis(entry_block->GetParent());
  127. if (!dominator_analysis->Dominates(entry_block, exit_block)) {
  128. return false;
  129. }
  130. // The exit block must post-dominate the entry block.
  131. auto postdominator_analysis =
  132. ir_context->GetPostDominatorAnalysis(entry_block->GetParent());
  133. if (!postdominator_analysis->Dominates(exit_block, entry_block)) {
  134. return false;
  135. }
  136. // Find all the blocks dominated by |message_.entry_block| and post-dominated
  137. // by |message_.exit_block|.
  138. auto region_set = GetRegionBlocks(
  139. ir_context,
  140. entry_block = ir_context->cfg()->block(message_.entry_block()),
  141. exit_block = ir_context->cfg()->block(message_.exit_block()));
  142. // Check whether |region_set| really is a single-entry single-exit region, and
  143. // also check whether structured control flow constructs and their merge
  144. // and continue constructs are either wholly in or wholly out of the region -
  145. // e.g. avoid the situation where the region contains the head of a loop but
  146. // not the loop's continue construct.
  147. //
  148. // This is achieved by going through every block in the function that contains
  149. // the region.
  150. for (auto& block : *entry_block->GetParent()) {
  151. if (&block == exit_block) {
  152. // It is OK (and typically expected) for the exit block of the region to
  153. // have successors outside the region.
  154. //
  155. // It is also OK for the exit block to head a selection construct: the
  156. // block containing the call to the outlined function will end up heading
  157. // this construct if outlining takes place. However, it is not OK for
  158. // the exit block to head a loop construct.
  159. if (block.GetLoopMergeInst()) {
  160. return false;
  161. }
  162. continue;
  163. }
  164. if (region_set.count(&block) != 0) {
  165. // The block is in the region and is not the region's exit block. Let's
  166. // see whether all of the block's successors are in the region. If they
  167. // are not, the region is not single-entry single-exit.
  168. bool all_successors_in_region = true;
  169. block.WhileEachSuccessorLabel([&all_successors_in_region, ir_context,
  170. &region_set](uint32_t successor) -> bool {
  171. if (region_set.count(ir_context->cfg()->block(successor)) == 0) {
  172. all_successors_in_region = false;
  173. return false;
  174. }
  175. return true;
  176. });
  177. if (!all_successors_in_region) {
  178. return false;
  179. }
  180. }
  181. if (auto merge = block.GetMergeInst()) {
  182. // The block is a loop or selection header -- the header and its
  183. // associated merge block had better both be in the region or both be
  184. // outside the region.
  185. auto merge_block =
  186. ir_context->cfg()->block(merge->GetSingleWordOperand(0));
  187. if (region_set.count(&block) != region_set.count(merge_block)) {
  188. return false;
  189. }
  190. }
  191. if (auto loop_merge = block.GetLoopMergeInst()) {
  192. // Similar to the above, but for the continue target of a loop.
  193. auto continue_target =
  194. ir_context->cfg()->block(loop_merge->GetSingleWordOperand(1));
  195. if (continue_target != exit_block &&
  196. region_set.count(&block) != region_set.count(continue_target)) {
  197. return false;
  198. }
  199. }
  200. }
  201. // For each region input id, i.e. every id defined outside the region but
  202. // used inside the region, ...
  203. auto input_id_to_fresh_id_map =
  204. fuzzerutil::RepeatedUInt32PairToMap(message_.input_id_to_fresh_id());
  205. for (auto id : GetRegionInputIds(ir_context, region_set, exit_block)) {
  206. // There needs to be a corresponding fresh id to be used as a function
  207. // parameter, or overflow ids need to be available.
  208. if (input_id_to_fresh_id_map.count(id) == 0 &&
  209. !transformation_context.GetOverflowIdSource()->HasOverflowIds()) {
  210. return false;
  211. }
  212. // Furthermore, if the input id has pointer type it must be an OpVariable
  213. // or OpFunctionParameter.
  214. auto input_id_inst = ir_context->get_def_use_mgr()->GetDef(id);
  215. if (ir_context->get_def_use_mgr()
  216. ->GetDef(input_id_inst->type_id())
  217. ->opcode() == SpvOpTypePointer) {
  218. switch (input_id_inst->opcode()) {
  219. case SpvOpFunctionParameter:
  220. case SpvOpVariable:
  221. // These are OK.
  222. break;
  223. default:
  224. // Anything else is not OK.
  225. return false;
  226. }
  227. }
  228. }
  229. // For each region output id -- i.e. every id defined inside the region but
  230. // used outside the region, ...
  231. auto output_id_to_fresh_id_map =
  232. fuzzerutil::RepeatedUInt32PairToMap(message_.output_id_to_fresh_id());
  233. for (auto id : GetRegionOutputIds(ir_context, region_set, exit_block)) {
  234. if (
  235. // ... there needs to be a corresponding fresh id that can hold the
  236. // value for this id computed in the outlined function (or overflow ids
  237. // must be available), and ...
  238. (output_id_to_fresh_id_map.count(id) == 0 &&
  239. !transformation_context.GetOverflowIdSource()->HasOverflowIds())
  240. // ... the output id must not have pointer type (to avoid creating a
  241. // struct with pointer members to pass data out of the outlined
  242. // function)
  243. || ir_context->get_def_use_mgr()
  244. ->GetDef(fuzzerutil::GetTypeId(ir_context, id))
  245. ->opcode() == SpvOpTypePointer) {
  246. return false;
  247. }
  248. }
  249. return true;
  250. }
  251. void TransformationOutlineFunction::Apply(
  252. opt::IRContext* ir_context,
  253. TransformationContext* transformation_context) const {
  254. // The entry block for the region before outlining.
  255. auto original_region_entry_block =
  256. ir_context->cfg()->block(message_.entry_block());
  257. // The exit block for the region before outlining.
  258. auto original_region_exit_block =
  259. ir_context->cfg()->block(message_.exit_block());
  260. // The single-entry single-exit region defined by |message_.entry_block| and
  261. // |message_.exit_block|.
  262. std::set<opt::BasicBlock*> region_blocks = GetRegionBlocks(
  263. ir_context, original_region_entry_block, original_region_exit_block);
  264. // Input and output ids for the region being outlined.
  265. std::vector<uint32_t> region_input_ids =
  266. GetRegionInputIds(ir_context, region_blocks, original_region_exit_block);
  267. std::vector<uint32_t> region_output_ids =
  268. GetRegionOutputIds(ir_context, region_blocks, original_region_exit_block);
  269. // Maps from input and output ids to fresh ids.
  270. auto input_id_to_fresh_id_map =
  271. fuzzerutil::RepeatedUInt32PairToMap(message_.input_id_to_fresh_id());
  272. auto output_id_to_fresh_id_map =
  273. fuzzerutil::RepeatedUInt32PairToMap(message_.output_id_to_fresh_id());
  274. // Use overflow ids to augment these maps at any locations where fresh ids are
  275. // required but not provided.
  276. for (uint32_t id : region_input_ids) {
  277. if (input_id_to_fresh_id_map.count(id) == 0) {
  278. input_id_to_fresh_id_map.insert(
  279. {id,
  280. transformation_context->GetOverflowIdSource()->GetNextOverflowId()});
  281. }
  282. }
  283. for (uint32_t id : region_output_ids) {
  284. if (output_id_to_fresh_id_map.count(id) == 0) {
  285. output_id_to_fresh_id_map.insert(
  286. {id,
  287. transformation_context->GetOverflowIdSource()->GetNextOverflowId()});
  288. }
  289. }
  290. UpdateModuleIdBoundForFreshIds(ir_context, input_id_to_fresh_id_map,
  291. output_id_to_fresh_id_map);
  292. // Construct a map that associates each output id with its type id.
  293. std::map<uint32_t, uint32_t> output_id_to_type_id;
  294. for (uint32_t output_id : region_output_ids) {
  295. output_id_to_type_id[output_id] =
  296. ir_context->get_def_use_mgr()->GetDef(output_id)->type_id();
  297. }
  298. // The region will be collapsed to a single block that calls a function
  299. // containing the outlined region. This block needs to end with whatever
  300. // the exit block of the region ended with before outlining. We thus clone
  301. // the terminator of the region's exit block, and the merge instruction for
  302. // the block if there is one, so that we can append them to the end of the
  303. // collapsed block later.
  304. std::unique_ptr<opt::Instruction> cloned_exit_block_terminator =
  305. std::unique_ptr<opt::Instruction>(
  306. original_region_exit_block->terminator()->Clone(ir_context));
  307. std::unique_ptr<opt::Instruction> cloned_exit_block_merge =
  308. original_region_exit_block->GetMergeInst()
  309. ? std::unique_ptr<opt::Instruction>(
  310. original_region_exit_block->GetMergeInst()->Clone(ir_context))
  311. : nullptr;
  312. // Make a function prototype for the outlined function, which involves
  313. // figuring out its required type.
  314. std::unique_ptr<opt::Function> outlined_function = PrepareFunctionPrototype(
  315. region_input_ids, region_output_ids, input_id_to_fresh_id_map, ir_context,
  316. transformation_context);
  317. // Adapt the region to be outlined so that its input ids are replaced with the
  318. // ids of the outlined function's input parameters, and so that output ids
  319. // are similarly remapped.
  320. RemapInputAndOutputIdsInRegion(
  321. ir_context, *original_region_exit_block, region_blocks, region_input_ids,
  322. region_output_ids, input_id_to_fresh_id_map, output_id_to_fresh_id_map);
  323. // Fill out the body of the outlined function according to the region that is
  324. // being outlined.
  325. PopulateOutlinedFunction(
  326. *original_region_entry_block, *original_region_exit_block, region_blocks,
  327. region_output_ids, output_id_to_type_id, output_id_to_fresh_id_map,
  328. ir_context, outlined_function.get());
  329. // Collapse the region that has been outlined into a function down to a single
  330. // block that calls said function.
  331. ShrinkOriginalRegion(
  332. ir_context, region_blocks, region_input_ids, region_output_ids,
  333. output_id_to_type_id, outlined_function->type_id(),
  334. std::move(cloned_exit_block_merge),
  335. std::move(cloned_exit_block_terminator), original_region_entry_block);
  336. // Add the outlined function to the module.
  337. const auto* outlined_function_ptr = outlined_function.get();
  338. ir_context->module()->AddFunction(std::move(outlined_function));
  339. // Major surgery has been conducted on the module, so invalidate all analyses.
  340. ir_context->InvalidateAnalysesExceptFor(
  341. opt::IRContext::Analysis::kAnalysisNone);
  342. // If the original function was livesafe, the new function should also be
  343. // livesafe.
  344. if (transformation_context->GetFactManager()->FunctionIsLivesafe(
  345. original_region_entry_block->GetParent()->result_id())) {
  346. transformation_context->GetFactManager()->AddFactFunctionIsLivesafe(
  347. message_.new_function_id());
  348. }
  349. // Record the fact that all blocks in the outlined region are dead if the
  350. // first block is dead.
  351. if (transformation_context->GetFactManager()->BlockIsDead(
  352. original_region_entry_block->id())) {
  353. transformation_context->GetFactManager()->AddFactBlockIsDead(
  354. outlined_function_ptr->entry()->id());
  355. }
  356. }
  357. protobufs::Transformation TransformationOutlineFunction::ToMessage() const {
  358. protobufs::Transformation result;
  359. *result.mutable_outline_function() = message_;
  360. return result;
  361. }
  362. std::vector<uint32_t> TransformationOutlineFunction::GetRegionInputIds(
  363. opt::IRContext* ir_context, const std::set<opt::BasicBlock*>& region_set,
  364. opt::BasicBlock* region_exit_block) {
  365. std::vector<uint32_t> result;
  366. auto enclosing_function = region_exit_block->GetParent();
  367. // Consider each parameter of the function containing the region.
  368. enclosing_function->ForEachParam(
  369. [ir_context, &region_set, &result](opt::Instruction* function_parameter) {
  370. // Consider every use of the parameter.
  371. ir_context->get_def_use_mgr()->WhileEachUse(
  372. function_parameter,
  373. [ir_context, function_parameter, &region_set, &result](
  374. opt::Instruction* use, uint32_t /*unused*/) {
  375. // Get the block, if any, in which the parameter is used.
  376. auto use_block = ir_context->get_instr_block(use);
  377. // If the use is in a block that lies within the region, the
  378. // parameter is an input id for the region.
  379. if (use_block && region_set.count(use_block) != 0) {
  380. result.push_back(function_parameter->result_id());
  381. return false;
  382. }
  383. return true;
  384. });
  385. });
  386. // Consider all definitions in the function that might turn out to be input
  387. // ids.
  388. for (auto& block : *enclosing_function) {
  389. std::vector<opt::Instruction*> candidate_input_ids_for_block;
  390. if (region_set.count(&block) == 0) {
  391. // All instructions in blocks outside the region are candidate's for
  392. // generating input ids.
  393. for (auto& inst : block) {
  394. candidate_input_ids_for_block.push_back(&inst);
  395. }
  396. } else {
  397. // Blocks in the region cannot generate input ids.
  398. continue;
  399. }
  400. // Consider each candidate input id to check whether it is used in the
  401. // region.
  402. for (auto& inst : candidate_input_ids_for_block) {
  403. ir_context->get_def_use_mgr()->WhileEachUse(
  404. inst,
  405. [ir_context, &inst, region_exit_block, &region_set, &result](
  406. opt::Instruction* use, uint32_t /*unused*/) -> bool {
  407. // Find the block in which this id use occurs, recording the id as
  408. // an input id if the block is outside the region, with some
  409. // exceptions detailed below.
  410. auto use_block = ir_context->get_instr_block(use);
  411. if (!use_block) {
  412. // There might be no containing block, e.g. if the use is in a
  413. // decoration.
  414. return true;
  415. }
  416. if (region_set.count(use_block) == 0) {
  417. // The use is not in the region: this does not make it an input
  418. // id.
  419. return true;
  420. }
  421. if (use_block == region_exit_block && use->IsBlockTerminator()) {
  422. // We do not regard uses in the exit block terminator as input
  423. // ids, as this terminator does not get outlined.
  424. return true;
  425. }
  426. result.push_back(inst->result_id());
  427. return false;
  428. });
  429. }
  430. }
  431. return result;
  432. }
  433. std::vector<uint32_t> TransformationOutlineFunction::GetRegionOutputIds(
  434. opt::IRContext* ir_context, const std::set<opt::BasicBlock*>& region_set,
  435. opt::BasicBlock* region_exit_block) {
  436. std::vector<uint32_t> result;
  437. // Consider each block in the function containing the region.
  438. for (auto& block : *region_exit_block->GetParent()) {
  439. if (region_set.count(&block) == 0) {
  440. // Skip blocks that are not in the region.
  441. continue;
  442. }
  443. // Consider each use of each instruction defined in the block.
  444. for (auto& inst : block) {
  445. ir_context->get_def_use_mgr()->WhileEachUse(
  446. &inst,
  447. [&region_set, ir_context, &inst, region_exit_block, &result](
  448. opt::Instruction* use, uint32_t /*unused*/) -> bool {
  449. // Find the block in which this id use occurs, recording the id as
  450. // an output id if the block is outside the region, with some
  451. // exceptions detailed below.
  452. auto use_block = ir_context->get_instr_block(use);
  453. if (!use_block) {
  454. // There might be no containing block, e.g. if the use is in a
  455. // decoration.
  456. return true;
  457. }
  458. if (region_set.count(use_block) != 0) {
  459. // The use is in the region.
  460. if (use_block != region_exit_block || !use->IsBlockTerminator()) {
  461. // Furthermore, the use is not in the terminator of the region's
  462. // exit block.
  463. return true;
  464. }
  465. }
  466. result.push_back(inst.result_id());
  467. return false;
  468. });
  469. }
  470. }
  471. return result;
  472. }
  473. std::set<opt::BasicBlock*> TransformationOutlineFunction::GetRegionBlocks(
  474. opt::IRContext* ir_context, opt::BasicBlock* entry_block,
  475. opt::BasicBlock* exit_block) {
  476. auto enclosing_function = entry_block->GetParent();
  477. auto dominator_analysis =
  478. ir_context->GetDominatorAnalysis(enclosing_function);
  479. auto postdominator_analysis =
  480. ir_context->GetPostDominatorAnalysis(enclosing_function);
  481. std::set<opt::BasicBlock*> result;
  482. for (auto& block : *enclosing_function) {
  483. if (dominator_analysis->Dominates(entry_block, &block) &&
  484. postdominator_analysis->Dominates(exit_block, &block)) {
  485. result.insert(&block);
  486. }
  487. }
  488. return result;
  489. }
  490. std::unique_ptr<opt::Function>
  491. TransformationOutlineFunction::PrepareFunctionPrototype(
  492. const std::vector<uint32_t>& region_input_ids,
  493. const std::vector<uint32_t>& region_output_ids,
  494. const std::map<uint32_t, uint32_t>& input_id_to_fresh_id_map,
  495. opt::IRContext* ir_context,
  496. TransformationContext* transformation_context) const {
  497. uint32_t return_type_id = 0;
  498. uint32_t function_type_id = 0;
  499. // First, try to find an existing function type that is suitable. This is
  500. // only possible if the region generates no output ids; if it generates output
  501. // ids we are going to make a new struct for those, and since that struct does
  502. // not exist there cannot already be a function type with this struct as its
  503. // return type.
  504. if (region_output_ids.empty()) {
  505. std::vector<uint32_t> return_and_parameter_types;
  506. opt::analysis::Void void_type;
  507. return_type_id = ir_context->get_type_mgr()->GetId(&void_type);
  508. return_and_parameter_types.push_back(return_type_id);
  509. for (auto id : region_input_ids) {
  510. return_and_parameter_types.push_back(
  511. ir_context->get_def_use_mgr()->GetDef(id)->type_id());
  512. }
  513. function_type_id =
  514. fuzzerutil::FindFunctionType(ir_context, return_and_parameter_types);
  515. }
  516. // If no existing function type was found, we need to create one.
  517. if (function_type_id == 0) {
  518. assert(
  519. ((return_type_id == 0) == !region_output_ids.empty()) &&
  520. "We should only have set the return type if there are no output ids.");
  521. // If the region generates output ids, we need to make a struct with one
  522. // field per output id.
  523. if (!region_output_ids.empty()) {
  524. opt::Instruction::OperandList struct_member_types;
  525. for (uint32_t output_id : region_output_ids) {
  526. auto output_id_type =
  527. ir_context->get_def_use_mgr()->GetDef(output_id)->type_id();
  528. if (ir_context->get_def_use_mgr()->GetDef(output_id_type)->opcode() ==
  529. SpvOpTypeVoid) {
  530. // We cannot add a void field to a struct. We instead use OpUndef to
  531. // handle void output ids.
  532. continue;
  533. }
  534. struct_member_types.push_back({SPV_OPERAND_TYPE_ID, {output_id_type}});
  535. }
  536. // Add a new struct type to the module.
  537. ir_context->module()->AddType(MakeUnique<opt::Instruction>(
  538. ir_context, SpvOpTypeStruct, 0,
  539. message_.new_function_struct_return_type_id(),
  540. std::move(struct_member_types)));
  541. // The return type for the function is the newly-created struct.
  542. return_type_id = message_.new_function_struct_return_type_id();
  543. }
  544. assert(
  545. return_type_id != 0 &&
  546. "We should either have a void return type, or have created a struct.");
  547. // The region's input ids dictate the parameter types to the function.
  548. opt::Instruction::OperandList function_type_operands;
  549. function_type_operands.push_back({SPV_OPERAND_TYPE_ID, {return_type_id}});
  550. for (auto id : region_input_ids) {
  551. function_type_operands.push_back(
  552. {SPV_OPERAND_TYPE_ID,
  553. {ir_context->get_def_use_mgr()->GetDef(id)->type_id()}});
  554. }
  555. // Add a new function type to the module, and record that this is the type
  556. // id for the new function.
  557. ir_context->module()->AddType(MakeUnique<opt::Instruction>(
  558. ir_context, SpvOpTypeFunction, 0, message_.new_function_type_id(),
  559. function_type_operands));
  560. function_type_id = message_.new_function_type_id();
  561. }
  562. // Create a new function with |message_.new_function_id| as the function id,
  563. // and the return type and function type prepared above.
  564. std::unique_ptr<opt::Function> outlined_function =
  565. MakeUnique<opt::Function>(MakeUnique<opt::Instruction>(
  566. ir_context, SpvOpFunction, return_type_id, message_.new_function_id(),
  567. opt::Instruction::OperandList(
  568. {{spv_operand_type_t ::SPV_OPERAND_TYPE_LITERAL_INTEGER,
  569. {SpvFunctionControlMaskNone}},
  570. {spv_operand_type_t::SPV_OPERAND_TYPE_ID,
  571. {function_type_id}}})));
  572. // Add one parameter to the function for each input id, using the fresh ids
  573. // provided in |input_id_to_fresh_id_map|, or overflow ids if needed.
  574. for (auto id : region_input_ids) {
  575. uint32_t fresh_id = input_id_to_fresh_id_map.at(id);
  576. outlined_function->AddParameter(MakeUnique<opt::Instruction>(
  577. ir_context, SpvOpFunctionParameter,
  578. ir_context->get_def_use_mgr()->GetDef(id)->type_id(), fresh_id,
  579. opt::Instruction::OperandList()));
  580. // Analyse the use of the new parameter instruction.
  581. outlined_function->ForEachParam(
  582. [fresh_id, ir_context](opt::Instruction* inst) {
  583. if (inst->result_id() == fresh_id) {
  584. ir_context->AnalyzeDefUse(inst);
  585. }
  586. });
  587. // If the input id is an irrelevant-valued variable, the same should be true
  588. // of the corresponding parameter.
  589. if (transformation_context->GetFactManager()->PointeeValueIsIrrelevant(
  590. id)) {
  591. transformation_context->GetFactManager()
  592. ->AddFactValueOfPointeeIsIrrelevant(input_id_to_fresh_id_map.at(id));
  593. }
  594. }
  595. return outlined_function;
  596. }
  597. void TransformationOutlineFunction::UpdateModuleIdBoundForFreshIds(
  598. opt::IRContext* ir_context,
  599. const std::map<uint32_t, uint32_t>& input_id_to_fresh_id_map,
  600. const std::map<uint32_t, uint32_t>& output_id_to_fresh_id_map) const {
  601. // Enlarge the module's id bound as needed to accommodate the various fresh
  602. // ids associated with the transformation.
  603. fuzzerutil::UpdateModuleIdBound(
  604. ir_context, message_.new_function_struct_return_type_id());
  605. fuzzerutil::UpdateModuleIdBound(ir_context, message_.new_function_type_id());
  606. fuzzerutil::UpdateModuleIdBound(ir_context, message_.new_function_id());
  607. fuzzerutil::UpdateModuleIdBound(ir_context,
  608. message_.new_function_region_entry_block());
  609. fuzzerutil::UpdateModuleIdBound(ir_context, message_.new_caller_result_id());
  610. fuzzerutil::UpdateModuleIdBound(ir_context, message_.new_callee_result_id());
  611. for (auto& entry : input_id_to_fresh_id_map) {
  612. fuzzerutil::UpdateModuleIdBound(ir_context, entry.second);
  613. }
  614. for (auto& entry : output_id_to_fresh_id_map) {
  615. fuzzerutil::UpdateModuleIdBound(ir_context, entry.second);
  616. }
  617. }
  618. void TransformationOutlineFunction::RemapInputAndOutputIdsInRegion(
  619. opt::IRContext* ir_context,
  620. const opt::BasicBlock& original_region_exit_block,
  621. const std::set<opt::BasicBlock*>& region_blocks,
  622. const std::vector<uint32_t>& region_input_ids,
  623. const std::vector<uint32_t>& region_output_ids,
  624. const std::map<uint32_t, uint32_t>& input_id_to_fresh_id_map,
  625. const std::map<uint32_t, uint32_t>& output_id_to_fresh_id_map) const {
  626. // Change all uses of input ids inside the region to the corresponding fresh
  627. // ids that will ultimately be parameters of the outlined function.
  628. // This is done by considering each region input id in turn.
  629. for (uint32_t id : region_input_ids) {
  630. // We then consider each use of the input id.
  631. ir_context->get_def_use_mgr()->ForEachUse(
  632. id, [ir_context, id, &input_id_to_fresh_id_map, region_blocks](
  633. opt::Instruction* use, uint32_t operand_index) {
  634. // Find the block in which this use of the input id occurs.
  635. opt::BasicBlock* use_block = ir_context->get_instr_block(use);
  636. // We want to rewrite the use id if its block occurs in the outlined
  637. // region.
  638. if (region_blocks.count(use_block) != 0) {
  639. // Rewrite this use of the input id.
  640. use->SetOperand(operand_index, {input_id_to_fresh_id_map.at(id)});
  641. }
  642. });
  643. }
  644. // Change each definition of a region output id to define the corresponding
  645. // fresh ids that will store intermediate value for the output ids. Also
  646. // change all uses of the output id located in the outlined region.
  647. // This is done by considering each region output id in turn.
  648. for (uint32_t id : region_output_ids) {
  649. // First consider each use of the output id and update the relevant uses.
  650. ir_context->get_def_use_mgr()->ForEachUse(
  651. id, [ir_context, &original_region_exit_block, id,
  652. &output_id_to_fresh_id_map,
  653. region_blocks](opt::Instruction* use, uint32_t operand_index) {
  654. // Find the block in which this use of the output id occurs.
  655. auto use_block = ir_context->get_instr_block(use);
  656. // We want to rewrite the use id if its block occurs in the outlined
  657. // region, with one exception: the terminator of the exit block of
  658. // the region is going to remain in the original function, so if the
  659. // use appears in such a terminator instruction we leave it alone.
  660. if (
  661. // The block is in the region ...
  662. region_blocks.count(use_block) != 0 &&
  663. // ... and the use is not in the terminator instruction of the
  664. // region's exit block.
  665. !(use_block == &original_region_exit_block &&
  666. use->IsBlockTerminator())) {
  667. // Rewrite this use of the output id.
  668. use->SetOperand(operand_index, {output_id_to_fresh_id_map.at(id)});
  669. }
  670. });
  671. // Now change the instruction that defines the output id so that it instead
  672. // defines the corresponding fresh id. We do this after changing all the
  673. // uses so that the definition of the original id is still registered when
  674. // we analyse its uses.
  675. ir_context->get_def_use_mgr()->GetDef(id)->SetResultId(
  676. output_id_to_fresh_id_map.at(id));
  677. }
  678. }
  679. void TransformationOutlineFunction::PopulateOutlinedFunction(
  680. const opt::BasicBlock& original_region_entry_block,
  681. const opt::BasicBlock& original_region_exit_block,
  682. const std::set<opt::BasicBlock*>& region_blocks,
  683. const std::vector<uint32_t>& region_output_ids,
  684. const std::map<uint32_t, uint32_t>& output_id_to_type_id,
  685. const std::map<uint32_t, uint32_t>& output_id_to_fresh_id_map,
  686. opt::IRContext* ir_context, opt::Function* outlined_function) const {
  687. // When we create the exit block for the outlined region, we use this pointer
  688. // to track of it so that we can manipulate it later.
  689. opt::BasicBlock* outlined_region_exit_block = nullptr;
  690. // The region entry block in the new function is identical to the entry block
  691. // of the region being outlined, except that it has
  692. // |message_.new_function_region_entry_block| as its id.
  693. std::unique_ptr<opt::BasicBlock> outlined_region_entry_block =
  694. MakeUnique<opt::BasicBlock>(MakeUnique<opt::Instruction>(
  695. ir_context, SpvOpLabel, 0, message_.new_function_region_entry_block(),
  696. opt::Instruction::OperandList()));
  697. if (&original_region_entry_block == &original_region_exit_block) {
  698. outlined_region_exit_block = outlined_region_entry_block.get();
  699. }
  700. for (auto& inst : original_region_entry_block) {
  701. outlined_region_entry_block->AddInstruction(
  702. std::unique_ptr<opt::Instruction>(inst.Clone(ir_context)));
  703. }
  704. outlined_function->AddBasicBlock(std::move(outlined_region_entry_block));
  705. // We now go through the single-entry single-exit region defined by the entry
  706. // and exit blocks, adding clones of all blocks to the new function.
  707. // Consider every block in the enclosing function.
  708. auto enclosing_function = original_region_entry_block.GetParent();
  709. for (auto block_it = enclosing_function->begin();
  710. block_it != enclosing_function->end();) {
  711. // Skip the region's entry block - we already dealt with it above.
  712. if (region_blocks.count(&*block_it) == 0 ||
  713. &*block_it == &original_region_entry_block) {
  714. ++block_it;
  715. continue;
  716. }
  717. // Clone the block so that it can be added to the new function.
  718. auto cloned_block =
  719. std::unique_ptr<opt::BasicBlock>(block_it->Clone(ir_context));
  720. // If this is the region's exit block, then the cloned block is the outlined
  721. // region's exit block.
  722. if (&*block_it == &original_region_exit_block) {
  723. assert(outlined_region_exit_block == nullptr &&
  724. "We should not yet have encountered the exit block.");
  725. outlined_region_exit_block = cloned_block.get();
  726. }
  727. // Redirect any OpPhi operands whose predecessors are the original region
  728. // entry block to become the new function entry block.
  729. cloned_block->ForEachPhiInst([this](opt::Instruction* phi_inst) {
  730. for (uint32_t predecessor_index = 1;
  731. predecessor_index < phi_inst->NumInOperands();
  732. predecessor_index += 2) {
  733. if (phi_inst->GetSingleWordInOperand(predecessor_index) ==
  734. message_.entry_block()) {
  735. phi_inst->SetInOperand(predecessor_index,
  736. {message_.new_function_region_entry_block()});
  737. }
  738. }
  739. });
  740. outlined_function->AddBasicBlock(std::move(cloned_block));
  741. block_it = block_it.Erase();
  742. }
  743. assert(outlined_region_exit_block != nullptr &&
  744. "We should have encountered the region's exit block when iterating "
  745. "through the function");
  746. // We now need to adapt the exit block for the region - in the new function -
  747. // so that it ends with a return.
  748. // We first eliminate the merge instruction (if any) and the terminator for
  749. // the cloned exit block.
  750. for (auto inst_it = outlined_region_exit_block->begin();
  751. inst_it != outlined_region_exit_block->end();) {
  752. if (inst_it->opcode() == SpvOpLoopMerge ||
  753. inst_it->opcode() == SpvOpSelectionMerge) {
  754. inst_it = inst_it.Erase();
  755. } else if (inst_it->IsBlockTerminator()) {
  756. inst_it = inst_it.Erase();
  757. } else {
  758. ++inst_it;
  759. }
  760. }
  761. // We now add either OpReturn or OpReturnValue as the cloned exit block's
  762. // terminator.
  763. if (region_output_ids.empty()) {
  764. // The case where there are no region output ids is simple: we just add
  765. // OpReturn.
  766. outlined_region_exit_block->AddInstruction(MakeUnique<opt::Instruction>(
  767. ir_context, SpvOpReturn, 0, 0, opt::Instruction::OperandList()));
  768. } else {
  769. // In the case where there are output ids, we add an OpCompositeConstruct
  770. // instruction to pack all the non-void output values into a struct, and
  771. // then an OpReturnValue instruction to return this struct.
  772. opt::Instruction::OperandList struct_member_operands;
  773. for (uint32_t id : region_output_ids) {
  774. if (ir_context->get_def_use_mgr()
  775. ->GetDef(output_id_to_type_id.at(id))
  776. ->opcode() != SpvOpTypeVoid) {
  777. struct_member_operands.push_back(
  778. {SPV_OPERAND_TYPE_ID, {output_id_to_fresh_id_map.at(id)}});
  779. }
  780. }
  781. outlined_region_exit_block->AddInstruction(MakeUnique<opt::Instruction>(
  782. ir_context, SpvOpCompositeConstruct,
  783. message_.new_function_struct_return_type_id(),
  784. message_.new_callee_result_id(), struct_member_operands));
  785. outlined_region_exit_block->AddInstruction(MakeUnique<opt::Instruction>(
  786. ir_context, SpvOpReturnValue, 0, 0,
  787. opt::Instruction::OperandList(
  788. {{SPV_OPERAND_TYPE_ID, {message_.new_callee_result_id()}}})));
  789. }
  790. outlined_function->SetFunctionEnd(MakeUnique<opt::Instruction>(
  791. ir_context, SpvOpFunctionEnd, 0, 0, opt::Instruction::OperandList()));
  792. }
  793. void TransformationOutlineFunction::ShrinkOriginalRegion(
  794. opt::IRContext* ir_context, const std::set<opt::BasicBlock*>& region_blocks,
  795. const std::vector<uint32_t>& region_input_ids,
  796. const std::vector<uint32_t>& region_output_ids,
  797. const std::map<uint32_t, uint32_t>& output_id_to_type_id,
  798. uint32_t return_type_id,
  799. std::unique_ptr<opt::Instruction> cloned_exit_block_merge,
  800. std::unique_ptr<opt::Instruction> cloned_exit_block_terminator,
  801. opt::BasicBlock* original_region_entry_block) const {
  802. // Erase all blocks from the original function that are in the outlined
  803. // region, except for the region's entry block.
  804. //
  805. // In the process, identify all references to the exit block of the region,
  806. // as merge blocks, continue targets, or OpPhi predecessors, and rewrite them
  807. // to refer to the region entry block (the single block to which we are
  808. // shrinking the region).
  809. auto enclosing_function = original_region_entry_block->GetParent();
  810. for (auto block_it = enclosing_function->begin();
  811. block_it != enclosing_function->end();) {
  812. if (&*block_it == original_region_entry_block) {
  813. ++block_it;
  814. } else if (region_blocks.count(&*block_it) == 0) {
  815. // The block is not in the region. Check whether it has the last block
  816. // of the region as an OpPhi predecessor, and if so change the
  817. // predecessor to be the first block of the region (i.e. the block
  818. // containing the call to what was outlined).
  819. assert(block_it->MergeBlockIdIfAny() != message_.exit_block() &&
  820. "Outlined region must not end with a merge block");
  821. assert(block_it->ContinueBlockIdIfAny() != message_.exit_block() &&
  822. "Outlined region must not end with a continue target");
  823. block_it->ForEachPhiInst([this](opt::Instruction* phi_inst) {
  824. for (uint32_t predecessor_index = 1;
  825. predecessor_index < phi_inst->NumInOperands();
  826. predecessor_index += 2) {
  827. if (phi_inst->GetSingleWordInOperand(predecessor_index) ==
  828. message_.exit_block()) {
  829. phi_inst->SetInOperand(predecessor_index, {message_.entry_block()});
  830. }
  831. }
  832. });
  833. ++block_it;
  834. } else {
  835. // The block is in the region and is not the region's entry block: kill
  836. // it.
  837. block_it = block_it.Erase();
  838. }
  839. }
  840. // Now erase all instructions from the region's entry block, as they have
  841. // been outlined.
  842. for (auto inst_it = original_region_entry_block->begin();
  843. inst_it != original_region_entry_block->end();) {
  844. inst_it = inst_it.Erase();
  845. }
  846. // Now we add a call to the outlined function to the region's entry block.
  847. opt::Instruction::OperandList function_call_operands;
  848. function_call_operands.push_back(
  849. {SPV_OPERAND_TYPE_ID, {message_.new_function_id()}});
  850. // The function parameters are the region input ids.
  851. for (auto input_id : region_input_ids) {
  852. function_call_operands.push_back({SPV_OPERAND_TYPE_ID, {input_id}});
  853. }
  854. original_region_entry_block->AddInstruction(MakeUnique<opt::Instruction>(
  855. ir_context, SpvOpFunctionCall, return_type_id,
  856. message_.new_caller_result_id(), function_call_operands));
  857. // If there are output ids, the function call will return a struct. For each
  858. // output id, we add an extract operation to pull the appropriate struct
  859. // member out into an output id. The exception is for output ids with void
  860. // type. There are no struct entries for these, so we use an OpUndef of void
  861. // type instead.
  862. uint32_t struct_member_index = 0;
  863. for (uint32_t output_id : region_output_ids) {
  864. uint32_t output_type_id = output_id_to_type_id.at(output_id);
  865. if (ir_context->get_def_use_mgr()->GetDef(output_type_id)->opcode() ==
  866. SpvOpTypeVoid) {
  867. original_region_entry_block->AddInstruction(MakeUnique<opt::Instruction>(
  868. ir_context, SpvOpUndef, output_type_id, output_id,
  869. opt::Instruction::OperandList()));
  870. // struct_member_index is not incremented since there was no struct member
  871. // associated with this void-typed output id.
  872. } else {
  873. original_region_entry_block->AddInstruction(MakeUnique<opt::Instruction>(
  874. ir_context, SpvOpCompositeExtract, output_type_id, output_id,
  875. opt::Instruction::OperandList(
  876. {{SPV_OPERAND_TYPE_ID, {message_.new_caller_result_id()}},
  877. {SPV_OPERAND_TYPE_LITERAL_INTEGER, {struct_member_index}}})));
  878. struct_member_index++;
  879. }
  880. }
  881. // Finally, we terminate the block with the merge instruction (if any) that
  882. // used to belong to the region's exit block, and the terminator that used
  883. // to belong to the region's exit block.
  884. if (cloned_exit_block_merge != nullptr) {
  885. original_region_entry_block->AddInstruction(
  886. std::move(cloned_exit_block_merge));
  887. }
  888. original_region_entry_block->AddInstruction(
  889. std::move(cloned_exit_block_terminator));
  890. }
  891. std::unordered_set<uint32_t> TransformationOutlineFunction::GetFreshIds()
  892. const {
  893. std::unordered_set<uint32_t> result = {
  894. message_.new_function_struct_return_type_id(),
  895. message_.new_function_type_id(),
  896. message_.new_function_id(),
  897. message_.new_function_region_entry_block(),
  898. message_.new_caller_result_id(),
  899. message_.new_callee_result_id()};
  900. for (auto& pair : message_.input_id_to_fresh_id()) {
  901. result.insert(pair.second());
  902. }
  903. for (auto& pair : message_.output_id_to_fresh_id()) {
  904. result.insert(pair.second());
  905. }
  906. return result;
  907. }
  908. } // namespace fuzz
  909. } // namespace spvtools