LLVM API Documentation

BasicBlock.cpp
Go to the documentation of this file.
00001 //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the BasicBlock class for the IR library.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/IR/BasicBlock.h"
00015 #include "SymbolTableListTraitsImpl.h"
00016 #include "llvm/ADT/STLExtras.h"
00017 #include "llvm/IR/CFG.h"
00018 #include "llvm/IR/Constants.h"
00019 #include "llvm/IR/Instructions.h"
00020 #include "llvm/IR/IntrinsicInst.h"
00021 #include "llvm/IR/LLVMContext.h"
00022 #include "llvm/IR/Type.h"
00023 #include <algorithm>
00024 using namespace llvm;
00025 
00026 ValueSymbolTable *BasicBlock::getValueSymbolTable() {
00027   if (Function *F = getParent())
00028     return &F->getValueSymbolTable();
00029   return nullptr;
00030 }
00031 
00032 const DataLayout *BasicBlock::getDataLayout() const {
00033   return getParent()->getDataLayout();
00034 }
00035 
00036 LLVMContext &BasicBlock::getContext() const {
00037   return getType()->getContext();
00038 }
00039 
00040 // Explicit instantiation of SymbolTableListTraits since some of the methods
00041 // are not in the public header file...
00042 template class llvm::SymbolTableListTraits<Instruction, BasicBlock>;
00043 
00044 
00045 BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
00046                        BasicBlock *InsertBefore)
00047   : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(nullptr) {
00048 
00049   if (NewParent)
00050     insertInto(NewParent, InsertBefore);
00051   else
00052     assert(!InsertBefore &&
00053            "Cannot insert block before another block with no function!");
00054 
00055   setName(Name);
00056 }
00057 
00058 void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) {
00059   assert(NewParent && "Expected a parent");
00060   assert(!Parent && "Already has a parent");
00061 
00062   if (InsertBefore)
00063     NewParent->getBasicBlockList().insert(InsertBefore, this);
00064   else
00065     NewParent->getBasicBlockList().push_back(this);
00066 }
00067 
00068 BasicBlock::~BasicBlock() {
00069   // If the address of the block is taken and it is being deleted (e.g. because
00070   // it is dead), this means that there is either a dangling constant expr
00071   // hanging off the block, or an undefined use of the block (source code
00072   // expecting the address of a label to keep the block alive even though there
00073   // is no indirect branch).  Handle these cases by zapping the BlockAddress
00074   // nodes.  There are no other possible uses at this point.
00075   if (hasAddressTaken()) {
00076     assert(!use_empty() && "There should be at least one blockaddress!");
00077     Constant *Replacement =
00078       ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
00079     while (!use_empty()) {
00080       BlockAddress *BA = cast<BlockAddress>(user_back());
00081       BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
00082                                                        BA->getType()));
00083       BA->destroyConstant();
00084     }
00085   }
00086 
00087   assert(getParent() == nullptr && "BasicBlock still linked into the program!");
00088   dropAllReferences();
00089   InstList.clear();
00090 }
00091 
00092 void BasicBlock::setParent(Function *parent) {
00093   // Set Parent=parent, updating instruction symtab entries as appropriate.
00094   InstList.setSymTabObject(&Parent, parent);
00095 }
00096 
00097 void BasicBlock::removeFromParent() {
00098   getParent()->getBasicBlockList().remove(this);
00099 }
00100 
00101 void BasicBlock::eraseFromParent() {
00102   getParent()->getBasicBlockList().erase(this);
00103 }
00104 
00105 /// moveBefore - Unlink this basic block from its current function and
00106 /// insert it into the function that MovePos lives in, right before MovePos.
00107 void BasicBlock::moveBefore(BasicBlock *MovePos) {
00108   MovePos->getParent()->getBasicBlockList().splice(MovePos,
00109                        getParent()->getBasicBlockList(), this);
00110 }
00111 
00112 /// moveAfter - Unlink this basic block from its current function and
00113 /// insert it into the function that MovePos lives in, right after MovePos.
00114 void BasicBlock::moveAfter(BasicBlock *MovePos) {
00115   Function::iterator I = MovePos;
00116   MovePos->getParent()->getBasicBlockList().splice(++I,
00117                                        getParent()->getBasicBlockList(), this);
00118 }
00119 
00120 
00121 TerminatorInst *BasicBlock::getTerminator() {
00122   if (InstList.empty()) return nullptr;
00123   return dyn_cast<TerminatorInst>(&InstList.back());
00124 }
00125 
00126 const TerminatorInst *BasicBlock::getTerminator() const {
00127   if (InstList.empty()) return nullptr;
00128   return dyn_cast<TerminatorInst>(&InstList.back());
00129 }
00130 
00131 CallInst *BasicBlock::getTerminatingMustTailCall() {
00132   if (InstList.empty())
00133     return nullptr;
00134   ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
00135   if (!RI || RI == &InstList.front())
00136     return nullptr;
00137 
00138   Instruction *Prev = RI->getPrevNode();
00139   if (!Prev)
00140     return nullptr;
00141 
00142   if (Value *RV = RI->getReturnValue()) {
00143     if (RV != Prev)
00144       return nullptr;
00145 
00146     // Look through the optional bitcast.
00147     if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
00148       RV = BI->getOperand(0);
00149       Prev = BI->getPrevNode();
00150       if (!Prev || RV != Prev)
00151         return nullptr;
00152     }
00153   }
00154 
00155   if (auto *CI = dyn_cast<CallInst>(Prev)) {
00156     if (CI->isMustTailCall())
00157       return CI;
00158   }
00159   return nullptr;
00160 }
00161 
00162 Instruction* BasicBlock::getFirstNonPHI() {
00163   BasicBlock::iterator i = begin();
00164   // All valid basic blocks should have a terminator,
00165   // which is not a PHINode. If we have an invalid basic
00166   // block we'll get an assertion failure when dereferencing
00167   // a past-the-end iterator.
00168   while (isa<PHINode>(i)) ++i;
00169   return &*i;
00170 }
00171 
00172 Instruction* BasicBlock::getFirstNonPHIOrDbg() {
00173   BasicBlock::iterator i = begin();
00174   // All valid basic blocks should have a terminator,
00175   // which is not a PHINode. If we have an invalid basic
00176   // block we'll get an assertion failure when dereferencing
00177   // a past-the-end iterator.
00178   while (isa<PHINode>(i) || isa<DbgInfoIntrinsic>(i)) ++i;
00179   return &*i;
00180 }
00181 
00182 Instruction* BasicBlock::getFirstNonPHIOrDbgOrLifetime() {
00183   // All valid basic blocks should have a terminator,
00184   // which is not a PHINode. If we have an invalid basic
00185   // block we'll get an assertion failure when dereferencing
00186   // a past-the-end iterator.
00187   BasicBlock::iterator i = begin();
00188   for (;; ++i) {
00189     if (isa<PHINode>(i) || isa<DbgInfoIntrinsic>(i))
00190       continue;
00191 
00192     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(i);
00193     if (!II)
00194       break;
00195     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
00196         II->getIntrinsicID() != Intrinsic::lifetime_end)
00197       break;
00198   }
00199   return &*i;
00200 }
00201 
00202 BasicBlock::iterator BasicBlock::getFirstInsertionPt() {
00203   iterator InsertPt = getFirstNonPHI();
00204   if (isa<LandingPadInst>(InsertPt)) ++InsertPt;
00205   return InsertPt;
00206 }
00207 
00208 void BasicBlock::dropAllReferences() {
00209   for(iterator I = begin(), E = end(); I != E; ++I)
00210     I->dropAllReferences();
00211 }
00212 
00213 /// getSinglePredecessor - If this basic block has a single predecessor block,
00214 /// return the block, otherwise return a null pointer.
00215 BasicBlock *BasicBlock::getSinglePredecessor() {
00216   pred_iterator PI = pred_begin(this), E = pred_end(this);
00217   if (PI == E) return nullptr;         // No preds.
00218   BasicBlock *ThePred = *PI;
00219   ++PI;
00220   return (PI == E) ? ThePred : nullptr /*multiple preds*/;
00221 }
00222 
00223 /// getUniquePredecessor - If this basic block has a unique predecessor block,
00224 /// return the block, otherwise return a null pointer.
00225 /// Note that unique predecessor doesn't mean single edge, there can be
00226 /// multiple edges from the unique predecessor to this block (for example
00227 /// a switch statement with multiple cases having the same destination).
00228 BasicBlock *BasicBlock::getUniquePredecessor() {
00229   pred_iterator PI = pred_begin(this), E = pred_end(this);
00230   if (PI == E) return nullptr; // No preds.
00231   BasicBlock *PredBB = *PI;
00232   ++PI;
00233   for (;PI != E; ++PI) {
00234     if (*PI != PredBB)
00235       return nullptr;
00236     // The same predecessor appears multiple times in the predecessor list.
00237     // This is OK.
00238   }
00239   return PredBB;
00240 }
00241 
00242 /// removePredecessor - This method is used to notify a BasicBlock that the
00243 /// specified Predecessor of the block is no longer able to reach it.  This is
00244 /// actually not used to update the Predecessor list, but is actually used to
00245 /// update the PHI nodes that reside in the block.  Note that this should be
00246 /// called while the predecessor still refers to this block.
00247 ///
00248 void BasicBlock::removePredecessor(BasicBlock *Pred,
00249                                    bool DontDeleteUselessPHIs) {
00250   assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
00251           find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
00252          "removePredecessor: BB is not a predecessor!");
00253 
00254   if (InstList.empty()) return;
00255   PHINode *APN = dyn_cast<PHINode>(&front());
00256   if (!APN) return;   // Quick exit.
00257 
00258   // If there are exactly two predecessors, then we want to nuke the PHI nodes
00259   // altogether.  However, we cannot do this, if this in this case:
00260   //
00261   //  Loop:
00262   //    %x = phi [X, Loop]
00263   //    %x2 = add %x, 1         ;; This would become %x2 = add %x2, 1
00264   //    br Loop                 ;; %x2 does not dominate all uses
00265   //
00266   // This is because the PHI node input is actually taken from the predecessor
00267   // basic block.  The only case this can happen is with a self loop, so we
00268   // check for this case explicitly now.
00269   //
00270   unsigned max_idx = APN->getNumIncomingValues();
00271   assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
00272   if (max_idx == 2) {
00273     BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
00274 
00275     // Disable PHI elimination!
00276     if (this == Other) max_idx = 3;
00277   }
00278 
00279   // <= Two predecessors BEFORE I remove one?
00280   if (max_idx <= 2 && !DontDeleteUselessPHIs) {
00281     // Yup, loop through and nuke the PHI nodes
00282     while (PHINode *PN = dyn_cast<PHINode>(&front())) {
00283       // Remove the predecessor first.
00284       PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
00285 
00286       // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
00287       if (max_idx == 2) {
00288         if (PN->getIncomingValue(0) != PN)
00289           PN->replaceAllUsesWith(PN->getIncomingValue(0));
00290         else
00291           // We are left with an infinite loop with no entries: kill the PHI.
00292           PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
00293         getInstList().pop_front();    // Remove the PHI node
00294       }
00295 
00296       // If the PHI node already only had one entry, it got deleted by
00297       // removeIncomingValue.
00298     }
00299   } else {
00300     // Okay, now we know that we need to remove predecessor #pred_idx from all
00301     // PHI nodes.  Iterate over each PHI node fixing them up
00302     PHINode *PN;
00303     for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
00304       ++II;
00305       PN->removeIncomingValue(Pred, false);
00306       // If all incoming values to the Phi are the same, we can replace the Phi
00307       // with that value.
00308       Value* PNV = nullptr;
00309       if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue()))
00310         if (PNV != PN) {
00311           PN->replaceAllUsesWith(PNV);
00312           PN->eraseFromParent();
00313         }
00314     }
00315   }
00316 }
00317 
00318 
00319 /// splitBasicBlock - This splits a basic block into two at the specified
00320 /// instruction.  Note that all instructions BEFORE the specified iterator stay
00321 /// as part of the original basic block, an unconditional branch is added to
00322 /// the new BB, and the rest of the instructions in the BB are moved to the new
00323 /// BB, including the old terminator.  This invalidates the iterator.
00324 ///
00325 /// Note that this only works on well formed basic blocks (must have a
00326 /// terminator), and 'I' must not be the end of instruction list (which would
00327 /// cause a degenerate basic block to be formed, having a terminator inside of
00328 /// the basic block).
00329 ///
00330 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
00331   assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
00332   assert(I != InstList.end() &&
00333          "Trying to get me to create degenerate basic block!");
00334 
00335   BasicBlock *InsertBefore = std::next(Function::iterator(this))
00336                                .getNodePtrUnchecked();
00337   BasicBlock *New = BasicBlock::Create(getContext(), BBName,
00338                                        getParent(), InsertBefore);
00339 
00340   // Move all of the specified instructions from the original basic block into
00341   // the new basic block.
00342   New->getInstList().splice(New->end(), this->getInstList(), I, end());
00343 
00344   // Add a branch instruction to the newly formed basic block.
00345   BranchInst::Create(New, this);
00346 
00347   // Now we must loop through all of the successors of the New block (which
00348   // _were_ the successors of the 'this' block), and update any PHI nodes in
00349   // successors.  If there were PHI nodes in the successors, then they need to
00350   // know that incoming branches will be from New, not from Old.
00351   //
00352   for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
00353     // Loop over any phi nodes in the basic block, updating the BB field of
00354     // incoming values...
00355     BasicBlock *Successor = *I;
00356     PHINode *PN;
00357     for (BasicBlock::iterator II = Successor->begin();
00358          (PN = dyn_cast<PHINode>(II)); ++II) {
00359       int IDX = PN->getBasicBlockIndex(this);
00360       while (IDX != -1) {
00361         PN->setIncomingBlock((unsigned)IDX, New);
00362         IDX = PN->getBasicBlockIndex(this);
00363       }
00364     }
00365   }
00366   return New;
00367 }
00368 
00369 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
00370   TerminatorInst *TI = getTerminator();
00371   if (!TI)
00372     // Cope with being called on a BasicBlock that doesn't have a terminator
00373     // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
00374     return;
00375   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
00376     BasicBlock *Succ = TI->getSuccessor(i);
00377     // N.B. Succ might not be a complete BasicBlock, so don't assume
00378     // that it ends with a non-phi instruction.
00379     for (iterator II = Succ->begin(), IE = Succ->end(); II != IE; ++II) {
00380       PHINode *PN = dyn_cast<PHINode>(II);
00381       if (!PN)
00382         break;
00383       int i;
00384       while ((i = PN->getBasicBlockIndex(this)) >= 0)
00385         PN->setIncomingBlock(i, New);
00386     }
00387   }
00388 }
00389 
00390 /// isLandingPad - Return true if this basic block is a landing pad. I.e., it's
00391 /// the destination of the 'unwind' edge of an invoke instruction.
00392 bool BasicBlock::isLandingPad() const {
00393   return isa<LandingPadInst>(getFirstNonPHI());
00394 }
00395 
00396 /// getLandingPadInst() - Return the landingpad instruction associated with
00397 /// the landing pad.
00398 LandingPadInst *BasicBlock::getLandingPadInst() {
00399   return dyn_cast<LandingPadInst>(getFirstNonPHI());
00400 }
00401 const LandingPadInst *BasicBlock::getLandingPadInst() const {
00402   return dyn_cast<LandingPadInst>(getFirstNonPHI());
00403 }