BasicBlockUtils.h 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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 detachDeadBlocks(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. Remove redundant
  104. /// pseudo ops when RemovePseudoOp is true.
  105. bool RemoveRedundantDbgInstrs(BasicBlock *BB);
  106. /// Replace all uses of an instruction (specified by BI) with a value, then
  107. /// remove and delete the original instruction.
  108. void ReplaceInstWithValue(BasicBlock::InstListType &BIL,
  109. BasicBlock::iterator &BI, Value *V);
  110. /// Replace the instruction specified by BI with the instruction specified by I.
  111. /// Copies DebugLoc from BI to I, if I doesn't already have a DebugLoc. The
  112. /// original instruction is deleted and BI is updated to point to the new
  113. /// instruction.
  114. void ReplaceInstWithInst(BasicBlock::InstListType &BIL,
  115. BasicBlock::iterator &BI, Instruction *I);
  116. /// Replace the instruction specified by From with the instruction specified by
  117. /// To. Copies DebugLoc from BI to I, if I doesn't already have a DebugLoc.
  118. void ReplaceInstWithInst(Instruction *From, Instruction *To);
  119. /// Check if we can prove that all paths starting from this block converge
  120. /// to a block that either has a @llvm.experimental.deoptimize call
  121. /// prior to its terminating return instruction or is terminated by unreachable.
  122. /// All blocks in the traversed sequence must have an unique successor, maybe
  123. /// except for the last one.
  124. bool IsBlockFollowedByDeoptOrUnreachable(const BasicBlock *BB);
  125. /// Option class for critical edge splitting.
  126. ///
  127. /// This provides a builder interface for overriding the default options used
  128. /// during critical edge splitting.
  129. struct CriticalEdgeSplittingOptions {
  130. DominatorTree *DT;
  131. PostDominatorTree *PDT;
  132. LoopInfo *LI;
  133. MemorySSAUpdater *MSSAU;
  134. bool MergeIdenticalEdges = false;
  135. bool KeepOneInputPHIs = false;
  136. bool PreserveLCSSA = false;
  137. bool IgnoreUnreachableDests = false;
  138. /// SplitCriticalEdge is guaranteed to preserve loop-simplify form if LI is
  139. /// provided. If it cannot be preserved, no splitting will take place. If it
  140. /// is not set, preserve loop-simplify form if possible.
  141. bool PreserveLoopSimplify = true;
  142. CriticalEdgeSplittingOptions(DominatorTree *DT = nullptr,
  143. LoopInfo *LI = nullptr,
  144. MemorySSAUpdater *MSSAU = nullptr,
  145. PostDominatorTree *PDT = nullptr)
  146. : DT(DT), PDT(PDT), LI(LI), MSSAU(MSSAU) {}
  147. CriticalEdgeSplittingOptions &setMergeIdenticalEdges() {
  148. MergeIdenticalEdges = true;
  149. return *this;
  150. }
  151. CriticalEdgeSplittingOptions &setKeepOneInputPHIs() {
  152. KeepOneInputPHIs = true;
  153. return *this;
  154. }
  155. CriticalEdgeSplittingOptions &setPreserveLCSSA() {
  156. PreserveLCSSA = true;
  157. return *this;
  158. }
  159. CriticalEdgeSplittingOptions &setIgnoreUnreachableDests() {
  160. IgnoreUnreachableDests = true;
  161. return *this;
  162. }
  163. CriticalEdgeSplittingOptions &unsetPreserveLoopSimplify() {
  164. PreserveLoopSimplify = false;
  165. return *this;
  166. }
  167. };
  168. /// When a loop exit edge is split, LCSSA form may require new PHIs in the new
  169. /// exit block. This function inserts the new PHIs, as needed. Preds is a list
  170. /// of preds inside the loop, SplitBB is the new loop exit block, and DestBB is
  171. /// the old loop exit, now the successor of SplitBB.
  172. void createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
  173. BasicBlock *SplitBB, BasicBlock *DestBB);
  174. /// If this edge is a critical edge, insert a new node to split the critical
  175. /// edge. This will update the analyses passed in through the option struct.
  176. /// This returns the new block if the edge was split, null otherwise.
  177. ///
  178. /// If MergeIdenticalEdges in the options struct is true (not the default),
  179. /// *all* edges from TI to the specified successor will be merged into the same
  180. /// critical edge block. This is most commonly interesting with switch
  181. /// instructions, which may have many edges to any one destination. This
  182. /// ensures that all edges to that dest go to one block instead of each going
  183. /// to a different block, but isn't the standard definition of a "critical
  184. /// edge".
  185. ///
  186. /// It is invalid to call this function on a critical edge that starts at an
  187. /// IndirectBrInst. Splitting these edges will almost always create an invalid
  188. /// program because the address of the new block won't be the one that is jumped
  189. /// to.
  190. BasicBlock *SplitCriticalEdge(Instruction *TI, unsigned SuccNum,
  191. const CriticalEdgeSplittingOptions &Options =
  192. CriticalEdgeSplittingOptions(),
  193. const Twine &BBName = "");
  194. /// If it is known that an edge is critical, SplitKnownCriticalEdge can be
  195. /// called directly, rather than calling SplitCriticalEdge first.
  196. BasicBlock *SplitKnownCriticalEdge(Instruction *TI, unsigned SuccNum,
  197. const CriticalEdgeSplittingOptions &Options =
  198. CriticalEdgeSplittingOptions(),
  199. const Twine &BBName = "");
  200. /// If an edge from Src to Dst is critical, split the edge and return true,
  201. /// otherwise return false. This method requires that there be an edge between
  202. /// the two blocks. It updates the analyses passed in the options struct
  203. inline BasicBlock *
  204. SplitCriticalEdge(BasicBlock *Src, BasicBlock *Dst,
  205. const CriticalEdgeSplittingOptions &Options =
  206. CriticalEdgeSplittingOptions()) {
  207. Instruction *TI = Src->getTerminator();
  208. unsigned i = 0;
  209. while (true) {
  210. assert(i != TI->getNumSuccessors() && "Edge doesn't exist!");
  211. if (TI->getSuccessor(i) == Dst)
  212. return SplitCriticalEdge(TI, i, Options);
  213. ++i;
  214. }
  215. }
  216. /// Loop over all of the edges in the CFG, breaking critical edges as they are
  217. /// found. Returns the number of broken edges.
  218. unsigned SplitAllCriticalEdges(Function &F,
  219. const CriticalEdgeSplittingOptions &Options =
  220. CriticalEdgeSplittingOptions());
  221. /// Split the edge connecting the specified blocks, and return the newly created
  222. /// basic block between \p From and \p To.
  223. BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To,
  224. DominatorTree *DT = nullptr, LoopInfo *LI = nullptr,
  225. MemorySSAUpdater *MSSAU = nullptr,
  226. const Twine &BBName = "");
  227. /// Sets the unwind edge of an instruction to a particular successor.
  228. void setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ);
  229. /// Replaces all uses of OldPred with the NewPred block in all PHINodes in a
  230. /// block.
  231. void updatePhiNodes(BasicBlock *DestBB, BasicBlock *OldPred,
  232. BasicBlock *NewPred, PHINode *Until = nullptr);
  233. /// Split the edge connect the specficed blocks in the case that \p Succ is an
  234. /// Exception Handling Block
  235. BasicBlock *ehAwareSplitEdge(BasicBlock *BB, BasicBlock *Succ,
  236. LandingPadInst *OriginalPad = nullptr,
  237. PHINode *LandingPadReplacement = nullptr,
  238. const CriticalEdgeSplittingOptions &Options =
  239. CriticalEdgeSplittingOptions(),
  240. const Twine &BBName = "");
  241. /// Split the specified block at the specified instruction.
  242. ///
  243. /// If \p Before is true, splitBlockBefore handles the block
  244. /// splitting. Otherwise, execution proceeds as described below.
  245. ///
  246. /// Everything before \p SplitPt stays in \p Old and everything starting with \p
  247. /// SplitPt moves to a new block. The two blocks are joined by an unconditional
  248. /// branch. The new block with name \p BBName is returned.
  249. ///
  250. /// FIXME: deprecated, switch to the DomTreeUpdater-based one.
  251. BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT,
  252. LoopInfo *LI = nullptr,
  253. MemorySSAUpdater *MSSAU = nullptr,
  254. const Twine &BBName = "", bool Before = false);
  255. /// Split the specified block at the specified instruction.
  256. ///
  257. /// If \p Before is true, splitBlockBefore handles the block
  258. /// splitting. Otherwise, execution proceeds as described below.
  259. ///
  260. /// Everything before \p SplitPt stays in \p Old and everything starting with \p
  261. /// SplitPt moves to a new block. The two blocks are joined by an unconditional
  262. /// branch. The new block with name \p BBName is returned.
  263. BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt,
  264. DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
  265. MemorySSAUpdater *MSSAU = nullptr,
  266. const Twine &BBName = "", bool Before = false);
  267. /// Split the specified block at the specified instruction \p SplitPt.
  268. /// All instructions before \p SplitPt are moved to a new block and all
  269. /// instructions after \p SplitPt stay in the old block. The new block and the
  270. /// old block are joined by inserting an unconditional branch to the end of the
  271. /// new block. The new block with name \p BBName is returned.
  272. BasicBlock *splitBlockBefore(BasicBlock *Old, Instruction *SplitPt,
  273. DomTreeUpdater *DTU, LoopInfo *LI,
  274. MemorySSAUpdater *MSSAU, const Twine &BBName = "");
  275. /// This method introduces at least one new basic block into the function and
  276. /// moves some of the predecessors of BB to be predecessors of the new block.
  277. /// The new predecessors are indicated by the Preds array. The new block is
  278. /// given a suffix of 'Suffix'. Returns new basic block to which predecessors
  279. /// from Preds are now pointing.
  280. ///
  281. /// If BB is a landingpad block then additional basicblock might be introduced.
  282. /// It will have Suffix+".split_lp". See SplitLandingPadPredecessors for more
  283. /// details on this case.
  284. ///
  285. /// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
  286. /// no other analyses. In particular, it does not preserve LoopSimplify
  287. /// (because it's complicated to handle the case where one of the edges being
  288. /// split is an exit of a loop with other exits).
  289. ///
  290. /// FIXME: deprecated, switch to the DomTreeUpdater-based one.
  291. BasicBlock *SplitBlockPredecessors(BasicBlock *BB, ArrayRef<BasicBlock *> Preds,
  292. const char *Suffix, DominatorTree *DT,
  293. LoopInfo *LI = nullptr,
  294. MemorySSAUpdater *MSSAU = nullptr,
  295. bool PreserveLCSSA = false);
  296. /// This method introduces at least one new basic block into the function and
  297. /// moves some of the predecessors of BB to be predecessors of the new block.
  298. /// The new predecessors are indicated by the Preds array. The new block is
  299. /// given a suffix of 'Suffix'. Returns new basic block to which predecessors
  300. /// from Preds are now pointing.
  301. ///
  302. /// If BB is a landingpad block then additional basicblock might be introduced.
  303. /// It will have Suffix+".split_lp". See SplitLandingPadPredecessors for more
  304. /// details on this case.
  305. ///
  306. /// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
  307. /// no other analyses. In particular, it does not preserve LoopSimplify
  308. /// (because it's complicated to handle the case where one of the edges being
  309. /// split is an exit of a loop with other exits).
  310. BasicBlock *SplitBlockPredecessors(BasicBlock *BB, ArrayRef<BasicBlock *> Preds,
  311. const char *Suffix,
  312. DomTreeUpdater *DTU = nullptr,
  313. LoopInfo *LI = nullptr,
  314. MemorySSAUpdater *MSSAU = nullptr,
  315. bool PreserveLCSSA = false);
  316. /// This method transforms the landing pad, OrigBB, by introducing two new basic
  317. /// blocks into the function. One of those new basic blocks gets the
  318. /// predecessors listed in Preds. The other basic block gets the remaining
  319. /// predecessors of OrigBB. The landingpad instruction OrigBB is clone into both
  320. /// of the new basic blocks. The new blocks are given the suffixes 'Suffix1' and
  321. /// 'Suffix2', and are returned in the NewBBs vector.
  322. ///
  323. /// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
  324. /// no other analyses. In particular, it does not preserve LoopSimplify
  325. /// (because it's complicated to handle the case where one of the edges being
  326. /// split is an exit of a loop with other exits).
  327. ///
  328. /// FIXME: deprecated, switch to the DomTreeUpdater-based one.
  329. void SplitLandingPadPredecessors(BasicBlock *OrigBB,
  330. ArrayRef<BasicBlock *> Preds,
  331. const char *Suffix, const char *Suffix2,
  332. SmallVectorImpl<BasicBlock *> &NewBBs,
  333. DominatorTree *DT, LoopInfo *LI = nullptr,
  334. MemorySSAUpdater *MSSAU = nullptr,
  335. bool PreserveLCSSA = false);
  336. /// This method transforms the landing pad, OrigBB, by introducing two new basic
  337. /// blocks into the function. One of those new basic blocks gets the
  338. /// predecessors listed in Preds. The other basic block gets the remaining
  339. /// predecessors of OrigBB. The landingpad instruction OrigBB is clone into both
  340. /// of the new basic blocks. The new blocks are given the suffixes 'Suffix1' and
  341. /// 'Suffix2', and are returned in the NewBBs vector.
  342. ///
  343. /// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
  344. /// no other analyses. In particular, it does not preserve LoopSimplify
  345. /// (because it's complicated to handle the case where one of the edges being
  346. /// split is an exit of a loop with other exits).
  347. void SplitLandingPadPredecessors(
  348. BasicBlock *OrigBB, ArrayRef<BasicBlock *> Preds, const char *Suffix,
  349. const char *Suffix2, SmallVectorImpl<BasicBlock *> &NewBBs,
  350. DomTreeUpdater *DTU = nullptr, LoopInfo *LI = nullptr,
  351. MemorySSAUpdater *MSSAU = nullptr, bool PreserveLCSSA = false);
  352. /// This method duplicates the specified return instruction into a predecessor
  353. /// which ends in an unconditional branch. If the return instruction returns a
  354. /// value defined by a PHI, propagate the right value into the return. It
  355. /// returns the new return instruction in the predecessor.
  356. ReturnInst *FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
  357. BasicBlock *Pred,
  358. DomTreeUpdater *DTU = nullptr);
  359. /// Split the containing block at the specified instruction - everything before
  360. /// SplitBefore stays in the old basic block, and the rest of the instructions
  361. /// in the BB are moved to a new block. The two blocks are connected by a
  362. /// conditional branch (with value of Cmp being the condition).
  363. /// Before:
  364. /// Head
  365. /// SplitBefore
  366. /// Tail
  367. /// After:
  368. /// Head
  369. /// if (Cond)
  370. /// ThenBlock
  371. /// SplitBefore
  372. /// Tail
  373. ///
  374. /// If \p ThenBlock is not specified, a new block will be created for it.
  375. /// If \p Unreachable is true, the newly created block will end with
  376. /// UnreachableInst, otherwise it branches to Tail.
  377. /// Returns the NewBasicBlock's terminator.
  378. ///
  379. /// Updates DT and LI if given.
  380. ///
  381. /// FIXME: deprecated, switch to the DomTreeUpdater-based one.
  382. Instruction *SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore,
  383. bool Unreachable, MDNode *BranchWeights,
  384. DominatorTree *DT,
  385. LoopInfo *LI = nullptr,
  386. BasicBlock *ThenBlock = nullptr);
  387. /// Split the containing block at the specified instruction - everything before
  388. /// SplitBefore stays in the old basic block, and the rest of the instructions
  389. /// in the BB are moved to a new block. The two blocks are connected by a
  390. /// conditional branch (with value of Cmp being the condition).
  391. /// Before:
  392. /// Head
  393. /// SplitBefore
  394. /// Tail
  395. /// After:
  396. /// Head
  397. /// if (Cond)
  398. /// ThenBlock
  399. /// SplitBefore
  400. /// Tail
  401. ///
  402. /// If \p ThenBlock is not specified, a new block will be created for it.
  403. /// If \p Unreachable is true, the newly created block will end with
  404. /// UnreachableInst, otherwise it branches to Tail.
  405. /// Returns the NewBasicBlock's terminator.
  406. ///
  407. /// Updates DT and LI if given.
  408. Instruction *SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore,
  409. bool Unreachable,
  410. MDNode *BranchWeights = nullptr,
  411. DomTreeUpdater *DTU = nullptr,
  412. LoopInfo *LI = nullptr,
  413. BasicBlock *ThenBlock = nullptr);
  414. /// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
  415. /// but also creates the ElseBlock.
  416. /// Before:
  417. /// Head
  418. /// SplitBefore
  419. /// Tail
  420. /// After:
  421. /// Head
  422. /// if (Cond)
  423. /// ThenBlock
  424. /// else
  425. /// ElseBlock
  426. /// SplitBefore
  427. /// Tail
  428. void SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
  429. Instruction **ThenTerm,
  430. Instruction **ElseTerm,
  431. MDNode *BranchWeights = nullptr);
  432. /// Check whether BB is the merge point of a if-region.
  433. /// If so, return the branch instruction that determines which entry into
  434. /// BB will be taken. Also, return by references the block that will be
  435. /// entered from if the condition is true, and the block that will be
  436. /// entered if the condition is false.
  437. ///
  438. /// This does no checking to see if the true/false blocks have large or unsavory
  439. /// instructions in them.
  440. BranchInst *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
  441. BasicBlock *&IfFalse);
  442. // Split critical edges where the source of the edge is an indirectbr
  443. // instruction. This isn't always possible, but we can handle some easy cases.
  444. // This is useful because MI is unable to split such critical edges,
  445. // which means it will not be able to sink instructions along those edges.
  446. // This is especially painful for indirect branches with many successors, where
  447. // we end up having to prepare all outgoing values in the origin block.
  448. //
  449. // Our normal algorithm for splitting critical edges requires us to update
  450. // the outgoing edges of the edge origin block, but for an indirectbr this
  451. // is hard, since it would require finding and updating the block addresses
  452. // the indirect branch uses. But if a block only has a single indirectbr
  453. // predecessor, with the others being regular branches, we can do it in a
  454. // different way.
  455. // Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr.
  456. // We can split D into D0 and D1, where D0 contains only the PHIs from D,
  457. // and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and
  458. // create the following structure:
  459. // A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1
  460. // If BPI and BFI aren't non-null, BPI/BFI will be updated accordingly.
  461. bool SplitIndirectBrCriticalEdges(Function &F,
  462. BranchProbabilityInfo *BPI = nullptr,
  463. BlockFrequencyInfo *BFI = nullptr);
  464. /// Given a set of incoming and outgoing blocks, create a "hub" such that every
  465. /// edge from an incoming block InBB to an outgoing block OutBB is now split
  466. /// into two edges, one from InBB to the hub and another from the hub to
  467. /// OutBB. The hub consists of a series of guard blocks, one for each outgoing
  468. /// block. Each guard block conditionally branches to the corresponding outgoing
  469. /// block, or the next guard block in the chain. These guard blocks are returned
  470. /// in the argument vector.
  471. ///
  472. /// Since the control flow edges from InBB to OutBB have now been replaced, the
  473. /// function also updates any PHINodes in OutBB. For each such PHINode, the
  474. /// operands corresponding to incoming blocks are moved to a new PHINode in the
  475. /// hub, and the hub is made an operand of the original PHINode.
  476. ///
  477. /// Input CFG:
  478. /// ----------
  479. ///
  480. /// Def
  481. /// |
  482. /// v
  483. /// In1 In2
  484. /// | |
  485. /// | |
  486. /// v v
  487. /// Foo ---> Out1 Out2
  488. /// |
  489. /// v
  490. /// Use
  491. ///
  492. ///
  493. /// Create hub: Incoming = {In1, In2}, Outgoing = {Out1, Out2}
  494. /// ----------------------------------------------------------
  495. ///
  496. /// Def
  497. /// |
  498. /// v
  499. /// In1 In2 Foo
  500. /// | Hub | |
  501. /// | + - - | - - + |
  502. /// | ' v ' V
  503. /// +------> Guard1 -----> Out1
  504. /// ' | '
  505. /// ' v '
  506. /// ' Guard2 -----> Out2
  507. /// ' ' |
  508. /// + - - - - - + |
  509. /// v
  510. /// Use
  511. ///
  512. /// Limitations:
  513. /// -----------
  514. /// 1. This assumes that all terminators in the CFG are direct branches (the
  515. /// "br" instruction). The presence of any other control flow such as
  516. /// indirectbr, switch or callbr will cause an assert.
  517. ///
  518. /// 2. The updates to the PHINodes are not sufficient to restore SSA
  519. /// form. Consider a definition Def, its use Use, incoming block In2 and
  520. /// outgoing block Out2, such that:
  521. /// a. In2 is reachable from D or contains D.
  522. /// b. U is reachable from Out2 or is contained in Out2.
  523. /// c. U is not a PHINode if U is contained in Out2.
  524. ///
  525. /// Clearly, Def dominates Out2 since the program is valid SSA. But when the
  526. /// hub is introduced, there is a new path through the hub along which Use is
  527. /// reachable from entry without passing through Def, and SSA is no longer
  528. /// valid. To fix this, we need to look at all the blocks post-dominated by
  529. /// the hub on the one hand, and dominated by Out2 on the other. This is left
  530. /// for the caller to accomplish, since each specific use of this function
  531. /// may have additional information which simplifies this fixup. For example,
  532. /// see restoreSSA() in the UnifyLoopExits pass.
  533. BasicBlock *CreateControlFlowHub(DomTreeUpdater *DTU,
  534. SmallVectorImpl<BasicBlock *> &GuardBlocks,
  535. const SetVector<BasicBlock *> &Predecessors,
  536. const SetVector<BasicBlock *> &Successors,
  537. const StringRef Prefix);
  538. } // end namespace llvm
  539. #endif // LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
  540. #ifdef __GNUC__
  541. #pragma GCC diagnostic pop
  542. #endif