eliminate RegisterOpt. It does the same thing as RegisterPass.
[oota-llvm.git] / lib / Transforms / Utils / BreakCriticalEdges.cpp
1 //===- BreakCriticalEdges.cpp - Critical Edge Elimination Pass ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
14 // forward dominator (set, immediate dominators, tree, and frontier)
15 // information.
16 //
17 //===----------------------------------------------------------------------===//
18
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/Function.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Type.h"
26 #include "llvm/Support/CFG.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/ADT/Statistic.h"
29 using namespace llvm;
30
31 namespace {
32   Statistic<> NumBroken("break-crit-edges", "Number of blocks inserted");
33
34   struct VISIBILITY_HIDDEN BreakCriticalEdges : public FunctionPass {
35     virtual bool runOnFunction(Function &F);
36
37     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
38       AU.addPreserved<ETForest>();
39       AU.addPreserved<DominatorSet>();
40       AU.addPreserved<ImmediateDominators>();
41       AU.addPreserved<DominatorTree>();
42       AU.addPreserved<DominanceFrontier>();
43       AU.addPreserved<LoopInfo>();
44
45       // No loop canonicalization guarantees are broken by this pass.
46       AU.addPreservedID(LoopSimplifyID);
47     }
48   };
49
50   RegisterPass<BreakCriticalEdges> X("break-crit-edges",
51                                     "Break critical edges in CFG");
52 }
53
54 // Publically exposed interface to pass...
55 const PassInfo *llvm::BreakCriticalEdgesID = X.getPassInfo();
56 FunctionPass *llvm::createBreakCriticalEdgesPass() {
57   return new BreakCriticalEdges();
58 }
59
60 // runOnFunction - Loop over all of the edges in the CFG, breaking critical
61 // edges as they are found.
62 //
63 bool BreakCriticalEdges::runOnFunction(Function &F) {
64   bool Changed = false;
65   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
66     TerminatorInst *TI = I->getTerminator();
67     if (TI->getNumSuccessors() > 1)
68       for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
69         if (SplitCriticalEdge(TI, i, this)) {
70           ++NumBroken;
71           Changed = true;
72         }
73   }
74
75   return Changed;
76 }
77
78 //===----------------------------------------------------------------------===//
79 //    Implementation of the external critical edge manipulation functions
80 //===----------------------------------------------------------------------===//
81
82 // isCriticalEdge - Return true if the specified edge is a critical edge.
83 // Critical edges are edges from a block with multiple successors to a block
84 // with multiple predecessors.
85 //
86 bool llvm::isCriticalEdge(const TerminatorInst *TI, unsigned SuccNum) {
87   assert(SuccNum < TI->getNumSuccessors() && "Illegal edge specification!");
88   if (TI->getNumSuccessors() == 1) return false;
89
90   const BasicBlock *Dest = TI->getSuccessor(SuccNum);
91   pred_const_iterator I = pred_begin(Dest), E = pred_end(Dest);
92
93   // If there is more than one predecessor, this is a critical edge...
94   assert(I != E && "No preds, but we have an edge to the block?");
95   ++I;        // Skip one edge due to the incoming arc from TI.
96   return I != E;
97 }
98
99 // SplitCriticalEdge - If this edge is a critical edge, insert a new node to
100 // split the critical edge.  This will update DominatorSet, ImmediateDominator,
101 // DominatorTree, and DominatorFrontier information if it is available, thus
102 // calling this pass will not invalidate either of them.  This returns true if
103 // the edge was split, false otherwise.
104 //
105 bool llvm::SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
106   if (!isCriticalEdge(TI, SuccNum)) return false;
107   BasicBlock *TIBB = TI->getParent();
108   BasicBlock *DestBB = TI->getSuccessor(SuccNum);
109
110   // Create a new basic block, linking it into the CFG.
111   BasicBlock *NewBB = new BasicBlock(TIBB->getName() + "." +
112                                      DestBB->getName() + "_crit_edge");
113   // Create our unconditional branch...
114   new BranchInst(DestBB, NewBB);
115
116   // Branch to the new block, breaking the edge...
117   TI->setSuccessor(SuccNum, NewBB);
118
119   // Insert the block into the function... right after the block TI lives in.
120   Function &F = *TIBB->getParent();
121   F.getBasicBlockList().insert(TIBB->getNext(), NewBB);
122
123   // If there are any PHI nodes in DestBB, we need to update them so that they
124   // merge incoming values from NewBB instead of from TIBB.
125   //
126   for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
127     PHINode *PN = cast<PHINode>(I);
128     // We no longer enter through TIBB, now we come in through NewBB.  Revector
129     // exactly one entry in the PHI node that used to come from TIBB to come
130     // from NewBB.
131     int BBIdx = PN->getBasicBlockIndex(TIBB);
132     PN->setIncomingBlock(BBIdx, NewBB);
133   }
134
135   // If we don't have a pass object, we can't update anything...
136   if (P == 0) return true;
137
138   // Now update analysis information.  These are the analyses that we are
139   // currently capable of updating...
140   //
141
142   // Should we update DominatorSet information?
143   if (DominatorSet *DS = P->getAnalysisToUpdate<DominatorSet>()) {
144     // The blocks that dominate the new one are the blocks that dominate TIBB
145     // plus the new block itself.
146     DominatorSet::DomSetType DomSet = DS->getDominators(TIBB);
147     DomSet.insert(NewBB);  // A block always dominates itself.
148     DS->addBasicBlock(NewBB, DomSet);
149   }
150
151   // Should we update ImmediateDominator information?
152   if (ImmediateDominators *ID = P->getAnalysisToUpdate<ImmediateDominators>()) {
153     // TIBB is the new immediate dominator for NewBB.  NewBB doesn't dominate
154     // anything.
155     ID->addNewBlock(NewBB, TIBB);
156   }
157
158   // Update the forest?
159   if (ETForest *EF = P->getAnalysisToUpdate<ETForest>())
160     EF->addNewBlock(NewBB, TIBB);
161
162   // Should we update DominatorTree information?
163   if (DominatorTree *DT = P->getAnalysisToUpdate<DominatorTree>()) {
164     DominatorTree::Node *TINode = DT->getNode(TIBB);
165
166     // The new block is not the immediate dominator for any other nodes, but
167     // TINode is the immediate dominator for the new node.
168     //
169     if (TINode)        // Don't break unreachable code!
170       DT->createNewNode(NewBB, TINode);
171   }
172
173   // Should we update DominanceFrontier information?
174   if (DominanceFrontier *DF = P->getAnalysisToUpdate<DominanceFrontier>()) {
175     // Since the new block is dominated by its only predecessor TIBB,
176     // it cannot be in any block's dominance frontier.  Its dominance
177     // frontier is {DestBB}.
178     DominanceFrontier::DomSetType NewDFSet;
179     NewDFSet.insert(DestBB);
180     DF->addBasicBlock(NewBB, NewDFSet);
181   }
182   
183   // Update LoopInfo if it is around.
184   if (LoopInfo *LI = P->getAnalysisToUpdate<LoopInfo>()) {
185     // If one or the other blocks were not in a loop, the new block is not
186     // either, and thus LI doesn't need to be updated.
187     if (Loop *TIL = LI->getLoopFor(TIBB))
188       if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
189         if (TIL == DestLoop) {
190           // Both in the same loop, the NewBB joins loop.
191           DestLoop->addBasicBlockToLoop(NewBB, *LI);
192         } else if (TIL->contains(DestLoop->getHeader())) {
193           // Edge from an outer loop to an inner loop.  Add to the outer lopo.
194           TIL->addBasicBlockToLoop(NewBB, *LI);
195         } else if (DestLoop->contains(TIL->getHeader())) {
196           // Edge from an inner loop to an outer loop.  Add to the outer lopo.
197           DestLoop->addBasicBlockToLoop(NewBB, *LI);
198         } else {
199           // Edge from two loops with no containment relation.  Because these
200           // are natural loops, we know that the destination block must be the
201           // header of its loop (adding a branch into a loop elsewhere would
202           // create an irreducible loop).
203           assert(DestLoop->getHeader() == DestBB &&
204                  "Should not create irreducible loops!");
205           if (Loop *P = DestLoop->getParentLoop())
206             P->addBasicBlockToLoop(NewBB, *LI);
207         }
208       }
209     
210   }
211   return true;
212 }