1 //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the BasicBlock class for the IR library.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/IR/BasicBlock.h"
15 #include "SymbolTableListTraitsImpl.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/IR/CFG.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/Instructions.h"
20 #include "llvm/IR/IntrinsicInst.h"
21 #include "llvm/IR/LLVMContext.h"
22 #include "llvm/IR/Type.h"
26 ValueSymbolTable *BasicBlock::getValueSymbolTable() {
27 if (Function *F = getParent())
28 return &F->getValueSymbolTable();
32 LLVMContext &BasicBlock::getContext() const {
33 return getType()->getContext();
36 // Explicit instantiation of SymbolTableListTraits since some of the methods
37 // are not in the public header file...
38 template class llvm::SymbolTableListTraits<Instruction, BasicBlock>;
41 BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
42 BasicBlock *InsertBefore)
43 : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(nullptr) {
46 insertInto(NewParent, InsertBefore);
48 assert(!InsertBefore &&
49 "Cannot insert block before another block with no function!");
54 void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) {
55 assert(NewParent && "Expected a parent");
56 assert(!Parent && "Already has a parent");
59 NewParent->getBasicBlockList().insert(InsertBefore, this);
61 NewParent->getBasicBlockList().push_back(this);
64 BasicBlock::~BasicBlock() {
65 // If the address of the block is taken and it is being deleted (e.g. because
66 // it is dead), this means that there is either a dangling constant expr
67 // hanging off the block, or an undefined use of the block (source code
68 // expecting the address of a label to keep the block alive even though there
69 // is no indirect branch). Handle these cases by zapping the BlockAddress
70 // nodes. There are no other possible uses at this point.
71 if (hasAddressTaken()) {
72 assert(!use_empty() && "There should be at least one blockaddress!");
73 Constant *Replacement =
74 ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
75 while (!use_empty()) {
76 BlockAddress *BA = cast<BlockAddress>(user_back());
77 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
79 BA->destroyConstant();
83 assert(getParent() == nullptr && "BasicBlock still linked into the program!");
88 void BasicBlock::setParent(Function *parent) {
89 // Set Parent=parent, updating instruction symtab entries as appropriate.
90 InstList.setSymTabObject(&Parent, parent);
93 void BasicBlock::removeFromParent() {
94 getParent()->getBasicBlockList().remove(this);
97 iplist<BasicBlock>::iterator BasicBlock::eraseFromParent() {
98 return getParent()->getBasicBlockList().erase(this);
101 /// 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);
108 /// 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);
116 const Module *BasicBlock::getModule() const {
117 return getParent()->getParent();
120 TerminatorInst *BasicBlock::getTerminator() {
121 if (InstList.empty()) return nullptr;
122 return dyn_cast<TerminatorInst>(&InstList.back());
125 const TerminatorInst *BasicBlock::getTerminator() const {
126 if (InstList.empty()) return nullptr;
127 return dyn_cast<TerminatorInst>(&InstList.back());
130 CallInst *BasicBlock::getTerminatingMustTailCall() {
131 if (InstList.empty())
133 ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
134 if (!RI || RI == &InstList.front())
137 Instruction *Prev = RI->getPrevNode();
141 if (Value *RV = RI->getReturnValue()) {
145 // Look through the optional bitcast.
146 if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
147 RV = BI->getOperand(0);
148 Prev = BI->getPrevNode();
149 if (!Prev || RV != Prev)
154 if (auto *CI = dyn_cast<CallInst>(Prev)) {
155 if (CI->isMustTailCall())
161 Instruction* BasicBlock::getFirstNonPHI() {
162 BasicBlock::iterator i = begin();
163 // All valid basic blocks should have a terminator,
164 // which is not a PHINode. If we have an invalid basic
165 // block we'll get an assertion failure when dereferencing
166 // a past-the-end iterator.
167 while (isa<PHINode>(i)) ++i;
171 Instruction* BasicBlock::getFirstNonPHIOrDbg() {
172 BasicBlock::iterator i = begin();
173 // All valid basic blocks should have a terminator,
174 // which is not a PHINode. If we have an invalid basic
175 // block we'll get an assertion failure when dereferencing
176 // a past-the-end iterator.
177 while (isa<PHINode>(i) || isa<DbgInfoIntrinsic>(i)) ++i;
181 Instruction* BasicBlock::getFirstNonPHIOrDbgOrLifetime() {
182 // All valid basic blocks should have a terminator,
183 // which is not a PHINode. If we have an invalid basic
184 // block we'll get an assertion failure when dereferencing
185 // a past-the-end iterator.
186 BasicBlock::iterator i = begin();
188 if (isa<PHINode>(i) || isa<DbgInfoIntrinsic>(i))
191 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(i);
194 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
195 II->getIntrinsicID() != Intrinsic::lifetime_end)
201 BasicBlock::iterator BasicBlock::getFirstInsertionPt() {
202 iterator InsertPt = getFirstNonPHI();
203 if (isa<LandingPadInst>(InsertPt)) ++InsertPt;
207 void BasicBlock::dropAllReferences() {
208 for(iterator I = begin(), E = end(); I != E; ++I)
209 I->dropAllReferences();
212 /// If this basic block has a single predecessor block,
213 /// return the block, otherwise return a null pointer.
214 BasicBlock *BasicBlock::getSinglePredecessor() {
215 pred_iterator PI = pred_begin(this), E = pred_end(this);
216 if (PI == E) return nullptr; // No preds.
217 BasicBlock *ThePred = *PI;
219 return (PI == E) ? ThePred : nullptr /*multiple preds*/;
222 /// If this basic block has a unique predecessor block,
223 /// return the block, otherwise return a null pointer.
224 /// Note that unique predecessor doesn't mean single edge, there can be
225 /// multiple edges from the unique predecessor to this block (for example
226 /// a switch statement with multiple cases having the same destination).
227 BasicBlock *BasicBlock::getUniquePredecessor() {
228 pred_iterator PI = pred_begin(this), E = pred_end(this);
229 if (PI == E) return nullptr; // No preds.
230 BasicBlock *PredBB = *PI;
232 for (;PI != E; ++PI) {
235 // The same predecessor appears multiple times in the predecessor list.
241 BasicBlock *BasicBlock::getSingleSuccessor() {
242 succ_iterator SI = succ_begin(this), E = succ_end(this);
243 if (SI == E) return nullptr; // no successors
244 BasicBlock *TheSucc = *SI;
246 return (SI == E) ? TheSucc : nullptr /* multiple successors */;
249 BasicBlock *BasicBlock::getUniqueSuccessor() {
250 succ_iterator SI = succ_begin(this), E = succ_end(this);
251 if (SI == E) return NULL; // No successors
252 BasicBlock *SuccBB = *SI;
254 for (;SI != E; ++SI) {
257 // The same successor appears multiple times in the successor list.
263 /// This method is used to notify a BasicBlock that the
264 /// specified Predecessor of the block is no longer able to reach it. This is
265 /// actually not used to update the Predecessor list, but is actually used to
266 /// update the PHI nodes that reside in the block. Note that this should be
267 /// called while the predecessor still refers to this block.
269 void BasicBlock::removePredecessor(BasicBlock *Pred,
270 bool DontDeleteUselessPHIs) {
271 assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
272 find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
273 "removePredecessor: BB is not a predecessor!");
275 if (InstList.empty()) return;
276 PHINode *APN = dyn_cast<PHINode>(&front());
277 if (!APN) return; // Quick exit.
279 // If there are exactly two predecessors, then we want to nuke the PHI nodes
280 // altogether. However, we cannot do this, if this in this case:
283 // %x = phi [X, Loop]
284 // %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1
285 // br Loop ;; %x2 does not dominate all uses
287 // This is because the PHI node input is actually taken from the predecessor
288 // basic block. The only case this can happen is with a self loop, so we
289 // check for this case explicitly now.
291 unsigned max_idx = APN->getNumIncomingValues();
292 assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
294 BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
296 // Disable PHI elimination!
297 if (this == Other) max_idx = 3;
300 // <= Two predecessors BEFORE I remove one?
301 if (max_idx <= 2 && !DontDeleteUselessPHIs) {
302 // Yup, loop through and nuke the PHI nodes
303 while (PHINode *PN = dyn_cast<PHINode>(&front())) {
304 // Remove the predecessor first.
305 PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
307 // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
309 if (PN->getIncomingValue(0) != PN)
310 PN->replaceAllUsesWith(PN->getIncomingValue(0));
312 // We are left with an infinite loop with no entries: kill the PHI.
313 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
314 getInstList().pop_front(); // Remove the PHI node
317 // If the PHI node already only had one entry, it got deleted by
318 // removeIncomingValue.
321 // Okay, now we know that we need to remove predecessor #pred_idx from all
322 // PHI nodes. Iterate over each PHI node fixing them up
324 for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
326 PN->removeIncomingValue(Pred, false);
327 // If all incoming values to the Phi are the same, we can replace the Phi
329 Value* PNV = nullptr;
330 if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue()))
332 PN->replaceAllUsesWith(PNV);
333 PN->eraseFromParent();
340 /// This splits a basic block into two at the specified
341 /// instruction. Note that all instructions BEFORE the specified iterator stay
342 /// as part of the original basic block, an unconditional branch is added to
343 /// the new BB, and the rest of the instructions in the BB are moved to the new
344 /// BB, including the old terminator. This invalidates the iterator.
346 /// Note that this only works on well formed basic blocks (must have a
347 /// terminator), and 'I' must not be the end of instruction list (which would
348 /// cause a degenerate basic block to be formed, having a terminator inside of
349 /// the basic block).
351 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
352 assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
353 assert(I != InstList.end() &&
354 "Trying to get me to create degenerate basic block!");
356 BasicBlock *InsertBefore = std::next(Function::iterator(this))
357 .getNodePtrUnchecked();
358 BasicBlock *New = BasicBlock::Create(getContext(), BBName,
359 getParent(), InsertBefore);
361 // Move all of the specified instructions from the original basic block into
362 // the new basic block.
363 New->getInstList().splice(New->end(), this->getInstList(), I, end());
365 // Add a branch instruction to the newly formed basic block.
366 BranchInst::Create(New, this);
368 // Now we must loop through all of the successors of the New block (which
369 // _were_ the successors of the 'this' block), and update any PHI nodes in
370 // successors. If there were PHI nodes in the successors, then they need to
371 // know that incoming branches will be from New, not from Old.
373 for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
374 // Loop over any phi nodes in the basic block, updating the BB field of
375 // incoming values...
376 BasicBlock *Successor = *I;
378 for (BasicBlock::iterator II = Successor->begin();
379 (PN = dyn_cast<PHINode>(II)); ++II) {
380 int IDX = PN->getBasicBlockIndex(this);
382 PN->setIncomingBlock((unsigned)IDX, New);
383 IDX = PN->getBasicBlockIndex(this);
390 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
391 TerminatorInst *TI = getTerminator();
393 // Cope with being called on a BasicBlock that doesn't have a terminator
394 // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
396 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
397 BasicBlock *Succ = TI->getSuccessor(i);
398 // N.B. Succ might not be a complete BasicBlock, so don't assume
399 // that it ends with a non-phi instruction.
400 for (iterator II = Succ->begin(), IE = Succ->end(); II != IE; ++II) {
401 PHINode *PN = dyn_cast<PHINode>(II);
405 while ((i = PN->getBasicBlockIndex(this)) >= 0)
406 PN->setIncomingBlock(i, New);
411 /// Return true if this basic block is a landing pad. I.e., it's
412 /// the destination of the 'unwind' edge of an invoke instruction.
413 bool BasicBlock::isLandingPad() const {
414 return isa<LandingPadInst>(getFirstNonPHI());
417 /// Return the landingpad instruction associated with the landing pad.
418 LandingPadInst *BasicBlock::getLandingPadInst() {
419 return dyn_cast<LandingPadInst>(getFirstNonPHI());
421 const LandingPadInst *BasicBlock::getLandingPadInst() const {
422 return dyn_cast<LandingPadInst>(getFirstNonPHI());