BasicBlockUtils.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- Transform/Utils/BasicBlockUtils.h - BasicBlock Utils -----*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This family of functions perform manipulations on basic blocks, and
  15. // instructions contained within basic blocks.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
  19. #define LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
  20. // FIXME: Move to this file: BasicBlock::removePredecessor, BB::splitBasicBlock
  21. #include "llvm/ADT/ArrayRef.h"
  22. #include "llvm/ADT/SetVector.h"
  23. #include "llvm/Analysis/DomTreeUpdater.h"
  24. #include "llvm/Analysis/LoopInfo.h"
  25. #include "llvm/IR/BasicBlock.h"
  26. #include "llvm/IR/CFG.h"
  27. #include "llvm/IR/InstrTypes.h"
  28. #include <cassert>
  29. namespace llvm {
  30. class BlockFrequencyInfo;
  31. class BranchProbabilityInfo;
  32. class DominatorTree;
  33. class DomTreeUpdater;
  34. class Function;
  35. class Instruction;
  36. class LoopInfo;
  37. class MDNode;
  38. class MemoryDependenceResults;
  39. class MemorySSAUpdater;
  40. class PostDominatorTree;
  41. class ReturnInst;
  42. class TargetLibraryInfo;
  43. class Value;
  44. /// Replace contents of every block in \p BBs with single unreachable
  45. /// instruction. If \p Updates is specified, collect all necessary DT updates
  46. /// into this vector. If \p KeepOneInputPHIs is true, one-input Phis in
  47. /// successors of blocks being deleted will be preserved.
  48. void DetatchDeadBlocks(ArrayRef <BasicBlock *> BBs,
  49. SmallVectorImpl<DominatorTree::UpdateType> *Updates,
  50. bool KeepOneInputPHIs = false);
  51. /// Delete the specified block, which must have no predecessors.
  52. void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU = nullptr,
  53. bool KeepOneInputPHIs = false);
  54. /// Delete the specified blocks from \p BB. The set of deleted blocks must have
  55. /// no predecessors that are not being deleted themselves. \p BBs must have no
  56. /// duplicating blocks. If there are loops among this set of blocks, all
  57. /// relevant loop info updates should be done before this function is called.
  58. /// If \p KeepOneInputPHIs is true, one-input Phis in successors of blocks
  59. /// being deleted will be preserved.
  60. void DeleteDeadBlocks(ArrayRef <BasicBlock *> BBs,
  61. DomTreeUpdater *DTU = nullptr,
  62. bool KeepOneInputPHIs = false);
  63. /// Delete all basic blocks from \p F that are not reachable from its entry
  64. /// node. If \p KeepOneInputPHIs is true, one-input Phis in successors of
  65. /// blocks being deleted will be preserved.
  66. bool EliminateUnreachableBlocks(Function &F, DomTreeUpdater *DTU = nullptr,
  67. bool KeepOneInputPHIs = false);
  68. /// We know that BB has one predecessor. If there are any single-entry PHI nodes
  69. /// in it, fold them away. This handles the case when all entries to the PHI
  70. /// nodes in a block are guaranteed equal, such as when the block has exactly
  71. /// one predecessor.
  72. bool FoldSingleEntryPHINodes(BasicBlock *BB,
  73. MemoryDependenceResults *MemDep = nullptr);
  74. /// Examine each PHI in the given block and delete it if it is dead. Also
  75. /// recursively delete any operands that become dead as a result. This includes
  76. /// tracing the def-use list from the PHI to see if it is ultimately unused or
  77. /// if it reaches an unused cycle. Return true if any PHIs were deleted.
  78. bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI = nullptr,
  79. MemorySSAUpdater *MSSAU = nullptr);
  80. /// Attempts to merge a block into its predecessor, if possible. The return
  81. /// value indicates success or failure.
  82. /// By default do not merge blocks if BB's predecessor has multiple successors.
  83. /// If PredecessorWithTwoSuccessors = true, the blocks can only be merged
  84. /// if BB's Pred has a branch to BB and to AnotherBB, and BB has a single
  85. /// successor Sing. In this case the branch will be updated with Sing instead of
  86. /// BB, and BB will still be merged into its predecessor and removed.
  87. bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU = nullptr,
  88. LoopInfo *LI = nullptr,
  89. MemorySSAUpdater *MSSAU = nullptr,
  90. MemoryDependenceResults *MemDep = nullptr,
  91. bool PredecessorWithTwoSuccessors = false);
  92. /// Merge block(s) sucessors, if possible. Return true if at least two
  93. /// of the blocks were merged together.
  94. /// In order to merge, each block must be terminated by an unconditional
  95. /// branch. If L is provided, then the blocks merged into their predecessors
  96. /// must be in L. In addition, This utility calls on another utility:
  97. /// MergeBlockIntoPredecessor. Blocks are successfully merged when the call to
  98. /// MergeBlockIntoPredecessor returns true.
  99. bool MergeBlockSuccessorsIntoGivenBlocks(
  100. SmallPtrSetImpl<BasicBlock *> &MergeBlocks, Loop *L = nullptr,
  101. DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr);
  102. /// Try to remove redundant dbg.value instructions from given basic block.
  103. /// Returns true if at least one instruction was removed.
  104. bool RemoveRedundantDbgInstrs(BasicBlock *BB);
  105. /// Replace all uses of an instruction (specified by BI) with a value, then
  106. /// remove and delete the original instruction.
  107. void ReplaceInstWithValue(BasicBlock::InstListType &BIL,
  108. BasicBlock::iterator &BI, Value *V);
  109. /// Replace the instruction specified by BI with the instruction specified by I.
  110. /// Copies DebugLoc from BI to I, if I doesn't already have a DebugLoc. The
  111. /// original instruction is deleted and BI is updated to point to the new
  112. /// instruction.
  113. void ReplaceInstWithInst(BasicBlock::InstListType &BIL,
  114. BasicBlock::iterator &BI, Instruction *I);
  115. /// Replace the instruction specified by From with the instruction specified by
  116. /// To. Copies DebugLoc from BI to I, if I doesn't already have a DebugLoc.
  117. void ReplaceInstWithInst(Instruction *From, Instruction *To);
  118. /// Option class for critical edge splitting.
  119. ///
  120. /// This provides a builder interface for overriding the default options used
  121. /// during critical edge splitting.
  122. struct CriticalEdgeSplittingOptions {
  123. DominatorTree *DT;
  124. PostDominatorTree *PDT;
  125. LoopInfo *LI;
  126. MemorySSAUpdater *MSSAU;
  127. bool MergeIdenticalEdges = false;
  128. bool KeepOneInputPHIs = false;
  129. bool PreserveLCSSA = false;
  130. bool IgnoreUnreachableDests = false;
  131. /// SplitCriticalEdge is guaranteed to preserve loop-simplify form if LI is
  132. /// provided. If it cannot be preserved, no splitting will take place. If it
  133. /// is not set, preserve loop-simplify form if possible.
  134. bool PreserveLoopSimplify = true;
  135. CriticalEdgeSplittingOptions(DominatorTree *DT = nullptr,
  136. LoopInfo *LI = nullptr,
  137. MemorySSAUpdater *MSSAU = nullptr,
  138. PostDominatorTree *PDT = nullptr)
  139. : DT(DT), PDT(PDT), LI(LI), MSSAU(MSSAU) {}
  140. CriticalEdgeSplittingOptions &setMergeIdenticalEdges() {
  141. MergeIdenticalEdges = true;
  142. return *this;
  143. }
  144. CriticalEdgeSplittingOptions &setKeepOneInputPHIs() {
  145. KeepOneInputPHIs = true;
  146. return *this;
  147. }
  148. CriticalEdgeSplittingOptions &setPreserveLCSSA() {
  149. PreserveLCSSA = true;
  150. return *this;
  151. }
  152. CriticalEdgeSplittingOptions &setIgnoreUnreachableDests() {
  153. IgnoreUnreachableDests = true;
  154. return *this;
  155. }
  156. CriticalEdgeSplittingOptions &unsetPreserveLoopSimplify() {
  157. PreserveLoopSimplify = false;
  158. return *this;
  159. }
  160. };
  161. /// If this edge is a critical edge, insert a new node to split the critical
  162. /// edge. This will update the analyses passed in through the option struct.
  163. /// This returns the new block if the edge was split, null otherwise.
  164. ///
  165. /// If MergeIdenticalEdges in the options struct is true (not the default),
  166. /// *all* edges from TI to the specified successor will be merged into the same
  167. /// critical edge block. This is most commonly interesting with switch
  168. /// instructions, which may have many edges to any one destination. This
  169. /// ensures that all edges to that dest go to one block instead of each going
  170. /// to a different block, but isn't the standard definition of a "critical
  171. /// edge".
  172. ///
  173. /// It is invalid to call this function on a critical edge that starts at an
  174. /// IndirectBrInst. Splitting these edges will almost always create an invalid
  175. /// program because the address of the new block won't be the one that is jumped
  176. /// to.
  177. BasicBlock *SplitCriticalEdge(Instruction *TI, unsigned SuccNum,
  178. const CriticalEdgeSplittingOptions &Options =
  179. CriticalEdgeSplittingOptions(),
  180. const Twine &BBName = "");
  181. inline BasicBlock *
  182. SplitCriticalEdge(BasicBlock *BB, succ_iterator SI,
  183. const CriticalEdgeSplittingOptions &Options =
  184. CriticalEdgeSplittingOptions()) {
  185. return SplitCriticalEdge(BB->getTerminator(), SI.getSuccessorIndex(),
  186. Options);
  187. }
  188. /// If the edge from *PI to BB is not critical, return false. Otherwise, split
  189. /// all edges between the two blocks and return true. This updates all of the
  190. /// same analyses as the other SplitCriticalEdge function. If P is specified, it
  191. /// updates the analyses described above.
  192. inline bool SplitCriticalEdge(BasicBlock *Succ, pred_iterator PI,
  193. const CriticalEdgeSplittingOptions &Options =
  194. CriticalEdgeSplittingOptions()) {
  195. bool MadeChange = false;
  196. Instruction *TI = (*PI)->getTerminator();
  197. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
  198. if (TI->getSuccessor(i) == Succ)
  199. MadeChange |= !!SplitCriticalEdge(TI, i, Options);
  200. return MadeChange;
  201. }
  202. /// If an edge from Src to Dst is critical, split the edge and return true,
  203. /// otherwise return false. This method requires that there be an edge between
  204. /// the two blocks. It updates the analyses passed in the options struct
  205. inline BasicBlock *
  206. SplitCriticalEdge(BasicBlock *Src, BasicBlock *Dst,
  207. const CriticalEdgeSplittingOptions &Options =
  208. CriticalEdgeSplittingOptions()) {
  209. Instruction *TI = Src->getTerminator();
  210. unsigned i = 0;
  211. while (true) {
  212. assert(i != TI->getNumSuccessors() && "Edge doesn't exist!");
  213. if (TI->getSuccessor(i) == Dst)
  214. return SplitCriticalEdge(TI, i, Options);
  215. ++i;
  216. }
  217. }
  218. /// Loop over all of the edges in the CFG, breaking critical edges as they are
  219. /// found. Returns the number of broken edges.
  220. unsigned SplitAllCriticalEdges(Function &F,
  221. const CriticalEdgeSplittingOptions &Options =
  222. CriticalEdgeSplittingOptions());
  223. /// Split the edge connecting the specified blocks, and return the newly created
  224. /// basic block between \p From and \p To.
  225. BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To,
  226. DominatorTree *DT = nullptr, LoopInfo *LI = nullptr,
  227. MemorySSAUpdater *MSSAU = nullptr,
  228. const Twine &BBName = "");
  229. /// Split the specified block at the specified instruction.
  230. ///
  231. /// If \p Before is true, splitBlockBefore handles the block
  232. /// splitting. Otherwise, execution proceeds as described below.
  233. ///
  234. /// Everything before \p SplitPt stays in \p Old and everything starting with \p
  235. /// SplitPt moves to a new block. The two blocks are joined by an unconditional
  236. /// branch. The new block with name \p BBName is returned.
  237. ///
  238. /// FIXME: deprecated, switch to the DomTreeUpdater-based one.
  239. BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT,
  240. LoopInfo *LI = nullptr,
  241. MemorySSAUpdater *MSSAU = nullptr,
  242. const Twine &BBName = "", bool Before = false);
  243. /// Split the specified block at the specified instruction.
  244. ///
  245. /// If \p Before is true, splitBlockBefore handles the block
  246. /// splitting. Otherwise, execution proceeds as described below.
  247. ///
  248. /// Everything before \p SplitPt stays in \p Old and everything starting with \p
  249. /// SplitPt moves to a new block. The two blocks are joined by an unconditional
  250. /// branch. The new block with name \p BBName is returned.
  251. BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt,
  252. DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
  253. MemorySSAUpdater *MSSAU = nullptr,
  254. const Twine &BBName = "", bool Before = false);
  255. /// Split the specified block at the specified instruction \p SplitPt.
  256. /// All instructions before \p SplitPt are moved to a new block and all
  257. /// instructions after \p SplitPt stay in the old block. The new block and the
  258. /// old block are joined by inserting an unconditional branch to the end of the
  259. /// new block. The new block with name \p BBName is returned.
  260. BasicBlock *splitBlockBefore(BasicBlock *Old, Instruction *SplitPt,
  261. DomTreeUpdater *DTU, LoopInfo *LI,
  262. MemorySSAUpdater *MSSAU, const Twine &BBName = "");
  263. /// This method introduces at least one new basic block into the function and
  264. /// moves some of the predecessors of BB to be predecessors of the new block.
  265. /// The new predecessors are indicated by the Preds array. The new block is
  266. /// given a suffix of 'Suffix'. Returns new basic block to which predecessors
  267. /// from Preds are now pointing.
  268. ///
  269. /// If BB is a landingpad block then additional basicblock might be introduced.
  270. /// It will have Suffix+".split_lp". See SplitLandingPadPredecessors for more
  271. /// details on this case.
  272. ///
  273. /// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
  274. /// no other analyses. In particular, it does not preserve LoopSimplify
  275. /// (because it's complicated to handle the case where one of the edges being
  276. /// split is an exit of a loop with other exits).
  277. ///
  278. /// FIXME: deprecated, switch to the DomTreeUpdater-based one.
  279. BasicBlock *SplitBlockPredecessors(BasicBlock *BB, ArrayRef<BasicBlock *> Preds,
  280. const char *Suffix, DominatorTree *DT,
  281. LoopInfo *LI = nullptr,
  282. MemorySSAUpdater *MSSAU = nullptr,
  283. bool PreserveLCSSA = false);
  284. /// This method introduces at least one new basic block into the function and
  285. /// moves some of the predecessors of BB to be predecessors of the new block.
  286. /// The new predecessors are indicated by the Preds array. The new block is
  287. /// given a suffix of 'Suffix'. Returns new basic block to which predecessors
  288. /// from Preds are now pointing.
  289. ///
  290. /// If BB is a landingpad block then additional basicblock might be introduced.
  291. /// It will have Suffix+".split_lp". See SplitLandingPadPredecessors for more
  292. /// details on this case.
  293. ///
  294. /// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
  295. /// no other analyses. In particular, it does not preserve LoopSimplify
  296. /// (because it's complicated to handle the case where one of the edges being
  297. /// split is an exit of a loop with other exits).
  298. BasicBlock *SplitBlockPredecessors(BasicBlock *BB, ArrayRef<BasicBlock *> Preds,
  299. const char *Suffix,
  300. DomTreeUpdater *DTU = nullptr,
  301. LoopInfo *LI = nullptr,
  302. MemorySSAUpdater *MSSAU = nullptr,
  303. bool PreserveLCSSA = false);
  304. /// This method transforms the landing pad, OrigBB, by introducing two new basic
  305. /// blocks into the function. One of those new basic blocks gets the
  306. /// predecessors listed in Preds. The other basic block gets the remaining
  307. /// predecessors of OrigBB. The landingpad instruction OrigBB is clone into both
  308. /// of the new basic blocks. The new blocks are given the suffixes 'Suffix1' and
  309. /// 'Suffix2', and are returned in the NewBBs vector.
  310. ///
  311. /// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
  312. /// no other analyses. In particular, it does not preserve LoopSimplify
  313. /// (because it's complicated to handle the case where one of the edges being
  314. /// split is an exit of a loop with other exits).
  315. ///
  316. /// FIXME: deprecated, switch to the DomTreeUpdater-based one.
  317. void SplitLandingPadPredecessors(BasicBlock *OrigBB,
  318. ArrayRef<BasicBlock *> Preds,
  319. const char *Suffix, const char *Suffix2,
  320. SmallVectorImpl<BasicBlock *> &NewBBs,
  321. DominatorTree *DT, LoopInfo *LI = nullptr,
  322. MemorySSAUpdater *MSSAU = nullptr,
  323. bool PreserveLCSSA = false);
  324. /// This method transforms the landing pad, OrigBB, by introducing two new basic
  325. /// blocks into the function. One of those new basic blocks gets the
  326. /// predecessors listed in Preds. The other basic block gets the remaining
  327. /// predecessors of OrigBB. The landingpad instruction OrigBB is clone into both
  328. /// of the new basic blocks. The new blocks are given the suffixes 'Suffix1' and
  329. /// 'Suffix2', and are returned in the NewBBs vector.
  330. ///
  331. /// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
  332. /// no other analyses. In particular, it does not preserve LoopSimplify
  333. /// (because it's complicated to handle the case where one of the edges being
  334. /// split is an exit of a loop with other exits).
  335. void SplitLandingPadPredecessors(
  336. BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix,
  337. const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
  338. DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
  339. MemorySSAUpdater *MSSAU = nullptr, bool PreserveLCSSA = false);
  340. /// This method duplicates the specified return instruction into a predecessor
  341. /// which ends in an unconditional branch. If the return instruction returns a
  342. /// value defined by a PHI, propagate the right value into the return. It
  343. /// returns the new return instruction in the predecessor.
  344. ReturnInst *FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
  345. BasicBlock *Pred,
  346. DomTreeUpdater *DTU = nullptr);
  347. /// Split the containing block at the specified instruction - everything before
  348. /// SplitBefore stays in the old basic block, and the rest of the instructions
  349. /// in the BB are moved to a new block. The two blocks are connected by a
  350. /// conditional branch (with value of Cmp being the condition).
  351. /// Before:
  352. /// Head
  353. /// SplitBefore
  354. /// Tail
  355. /// After:
  356. /// Head
  357. /// if (Cond)
  358. /// ThenBlock
  359. /// SplitBefore
  360. /// Tail
  361. ///
  362. /// If \p ThenBlock is not specified, a new block will be created for it.
  363. /// If \p Unreachable is true, the newly created block will end with
  364. /// UnreachableInst, otherwise it branches to Tail.
  365. /// Returns the NewBasicBlock's terminator.
  366. ///
  367. /// Updates DT and LI if given.
  368. ///
  369. /// FIXME: deprecated, switch to the DomTreeUpdater-based one.
  370. Instruction *SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore,
  371. bool Unreachable, MDNode *BranchWeights,
  372. DominatorTree *DT,
  373. LoopInfo *LI = nullptr,
  374. BasicBlock *ThenBlock = nullptr);
  375. /// Split the containing block at the specified instruction - everything before
  376. /// SplitBefore stays in the old basic block, and the rest of the instructions
  377. /// in the BB are moved to a new block. The two blocks are connected by a
  378. /// conditional branch (with value of Cmp being the condition).
  379. /// Before:
  380. /// Head
  381. /// SplitBefore
  382. /// Tail
  383. /// After:
  384. /// Head
  385. /// if (Cond)
  386. /// ThenBlock
  387. /// SplitBefore
  388. /// Tail
  389. ///
  390. /// If \p ThenBlock is not specified, a new block will be created for it.
  391. /// If \p Unreachable is true, the newly created block will end with
  392. /// UnreachableInst, otherwise it branches to Tail.
  393. /// Returns the NewBasicBlock's terminator.
  394. ///
  395. /// Updates DT and LI if given.
  396. Instruction *SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore,
  397. bool Unreachable,
  398. MDNode *BranchWeights = nullptr,
  399. DomTreeUpdater *DTU = nullptr,
  400. LoopInfo *LI = nullptr,
  401. BasicBlock *ThenBlock = nullptr);
  402. /// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
  403. /// but also creates the ElseBlock.
  404. /// Before:
  405. /// Head
  406. /// SplitBefore
  407. /// Tail
  408. /// After:
  409. /// Head
  410. /// if (Cond)
  411. /// ThenBlock
  412. /// else
  413. /// ElseBlock
  414. /// SplitBefore
  415. /// Tail
  416. void SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
  417. Instruction **ThenTerm,
  418. Instruction **ElseTerm,
  419. MDNode *BranchWeights = nullptr);
  420. /// Check whether BB is the merge point of a if-region.
  421. /// If so, return the boolean condition that determines which entry into
  422. /// BB will be taken. Also, return by references the block that will be
  423. /// entered from if the condition is true, and the block that will be
  424. /// entered if the condition is false.
  425. ///
  426. /// This does no checking to see if the true/false blocks have large or unsavory
  427. /// instructions in them.
  428. Value *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
  429. BasicBlock *&IfFalse);
  430. // Split critical edges where the source of the edge is an indirectbr
  431. // instruction. This isn't always possible, but we can handle some easy cases.
  432. // This is useful because MI is unable to split such critical edges,
  433. // which means it will not be able to sink instructions along those edges.
  434. // This is especially painful for indirect branches with many successors, where
  435. // we end up having to prepare all outgoing values in the origin block.
  436. //
  437. // Our normal algorithm for splitting critical edges requires us to update
  438. // the outgoing edges of the edge origin block, but for an indirectbr this
  439. // is hard, since it would require finding and updating the block addresses
  440. // the indirect branch uses. But if a block only has a single indirectbr
  441. // predecessor, with the others being regular branches, we can do it in a
  442. // different way.
  443. // Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr.
  444. // We can split D into D0 and D1, where D0 contains only the PHIs from D,
  445. // and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and
  446. // create the following structure:
  447. // A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1
  448. // If BPI and BFI aren't non-null, BPI/BFI will be updated accordingly.
  449. bool SplitIndirectBrCriticalEdges(Function &F,
  450. BranchProbabilityInfo *BPI = nullptr,
  451. BlockFrequencyInfo *BFI = nullptr);
  452. /// Given a set of incoming and outgoing blocks, create a "hub" such that every
  453. /// edge from an incoming block InBB to an outgoing block OutBB is now split
  454. /// into two edges, one from InBB to the hub and another from the hub to
  455. /// OutBB. The hub consists of a series of guard blocks, one for each outgoing
  456. /// block. Each guard block conditionally branches to the corresponding outgoing
  457. /// block, or the next guard block in the chain. These guard blocks are returned
  458. /// in the argument vector.
  459. ///
  460. /// Since the control flow edges from InBB to OutBB have now been replaced, the
  461. /// function also updates any PHINodes in OutBB. For each such PHINode, the
  462. /// operands corresponding to incoming blocks are moved to a new PHINode in the
  463. /// hub, and the hub is made an operand of the original PHINode.
  464. ///
  465. /// Input CFG:
  466. /// ----------
  467. ///
  468. /// Def
  469. /// |
  470. /// v
  471. /// In1 In2
  472. /// | |
  473. /// | |
  474. /// v v
  475. /// Foo ---> Out1 Out2
  476. /// |
  477. /// v
  478. /// Use
  479. ///
  480. ///
  481. /// Create hub: Incoming = {In1, In2}, Outgoing = {Out1, Out2}
  482. /// ----------------------------------------------------------
  483. ///
  484. /// Def
  485. /// |
  486. /// v
  487. /// In1 In2 Foo
  488. /// | Hub | |
  489. /// | + - - | - - + |
  490. /// | ' v ' V
  491. /// +------> Guard1 -----> Out1
  492. /// ' | '
  493. /// ' v '
  494. /// ' Guard2 -----> Out2
  495. /// ' ' |
  496. /// + - - - - - + |
  497. /// v
  498. /// Use
  499. ///
  500. /// Limitations:
  501. /// -----------
  502. /// 1. This assumes that all terminators in the CFG are direct branches (the
  503. /// "br" instruction). The presence of any other control flow such as
  504. /// indirectbr, switch or callbr will cause an assert.
  505. ///
  506. /// 2. The updates to the PHINodes are not sufficient to restore SSA
  507. /// form. Consider a definition Def, its use Use, incoming block In2 and
  508. /// outgoing block Out2, such that:
  509. /// a. In2 is reachable from D or contains D.
  510. /// b. U is reachable from Out2 or is contained in Out2.
  511. /// c. U is not a PHINode if U is contained in Out2.
  512. ///
  513. /// Clearly, Def dominates Out2 since the program is valid SSA. But when the
  514. /// hub is introduced, there is a new path through the hub along which Use is
  515. /// reachable from entry without passing through Def, and SSA is no longer
  516. /// valid. To fix this, we need to look at all the blocks post-dominated by
  517. /// the hub on the one hand, and dominated by Out2 on the other. This is left
  518. /// for the caller to accomplish, since each specific use of this function
  519. /// may have additional information which simplifies this fixup. For example,
  520. /// see restoreSSA() in the UnifyLoopExits pass.
  521. BasicBlock *CreateControlFlowHub(DomTreeUpdater *DTU,
  522. SmallVectorImpl<BasicBlock *> &GuardBlocks,
  523. const SetVector<BasicBlock *> &Predecessors,
  524. const SetVector<BasicBlock *> &Successors,
  525. const StringRef Prefix);
  526. } // end namespace llvm
  527. #endif // LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
  528. #ifdef __GNUC__
  529. #pragma GCC diagnostic pop
  530. #endif