1 //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
3 // This file implements the BasicBlock class for the VMCore library.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/BasicBlock.h"
8 #include "llvm/iTerminators.h"
10 #include "llvm/Support/CFG.h"
11 #include "llvm/Constant.h"
12 #include "llvm/iPHINode.h"
13 #include "llvm/SymbolTable.h"
14 #include "Support/LeakDetector.h"
15 #include "SymbolTableListTraitsImpl.h"
18 // DummyInst - An instance of this class is used to mark the end of the
19 // instruction list. This is not a real instruction.
21 struct DummyInst : public Instruction {
22 DummyInst() : Instruction(Type::VoidTy, OtherOpsEnd) {
23 // This should not be garbage monitored.
24 LeakDetector::removeGarbageObject(this);
27 virtual Instruction *clone() const {
28 assert(0 && "Cannot clone EOL");abort();
31 virtual const char *getOpcodeName() const { return "*end-of-list-inst*"; }
33 // Methods for support type inquiry through isa, cast, and dyn_cast...
34 static inline bool classof(const DummyInst *) { return true; }
35 static inline bool classof(const Instruction *I) {
36 return I->getOpcode() == OtherOpsEnd;
38 static inline bool classof(const Value *V) {
39 return isa<Instruction>(V) && classof(cast<Instruction>(V));
43 Instruction *ilist_traits<Instruction>::createNode() {
44 return new DummyInst();
46 iplist<Instruction> &ilist_traits<Instruction>::getList(BasicBlock *BB) {
47 return BB->getInstList();
50 // Explicit instantiation of SymbolTableListTraits since some of the methods
51 // are not in the public header file...
52 template SymbolTableListTraits<Instruction, BasicBlock, Function>;
55 // BasicBlock ctor - If the function parameter is specified, the basic block is
56 // automatically inserted at the end of the function.
58 BasicBlock::BasicBlock(const std::string &name, Function *Parent)
59 : Value(Type::LabelTy, Value::BasicBlockVal, name) {
60 // Initialize the instlist...
61 InstList.setItemParent(this);
63 // Make sure that we get added to a function
64 LeakDetector::addGarbageObject(this);
67 Parent->getBasicBlockList().push_back(this);
70 /// BasicBlock ctor - If the InsertBefore parameter is specified, the basic
71 /// block is automatically inserted right before the specified block.
73 BasicBlock::BasicBlock(const std::string &Name, BasicBlock *InsertBefore)
74 : Value(Type::LabelTy, Value::BasicBlockVal, Name) {
75 // Initialize the instlist...
76 InstList.setItemParent(this);
78 // Make sure that we get added to a function
79 LeakDetector::addGarbageObject(this);
82 assert(InsertBefore->getParent() &&
83 "Cannot insert block before another block that is not embedded into"
85 InsertBefore->getParent()->getBasicBlockList().insert(InsertBefore, this);
90 BasicBlock::~BasicBlock() {
95 void BasicBlock::setParent(Function *parent) {
97 LeakDetector::addGarbageObject(this);
99 InstList.setParent(parent);
102 LeakDetector::removeGarbageObject(this);
105 // Specialize setName to take care of symbol table majik
106 void BasicBlock::setName(const std::string &name, SymbolTable *ST) {
108 assert((ST == 0 || (!getParent() || ST == getParent()->getSymbolTable())) &&
109 "Invalid symtab argument!");
110 if ((P = getParent()) && hasName()) P->getSymbolTable()->remove(this);
111 Value::setName(name);
112 if (P && hasName()) P->getSymbolTable()->insert(this);
115 TerminatorInst *BasicBlock::getTerminator() {
116 if (InstList.empty()) return 0;
117 return dyn_cast<TerminatorInst>(&InstList.back());
120 const TerminatorInst *const BasicBlock::getTerminator() const {
121 if (InstList.empty()) return 0;
122 return dyn_cast<TerminatorInst>(&InstList.back());
125 void BasicBlock::dropAllReferences() {
126 for(iterator I = begin(), E = end(); I != E; ++I)
127 I->dropAllReferences();
130 // hasConstantReferences() - This predicate is true if there is a
131 // reference to this basic block in the constant pool for this method. For
132 // example, if a block is reached through a switch table, that table resides
133 // in the constant pool, and the basic block is reference from it.
135 bool BasicBlock::hasConstantReferences() const {
136 for (use_const_iterator I = use_begin(), E = use_end(); I != E; ++I)
137 if (::isa<Constant>((Value*)*I))
143 // removePredecessor - This method is used to notify a BasicBlock that the
144 // specified Predecessor of the block is no longer able to reach it. This is
145 // actually not used to update the Predecessor list, but is actually used to
146 // update the PHI nodes that reside in the block. Note that this should be
147 // called while the predecessor still refers to this block.
149 void BasicBlock::removePredecessor(BasicBlock *Pred) {
150 assert(find(pred_begin(this), pred_end(this), Pred) != pred_end(this) &&
151 "removePredecessor: BB is not a predecessor!");
152 if (!isa<PHINode>(front())) return; // Quick exit.
154 pred_iterator PI(pred_begin(this)), EI(pred_end(this));
157 // Loop over the rest of the predecessors until we run out, or until we find
158 // out that there are more than 2 predecessors.
159 for (max_idx = 0; PI != EI && max_idx < 3; ++PI, ++max_idx) /*empty*/;
161 // If there are exactly two predecessors, then we want to nuke the PHI nodes
162 // altogether. We cannot do this, however if this in this case however:
165 // %x = phi [X, Loop]
166 // %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1
167 // br Loop ;; %x2 does not dominate all uses
169 // This is because the PHI node input is actually taken from the predecessor
170 // basic block. The only case this can happen is with a self loop, so we
171 // check for this case explicitly now.
173 assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
175 PI = pred_begin(this);
176 BasicBlock *Other = *PI == Pred ? *++PI : *PI;
178 // Disable PHI elimination!
179 if (this == Other) max_idx = 3;
182 if (max_idx <= 2) { // <= Two predecessors BEFORE I remove one?
183 // Yup, loop through and nuke the PHI nodes
184 while (PHINode *PN = dyn_cast<PHINode>(&front())) {
185 PN->removeIncomingValue(Pred); // Remove the predecessor first...
187 // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
189 PN->replaceAllUsesWith(PN->getOperand(0));
190 getInstList().pop_front(); // Remove the PHI node
193 // If the PHI node already only had one entry, it got deleted by
194 // removeIncomingValue.
197 // Okay, now we know that we need to remove predecessor #pred_idx from all
198 // PHI nodes. Iterate over each PHI node fixing them up
199 for (iterator II = begin(); PHINode *PN = dyn_cast<PHINode>(&*II); ++II)
200 PN->removeIncomingValue(Pred);
205 // splitBasicBlock - This splits a basic block into two at the specified
206 // instruction. Note that all instructions BEFORE the specified iterator stay
207 // as part of the original basic block, an unconditional branch is added to
208 // the new BB, and the rest of the instructions in the BB are moved to the new
209 // BB, including the old terminator. This invalidates the iterator.
211 // Note that this only works on well formed basic blocks (must have a
212 // terminator), and 'I' must not be the end of instruction list (which would
213 // cause a degenerate basic block to be formed, having a terminator inside of
216 BasicBlock *BasicBlock::splitBasicBlock(iterator I) {
217 assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
218 assert(I != InstList.end() &&
219 "Trying to get me to create degenerate basic block!");
221 BasicBlock *New = new BasicBlock("", getParent());
223 // Go from the end of the basic block through to the iterator pointer, moving
224 // to the new basic block...
225 Instruction *Inst = 0;
227 iterator EndIt = end();
228 Inst = InstList.remove(--EndIt); // Remove from end
229 New->InstList.push_front(Inst); // Add to front
230 } while (Inst != &*I); // Loop until we move the specified instruction.
232 // Add a branch instruction to the newly formed basic block.
233 InstList.push_back(new BranchInst(New));
235 // Now we must loop through all of the successors of the New block (which
236 // _were_ the successors of the 'this' block), and update any PHI nodes in
237 // successors. If there were PHI nodes in the successors, then they need to
238 // know that incoming branches will be from New, not from Old.
240 for (BasicBlock::succ_iterator I = succ_begin(New), E = succ_end(New);
242 // Loop over any phi nodes in the basic block, updating the BB field of
243 // incoming values...
244 BasicBlock *Successor = *I;
245 for (BasicBlock::iterator II = Successor->begin();
246 PHINode *PN = dyn_cast<PHINode>(&*II); ++II) {
247 int IDX = PN->getBasicBlockIndex(this);
249 PN->setIncomingBlock((unsigned)IDX, New);
250 IDX = PN->getBasicBlockIndex(this);