1 //===- BreakCriticalEdges.cpp - Critical Edge Elimination Pass ------------===//
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 // BreakCriticalEdges pass - Break all of the critical edges in the CFG by
11 // inserting a dummy basic block. This pass may be "required" by passes that
12 // cannot deal with critical edges. For this usage, the structure type is
13 // forward declared. This pass obviously invalidates the CFG, but can update
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "break-crit-edges"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
21 #include "llvm/Analysis/Dominators.h"
22 #include "llvm/Analysis/LoopInfo.h"
23 #include "llvm/Analysis/ProfileInfo.h"
24 #include "llvm/Function.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Type.h"
27 #include "llvm/Support/CFG.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
33 STATISTIC(NumBroken
, "Number of blocks inserted");
36 struct BreakCriticalEdges
: public FunctionPass
{
37 static char ID
; // Pass identification, replacement for typeid
38 BreakCriticalEdges() : FunctionPass(ID
) {
39 initializeBreakCriticalEdgesPass(*PassRegistry::getPassRegistry());
42 virtual bool runOnFunction(Function
&F
);
44 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
45 AU
.addPreserved
<DominatorTree
>();
46 AU
.addPreserved
<LoopInfo
>();
47 AU
.addPreserved
<ProfileInfo
>();
49 // No loop canonicalization guarantees are broken by this pass.
50 AU
.addPreservedID(LoopSimplifyID
);
55 char BreakCriticalEdges::ID
= 0;
56 INITIALIZE_PASS(BreakCriticalEdges
, "break-crit-edges",
57 "Break critical edges in CFG", false, false)
59 // Publicly exposed interface to pass...
60 char &llvm::BreakCriticalEdgesID
= BreakCriticalEdges::ID
;
61 FunctionPass
*llvm::createBreakCriticalEdgesPass() {
62 return new BreakCriticalEdges();
65 // runOnFunction - Loop over all of the edges in the CFG, breaking critical
66 // edges as they are found.
68 bool BreakCriticalEdges::runOnFunction(Function
&F
) {
70 for (Function::iterator I
= F
.begin(), E
= F
.end(); I
!= E
; ++I
) {
71 TerminatorInst
*TI
= I
->getTerminator();
72 if (TI
->getNumSuccessors() > 1 && !isa
<IndirectBrInst
>(TI
))
73 for (unsigned i
= 0, e
= TI
->getNumSuccessors(); i
!= e
; ++i
)
74 if (SplitCriticalEdge(TI
, i
, this)) {
83 //===----------------------------------------------------------------------===//
84 // Implementation of the external critical edge manipulation functions
85 //===----------------------------------------------------------------------===//
87 // isCriticalEdge - Return true if the specified edge is a critical edge.
88 // Critical edges are edges from a block with multiple successors to a block
89 // with multiple predecessors.
91 bool llvm::isCriticalEdge(const TerminatorInst
*TI
, unsigned SuccNum
,
92 bool AllowIdenticalEdges
) {
93 assert(SuccNum
< TI
->getNumSuccessors() && "Illegal edge specification!");
94 if (TI
->getNumSuccessors() == 1) return false;
96 const BasicBlock
*Dest
= TI
->getSuccessor(SuccNum
);
97 const_pred_iterator I
= pred_begin(Dest
), E
= pred_end(Dest
);
99 // If there is more than one predecessor, this is a critical edge...
100 assert(I
!= E
&& "No preds, but we have an edge to the block?");
101 const BasicBlock
*FirstPred
= *I
;
102 ++I
; // Skip one edge due to the incoming arc from TI.
103 if (!AllowIdenticalEdges
)
106 // If AllowIdenticalEdges is true, then we allow this edge to be considered
107 // non-critical iff all preds come from TI's block.
109 const BasicBlock
*P
= *I
;
112 // Note: leave this as is until no one ever compiles with either gcc 4.0.1
113 // or Xcode 2. This seems to work around the pred_iterator assert in PR 2207
120 /// CreatePHIsForSplitLoopExit - When a loop exit edge is split, LCSSA form
121 /// may require new PHIs in the new exit block. This function inserts the
122 /// new PHIs, as needed. Preds is a list of preds inside the loop, SplitBB
123 /// is the new loop exit block, and DestBB is the old loop exit, now the
124 /// successor of SplitBB.
125 static void CreatePHIsForSplitLoopExit(SmallVectorImpl
<BasicBlock
*> &Preds
,
127 BasicBlock
*DestBB
) {
128 // SplitBB shouldn't have anything non-trivial in it yet.
129 assert(SplitBB
->getFirstNonPHI() == SplitBB
->getTerminator() &&
130 "SplitBB has non-PHI nodes!");
132 // For each PHI in the destination block...
133 for (BasicBlock::iterator I
= DestBB
->begin();
134 PHINode
*PN
= dyn_cast
<PHINode
>(I
); ++I
) {
135 unsigned Idx
= PN
->getBasicBlockIndex(SplitBB
);
136 Value
*V
= PN
->getIncomingValue(Idx
);
137 // If the input is a PHI which already satisfies LCSSA, don't create
139 if (const PHINode
*VP
= dyn_cast
<PHINode
>(V
))
140 if (VP
->getParent() == SplitBB
)
142 // Otherwise a new PHI is needed. Create one and populate it.
143 PHINode
*NewPN
= PHINode::Create(PN
->getType(), Preds
.size(), "split",
144 SplitBB
->getTerminator());
145 for (unsigned i
= 0, e
= Preds
.size(); i
!= e
; ++i
)
146 NewPN
->addIncoming(V
, Preds
[i
]);
147 // Update the original PHI.
148 PN
->setIncomingValue(Idx
, NewPN
);
152 /// SplitCriticalEdge - If this edge is a critical edge, insert a new node to
153 /// split the critical edge. This will update DominatorTree information if it
154 /// is available, thus calling this pass will not invalidate either of them.
155 /// This returns the new block if the edge was split, null otherwise.
157 /// If MergeIdenticalEdges is true (not the default), *all* edges from TI to the
158 /// specified successor will be merged into the same critical edge block.
159 /// This is most commonly interesting with switch instructions, which may
160 /// have many edges to any one destination. This ensures that all edges to that
161 /// dest go to one block instead of each going to a different block, but isn't
162 /// the standard definition of a "critical edge".
164 /// It is invalid to call this function on a critical edge that starts at an
165 /// IndirectBrInst. Splitting these edges will almost always create an invalid
166 /// program because the address of the new block won't be the one that is jumped
169 BasicBlock
*llvm::SplitCriticalEdge(TerminatorInst
*TI
, unsigned SuccNum
,
170 Pass
*P
, bool MergeIdenticalEdges
) {
171 if (!isCriticalEdge(TI
, SuccNum
, MergeIdenticalEdges
)) return 0;
173 assert(!isa
<IndirectBrInst
>(TI
) &&
174 "Cannot split critical edge from IndirectBrInst");
176 BasicBlock
*TIBB
= TI
->getParent();
177 BasicBlock
*DestBB
= TI
->getSuccessor(SuccNum
);
179 // Create a new basic block, linking it into the CFG.
180 BasicBlock
*NewBB
= BasicBlock::Create(TI
->getContext(),
181 TIBB
->getName() + "." + DestBB
->getName() + "_crit_edge");
182 // Create our unconditional branch.
183 BranchInst
*NewBI
= BranchInst::Create(DestBB
, NewBB
);
184 NewBI
->setDebugLoc(TI
->getDebugLoc());
186 // Branch to the new block, breaking the edge.
187 TI
->setSuccessor(SuccNum
, NewBB
);
189 // Insert the block into the function... right after the block TI lives in.
190 Function
&F
= *TIBB
->getParent();
191 Function::iterator FBBI
= TIBB
;
192 F
.getBasicBlockList().insert(++FBBI
, NewBB
);
194 // If there are any PHI nodes in DestBB, we need to update them so that they
195 // merge incoming values from NewBB instead of from TIBB.
198 for (BasicBlock::iterator I
= DestBB
->begin(); isa
<PHINode
>(I
); ++I
) {
199 // We no longer enter through TIBB, now we come in through NewBB.
200 // Revector exactly one entry in the PHI node that used to come from
201 // TIBB to come from NewBB.
202 PHINode
*PN
= cast
<PHINode
>(I
);
204 // Reuse the previous value of BBIdx if it lines up. In cases where we
205 // have multiple phi nodes with *lots* of predecessors, this is a speed
206 // win because we don't have to scan the PHI looking for TIBB. This
207 // happens because the BB list of PHI nodes are usually in the same
209 if (PN
->getIncomingBlock(BBIdx
) != TIBB
)
210 BBIdx
= PN
->getBasicBlockIndex(TIBB
);
211 PN
->setIncomingBlock(BBIdx
, NewBB
);
215 // If there are any other edges from TIBB to DestBB, update those to go
216 // through the split block, making those edges non-critical as well (and
217 // reducing the number of phi entries in the DestBB if relevant).
218 if (MergeIdenticalEdges
) {
219 for (unsigned i
= SuccNum
+1, e
= TI
->getNumSuccessors(); i
!= e
; ++i
) {
220 if (TI
->getSuccessor(i
) != DestBB
) continue;
222 // Remove an entry for TIBB from DestBB phi nodes.
223 DestBB
->removePredecessor(TIBB
);
225 // We found another edge to DestBB, go to NewBB instead.
226 TI
->setSuccessor(i
, NewBB
);
232 // If we don't have a pass object, we can't update anything...
233 if (P
== 0) return NewBB
;
235 DominatorTree
*DT
= P
->getAnalysisIfAvailable
<DominatorTree
>();
236 LoopInfo
*LI
= P
->getAnalysisIfAvailable
<LoopInfo
>();
237 ProfileInfo
*PI
= P
->getAnalysisIfAvailable
<ProfileInfo
>();
239 // If we have nothing to update, just return.
240 if (DT
== 0 && LI
== 0 && PI
== 0)
243 // Now update analysis information. Since the only predecessor of NewBB is
244 // the TIBB, TIBB clearly dominates NewBB. TIBB usually doesn't dominate
245 // anything, as there are other successors of DestBB. However, if all other
246 // predecessors of DestBB are already dominated by DestBB (e.g. DestBB is a
247 // loop header) then NewBB dominates DestBB.
248 SmallVector
<BasicBlock
*, 8> OtherPreds
;
250 // If there is a PHI in the block, loop over predecessors with it, which is
251 // faster than iterating pred_begin/end.
252 if (PHINode
*PN
= dyn_cast
<PHINode
>(DestBB
->begin())) {
253 for (unsigned i
= 0, e
= PN
->getNumIncomingValues(); i
!= e
; ++i
)
254 if (PN
->getIncomingBlock(i
) != NewBB
)
255 OtherPreds
.push_back(PN
->getIncomingBlock(i
));
257 for (pred_iterator I
= pred_begin(DestBB
), E
= pred_end(DestBB
);
261 OtherPreds
.push_back(P
);
265 bool NewBBDominatesDestBB
= true;
267 // Should we update DominatorTree information?
269 DomTreeNode
*TINode
= DT
->getNode(TIBB
);
271 // The new block is not the immediate dominator for any other nodes, but
272 // TINode is the immediate dominator for the new node.
274 if (TINode
) { // Don't break unreachable code!
275 DomTreeNode
*NewBBNode
= DT
->addNewBlock(NewBB
, TIBB
);
276 DomTreeNode
*DestBBNode
= 0;
278 // If NewBBDominatesDestBB hasn't been computed yet, do so with DT.
279 if (!OtherPreds
.empty()) {
280 DestBBNode
= DT
->getNode(DestBB
);
281 while (!OtherPreds
.empty() && NewBBDominatesDestBB
) {
282 if (DomTreeNode
*OPNode
= DT
->getNode(OtherPreds
.back()))
283 NewBBDominatesDestBB
= DT
->dominates(DestBBNode
, OPNode
);
284 OtherPreds
.pop_back();
289 // If NewBBDominatesDestBB, then NewBB dominates DestBB, otherwise it
290 // doesn't dominate anything.
291 if (NewBBDominatesDestBB
) {
292 if (!DestBBNode
) DestBBNode
= DT
->getNode(DestBB
);
293 DT
->changeImmediateDominator(DestBBNode
, NewBBNode
);
298 // Update LoopInfo if it is around.
300 if (Loop
*TIL
= LI
->getLoopFor(TIBB
)) {
301 // If one or the other blocks were not in a loop, the new block is not
302 // either, and thus LI doesn't need to be updated.
303 if (Loop
*DestLoop
= LI
->getLoopFor(DestBB
)) {
304 if (TIL
== DestLoop
) {
305 // Both in the same loop, the NewBB joins loop.
306 DestLoop
->addBasicBlockToLoop(NewBB
, LI
->getBase());
307 } else if (TIL
->contains(DestLoop
)) {
308 // Edge from an outer loop to an inner loop. Add to the outer loop.
309 TIL
->addBasicBlockToLoop(NewBB
, LI
->getBase());
310 } else if (DestLoop
->contains(TIL
)) {
311 // Edge from an inner loop to an outer loop. Add to the outer loop.
312 DestLoop
->addBasicBlockToLoop(NewBB
, LI
->getBase());
314 // Edge from two loops with no containment relation. Because these
315 // are natural loops, we know that the destination block must be the
316 // header of its loop (adding a branch into a loop elsewhere would
317 // create an irreducible loop).
318 assert(DestLoop
->getHeader() == DestBB
&&
319 "Should not create irreducible loops!");
320 if (Loop
*P
= DestLoop
->getParentLoop())
321 P
->addBasicBlockToLoop(NewBB
, LI
->getBase());
324 // If TIBB is in a loop and DestBB is outside of that loop, split the
325 // other exit blocks of the loop that also have predecessors outside
326 // the loop, to maintain a LoopSimplify guarantee.
327 if (!TIL
->contains(DestBB
) &&
328 P
->mustPreserveAnalysisID(LoopSimplifyID
)) {
329 assert(!TIL
->contains(NewBB
) &&
330 "Split point for loop exit is contained in loop!");
332 // Update LCSSA form in the newly created exit block.
333 if (P
->mustPreserveAnalysisID(LCSSAID
)) {
334 SmallVector
<BasicBlock
*, 1> OrigPred
;
335 OrigPred
.push_back(TIBB
);
336 CreatePHIsForSplitLoopExit(OrigPred
, NewBB
, DestBB
);
339 // For each unique exit block...
340 SmallVector
<BasicBlock
*, 4> ExitBlocks
;
341 TIL
->getExitBlocks(ExitBlocks
);
342 for (unsigned i
= 0, e
= ExitBlocks
.size(); i
!= e
; ++i
) {
343 // Collect all the preds that are inside the loop, and note
344 // whether there are any preds outside the loop.
345 SmallVector
<BasicBlock
*, 4> Preds
;
346 bool HasPredOutsideOfLoop
= false;
347 BasicBlock
*Exit
= ExitBlocks
[i
];
348 for (pred_iterator I
= pred_begin(Exit
), E
= pred_end(Exit
);
351 if (TIL
->contains(P
))
354 HasPredOutsideOfLoop
= true;
356 // If there are any preds not in the loop, we'll need to split
357 // the edges. The Preds.empty() check is needed because a block
358 // may appear multiple times in the list. We can't use
359 // getUniqueExitBlocks above because that depends on LoopSimplify
360 // form, which we're in the process of restoring!
361 if (!Preds
.empty() && HasPredOutsideOfLoop
) {
362 BasicBlock
*NewExitBB
=
363 SplitBlockPredecessors(Exit
, Preds
.data(), Preds
.size(),
365 if (P
->mustPreserveAnalysisID(LCSSAID
))
366 CreatePHIsForSplitLoopExit(Preds
, NewExitBB
, Exit
);
370 // LCSSA form was updated above for the case where LoopSimplify is
371 // available, which means that all predecessors of loop exit blocks
372 // are within the loop. Without LoopSimplify form, it would be
373 // necessary to insert a new phi.
374 assert((!P
->mustPreserveAnalysisID(LCSSAID
) ||
375 P
->mustPreserveAnalysisID(LoopSimplifyID
)) &&
376 "SplitCriticalEdge doesn't know how to update LCCSA form "
377 "without LoopSimplify!");
381 // Update ProfileInfo if it is around.
383 PI
->splitEdge(TIBB
, DestBB
, NewBB
, MergeIdenticalEdges
);