1 //===- Transform/Utils/BasicBlockUtils.h - BasicBlock Utils -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This family of functions perform manipulations on basic blocks, and
11 // instructions contained within basic blocks.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
16 #define LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
18 // FIXME: Move to this file: BasicBlock::removePredecessor, BB::splitBasicBlock
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/IR/BasicBlock.h"
22 #include "llvm/IR/CFG.h"
23 #include "llvm/IR/InstrTypes.h"
28 class BlockFrequencyInfo;
29 class BranchProbabilityInfo;
30 class DeferredDominance;
36 class MemoryDependenceResults;
38 class TargetLibraryInfo;
41 /// Delete the specified block, which must have no predecessors.
42 void DeleteDeadBlock(BasicBlock *BB, DeferredDominance *DDT = nullptr);
44 /// We know that BB has one predecessor. If there are any single-entry PHI nodes
45 /// in it, fold them away. This handles the case when all entries to the PHI
46 /// nodes in a block are guaranteed equal, such as when the block has exactly
48 void FoldSingleEntryPHINodes(BasicBlock *BB,
49 MemoryDependenceResults *MemDep = nullptr);
51 /// Examine each PHI in the given block and delete it if it is dead. Also
52 /// recursively delete any operands that become dead as a result. This includes
53 /// tracing the def-use list from the PHI to see if it is ultimately unused or
54 /// if it reaches an unused cycle. Return true if any PHIs were deleted.
55 bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI = nullptr);
57 /// Attempts to merge a block into its predecessor, if possible. The return
58 /// value indicates success or failure.
59 bool MergeBlockIntoPredecessor(BasicBlock *BB, DominatorTree *DT = nullptr,
60 LoopInfo *LI = nullptr,
61 MemoryDependenceResults *MemDep = nullptr,
62 DeferredDominance *DDT = nullptr);
64 /// Replace all uses of an instruction (specified by BI) with a value, then
65 /// remove and delete the original instruction.
66 void ReplaceInstWithValue(BasicBlock::InstListType &BIL,
67 BasicBlock::iterator &BI, Value *V);
69 /// Replace the instruction specified by BI with the instruction specified by I.
70 /// Copies DebugLoc from BI to I, if I doesn't already have a DebugLoc. The
71 /// original instruction is deleted and BI is updated to point to the new
73 void ReplaceInstWithInst(BasicBlock::InstListType &BIL,
74 BasicBlock::iterator &BI, Instruction *I);
76 /// Replace the instruction specified by From with the instruction specified by
77 /// To. Copies DebugLoc from BI to I, if I doesn't already have a DebugLoc.
78 void ReplaceInstWithInst(Instruction *From, Instruction *To);
80 /// Option class for critical edge splitting.
82 /// This provides a builder interface for overriding the default options used
83 /// during critical edge splitting.
84 struct CriticalEdgeSplittingOptions {
87 bool MergeIdenticalEdges = false;
88 bool DontDeleteUselessPHIs = false;
89 bool PreserveLCSSA = false;
91 CriticalEdgeSplittingOptions(DominatorTree *DT = nullptr,
92 LoopInfo *LI = nullptr)
95 CriticalEdgeSplittingOptions &setMergeIdenticalEdges() {
96 MergeIdenticalEdges = true;
100 CriticalEdgeSplittingOptions &setDontDeleteUselessPHIs() {
101 DontDeleteUselessPHIs = true;
105 CriticalEdgeSplittingOptions &setPreserveLCSSA() {
106 PreserveLCSSA = true;
111 /// If this edge is a critical edge, insert a new node to split the critical
112 /// edge. This will update the analyses passed in through the option struct.
113 /// This returns the new block if the edge was split, null otherwise.
115 /// If MergeIdenticalEdges in the options struct is true (not the default),
116 /// *all* edges from TI to the specified successor will be merged into the same
117 /// critical edge block. This is most commonly interesting with switch
118 /// instructions, which may have many edges to any one destination. This
119 /// ensures that all edges to that dest go to one block instead of each going
120 /// to a different block, but isn't the standard definition of a "critical
123 /// It is invalid to call this function on a critical edge that starts at an
124 /// IndirectBrInst. Splitting these edges will almost always create an invalid
125 /// program because the address of the new block won't be the one that is jumped
127 BasicBlock *SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum,
128 const CriticalEdgeSplittingOptions &Options =
129 CriticalEdgeSplittingOptions());
132 SplitCriticalEdge(BasicBlock *BB, succ_iterator SI,
133 const CriticalEdgeSplittingOptions &Options =
134 CriticalEdgeSplittingOptions()) {
135 return SplitCriticalEdge(BB->getTerminator(), SI.getSuccessorIndex(),
139 /// If the edge from *PI to BB is not critical, return false. Otherwise, split
140 /// all edges between the two blocks and return true. This updates all of the
141 /// same analyses as the other SplitCriticalEdge function. If P is specified, it
142 /// updates the analyses described above.
143 inline bool SplitCriticalEdge(BasicBlock *Succ, pred_iterator PI,
144 const CriticalEdgeSplittingOptions &Options =
145 CriticalEdgeSplittingOptions()) {
146 bool MadeChange = false;
147 TerminatorInst *TI = (*PI)->getTerminator();
148 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
149 if (TI->getSuccessor(i) == Succ)
150 MadeChange |= !!SplitCriticalEdge(TI, i, Options);
154 /// If an edge from Src to Dst is critical, split the edge and return true,
155 /// otherwise return false. This method requires that there be an edge between
156 /// the two blocks. It updates the analyses passed in the options struct
158 SplitCriticalEdge(BasicBlock *Src, BasicBlock *Dst,
159 const CriticalEdgeSplittingOptions &Options =
160 CriticalEdgeSplittingOptions()) {
161 TerminatorInst *TI = Src->getTerminator();
164 assert(i != TI->getNumSuccessors() && "Edge doesn't exist!");
165 if (TI->getSuccessor(i) == Dst)
166 return SplitCriticalEdge(TI, i, Options);
171 /// Loop over all of the edges in the CFG, breaking critical edges as they are
172 /// found. Returns the number of broken edges.
173 unsigned SplitAllCriticalEdges(Function &F,
174 const CriticalEdgeSplittingOptions &Options =
175 CriticalEdgeSplittingOptions());
177 /// Split the edge connecting specified block.
178 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To,
179 DominatorTree *DT = nullptr, LoopInfo *LI = nullptr);
181 /// Split the specified block at the specified instruction - everything before
182 /// SplitPt stays in Old and everything starting with SplitPt moves to a new
183 /// block. The two blocks are joined by an unconditional branch and the loop
185 BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt,
186 DominatorTree *DT = nullptr, LoopInfo *LI = nullptr);
188 /// This method introduces at least one new basic block into the function and
189 /// moves some of the predecessors of BB to be predecessors of the new block.
190 /// The new predecessors are indicated by the Preds array. The new block is
191 /// given a suffix of 'Suffix'. Returns new basic block to which predecessors
192 /// from Preds are now pointing.
194 /// If BB is a landingpad block then additional basicblock might be introduced.
195 /// It will have Suffix+".split_lp". See SplitLandingPadPredecessors for more
196 /// details on this case.
198 /// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
199 /// no other analyses. In particular, it does not preserve LoopSimplify
200 /// (because it's complicated to handle the case where one of the edges being
201 /// split is an exit of a loop with other exits).
202 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, ArrayRef<BasicBlock *> Preds,
204 DominatorTree *DT = nullptr,
205 LoopInfo *LI = nullptr,
206 bool PreserveLCSSA = false);
208 /// This method transforms the landing pad, OrigBB, by introducing two new basic
209 /// blocks into the function. One of those new basic blocks gets the
210 /// predecessors listed in Preds. The other basic block gets the remaining
211 /// predecessors of OrigBB. The landingpad instruction OrigBB is clone into both
212 /// of the new basic blocks. The new blocks are given the suffixes 'Suffix1' and
213 /// 'Suffix2', and are returned in the NewBBs vector.
215 /// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
216 /// no other analyses. In particular, it does not preserve LoopSimplify
217 /// (because it's complicated to handle the case where one of the edges being
218 /// split is an exit of a loop with other exits).
219 void SplitLandingPadPredecessors(BasicBlock *OrigBB,
220 ArrayRef<BasicBlock *> Preds,
221 const char *Suffix, const char *Suffix2,
222 SmallVectorImpl<BasicBlock *> &NewBBs,
223 DominatorTree *DT = nullptr,
224 LoopInfo *LI = nullptr,
225 bool PreserveLCSSA = false);
227 /// This method duplicates the specified return instruction into a predecessor
228 /// which ends in an unconditional branch. If the return instruction returns a
229 /// value defined by a PHI, propagate the right value into the return. It
230 /// returns the new return instruction in the predecessor.
231 ReturnInst *FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
234 /// Split the containing block at the specified instruction - everything before
235 /// SplitBefore stays in the old basic block, and the rest of the instructions
236 /// in the BB are moved to a new block. The two blocks are connected by a
237 /// conditional branch (with value of Cmp being the condition).
249 /// If Unreachable is true, then ThenBlock ends with
250 /// UnreachableInst, otherwise it branches to Tail.
251 /// Returns the NewBasicBlock's terminator.
253 /// Updates DT and LI if given.
254 TerminatorInst *SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore,
256 MDNode *BranchWeights = nullptr,
257 DominatorTree *DT = nullptr,
258 LoopInfo *LI = nullptr);
260 /// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
261 /// but also creates the ElseBlock.
274 void SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
275 TerminatorInst **ThenTerm,
276 TerminatorInst **ElseTerm,
277 MDNode *BranchWeights = nullptr);
279 /// Check whether BB is the merge point of a if-region.
280 /// If so, return the boolean condition that determines which entry into
281 /// BB will be taken. Also, return by references the block that will be
282 /// entered from if the condition is true, and the block that will be
283 /// entered if the condition is false.
285 /// This does no checking to see if the true/false blocks have large or unsavory
286 /// instructions in them.
287 Value *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
288 BasicBlock *&IfFalse);
290 // Split critical edges where the source of the edge is an indirectbr
291 // instruction. This isn't always possible, but we can handle some easy cases.
292 // This is useful because MI is unable to split such critical edges,
293 // which means it will not be able to sink instructions along those edges.
294 // This is especially painful for indirect branches with many successors, where
295 // we end up having to prepare all outgoing values in the origin block.
297 // Our normal algorithm for splitting critical edges requires us to update
298 // the outgoing edges of the edge origin block, but for an indirectbr this
299 // is hard, since it would require finding and updating the block addresses
300 // the indirect branch uses. But if a block only has a single indirectbr
301 // predecessor, with the others being regular branches, we can do it in a
303 // Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr.
304 // We can split D into D0 and D1, where D0 contains only the PHIs from D,
305 // and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and
306 // create the following structure:
307 // A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1
308 // If BPI and BFI aren't non-null, BPI/BFI will be updated accordingly.
309 bool SplitIndirectBrCriticalEdges(Function &F,
310 BranchProbabilityInfo *BPI = nullptr,
311 BlockFrequencyInfo *BFI = nullptr);
313 } // end namespace llvm
315 #endif // LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H