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