]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/Transforms/Utils/BasicBlockUtils.h
Merge lldb trunk r338150 (just before the 7.0.0 branch point), and
[FreeBSD/FreeBSD.git] / contrib / llvm / include / llvm / Transforms / Utils / BasicBlockUtils.h
1 //===- Transform/Utils/BasicBlockUtils.h - BasicBlock Utils -----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This family of functions perform manipulations on basic blocks, and
11 // instructions contained within basic blocks.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
16 #define LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
17
18 // FIXME: Move to this file: BasicBlock::removePredecessor, BB::splitBasicBlock
19
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/IR/BasicBlock.h"
22 #include "llvm/IR/CFG.h"
23 #include "llvm/IR/InstrTypes.h"
24 #include <cassert>
25
26 namespace llvm {
27
28 class BlockFrequencyInfo;
29 class BranchProbabilityInfo;
30 class DeferredDominance;
31 class DominatorTree;
32 class Function;
33 class Instruction;
34 class LoopInfo;
35 class MDNode;
36 class MemoryDependenceResults;
37 class ReturnInst;
38 class TargetLibraryInfo;
39 class Value;
40
41 /// Delete the specified block, which must have no predecessors.
42 void DeleteDeadBlock(BasicBlock *BB, DeferredDominance *DDT = nullptr);
43
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
47 /// one predecessor.
48 void FoldSingleEntryPHINodes(BasicBlock *BB,
49                              MemoryDependenceResults *MemDep = nullptr);
50
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);
56
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);
63
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);
68
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
72 /// instruction.
73 void ReplaceInstWithInst(BasicBlock::InstListType &BIL,
74                          BasicBlock::iterator &BI, Instruction *I);
75
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);
79
80 /// Option class for critical edge splitting.
81 ///
82 /// This provides a builder interface for overriding the default options used
83 /// during critical edge splitting.
84 struct CriticalEdgeSplittingOptions {
85   DominatorTree *DT;
86   LoopInfo *LI;
87   bool MergeIdenticalEdges = false;
88   bool DontDeleteUselessPHIs = false;
89   bool PreserveLCSSA = false;
90
91   CriticalEdgeSplittingOptions(DominatorTree *DT = nullptr,
92                                LoopInfo *LI = nullptr)
93       : DT(DT), LI(LI) {}
94
95   CriticalEdgeSplittingOptions &setMergeIdenticalEdges() {
96     MergeIdenticalEdges = true;
97     return *this;
98   }
99
100   CriticalEdgeSplittingOptions &setDontDeleteUselessPHIs() {
101     DontDeleteUselessPHIs = true;
102     return *this;
103   }
104
105   CriticalEdgeSplittingOptions &setPreserveLCSSA() {
106     PreserveLCSSA = true;
107     return *this;
108   }
109 };
110
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.
114 ///
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
121 /// edge".
122 ///
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
126 /// to.
127 BasicBlock *SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum,
128                               const CriticalEdgeSplittingOptions &Options =
129                                   CriticalEdgeSplittingOptions());
130
131 inline BasicBlock *
132 SplitCriticalEdge(BasicBlock *BB, succ_iterator SI,
133                   const CriticalEdgeSplittingOptions &Options =
134                       CriticalEdgeSplittingOptions()) {
135   return SplitCriticalEdge(BB->getTerminator(), SI.getSuccessorIndex(),
136                            Options);
137 }
138
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);
151   return MadeChange;
152 }
153
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
157 inline BasicBlock *
158 SplitCriticalEdge(BasicBlock *Src, BasicBlock *Dst,
159                   const CriticalEdgeSplittingOptions &Options =
160                       CriticalEdgeSplittingOptions()) {
161   TerminatorInst *TI = Src->getTerminator();
162   unsigned i = 0;
163   while (true) {
164     assert(i != TI->getNumSuccessors() && "Edge doesn't exist!");
165     if (TI->getSuccessor(i) == Dst)
166       return SplitCriticalEdge(TI, i, Options);
167     ++i;
168   }
169 }
170
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());
176
177 /// Split the edge connecting specified block.
178 BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To,
179                       DominatorTree *DT = nullptr, LoopInfo *LI = nullptr);
180
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
184 /// info is updated.
185 BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt,
186                        DominatorTree *DT = nullptr, LoopInfo *LI = nullptr);
187
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.
193 ///
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.
197 ///
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,
203                                    const char *Suffix,
204                                    DominatorTree *DT = nullptr,
205                                    LoopInfo *LI = nullptr,
206                                    bool PreserveLCSSA = false);
207
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.
214 ///
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);
226
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,
232                                        BasicBlock *Pred);
233
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).
238 /// Before:
239 ///   Head
240 ///   SplitBefore
241 ///   Tail
242 /// After:
243 ///   Head
244 ///   if (Cond)
245 ///     ThenBlock
246 ///   SplitBefore
247 ///   Tail
248 ///
249 /// If Unreachable is true, then ThenBlock ends with
250 /// UnreachableInst, otherwise it branches to Tail.
251 /// Returns the NewBasicBlock's terminator.
252 ///
253 /// Updates DT and LI if given.
254 TerminatorInst *SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore,
255                                           bool Unreachable,
256                                           MDNode *BranchWeights = nullptr,
257                                           DominatorTree *DT = nullptr,
258                                           LoopInfo *LI = nullptr);
259
260 /// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
261 /// but also creates the ElseBlock.
262 /// Before:
263 ///   Head
264 ///   SplitBefore
265 ///   Tail
266 /// After:
267 ///   Head
268 ///   if (Cond)
269 ///     ThenBlock
270 ///   else
271 ///     ElseBlock
272 ///   SplitBefore
273 ///   Tail
274 void SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
275                                    TerminatorInst **ThenTerm,
276                                    TerminatorInst **ElseTerm,
277                                    MDNode *BranchWeights = nullptr);
278
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.
284 ///
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);
289
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.
296 //
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
302 // different way.
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);
312
313 } // end namespace llvm
314
315 #endif // LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H