1 //===- Transform/Utils/BasicBlockUtils.h - BasicBlock Utils -----*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This family of functions perform manipulations on basic blocks, and
10 // instructions contained within basic blocks.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
15 #define LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
17 // FIXME: Move to this file: BasicBlock::removePredecessor, BB::splitBasicBlock
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/Analysis/DomTreeUpdater.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
;
36 class MemoryDependenceResults
;
37 class MemorySSAUpdater
;
39 class TargetLibraryInfo
;
42 /// Replace contents of every block in \p BBs with single unreachable
43 /// instruction. If \p Updates is specified, collect all necessary DT updates
44 /// into this vector. If \p KeepOneInputPHIs is true, one-input Phis in
45 /// successors of blocks being deleted will be preserved.
46 void DetatchDeadBlocks(ArrayRef
<BasicBlock
*> BBs
,
47 SmallVectorImpl
<DominatorTree::UpdateType
> *Updates
,
48 bool KeepOneInputPHIs
= false);
50 /// Delete the specified block, which must have no predecessors.
51 void DeleteDeadBlock(BasicBlock
*BB
, DomTreeUpdater
*DTU
= nullptr,
52 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);
64 /// We know that BB has one predecessor. If there are any single-entry PHI nodes
65 /// in it, fold them away. This handles the case when all entries to the PHI
66 /// nodes in a block are guaranteed equal, such as when the block has exactly
68 void FoldSingleEntryPHINodes(BasicBlock
*BB
,
69 MemoryDependenceResults
*MemDep
= nullptr);
71 /// Examine each PHI in the given block and delete it if it is dead. Also
72 /// recursively delete any operands that become dead as a result. This includes
73 /// tracing the def-use list from the PHI to see if it is ultimately unused or
74 /// if it reaches an unused cycle. Return true if any PHIs were deleted.
75 bool DeleteDeadPHIs(BasicBlock
*BB
, const TargetLibraryInfo
*TLI
= nullptr);
77 /// Attempts to merge a block into its predecessor, if possible. The return
78 /// value indicates success or failure.
79 bool MergeBlockIntoPredecessor(BasicBlock
*BB
, DomTreeUpdater
*DTU
= nullptr,
80 LoopInfo
*LI
= nullptr,
81 MemorySSAUpdater
*MSSAU
= nullptr,
82 MemoryDependenceResults
*MemDep
= nullptr);
84 /// Replace all uses of an instruction (specified by BI) with a value, then
85 /// remove and delete the original instruction.
86 void ReplaceInstWithValue(BasicBlock::InstListType
&BIL
,
87 BasicBlock::iterator
&BI
, Value
*V
);
89 /// Replace the instruction specified by BI with the instruction specified by I.
90 /// Copies DebugLoc from BI to I, if I doesn't already have a DebugLoc. The
91 /// original instruction is deleted and BI is updated to point to the new
93 void ReplaceInstWithInst(BasicBlock::InstListType
&BIL
,
94 BasicBlock::iterator
&BI
, Instruction
*I
);
96 /// Replace the instruction specified by From with the instruction specified by
97 /// To. Copies DebugLoc from BI to I, if I doesn't already have a DebugLoc.
98 void ReplaceInstWithInst(Instruction
*From
, Instruction
*To
);
100 /// Option class for critical edge splitting.
102 /// This provides a builder interface for overriding the default options used
103 /// during critical edge splitting.
104 struct CriticalEdgeSplittingOptions
{
107 MemorySSAUpdater
*MSSAU
;
108 bool MergeIdenticalEdges
= false;
109 bool KeepOneInputPHIs
= false;
110 bool PreserveLCSSA
= false;
112 CriticalEdgeSplittingOptions(DominatorTree
*DT
= nullptr,
113 LoopInfo
*LI
= nullptr,
114 MemorySSAUpdater
*MSSAU
= nullptr)
115 : DT(DT
), LI(LI
), MSSAU(MSSAU
) {}
117 CriticalEdgeSplittingOptions
&setMergeIdenticalEdges() {
118 MergeIdenticalEdges
= true;
122 CriticalEdgeSplittingOptions
&setKeepOneInputPHIs() {
123 KeepOneInputPHIs
= true;
127 CriticalEdgeSplittingOptions
&setPreserveLCSSA() {
128 PreserveLCSSA
= true;
133 /// If this edge is a critical edge, insert a new node to split the critical
134 /// edge. This will update the analyses passed in through the option struct.
135 /// This returns the new block if the edge was split, null otherwise.
137 /// If MergeIdenticalEdges in the options struct is true (not the default),
138 /// *all* edges from TI to the specified successor will be merged into the same
139 /// critical edge block. This is most commonly interesting with switch
140 /// instructions, which may have many edges to any one destination. This
141 /// ensures that all edges to that dest go to one block instead of each going
142 /// to a different block, but isn't the standard definition of a "critical
145 /// It is invalid to call this function on a critical edge that starts at an
146 /// IndirectBrInst. Splitting these edges will almost always create an invalid
147 /// program because the address of the new block won't be the one that is jumped
149 BasicBlock
*SplitCriticalEdge(Instruction
*TI
, unsigned SuccNum
,
150 const CriticalEdgeSplittingOptions
&Options
=
151 CriticalEdgeSplittingOptions());
154 SplitCriticalEdge(BasicBlock
*BB
, succ_iterator SI
,
155 const CriticalEdgeSplittingOptions
&Options
=
156 CriticalEdgeSplittingOptions()) {
157 return SplitCriticalEdge(BB
->getTerminator(), SI
.getSuccessorIndex(),
161 /// If the edge from *PI to BB is not critical, return false. Otherwise, split
162 /// all edges between the two blocks and return true. This updates all of the
163 /// same analyses as the other SplitCriticalEdge function. If P is specified, it
164 /// updates the analyses described above.
165 inline bool SplitCriticalEdge(BasicBlock
*Succ
, pred_iterator PI
,
166 const CriticalEdgeSplittingOptions
&Options
=
167 CriticalEdgeSplittingOptions()) {
168 bool MadeChange
= false;
169 Instruction
*TI
= (*PI
)->getTerminator();
170 for (unsigned i
= 0, e
= TI
->getNumSuccessors(); i
!= e
; ++i
)
171 if (TI
->getSuccessor(i
) == Succ
)
172 MadeChange
|= !!SplitCriticalEdge(TI
, i
, Options
);
176 /// If an edge from Src to Dst is critical, split the edge and return true,
177 /// otherwise return false. This method requires that there be an edge between
178 /// the two blocks. It updates the analyses passed in the options struct
180 SplitCriticalEdge(BasicBlock
*Src
, BasicBlock
*Dst
,
181 const CriticalEdgeSplittingOptions
&Options
=
182 CriticalEdgeSplittingOptions()) {
183 Instruction
*TI
= Src
->getTerminator();
186 assert(i
!= TI
->getNumSuccessors() && "Edge doesn't exist!");
187 if (TI
->getSuccessor(i
) == Dst
)
188 return SplitCriticalEdge(TI
, i
, Options
);
193 /// Loop over all of the edges in the CFG, breaking critical edges as they are
194 /// found. Returns the number of broken edges.
195 unsigned SplitAllCriticalEdges(Function
&F
,
196 const CriticalEdgeSplittingOptions
&Options
=
197 CriticalEdgeSplittingOptions());
199 /// Split the edge connecting specified block.
200 BasicBlock
*SplitEdge(BasicBlock
*From
, BasicBlock
*To
,
201 DominatorTree
*DT
= nullptr, LoopInfo
*LI
= nullptr,
202 MemorySSAUpdater
*MSSAU
= nullptr);
204 /// Split the specified block at the specified instruction - everything before
205 /// SplitPt stays in Old and everything starting with SplitPt moves to a new
206 /// block. The two blocks are joined by an unconditional branch and the loop
208 BasicBlock
*SplitBlock(BasicBlock
*Old
, Instruction
*SplitPt
,
209 DominatorTree
*DT
= nullptr, LoopInfo
*LI
= nullptr,
210 MemorySSAUpdater
*MSSAU
= nullptr);
212 /// This method introduces at least one new basic block into the function and
213 /// moves some of the predecessors of BB to be predecessors of the new block.
214 /// The new predecessors are indicated by the Preds array. The new block is
215 /// given a suffix of 'Suffix'. Returns new basic block to which predecessors
216 /// from Preds are now pointing.
218 /// If BB is a landingpad block then additional basicblock might be introduced.
219 /// It will have Suffix+".split_lp". See SplitLandingPadPredecessors for more
220 /// details on this case.
222 /// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
223 /// no other analyses. In particular, it does not preserve LoopSimplify
224 /// (because it's complicated to handle the case where one of the edges being
225 /// split is an exit of a loop with other exits).
226 BasicBlock
*SplitBlockPredecessors(BasicBlock
*BB
, ArrayRef
<BasicBlock
*> Preds
,
228 DominatorTree
*DT
= nullptr,
229 LoopInfo
*LI
= nullptr,
230 MemorySSAUpdater
*MSSAU
= nullptr,
231 bool PreserveLCSSA
= false);
233 /// This method transforms the landing pad, OrigBB, by introducing two new basic
234 /// blocks into the function. One of those new basic blocks gets the
235 /// predecessors listed in Preds. The other basic block gets the remaining
236 /// predecessors of OrigBB. The landingpad instruction OrigBB is clone into both
237 /// of the new basic blocks. The new blocks are given the suffixes 'Suffix1' and
238 /// 'Suffix2', and are returned in the NewBBs vector.
240 /// This currently updates the LLVM IR, DominatorTree, LoopInfo, and LCCSA but
241 /// no other analyses. In particular, it does not preserve LoopSimplify
242 /// (because it's complicated to handle the case where one of the edges being
243 /// split is an exit of a loop with other exits).
244 void SplitLandingPadPredecessors(
245 BasicBlock
*OrigBB
, ArrayRef
<BasicBlock
*> Preds
, const char *Suffix
,
246 const char *Suffix2
, SmallVectorImpl
<BasicBlock
*> &NewBBs
,
247 DominatorTree
*DT
= nullptr, LoopInfo
*LI
= nullptr,
248 MemorySSAUpdater
*MSSAU
= nullptr, bool PreserveLCSSA
= false);
250 /// This method duplicates the specified return instruction into a predecessor
251 /// which ends in an unconditional branch. If the return instruction returns a
252 /// value defined by a PHI, propagate the right value into the return. It
253 /// returns the new return instruction in the predecessor.
254 ReturnInst
*FoldReturnIntoUncondBranch(ReturnInst
*RI
, BasicBlock
*BB
,
256 DomTreeUpdater
*DTU
= nullptr);
258 /// Split the containing block at the specified instruction - everything before
259 /// SplitBefore stays in the old basic block, and the rest of the instructions
260 /// in the BB are moved to a new block. The two blocks are connected by a
261 /// conditional branch (with value of Cmp being the condition).
273 /// If \p ThenBlock is not specified, a new block will be created for it.
274 /// If \p Unreachable is true, the newly created block will end with
275 /// UnreachableInst, otherwise it branches to Tail.
276 /// Returns the NewBasicBlock's terminator.
278 /// Updates DT and LI if given.
279 Instruction
*SplitBlockAndInsertIfThen(Value
*Cond
, Instruction
*SplitBefore
,
281 MDNode
*BranchWeights
= nullptr,
282 DominatorTree
*DT
= nullptr,
283 LoopInfo
*LI
= nullptr,
284 BasicBlock
*ThenBlock
= nullptr);
286 /// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
287 /// but also creates the ElseBlock.
300 void SplitBlockAndInsertIfThenElse(Value
*Cond
, Instruction
*SplitBefore
,
301 Instruction
**ThenTerm
,
302 Instruction
**ElseTerm
,
303 MDNode
*BranchWeights
= nullptr);
305 /// Check whether BB is the merge point of a if-region.
306 /// If so, return the boolean condition that determines which entry into
307 /// BB will be taken. Also, return by references the block that will be
308 /// entered from if the condition is true, and the block that will be
309 /// entered if the condition is false.
311 /// This does no checking to see if the true/false blocks have large or unsavory
312 /// instructions in them.
313 Value
*GetIfCondition(BasicBlock
*BB
, BasicBlock
*&IfTrue
,
314 BasicBlock
*&IfFalse
);
316 // Split critical edges where the source of the edge is an indirectbr
317 // instruction. This isn't always possible, but we can handle some easy cases.
318 // This is useful because MI is unable to split such critical edges,
319 // which means it will not be able to sink instructions along those edges.
320 // This is especially painful for indirect branches with many successors, where
321 // we end up having to prepare all outgoing values in the origin block.
323 // Our normal algorithm for splitting critical edges requires us to update
324 // the outgoing edges of the edge origin block, but for an indirectbr this
325 // is hard, since it would require finding and updating the block addresses
326 // the indirect branch uses. But if a block only has a single indirectbr
327 // predecessor, with the others being regular branches, we can do it in a
329 // Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr.
330 // We can split D into D0 and D1, where D0 contains only the PHIs from D,
331 // and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and
332 // create the following structure:
333 // A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1
334 // If BPI and BFI aren't non-null, BPI/BFI will be updated accordingly.
335 bool SplitIndirectBrCriticalEdges(Function
&F
,
336 BranchProbabilityInfo
*BPI
= nullptr,
337 BlockFrequencyInfo
*BFI
= nullptr);
339 } // end namespace llvm
341 #endif // LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H