1 //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the BasicBlock class for the VMCore library.
12 //===----------------------------------------------------------------------===//
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"
25 inline ValueSymbolTable *
26 ilist_traits<Instruction>::getSymTab(BasicBlock *BB) {
28 if (Function *F = BB->getParent())
29 return &F->getValueSymbolTable();
33 DummyInst::DummyInst() : Instruction(Type::VoidTy, OtherOpsEnd, 0, 0) {
34 // This should not be garbage monitored.
35 LeakDetector::removeGarbageObject(this);
38 Instruction *ilist_traits<Instruction>::createSentinel() {
39 return new DummyInst();
41 iplist<Instruction> &ilist_traits<Instruction>::getList(BasicBlock *BB) {
42 return BB->getInstList();
45 // Explicit instantiation of SymbolTableListTraits since some of the methods
46 // are not in the public header file...
47 template class SymbolTableListTraits<Instruction, BasicBlock>;
50 BasicBlock::BasicBlock(const std::string &Name, Function *NewParent,
51 BasicBlock *InsertBefore)
52 : Value(Type::LabelTy, Value::BasicBlockVal), Parent(0) {
54 // Make sure that we get added to a function
55 LeakDetector::addGarbageObject(this);
59 "Cannot insert block before another block with no function!");
60 NewParent->getBasicBlockList().insert(InsertBefore, this);
61 } else if (NewParent) {
62 NewParent->getBasicBlockList().push_back(this);
69 void BasicBlock::destroyThis(BasicBlock*v)
71 assert(v->getParent() == 0 && "BasicBlock still linked into the program!");
72 v->dropAllReferences();
74 Value::destroyThis(v);
77 void BasicBlock::setParent(Function *parent) {
79 LeakDetector::addGarbageObject(this);
81 // Set Parent=parent, updating instruction symtab entries as appropriate.
82 InstList.setSymTabObject(&Parent, parent);
85 LeakDetector::removeGarbageObject(this);
88 void BasicBlock::removeFromParent() {
89 getParent()->getBasicBlockList().remove(this);
92 void BasicBlock::eraseFromParent() {
93 getParent()->getBasicBlockList().erase(this);
96 /// moveBefore - Unlink this basic block from its current function and
97 /// insert it into the function that MovePos lives in, right before MovePos.
98 void BasicBlock::moveBefore(BasicBlock *MovePos) {
99 MovePos->getParent()->getBasicBlockList().splice(MovePos,
100 getParent()->getBasicBlockList(), this);
103 /// moveAfter - Unlink this basic block from its current function and
104 /// insert it into the function that MovePos lives in, right after MovePos.
105 void BasicBlock::moveAfter(BasicBlock *MovePos) {
106 Function::iterator I = MovePos;
107 MovePos->getParent()->getBasicBlockList().splice(++I,
108 getParent()->getBasicBlockList(), this);
112 TerminatorInst *BasicBlock::getTerminator() {
113 if (InstList.empty()) return 0;
114 return dyn_cast<TerminatorInst>(&InstList.back());
117 const TerminatorInst *BasicBlock::getTerminator() const {
118 if (InstList.empty()) return 0;
119 return dyn_cast<TerminatorInst>(&InstList.back());
122 Instruction* BasicBlock::getFirstNonPHI()
124 BasicBlock::iterator i = begin();
125 // All valid basic blocks should have a terminator,
126 // which is not a PHINode. If we have invalid basic
127 // block we'll get assert when dereferencing past-the-end
129 while (isa<PHINode>(i)) ++i;
133 void BasicBlock::dropAllReferences() {
134 for(iterator I = begin(), E = end(); I != E; ++I)
135 I->dropAllReferences();
138 /// getSinglePredecessor - If this basic block has a single predecessor block,
139 /// return the block, otherwise return a null pointer.
140 BasicBlock *BasicBlock::getSinglePredecessor() {
141 pred_iterator PI = pred_begin(this), E = pred_end(this);
142 if (PI == E) return 0; // No preds.
143 BasicBlock *ThePred = *PI;
145 return (PI == E) ? ThePred : 0 /*multiple preds*/;
148 /// removePredecessor - This method is used to notify a BasicBlock that the
149 /// specified Predecessor of the block is no longer able to reach it. This is
150 /// actually not used to update the Predecessor list, but is actually used to
151 /// update the PHI nodes that reside in the block. Note that this should be
152 /// called while the predecessor still refers to this block.
154 void BasicBlock::removePredecessor(BasicBlock *Pred,
155 bool DontDeleteUselessPHIs) {
156 assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
157 find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
158 "removePredecessor: BB is not a predecessor!");
160 if (InstList.empty()) return;
161 PHINode *APN = dyn_cast<PHINode>(&front());
162 if (!APN) return; // Quick exit.
164 // If there are exactly two predecessors, then we want to nuke the PHI nodes
165 // altogether. However, we cannot do this, if this in this case:
168 // %x = phi [X, Loop]
169 // %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1
170 // br Loop ;; %x2 does not dominate all uses
172 // This is because the PHI node input is actually taken from the predecessor
173 // basic block. The only case this can happen is with a self loop, so we
174 // check for this case explicitly now.
176 unsigned max_idx = APN->getNumIncomingValues();
177 assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
179 BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
181 // Disable PHI elimination!
182 if (this == Other) max_idx = 3;
185 // <= Two predecessors BEFORE I remove one?
186 if (max_idx <= 2 && !DontDeleteUselessPHIs) {
187 // Yup, loop through and nuke the PHI nodes
188 while (PHINode *PN = dyn_cast<PHINode>(&front())) {
189 // Remove the predecessor first.
190 PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
192 // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
194 if (PN->getOperand(0) != PN)
195 PN->replaceAllUsesWith(PN->getOperand(0));
197 // We are left with an infinite loop with no entries: kill the PHI.
198 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
199 getInstList().pop_front(); // Remove the PHI node
202 // If the PHI node already only had one entry, it got deleted by
203 // removeIncomingValue.
206 // Okay, now we know that we need to remove predecessor #pred_idx from all
207 // PHI nodes. Iterate over each PHI node fixing them up
209 for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
211 PN->removeIncomingValue(Pred, false);
212 // If all incoming values to the Phi are the same, we can replace the Phi
215 if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue())) {
216 PN->replaceAllUsesWith(PNV);
217 PN->eraseFromParent();
224 /// splitBasicBlock - This splits a basic block into two at the specified
225 /// instruction. Note that all instructions BEFORE the specified iterator stay
226 /// as part of the original basic block, an unconditional branch is added to
227 /// the new BB, and the rest of the instructions in the BB are moved to the new
228 /// BB, including the old terminator. This invalidates the iterator.
230 /// Note that this only works on well formed basic blocks (must have a
231 /// terminator), and 'I' must not be the end of instruction list (which would
232 /// cause a degenerate basic block to be formed, having a terminator inside of
233 /// the basic block).
235 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const std::string &BBName) {
236 assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
237 assert(I != InstList.end() &&
238 "Trying to get me to create degenerate basic block!");
240 BasicBlock *New = new BasicBlock(BBName, getParent(), getNext());
242 // Move all of the specified instructions from the original basic block into
243 // the new basic block.
244 New->getInstList().splice(New->end(), this->getInstList(), I, end());
246 // Add a branch instruction to the newly formed basic block.
247 new BranchInst(New, this);
249 // Now we must loop through all of the successors of the New block (which
250 // _were_ the successors of the 'this' block), and update any PHI nodes in
251 // successors. If there were PHI nodes in the successors, then they need to
252 // know that incoming branches will be from New, not from Old.
254 for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
255 // Loop over any phi nodes in the basic block, updating the BB field of
256 // incoming values...
257 BasicBlock *Successor = *I;
259 for (BasicBlock::iterator II = Successor->begin();
260 (PN = dyn_cast<PHINode>(II)); ++II) {
261 int IDX = PN->getBasicBlockIndex(this);
263 PN->setIncomingBlock((unsigned)IDX, New);
264 IDX = PN->getBasicBlockIndex(this);