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 const DataLayout *BasicBlock::getDataLayout() const {
33 return getParent()->getDataLayout();
36 LLVMContext &BasicBlock::getContext() const {
37 return getType()->getContext();
40 // Explicit instantiation of SymbolTableListTraits since some of the methods
41 // are not in the public header file...
42 template class llvm::SymbolTableListTraits<Instruction, BasicBlock>;
45 BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
46 BasicBlock *InsertBefore)
47 : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(nullptr) {
50 insertInto(NewParent, InsertBefore);
52 assert(!InsertBefore &&
53 "Cannot insert block before another block with no function!");
58 void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) {
59 assert(NewParent && "Expected a parent");
60 assert(!Parent && "Already has a parent");
63 NewParent->getBasicBlockList().insert(InsertBefore, this);
65 NewParent->getBasicBlockList().push_back(this);
68 BasicBlock::~BasicBlock() {
69 // If the address of the block is taken and it is being deleted (e.g. because
70 // it is dead), this means that there is either a dangling constant expr
71 // hanging off the block, or an undefined use of the block (source code
72 // expecting the address of a label to keep the block alive even though there
73 // is no indirect branch). Handle these cases by zapping the BlockAddress
74 // nodes. There are no other possible uses at this point.
75 if (hasAddressTaken()) {
76 assert(!use_empty() && "There should be at least one blockaddress!");
77 Constant *Replacement =
78 ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
79 while (!use_empty()) {
80 BlockAddress *BA = cast<BlockAddress>(user_back());
81 BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
83 BA->destroyConstant();
87 assert(getParent() == nullptr && "BasicBlock still linked into the program!");
92 void BasicBlock::setParent(Function *parent) {
93 // Set Parent=parent, updating instruction symtab entries as appropriate.
94 InstList.setSymTabObject(&Parent, parent);
97 void BasicBlock::removeFromParent() {
98 getParent()->getBasicBlockList().remove(this);
101 void BasicBlock::eraseFromParent() {
102 getParent()->getBasicBlockList().erase(this);
105 /// moveBefore - Unlink this basic block from its current function and
106 /// insert it into the function that MovePos lives in, right before MovePos.
107 void BasicBlock::moveBefore(BasicBlock *MovePos) {
108 MovePos->getParent()->getBasicBlockList().splice(MovePos,
109 getParent()->getBasicBlockList(), this);
112 /// moveAfter - Unlink this basic block from its current function and
113 /// insert it into the function that MovePos lives in, right after MovePos.
114 void BasicBlock::moveAfter(BasicBlock *MovePos) {
115 Function::iterator I = MovePos;
116 MovePos->getParent()->getBasicBlockList().splice(++I,
117 getParent()->getBasicBlockList(), this);
121 TerminatorInst *BasicBlock::getTerminator() {
122 if (InstList.empty()) return nullptr;
123 return dyn_cast<TerminatorInst>(&InstList.back());
126 const TerminatorInst *BasicBlock::getTerminator() const {
127 if (InstList.empty()) return nullptr;
128 return dyn_cast<TerminatorInst>(&InstList.back());
131 CallInst *BasicBlock::getTerminatingMustTailCall() {
132 if (InstList.empty())
134 ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
135 if (!RI || RI == &InstList.front())
138 Instruction *Prev = RI->getPrevNode();
142 if (Value *RV = RI->getReturnValue()) {
146 // Look through the optional bitcast.
147 if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
148 RV = BI->getOperand(0);
149 Prev = BI->getPrevNode();
150 if (!Prev || RV != Prev)
155 if (auto *CI = dyn_cast<CallInst>(Prev)) {
156 if (CI->isMustTailCall())
162 Instruction* BasicBlock::getFirstNonPHI() {
163 BasicBlock::iterator i = begin();
164 // All valid basic blocks should have a terminator,
165 // which is not a PHINode. If we have an invalid basic
166 // block we'll get an assertion failure when dereferencing
167 // a past-the-end iterator.
168 while (isa<PHINode>(i)) ++i;
172 Instruction* BasicBlock::getFirstNonPHIOrDbg() {
173 BasicBlock::iterator i = begin();
174 // All valid basic blocks should have a terminator,
175 // which is not a PHINode. If we have an invalid basic
176 // block we'll get an assertion failure when dereferencing
177 // a past-the-end iterator.
178 while (isa<PHINode>(i) || isa<DbgInfoIntrinsic>(i)) ++i;
182 Instruction* BasicBlock::getFirstNonPHIOrDbgOrLifetime() {
183 // All valid basic blocks should have a terminator,
184 // which is not a PHINode. If we have an invalid basic
185 // block we'll get an assertion failure when dereferencing
186 // a past-the-end iterator.
187 BasicBlock::iterator i = begin();
189 if (isa<PHINode>(i) || isa<DbgInfoIntrinsic>(i))
192 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(i);
195 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
196 II->getIntrinsicID() != Intrinsic::lifetime_end)
202 BasicBlock::iterator BasicBlock::getFirstInsertionPt() {
203 iterator InsertPt = getFirstNonPHI();
204 if (isa<LandingPadInst>(InsertPt)) ++InsertPt;
208 void BasicBlock::dropAllReferences() {
209 for(iterator I = begin(), E = end(); I != E; ++I)
210 I->dropAllReferences();
213 /// getSinglePredecessor - If this basic block has a single predecessor block,
214 /// return the block, otherwise return a null pointer.
215 BasicBlock *BasicBlock::getSinglePredecessor() {
216 pred_iterator PI = pred_begin(this), E = pred_end(this);
217 if (PI == E) return nullptr; // No preds.
218 BasicBlock *ThePred = *PI;
220 return (PI == E) ? ThePred : nullptr /*multiple preds*/;
223 /// getUniquePredecessor - If this basic block has a unique predecessor block,
224 /// return the block, otherwise return a null pointer.
225 /// Note that unique predecessor doesn't mean single edge, there can be
226 /// multiple edges from the unique predecessor to this block (for example
227 /// a switch statement with multiple cases having the same destination).
228 BasicBlock *BasicBlock::getUniquePredecessor() {
229 pred_iterator PI = pred_begin(this), E = pred_end(this);
230 if (PI == E) return nullptr; // No preds.
231 BasicBlock *PredBB = *PI;
233 for (;PI != E; ++PI) {
236 // The same predecessor appears multiple times in the predecessor list.
242 BasicBlock *BasicBlock::getUniqueSuccessor() {
243 succ_iterator SI = succ_begin(this), E = succ_end(this);
244 if (SI == E) return NULL; // No successors
245 BasicBlock *SuccBB = *SI;
247 for (;SI != E; ++SI) {
250 // The same successor appears multiple times in the successor list.
256 /// removePredecessor - This method is used to notify a BasicBlock that the
257 /// specified Predecessor of the block is no longer able to reach it. This is
258 /// actually not used to update the Predecessor list, but is actually used to
259 /// update the PHI nodes that reside in the block. Note that this should be
260 /// called while the predecessor still refers to this block.
262 void BasicBlock::removePredecessor(BasicBlock *Pred,
263 bool DontDeleteUselessPHIs) {
264 assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
265 find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
266 "removePredecessor: BB is not a predecessor!");
268 if (InstList.empty()) return;
269 PHINode *APN = dyn_cast<PHINode>(&front());
270 if (!APN) return; // Quick exit.
272 // If there are exactly two predecessors, then we want to nuke the PHI nodes
273 // altogether. However, we cannot do this, if this in this case:
276 // %x = phi [X, Loop]
277 // %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1
278 // br Loop ;; %x2 does not dominate all uses
280 // This is because the PHI node input is actually taken from the predecessor
281 // basic block. The only case this can happen is with a self loop, so we
282 // check for this case explicitly now.
284 unsigned max_idx = APN->getNumIncomingValues();
285 assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
287 BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
289 // Disable PHI elimination!
290 if (this == Other) max_idx = 3;
293 // <= Two predecessors BEFORE I remove one?
294 if (max_idx <= 2 && !DontDeleteUselessPHIs) {
295 // Yup, loop through and nuke the PHI nodes
296 while (PHINode *PN = dyn_cast<PHINode>(&front())) {
297 // Remove the predecessor first.
298 PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
300 // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
302 if (PN->getIncomingValue(0) != PN)
303 PN->replaceAllUsesWith(PN->getIncomingValue(0));
305 // We are left with an infinite loop with no entries: kill the PHI.
306 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
307 getInstList().pop_front(); // Remove the PHI node
310 // If the PHI node already only had one entry, it got deleted by
311 // removeIncomingValue.
314 // Okay, now we know that we need to remove predecessor #pred_idx from all
315 // PHI nodes. Iterate over each PHI node fixing them up
317 for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
319 PN->removeIncomingValue(Pred, false);
320 // If all incoming values to the Phi are the same, we can replace the Phi
322 Value* PNV = nullptr;
323 if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue()))
325 PN->replaceAllUsesWith(PNV);
326 PN->eraseFromParent();
333 /// splitBasicBlock - This splits a basic block into two at the specified
334 /// instruction. Note that all instructions BEFORE the specified iterator stay
335 /// as part of the original basic block, an unconditional branch is added to
336 /// the new BB, and the rest of the instructions in the BB are moved to the new
337 /// BB, including the old terminator. This invalidates the iterator.
339 /// Note that this only works on well formed basic blocks (must have a
340 /// terminator), and 'I' must not be the end of instruction list (which would
341 /// cause a degenerate basic block to be formed, having a terminator inside of
342 /// the basic block).
344 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
345 assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
346 assert(I != InstList.end() &&
347 "Trying to get me to create degenerate basic block!");
349 BasicBlock *InsertBefore = std::next(Function::iterator(this))
350 .getNodePtrUnchecked();
351 BasicBlock *New = BasicBlock::Create(getContext(), BBName,
352 getParent(), InsertBefore);
354 // Move all of the specified instructions from the original basic block into
355 // the new basic block.
356 New->getInstList().splice(New->end(), this->getInstList(), I, end());
358 // Add a branch instruction to the newly formed basic block.
359 BranchInst::Create(New, this);
361 // Now we must loop through all of the successors of the New block (which
362 // _were_ the successors of the 'this' block), and update any PHI nodes in
363 // successors. If there were PHI nodes in the successors, then they need to
364 // know that incoming branches will be from New, not from Old.
366 for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
367 // Loop over any phi nodes in the basic block, updating the BB field of
368 // incoming values...
369 BasicBlock *Successor = *I;
371 for (BasicBlock::iterator II = Successor->begin();
372 (PN = dyn_cast<PHINode>(II)); ++II) {
373 int IDX = PN->getBasicBlockIndex(this);
375 PN->setIncomingBlock((unsigned)IDX, New);
376 IDX = PN->getBasicBlockIndex(this);
383 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
384 TerminatorInst *TI = getTerminator();
386 // Cope with being called on a BasicBlock that doesn't have a terminator
387 // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
389 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
390 BasicBlock *Succ = TI->getSuccessor(i);
391 // N.B. Succ might not be a complete BasicBlock, so don't assume
392 // that it ends with a non-phi instruction.
393 for (iterator II = Succ->begin(), IE = Succ->end(); II != IE; ++II) {
394 PHINode *PN = dyn_cast<PHINode>(II);
398 while ((i = PN->getBasicBlockIndex(this)) >= 0)
399 PN->setIncomingBlock(i, New);
404 /// isLandingPad - Return true if this basic block is a landing pad. I.e., it's
405 /// the destination of the 'unwind' edge of an invoke instruction.
406 bool BasicBlock::isLandingPad() const {
407 return isa<LandingPadInst>(getFirstNonPHI());
410 /// getLandingPadInst() - Return the landingpad instruction associated with
412 LandingPadInst *BasicBlock::getLandingPadInst() {
413 return dyn_cast<LandingPadInst>(getFirstNonPHI());
415 const LandingPadInst *BasicBlock::getLandingPadInst() const {
416 return dyn_cast<LandingPadInst>(getFirstNonPHI());