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