make this more efficient. Scan up to 16 nodes, not the whole list.
[oota-llvm.git] / lib / VMCore / BasicBlock.cpp
1 //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
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 // This file implements the BasicBlock class for the VMCore library.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/BasicBlock.h"
15 #include "llvm/Constant.h"
16 #include "llvm/Instructions.h"
17 #include "llvm/Type.h"
18 #include "llvm/Support/CFG.h"
19 #include "llvm/SymbolTable.h"
20 #include "llvm/Support/LeakDetector.h"
21 #include "SymbolTableListTraitsImpl.h"
22 #include <algorithm>
23 using namespace llvm;
24
25 namespace {
26   /// DummyInst - An instance of this class is used to mark the end of the
27   /// instruction list.  This is not a real instruction.
28   struct DummyInst : public Instruction {
29     DummyInst() : Instruction(Type::VoidTy, OtherOpsEnd, 0, 0) {
30       // This should not be garbage monitored.
31       LeakDetector::removeGarbageObject(this);
32     }
33
34     virtual Instruction *clone() const {
35       assert(0 && "Cannot clone EOL");abort();
36       return 0;
37     }
38     virtual const char *getOpcodeName() const { return "*end-of-list-inst*"; }
39
40     // Methods for support type inquiry through isa, cast, and dyn_cast...
41     static inline bool classof(const DummyInst *) { return true; }
42     static inline bool classof(const Instruction *I) {
43       return I->getOpcode() == OtherOpsEnd;
44     }
45     static inline bool classof(const Value *V) {
46       return isa<Instruction>(V) && classof(cast<Instruction>(V));
47     }
48   };
49 }
50
51 Instruction *ilist_traits<Instruction>::createSentinel() {
52   return new DummyInst();
53 }
54 iplist<Instruction> &ilist_traits<Instruction>::getList(BasicBlock *BB) {
55   return BB->getInstList();
56 }
57
58 // Explicit instantiation of SymbolTableListTraits since some of the methods
59 // are not in the public header file...
60 template class SymbolTableListTraits<Instruction, BasicBlock, Function>;
61
62
63 BasicBlock::BasicBlock(const std::string &Name, Function *Parent,
64                        BasicBlock *InsertBefore)
65   : Value(Type::LabelTy, Value::BasicBlockVal, Name) {
66   // Initialize the instlist...
67   InstList.setItemParent(this);
68
69   // Make sure that we get added to a function
70   LeakDetector::addGarbageObject(this);
71
72   if (InsertBefore) {
73     assert(Parent &&
74            "Cannot insert block before another block with no function!");
75     Parent->getBasicBlockList().insert(InsertBefore, this);
76   } else if (Parent) {
77     Parent->getBasicBlockList().push_back(this);
78   }
79 }
80
81
82 BasicBlock::~BasicBlock() {
83   assert(getParent() == 0 && "BasicBlock still linked into the program!");
84   dropAllReferences();
85   InstList.clear();
86 }
87
88 void BasicBlock::setParent(Function *parent) {
89   if (getParent())
90     LeakDetector::addGarbageObject(this);
91
92   InstList.setParent(parent);
93
94   if (getParent())
95     LeakDetector::removeGarbageObject(this);
96 }
97
98 // Specialize setName to take care of symbol table majik
99 void BasicBlock::setName(const std::string &name, SymbolTable *ST) {
100   Function *P;
101   assert((ST == 0 || (!getParent() || ST == &getParent()->getSymbolTable())) &&
102          "Invalid symtab argument!");
103   if ((P = getParent()) && hasName()) P->getSymbolTable().remove(this);
104   Value::setName(name);
105   if (P && hasName()) P->getSymbolTable().insert(this);
106 }
107
108 void BasicBlock::removeFromParent() {
109   getParent()->getBasicBlockList().remove(this);
110 }
111
112 void BasicBlock::eraseFromParent() {
113   getParent()->getBasicBlockList().erase(this);
114 }
115
116
117 TerminatorInst *BasicBlock::getTerminator() {
118   if (InstList.empty()) return 0;
119   return dyn_cast<TerminatorInst>(&InstList.back());
120 }
121
122 const TerminatorInst *const BasicBlock::getTerminator() const {
123   if (InstList.empty()) return 0;
124   return dyn_cast<TerminatorInst>(&InstList.back());
125 }
126
127 void BasicBlock::dropAllReferences() {
128   for(iterator I = begin(), E = end(); I != E; ++I)
129     I->dropAllReferences();
130 }
131
132 // removePredecessor - This method is used to notify a BasicBlock that the
133 // specified Predecessor of the block is no longer able to reach it.  This is
134 // actually not used to update the Predecessor list, but is actually used to 
135 // update the PHI nodes that reside in the block.  Note that this should be
136 // called while the predecessor still refers to this block.
137 //
138 void BasicBlock::removePredecessor(BasicBlock *Pred) {
139   assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
140           find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
141          "removePredecessor: BB is not a predecessor!");
142
143   if (InstList.empty()) return;
144   PHINode *APN = dyn_cast<PHINode>(&front());
145   if (!APN) return;   // Quick exit.
146
147   // If there are exactly two predecessors, then we want to nuke the PHI nodes
148   // altogether.  However, we cannot do this, if this in this case:
149   //
150   //  Loop:
151   //    %x = phi [X, Loop]
152   //    %x2 = add %x, 1         ;; This would become %x2 = add %x2, 1
153   //    br Loop                 ;; %x2 does not dominate all uses
154   //
155   // This is because the PHI node input is actually taken from the predecessor
156   // basic block.  The only case this can happen is with a self loop, so we 
157   // check for this case explicitly now.
158   // 
159   unsigned max_idx = APN->getNumIncomingValues();
160   assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
161   if (max_idx == 2) {
162     BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
163
164     // Disable PHI elimination!
165     if (this == Other) max_idx = 3;
166   }
167
168   if (max_idx <= 2) {                // <= Two predecessors BEFORE I remove one?
169     // Yup, loop through and nuke the PHI nodes
170     while (PHINode *PN = dyn_cast<PHINode>(&front())) {
171       PN->removeIncomingValue(Pred); // Remove the predecessor first...
172
173       // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
174       if (max_idx == 2) {
175         if (PN->getOperand(0) != PN)
176           PN->replaceAllUsesWith(PN->getOperand(0));
177         else
178           // We are left with an infinite loop with no entries: kill the PHI.
179           PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
180         getInstList().pop_front();    // Remove the PHI node
181       }
182
183       // If the PHI node already only had one entry, it got deleted by
184       // removeIncomingValue.
185     }
186   } else {
187     // Okay, now we know that we need to remove predecessor #pred_idx from all
188     // PHI nodes.  Iterate over each PHI node fixing them up
189     PHINode *PN;
190     for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ++II)
191       PN->removeIncomingValue(Pred);
192   }
193 }
194
195
196 // splitBasicBlock - This splits a basic block into two at the specified
197 // instruction.  Note that all instructions BEFORE the specified iterator stay
198 // as part of the original basic block, an unconditional branch is added to 
199 // the new BB, and the rest of the instructions in the BB are moved to the new
200 // BB, including the old terminator.  This invalidates the iterator.
201 //
202 // Note that this only works on well formed basic blocks (must have a 
203 // terminator), and 'I' must not be the end of instruction list (which would
204 // cause a degenerate basic block to be formed, having a terminator inside of
205 // the basic block). 
206 //
207 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const std::string &BBName) {
208   assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
209   assert(I != InstList.end() && 
210          "Trying to get me to create degenerate basic block!");
211
212   BasicBlock *New = new BasicBlock(BBName, getParent(), getNext());
213
214   // Move all of the specified instructions from the original basic block into
215   // the new basic block.
216   New->getInstList().splice(New->end(), this->getInstList(), I, end());
217
218   // Add a branch instruction to the newly formed basic block.
219   new BranchInst(New, this);
220
221   // Now we must loop through all of the successors of the New block (which
222   // _were_ the successors of the 'this' block), and update any PHI nodes in
223   // successors.  If there were PHI nodes in the successors, then they need to
224   // know that incoming branches will be from New, not from Old.
225   //
226   for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
227     // Loop over any phi nodes in the basic block, updating the BB field of
228     // incoming values...
229     BasicBlock *Successor = *I;
230     PHINode *PN;
231     for (BasicBlock::iterator II = Successor->begin();
232          (PN = dyn_cast<PHINode>(II)); ++II) {
233       int IDX = PN->getBasicBlockIndex(this);
234       while (IDX != -1) {
235         PN->setIncomingBlock((unsigned)IDX, New);
236         IDX = PN->getBasicBlockIndex(this);
237       }
238     }
239   }
240   return New;
241 }