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