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