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