f68223155dcdd06ae2ec7aacda3e387bacc84f75
[oota-llvm.git] / lib / VMCore / BasicBlock.cpp
1 //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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/Constants.h"
16 #include "llvm/Instructions.h"
17 #include "llvm/Type.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/Support/CFG.h"
20 #include "llvm/Support/LeakDetector.h"
21 #include "llvm/Support/Compiler.h"
22 #include "SymbolTableListTraitsImpl.h"
23 #include <algorithm>
24 using namespace llvm;
25
26 inline ValueSymbolTable *
27 ilist_traits<Instruction>::getSymTab(BasicBlock *BB) {
28   if (BB)
29     if (Function *F = BB->getParent())
30       return &F->getValueSymbolTable();
31   return 0;
32 }
33
34 // Explicit instantiation of SymbolTableListTraits since some of the methods
35 // are not in the public header file...
36 template class SymbolTableListTraits<Instruction, BasicBlock>;
37
38
39 BasicBlock::BasicBlock(const std::string &Name, Function *NewParent,
40                        BasicBlock *InsertBefore)
41   : Value(Type::LabelTy, Value::BasicBlockVal), Parent(0) {
42
43   // Make sure that we get added to a function
44   LeakDetector::addGarbageObject(this);
45
46   if (InsertBefore) {
47     assert(NewParent &&
48            "Cannot insert block before another block with no function!");
49     NewParent->getBasicBlockList().insert(InsertBefore, this);
50   } else if (NewParent) {
51     NewParent->getBasicBlockList().push_back(this);
52   }
53   
54   setName(Name);
55 }
56
57
58 BasicBlock::~BasicBlock() {
59   assert(getParent() == 0 && "BasicBlock still linked into the program!");
60   dropAllReferences();
61   InstList.clear();
62 }
63
64 void BasicBlock::setParent(Function *parent) {
65   if (getParent())
66     LeakDetector::addGarbageObject(this);
67
68   // Set Parent=parent, updating instruction symtab entries as appropriate.
69   InstList.setSymTabObject(&Parent, parent);
70
71   if (getParent())
72     LeakDetector::removeGarbageObject(this);
73 }
74
75 void BasicBlock::removeFromParent() {
76   getParent()->getBasicBlockList().remove(this);
77 }
78
79 void BasicBlock::eraseFromParent() {
80   getParent()->getBasicBlockList().erase(this);
81 }
82
83 /// moveBefore - Unlink this basic block from its current function and
84 /// insert it into the function that MovePos lives in, right before MovePos.
85 void BasicBlock::moveBefore(BasicBlock *MovePos) {
86   MovePos->getParent()->getBasicBlockList().splice(MovePos,
87                        getParent()->getBasicBlockList(), this);
88 }
89
90 /// moveAfter - Unlink this basic block from its current function and
91 /// insert it into the function that MovePos lives in, right after MovePos.
92 void BasicBlock::moveAfter(BasicBlock *MovePos) {
93   Function::iterator I = MovePos;
94   MovePos->getParent()->getBasicBlockList().splice(++I,
95                                        getParent()->getBasicBlockList(), this);
96 }
97
98
99 TerminatorInst *BasicBlock::getTerminator() {
100   if (InstList.empty()) return 0;
101   return dyn_cast<TerminatorInst>(&InstList.back());
102 }
103
104 const TerminatorInst *BasicBlock::getTerminator() const {
105   if (InstList.empty()) return 0;
106   return dyn_cast<TerminatorInst>(&InstList.back());
107 }
108
109 Instruction* BasicBlock::getFirstNonPHI() {
110   BasicBlock::iterator i = begin();
111   // All valid basic blocks should have a terminator,
112   // which is not a PHINode. If we have an invalid basic
113   // block we'll get an assertion failure when dereferencing
114   // a past-the-end iterator.
115   while (isa<PHINode>(i)) ++i;
116   return &*i;
117 }
118
119 void BasicBlock::dropAllReferences() {
120   for(iterator I = begin(), E = end(); I != E; ++I)
121     I->dropAllReferences();
122 }
123
124 /// getSinglePredecessor - If this basic block has a single predecessor block,
125 /// return the block, otherwise return a null pointer.
126 BasicBlock *BasicBlock::getSinglePredecessor() {
127   pred_iterator PI = pred_begin(this), E = pred_end(this);
128   if (PI == E) return 0;         // No preds.
129   BasicBlock *ThePred = *PI;
130   ++PI;
131   return (PI == E) ? ThePred : 0 /*multiple preds*/;
132 }
133
134 /// getUniquePredecessor - If this basic block has a unique predecessor block,
135 /// return the block, otherwise return a null pointer.
136 /// Note that unique predecessor doesn't mean single edge, there can be 
137 /// multiple edges from the unique predecessor to this block (for example 
138 /// a switch statement with multiple cases having the same destination).
139 BasicBlock *BasicBlock::getUniquePredecessor() {
140   pred_iterator PI = pred_begin(this), E = pred_end(this);
141   if (PI == E) return 0; // No preds.
142   BasicBlock *PredBB = *PI;
143   ++PI;
144   for (;PI != E; ++PI) {
145     if (*PI != PredBB)
146       return 0;
147     // The same predecessor appears multiple times in the predecessor list.
148     // This is OK.
149   }
150   return PredBB;
151 }
152
153 /// removePredecessor - This method is used to notify a BasicBlock that the
154 /// specified Predecessor of the block is no longer able to reach it.  This is
155 /// actually not used to update the Predecessor list, but is actually used to
156 /// update the PHI nodes that reside in the block.  Note that this should be
157 /// called while the predecessor still refers to this block.
158 ///
159 void BasicBlock::removePredecessor(BasicBlock *Pred,
160                                    bool DontDeleteUselessPHIs) {
161   assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
162           find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
163          "removePredecessor: BB is not a predecessor!");
164
165   if (InstList.empty()) return;
166   PHINode *APN = dyn_cast<PHINode>(&front());
167   if (!APN) return;   // Quick exit.
168
169   // If there are exactly two predecessors, then we want to nuke the PHI nodes
170   // altogether.  However, we cannot do this, if this in this case:
171   //
172   //  Loop:
173   //    %x = phi [X, Loop]
174   //    %x2 = add %x, 1         ;; This would become %x2 = add %x2, 1
175   //    br Loop                 ;; %x2 does not dominate all uses
176   //
177   // This is because the PHI node input is actually taken from the predecessor
178   // basic block.  The only case this can happen is with a self loop, so we
179   // check for this case explicitly now.
180   //
181   unsigned max_idx = APN->getNumIncomingValues();
182   assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
183   if (max_idx == 2) {
184     BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
185
186     // Disable PHI elimination!
187     if (this == Other) max_idx = 3;
188   }
189
190   // <= Two predecessors BEFORE I remove one?
191   if (max_idx <= 2 && !DontDeleteUselessPHIs) {
192     // Yup, loop through and nuke the PHI nodes
193     while (PHINode *PN = dyn_cast<PHINode>(&front())) {
194       // Remove the predecessor first.
195       PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
196
197       // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
198       if (max_idx == 2) {
199         if (PN->getOperand(0) != PN)
200           PN->replaceAllUsesWith(PN->getOperand(0));
201         else
202           // We are left with an infinite loop with no entries: kill the PHI.
203           PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
204         getInstList().pop_front();    // Remove the PHI node
205       }
206
207       // If the PHI node already only had one entry, it got deleted by
208       // removeIncomingValue.
209     }
210   } else {
211     // Okay, now we know that we need to remove predecessor #pred_idx from all
212     // PHI nodes.  Iterate over each PHI node fixing them up
213     PHINode *PN;
214     for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
215       ++II;
216       PN->removeIncomingValue(Pred, false);
217       // If all incoming values to the Phi are the same, we can replace the Phi
218       // with that value.
219       Value* PNV = 0;
220       if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue())) {
221         PN->replaceAllUsesWith(PNV);
222         PN->eraseFromParent();
223       }
224     }
225   }
226 }
227
228
229 /// splitBasicBlock - This splits a basic block into two at the specified
230 /// instruction.  Note that all instructions BEFORE the specified iterator stay
231 /// as part of the original basic block, an unconditional branch is added to
232 /// the new BB, and the rest of the instructions in the BB are moved to the new
233 /// BB, including the old terminator.  This invalidates the iterator.
234 ///
235 /// Note that this only works on well formed basic blocks (must have a
236 /// terminator), and 'I' must not be the end of instruction list (which would
237 /// cause a degenerate basic block to be formed, having a terminator inside of
238 /// the basic block).
239 ///
240 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const std::string &BBName) {
241   assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
242   assert(I != InstList.end() &&
243          "Trying to get me to create degenerate basic block!");
244
245   BasicBlock *InsertBefore = next(Function::iterator(this))
246                                .getNodePtrUnchecked();
247   BasicBlock *New = BasicBlock::Create(BBName, getParent(), InsertBefore);
248
249   // Move all of the specified instructions from the original basic block into
250   // the new basic block.
251   New->getInstList().splice(New->end(), this->getInstList(), I, end());
252
253   // Add a branch instruction to the newly formed basic block.
254   BranchInst::Create(New, this);
255
256   // Now we must loop through all of the successors of the New block (which
257   // _were_ the successors of the 'this' block), and update any PHI nodes in
258   // successors.  If there were PHI nodes in the successors, then they need to
259   // know that incoming branches will be from New, not from Old.
260   //
261   for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
262     // Loop over any phi nodes in the basic block, updating the BB field of
263     // incoming values...
264     BasicBlock *Successor = *I;
265     PHINode *PN;
266     for (BasicBlock::iterator II = Successor->begin();
267          (PN = dyn_cast<PHINode>(II)); ++II) {
268       int IDX = PN->getBasicBlockIndex(this);
269       while (IDX != -1) {
270         PN->setIncomingBlock((unsigned)IDX, New);
271         IDX = PN->getBasicBlockIndex(this);
272       }
273     }
274   }
275   return New;
276 }