blob: 16aa7faa0859f6166f91058989ed24a42e1574b7 [file] [log] [blame]
Chris Lattnerd1e693f2002-09-08 18:59:35 +00001//===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
Chris Lattnerb7653df2002-04-08 22:03:57 +000010// This file implements the BasicBlock class for the VMCore library.
Chris Lattner00950542001-06-06 20:29:01 +000011//
12//===----------------------------------------------------------------------===//
13
Chris Lattner7e708292002-06-25 16:13:24 +000014#include "llvm/BasicBlock.h"
Chris Lattner34645472005-04-12 18:52:14 +000015#include "llvm/Constants.h"
Misha Brukman44336292004-07-29 16:53:53 +000016#include "llvm/Instructions.h"
Chris Lattner00950542001-06-06 20:29:01 +000017#include "llvm/Type.h"
Chris Lattner455889a2002-02-12 22:39:50 +000018#include "llvm/Support/CFG.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000019#include "llvm/Support/LeakDetector.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000020#include "llvm/Support/Compiler.h"
Chris Lattner7e708292002-06-25 16:13:24 +000021#include "SymbolTableListTraitsImpl.h"
22#include <algorithm>
Chris Lattner108e4ab2003-11-21 16:52:05 +000023using namespace llvm;
Chris Lattner00950542001-06-06 20:29:01 +000024
Chris Lattner17fcdd52007-04-17 03:26:42 +000025inline ValueSymbolTable *
26ilist_traits<Instruction>::getSymTab(BasicBlock *BB) {
27 if (BB)
28 if (Function *F = BB->getParent())
29 return &F->getValueSymbolTable();
30 return 0;
31}
32
Gordon Henriksenafba8fe2007-12-10 02:14:30 +000033
34namespace {
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 {
Gabor Greif051a9502008-04-06 20:25:17 +000038 // allocate space for exactly zero operands
39 void *operator new(size_t s) {
40 return User::operator new(s, 0);
41 }
Gordon Henriksenafba8fe2007-12-10 02:14:30 +000042 DummyInst() : Instruction(Type::VoidTy, OtherOpsEnd, 0, 0) {
43 // This should not be garbage monitored.
44 LeakDetector::removeGarbageObject(this);
45 }
46
47 Instruction *clone() const {
48 assert(0 && "Cannot clone EOL");abort();
49 return 0;
50 }
51 const char *getOpcodeName() const { return "*end-of-list-inst*"; }
52
53 // Methods for support type inquiry through isa, cast, and dyn_cast...
54 static inline bool classof(const DummyInst *) { return true; }
55 static inline bool classof(const Instruction *I) {
56 return I->getOpcode() == OtherOpsEnd;
57 }
58 static inline bool classof(const Value *V) {
59 return isa<Instruction>(V) && classof(cast<Instruction>(V));
60 }
61 };
Chris Lattner108e4ab2003-11-21 16:52:05 +000062}
Chris Lattner7e708292002-06-25 16:13:24 +000063
Chris Lattnerbca81442005-01-30 00:09:23 +000064Instruction *ilist_traits<Instruction>::createSentinel() {
Chris Lattner7e708292002-06-25 16:13:24 +000065 return new DummyInst();
66}
67iplist<Instruction> &ilist_traits<Instruction>::getList(BasicBlock *BB) {
68 return BB->getInstList();
69}
70
71// Explicit instantiation of SymbolTableListTraits since some of the methods
72// are not in the public header file...
Chris Lattner17fcdd52007-04-17 03:26:42 +000073template class SymbolTableListTraits<Instruction, BasicBlock>;
Chris Lattner7e708292002-06-25 16:13:24 +000074
Chris Lattner00950542001-06-06 20:29:01 +000075
Chris Lattner17fcdd52007-04-17 03:26:42 +000076BasicBlock::BasicBlock(const std::string &Name, Function *NewParent,
Nick Lewyckyfc82fab2008-03-02 02:48:09 +000077 BasicBlock *InsertBefore, BasicBlock *Dest)
Gabor Greif051a9502008-04-06 20:25:17 +000078 : User(Type::LabelTy, Value::BasicBlockVal, &unwindDest, 0/*FIXME*/), Parent(0) {
Chris Lattner0a1a8742002-09-26 05:03:22 +000079
80 // Make sure that we get added to a function
81 LeakDetector::addGarbageObject(this);
82
83 if (InsertBefore) {
Chris Lattner17fcdd52007-04-17 03:26:42 +000084 assert(NewParent &&
Chris Lattner4f056112004-02-04 03:57:50 +000085 "Cannot insert block before another block with no function!");
Chris Lattner17fcdd52007-04-17 03:26:42 +000086 NewParent->getBasicBlockList().insert(InsertBefore, this);
87 } else if (NewParent) {
88 NewParent->getBasicBlockList().push_back(this);
Chris Lattner0a1a8742002-09-26 05:03:22 +000089 }
Chris Lattnerdec628e2007-02-12 05:18:08 +000090
91 setName(Name);
Nick Lewyckyfc82fab2008-03-02 02:48:09 +000092 unwindDest.init(NULL, this);
93 setUnwindDest(Dest);
Chris Lattner0a1a8742002-09-26 05:03:22 +000094}
95
96
Gordon Henriksenafba8fe2007-12-10 02:14:30 +000097BasicBlock::~BasicBlock() {
98 assert(getParent() == 0 && "BasicBlock still linked into the program!");
99 dropAllReferences();
100 InstList.clear();
Chris Lattner00950542001-06-06 20:29:01 +0000101}
102
Chris Lattnerbded1322002-09-06 21:33:15 +0000103void BasicBlock::setParent(Function *parent) {
Chris Lattnerd1e693f2002-09-08 18:59:35 +0000104 if (getParent())
105 LeakDetector::addGarbageObject(this);
106
Chris Lattner17fcdd52007-04-17 03:26:42 +0000107 // Set Parent=parent, updating instruction symtab entries as appropriate.
108 InstList.setSymTabObject(&Parent, parent);
Chris Lattnerd1e693f2002-09-08 18:59:35 +0000109
110 if (getParent())
111 LeakDetector::removeGarbageObject(this);
Chris Lattnerbded1322002-09-06 21:33:15 +0000112}
113
Chris Lattner4b833802004-10-11 22:21:39 +0000114void BasicBlock::removeFromParent() {
115 getParent()->getBasicBlockList().remove(this);
116}
117
118void BasicBlock::eraseFromParent() {
119 getParent()->getBasicBlockList().erase(this);
120}
121
Nick Lewyckyfc82fab2008-03-02 02:48:09 +0000122const BasicBlock *BasicBlock::getUnwindDest() const {
123 return cast_or_null<const BasicBlock>(unwindDest.get());
124}
125
126BasicBlock *BasicBlock::getUnwindDest() {
127 return cast_or_null<BasicBlock>(unwindDest.get());
128}
129
130void BasicBlock::setUnwindDest(BasicBlock *dest) {
131 NumOperands = unwindDest ? 1 : 0;
132 unwindDest.set(dest);
133}
134
Chris Lattnera71965b2006-09-23 04:03:45 +0000135/// moveBefore - Unlink this basic block from its current function and
136/// insert it into the function that MovePos lives in, right before MovePos.
Chris Lattner6a13aed2005-08-12 22:14:06 +0000137void BasicBlock::moveBefore(BasicBlock *MovePos) {
138 MovePos->getParent()->getBasicBlockList().splice(MovePos,
139 getParent()->getBasicBlockList(), this);
140}
141
Chris Lattnera71965b2006-09-23 04:03:45 +0000142/// moveAfter - Unlink this basic block from its current function and
143/// insert it into the function that MovePos lives in, right after MovePos.
144void BasicBlock::moveAfter(BasicBlock *MovePos) {
145 Function::iterator I = MovePos;
146 MovePos->getParent()->getBasicBlockList().splice(++I,
147 getParent()->getBasicBlockList(), this);
148}
149
Chris Lattner4b833802004-10-11 22:21:39 +0000150
Chris Lattner00950542001-06-06 20:29:01 +0000151TerminatorInst *BasicBlock::getTerminator() {
152 if (InstList.empty()) return 0;
Chris Lattner7e708292002-06-25 16:13:24 +0000153 return dyn_cast<TerminatorInst>(&InstList.back());
Chris Lattner00950542001-06-06 20:29:01 +0000154}
155
Dan Gohman50cdabc2007-11-19 20:46:23 +0000156const TerminatorInst *BasicBlock::getTerminator() const {
Chris Lattner00950542001-06-06 20:29:01 +0000157 if (InstList.empty()) return 0;
Chris Lattner7e708292002-06-25 16:13:24 +0000158 return dyn_cast<TerminatorInst>(&InstList.back());
Chris Lattner00950542001-06-06 20:29:01 +0000159}
160
Vladimir Prusdd49dbf2006-06-08 15:46:18 +0000161Instruction* BasicBlock::getFirstNonPHI()
162{
Vladimir Prus28962f32006-06-08 16:03:13 +0000163 BasicBlock::iterator i = begin();
Vladimir Prusdd49dbf2006-06-08 15:46:18 +0000164 // All valid basic blocks should have a terminator,
165 // which is not a PHINode. If we have invalid basic
166 // block we'll get assert when dereferencing past-the-end
167 // iterator.
168 while (isa<PHINode>(i)) ++i;
169 return &*i;
170}
171
Chris Lattner00950542001-06-06 20:29:01 +0000172void BasicBlock::dropAllReferences() {
Nick Lewyckyfc82fab2008-03-02 02:48:09 +0000173 setUnwindDest(NULL);
Chris Lattner7e708292002-06-25 16:13:24 +0000174 for(iterator I = begin(), E = end(); I != E; ++I)
175 I->dropAllReferences();
Chris Lattner00950542001-06-06 20:29:01 +0000176}
177
Chris Lattnerad993cb2005-02-24 02:37:26 +0000178/// getSinglePredecessor - If this basic block has a single predecessor block,
179/// return the block, otherwise return a null pointer.
180BasicBlock *BasicBlock::getSinglePredecessor() {
181 pred_iterator PI = pred_begin(this), E = pred_end(this);
182 if (PI == E) return 0; // No preds.
183 BasicBlock *ThePred = *PI;
184 ++PI;
185 return (PI == E) ? ThePred : 0 /*multiple preds*/;
186}
187
Chris Lattner566f6002005-04-21 16:06:03 +0000188/// removePredecessor - This method is used to notify a BasicBlock that the
189/// specified Predecessor of the block is no longer able to reach it. This is
Misha Brukmanfd939082005-04-21 23:48:37 +0000190/// actually not used to update the Predecessor list, but is actually used to
Chris Lattner566f6002005-04-21 16:06:03 +0000191/// update the PHI nodes that reside in the block. Note that this should be
192/// called while the predecessor still refers to this block.
193///
Chris Lattner34645472005-04-12 18:52:14 +0000194void BasicBlock::removePredecessor(BasicBlock *Pred,
Nick Lewyckyc6694222008-03-09 05:04:48 +0000195 bool DontDeleteUselessPHIs,
196 bool OnlyDeleteOne) {
Chris Lattner1f21ef12005-02-23 16:53:04 +0000197 assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
Chris Lattner35f0aec2005-02-23 07:09:08 +0000198 find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
Jeff Cohen9d809302005-04-23 21:38:35 +0000199 "removePredecessor: BB is not a predecessor!");
Chris Lattner35f0aec2005-02-23 07:09:08 +0000200
Chris Lattnerf23586c2004-12-11 22:10:29 +0000201 if (InstList.empty()) return;
Chris Lattnera9e77812004-07-06 17:44:17 +0000202 PHINode *APN = dyn_cast<PHINode>(&front());
203 if (!APN) return; // Quick exit.
Chris Lattnerb47af252001-06-29 05:25:23 +0000204
205 // If there are exactly two predecessors, then we want to nuke the PHI nodes
Chris Lattnera9e77812004-07-06 17:44:17 +0000206 // altogether. However, we cannot do this, if this in this case:
Chris Lattner87a09b12002-05-21 19:52:49 +0000207 //
208 // Loop:
209 // %x = phi [X, Loop]
210 // %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1
211 // br Loop ;; %x2 does not dominate all uses
212 //
213 // This is because the PHI node input is actually taken from the predecessor
Misha Brukmanfd939082005-04-21 23:48:37 +0000214 // basic block. The only case this can happen is with a self loop, so we
Chris Lattner87a09b12002-05-21 19:52:49 +0000215 // check for this case explicitly now.
Misha Brukmanfd939082005-04-21 23:48:37 +0000216 //
Chris Lattnera9e77812004-07-06 17:44:17 +0000217 unsigned max_idx = APN->getNumIncomingValues();
Chris Lattnerb47af252001-06-29 05:25:23 +0000218 assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
Chris Lattner87a09b12002-05-21 19:52:49 +0000219 if (max_idx == 2) {
Chris Lattnera9e77812004-07-06 17:44:17 +0000220 BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
Chris Lattner87a09b12002-05-21 19:52:49 +0000221
222 // Disable PHI elimination!
223 if (this == Other) max_idx = 3;
224 }
225
Chris Lattner34645472005-04-12 18:52:14 +0000226 // <= Two predecessors BEFORE I remove one?
227 if (max_idx <= 2 && !DontDeleteUselessPHIs) {
Chris Lattnerb00c5822001-10-02 03:41:24 +0000228 // Yup, loop through and nuke the PHI nodes
Chris Lattner7e708292002-06-25 16:13:24 +0000229 while (PHINode *PN = dyn_cast<PHINode>(&front())) {
Chris Lattner34645472005-04-12 18:52:14 +0000230 // Remove the predecessor first.
Nick Lewyckyc6694222008-03-09 05:04:48 +0000231 if (OnlyDeleteOne) {
232 int idx = PN->getBasicBlockIndex(Pred);
233 PN->removeIncomingValue(idx, !DontDeleteUselessPHIs);
234 } else
235 PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
Chris Lattnerb47af252001-06-29 05:25:23 +0000236
237 // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
Chris Lattnerdee430d2002-10-08 21:36:34 +0000238 if (max_idx == 2) {
Chris Lattner02a78cf2003-04-25 23:14:19 +0000239 if (PN->getOperand(0) != PN)
240 PN->replaceAllUsesWith(PN->getOperand(0));
241 else
242 // We are left with an infinite loop with no entries: kill the PHI.
Chris Lattner34645472005-04-12 18:52:14 +0000243 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattnerdee430d2002-10-08 21:36:34 +0000244 getInstList().pop_front(); // Remove the PHI node
245 }
246
247 // If the PHI node already only had one entry, it got deleted by
248 // removeIncomingValue.
Chris Lattnerb47af252001-06-29 05:25:23 +0000249 }
250 } else {
251 // Okay, now we know that we need to remove predecessor #pred_idx from all
252 // PHI nodes. Iterate over each PHI node fixing them up
Chris Lattnerf8782182004-06-05 00:11:27 +0000253 PHINode *PN;
Chris Lattner80f4d882005-08-05 15:34:10 +0000254 for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
255 ++II;
Nick Lewyckyc6694222008-03-09 05:04:48 +0000256 if (OnlyDeleteOne) {
257 int idx = PN->getBasicBlockIndex(Pred);
258 PN->removeIncomingValue(idx, false);
259 } else
260 PN->removeIncomingValue(Pred, false);
261
Nate Begemana83ba0f2005-08-04 23:24:19 +0000262 // If all incoming values to the Phi are the same, we can replace the Phi
263 // with that value.
Owen Anderson90245d42006-06-14 04:43:14 +0000264 Value* PNV = 0;
265 if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue())) {
Chris Lattner1325b422005-08-05 01:02:04 +0000266 PN->replaceAllUsesWith(PNV);
267 PN->eraseFromParent();
268 }
Nate Begemana83ba0f2005-08-04 23:24:19 +0000269 }
Chris Lattnerb47af252001-06-29 05:25:23 +0000270 }
271}
272
Chris Lattner00950542001-06-06 20:29:01 +0000273
Chris Lattner0f67dd62005-04-21 16:04:49 +0000274/// splitBasicBlock - This splits a basic block into two at the specified
275/// instruction. Note that all instructions BEFORE the specified iterator stay
Misha Brukmanfd939082005-04-21 23:48:37 +0000276/// as part of the original basic block, an unconditional branch is added to
Chris Lattner0f67dd62005-04-21 16:04:49 +0000277/// the new BB, and the rest of the instructions in the BB are moved to the new
278/// BB, including the old terminator. This invalidates the iterator.
279///
Misha Brukmanfd939082005-04-21 23:48:37 +0000280/// Note that this only works on well formed basic blocks (must have a
Chris Lattner0f67dd62005-04-21 16:04:49 +0000281/// terminator), and 'I' must not be the end of instruction list (which would
282/// cause a degenerate basic block to be formed, having a terminator inside of
Misha Brukmanfd939082005-04-21 23:48:37 +0000283/// the basic block).
Chris Lattner0f67dd62005-04-21 16:04:49 +0000284///
Chris Lattner4bd4aa52003-08-24 03:41:39 +0000285BasicBlock *BasicBlock::splitBasicBlock(iterator I, const std::string &BBName) {
Chris Lattner00950542001-06-06 20:29:01 +0000286 assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000287 assert(I != InstList.end() &&
Jeff Cohen9d809302005-04-23 21:38:35 +0000288 "Trying to get me to create degenerate basic block!");
Chris Lattner00950542001-06-06 20:29:01 +0000289
Gabor Greif051a9502008-04-06 20:25:17 +0000290 BasicBlock *New = new(0/*FIXME*/) BasicBlock(BBName, getParent(), getNext());
Chris Lattner00950542001-06-06 20:29:01 +0000291
Chris Lattnerf2c31062004-02-03 23:11:21 +0000292 // Move all of the specified instructions from the original basic block into
293 // the new basic block.
294 New->getInstList().splice(New->end(), this->getInstList(), I, end());
Chris Lattner00950542001-06-06 20:29:01 +0000295
296 // Add a branch instruction to the newly formed basic block.
Gabor Greif051a9502008-04-06 20:25:17 +0000297 BranchInst::Create(New, this);
Chris Lattnere8e320d2002-02-25 00:35:07 +0000298
299 // Now we must loop through all of the successors of the New block (which
300 // _were_ the successors of the 'this' block), and update any PHI nodes in
301 // successors. If there were PHI nodes in the successors, then they need to
302 // know that incoming branches will be from New, not from Old.
303 //
Chris Lattner1c9ab512003-09-24 22:03:22 +0000304 for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
Chris Lattnere8e320d2002-02-25 00:35:07 +0000305 // Loop over any phi nodes in the basic block, updating the BB field of
306 // incoming values...
307 BasicBlock *Successor = *I;
Chris Lattnerf8782182004-06-05 00:11:27 +0000308 PHINode *PN;
Chris Lattnere8e320d2002-02-25 00:35:07 +0000309 for (BasicBlock::iterator II = Successor->begin();
Chris Lattner9bf2a922004-06-05 17:43:52 +0000310 (PN = dyn_cast<PHINode>(II)); ++II) {
Chris Lattnere8e320d2002-02-25 00:35:07 +0000311 int IDX = PN->getBasicBlockIndex(this);
312 while (IDX != -1) {
313 PN->setIncomingBlock((unsigned)IDX, New);
314 IDX = PN->getBasicBlockIndex(this);
315 }
316 }
317 }
Chris Lattner00950542001-06-06 20:29:01 +0000318 return New;
319}