Put all LLVM code into the llvm namespace, as per bug 109.
[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/Function.h"
23 #include "llvm/iTerminators.h"
24 #include "llvm/iPHINode.h"
25 #include "llvm/Support/CFG.h"
26 #include "Support/Statistic.h"
27
28 namespace llvm {
29
30 namespace {
31   Statistic<> NumBroken("break-crit-edges", "Number of blocks inserted");
32
33   struct BreakCriticalEdges : public FunctionPass {
34     virtual bool runOnFunction(Function &F);
35     
36     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
37       AU.addPreserved<DominatorSet>();
38       AU.addPreserved<ImmediateDominators>();
39       AU.addPreserved<DominatorTree>();
40       AU.addPreserved<DominanceFrontier>();
41
42       // No loop canonicalization guarantees are broken by this pass.
43       AU.addPreservedID(LoopSimplifyID);
44     }
45   };
46
47   RegisterOpt<BreakCriticalEdges> X("break-crit-edges",
48                                     "Break critical edges in CFG");
49 }
50
51 // Publically exposed interface to pass...
52 const PassInfo *BreakCriticalEdgesID = X.getPassInfo();
53 Pass *createBreakCriticalEdgesPass() { return new BreakCriticalEdges(); }
54
55 // runOnFunction - Loop over all of the edges in the CFG, breaking critical
56 // edges as they are found.
57 //
58 bool BreakCriticalEdges::runOnFunction(Function &F) {
59   bool Changed = false;
60   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
61     TerminatorInst *TI = I->getTerminator();
62     if (TI->getNumSuccessors() > 1)
63       for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
64         if (SplitCriticalEdge(TI, i, this)) {
65           ++NumBroken;
66           Changed = true;
67         }
68   }
69
70   return Changed;
71 }
72
73 //===----------------------------------------------------------------------===//
74 //    Implementation of the external critical edge manipulation functions
75 //===----------------------------------------------------------------------===//
76
77 // isCriticalEdge - Return true if the specified edge is a critical edge.
78 // Critical edges are edges from a block with multiple successors to a block
79 // with multiple predecessors.
80 //
81 bool isCriticalEdge(const TerminatorInst *TI, unsigned SuccNum) {
82   assert(SuccNum < TI->getNumSuccessors() && "Illegal edge specification!");
83   if (TI->getNumSuccessors() == 1) return false;
84
85   const BasicBlock *Dest = TI->getSuccessor(SuccNum);
86   pred_const_iterator I = pred_begin(Dest), E = pred_end(Dest);
87
88   // If there is more than one predecessor, this is a critical edge...
89   assert(I != E && "No preds, but we have an edge to the block?");
90   ++I;        // Skip one edge due to the incoming arc from TI.
91   return I != E;
92 }
93
94 // SplitCriticalEdge - If this edge is a critical edge, insert a new node to
95 // split the critical edge.  This will update DominatorSet, ImmediateDominator,
96 // DominatorTree, and DominatorFrontier information if it is available, thus
97 // calling this pass will not invalidate either of them.  This returns true if
98 // the edge was split, false otherwise.
99 //
100 bool SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
101   if (!isCriticalEdge(TI, SuccNum)) return false;
102   BasicBlock *TIBB = TI->getParent();
103   BasicBlock *DestBB = TI->getSuccessor(SuccNum);
104
105   // Create a new basic block, linking it into the CFG.
106   BasicBlock *NewBB = new BasicBlock(TIBB->getName() + "." +
107                                      DestBB->getName() + "_crit_edge");
108   // Create our unconditional branch...
109   BranchInst *BI = new BranchInst(DestBB);
110   NewBB->getInstList().push_back(BI);
111   
112   // Branch to the new block, breaking the edge...
113   TI->setSuccessor(SuccNum, NewBB);
114
115   // Insert the block into the function... right after the block TI lives in.
116   Function &F = *TIBB->getParent();
117   F.getBasicBlockList().insert(TIBB->getNext(), NewBB);
118
119   // If there are any PHI nodes in DestBB, we need to update them so that they
120   // merge incoming values from NewBB instead of from TIBB.
121   //
122   for (BasicBlock::iterator I = DestBB->begin();
123        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
124     // We no longer enter through TIBB, now we come in through NewBB.
125     PN->replaceUsesOfWith(TIBB, NewBB);
126   }
127
128   // If we don't have a pass object, we can't update anything...
129   if (P == 0) return true;
130
131   // Now update analysis information.  These are the analyses that we are
132   // currently capable of updating...
133   //
134
135   // Should we update DominatorSet information?
136   if (DominatorSet *DS = P->getAnalysisToUpdate<DominatorSet>()) {
137     // The blocks that dominate the new one are the blocks that dominate TIBB
138     // plus the new block itself.
139     DominatorSet::DomSetType DomSet = DS->getDominators(TIBB);
140     DomSet.insert(NewBB);  // A block always dominates itself.
141     DS->addBasicBlock(NewBB, DomSet);
142   }
143
144   // Should we update ImmediateDominator information?
145   if (ImmediateDominators *ID = P->getAnalysisToUpdate<ImmediateDominators>()) {
146     // TIBB is the new immediate dominator for NewBB.  NewBB doesn't dominate
147     // anything.
148     ID->addNewBlock(NewBB, TIBB);
149   }
150   
151   // Should we update DominatorTree information?
152   if (DominatorTree *DT = P->getAnalysisToUpdate<DominatorTree>()) {
153     DominatorTree::Node *TINode = DT->getNode(TIBB);
154     
155     // The new block is not the immediate dominator for any other nodes, but
156     // TINode is the immediate dominator for the new node.
157     //
158     if (TINode)        // Don't break unreachable code!
159       DT->createNewNode(NewBB, TINode);
160   }
161
162   // Should we update DominanceFrontier information?
163   if (DominanceFrontier *DF = P->getAnalysisToUpdate<DominanceFrontier>()) {
164     // Since the new block is dominated by its only predecessor TIBB,
165     // it cannot be in any block's dominance frontier.  Its dominance
166     // frontier is {DestBB}.
167     DominanceFrontier::DomSetType NewDFSet;
168     NewDFSet.insert(DestBB);
169     DF->addBasicBlock(NewBB, NewDFSet);
170   }
171   return true;
172 }
173
174 } // End llvm namespace