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 /// 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 /// 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 /// 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 /// 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 BasicBlock *BasicBlock::getUniqueSuccessor() {
00243   succ_iterator SI = succ_begin(this), E = succ_end(this);
00244   if (SI == E) return NULL; // No successors
00245   BasicBlock *SuccBB = *SI;
00246   ++SI;
00247   for (;SI != E; ++SI) {
00248     if (*SI != SuccBB)
00249       return NULL;
00250     // The same successor appears multiple times in the successor list.
00251     // This is OK.
00252   }
00253   return SuccBB;
00254 }
00255 
00256 /// This method is used to notify a BasicBlock that the
00257 /// specified Predecessor of the block is no longer able to reach it.  This is
00258 /// actually not used to update the Predecessor list, but is actually used to
00259 /// update the PHI nodes that reside in the block.  Note that this should be
00260 /// called while the predecessor still refers to this block.
00261 ///
00262 void BasicBlock::removePredecessor(BasicBlock *Pred,
00263                                    bool DontDeleteUselessPHIs) {
00264   assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
00265           find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
00266          "removePredecessor: BB is not a predecessor!");
00267 
00268   if (InstList.empty()) return;
00269   PHINode *APN = dyn_cast<PHINode>(&front());
00270   if (!APN) return;   // Quick exit.
00271 
00272   // If there are exactly two predecessors, then we want to nuke the PHI nodes
00273   // altogether.  However, we cannot do this, if this in this case:
00274   //
00275   //  Loop:
00276   //    %x = phi [X, Loop]
00277   //    %x2 = add %x, 1         ;; This would become %x2 = add %x2, 1
00278   //    br Loop                 ;; %x2 does not dominate all uses
00279   //
00280   // This is because the PHI node input is actually taken from the predecessor
00281   // basic block.  The only case this can happen is with a self loop, so we
00282   // check for this case explicitly now.
00283   //
00284   unsigned max_idx = APN->getNumIncomingValues();
00285   assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
00286   if (max_idx == 2) {
00287     BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
00288 
00289     // Disable PHI elimination!
00290     if (this == Other) max_idx = 3;
00291   }
00292 
00293   // <= Two predecessors BEFORE I remove one?
00294   if (max_idx <= 2 && !DontDeleteUselessPHIs) {
00295     // Yup, loop through and nuke the PHI nodes
00296     while (PHINode *PN = dyn_cast<PHINode>(&front())) {
00297       // Remove the predecessor first.
00298       PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
00299 
00300       // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
00301       if (max_idx == 2) {
00302         if (PN->getIncomingValue(0) != PN)
00303           PN->replaceAllUsesWith(PN->getIncomingValue(0));
00304         else
00305           // We are left with an infinite loop with no entries: kill the PHI.
00306           PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
00307         getInstList().pop_front();    // Remove the PHI node
00308       }
00309 
00310       // If the PHI node already only had one entry, it got deleted by
00311       // removeIncomingValue.
00312     }
00313   } else {
00314     // Okay, now we know that we need to remove predecessor #pred_idx from all
00315     // PHI nodes.  Iterate over each PHI node fixing them up
00316     PHINode *PN;
00317     for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
00318       ++II;
00319       PN->removeIncomingValue(Pred, false);
00320       // If all incoming values to the Phi are the same, we can replace the Phi
00321       // with that value.
00322       Value* PNV = nullptr;
00323       if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue()))
00324         if (PNV != PN) {
00325           PN->replaceAllUsesWith(PNV);
00326           PN->eraseFromParent();
00327         }
00328     }
00329   }
00330 }
00331 
00332 
00333 /// This splits a basic block into two at the specified
00334 /// instruction.  Note that all instructions BEFORE the specified iterator stay
00335 /// as part of the original basic block, an unconditional branch is added to
00336 /// the new BB, and the rest of the instructions in the BB are moved to the new
00337 /// BB, including the old terminator.  This invalidates the iterator.
00338 ///
00339 /// Note that this only works on well formed basic blocks (must have a
00340 /// terminator), and 'I' must not be the end of instruction list (which would
00341 /// cause a degenerate basic block to be formed, having a terminator inside of
00342 /// the basic block).
00343 ///
00344 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
00345   assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
00346   assert(I != InstList.end() &&
00347          "Trying to get me to create degenerate basic block!");
00348 
00349   BasicBlock *InsertBefore = std::next(Function::iterator(this))
00350                                .getNodePtrUnchecked();
00351   BasicBlock *New = BasicBlock::Create(getContext(), BBName,
00352                                        getParent(), InsertBefore);
00353 
00354   // Move all of the specified instructions from the original basic block into
00355   // the new basic block.
00356   New->getInstList().splice(New->end(), this->getInstList(), I, end());
00357 
00358   // Add a branch instruction to the newly formed basic block.
00359   BranchInst::Create(New, this);
00360 
00361   // Now we must loop through all of the successors of the New block (which
00362   // _were_ the successors of the 'this' block), and update any PHI nodes in
00363   // successors.  If there were PHI nodes in the successors, then they need to
00364   // know that incoming branches will be from New, not from Old.
00365   //
00366   for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
00367     // Loop over any phi nodes in the basic block, updating the BB field of
00368     // incoming values...
00369     BasicBlock *Successor = *I;
00370     PHINode *PN;
00371     for (BasicBlock::iterator II = Successor->begin();
00372          (PN = dyn_cast<PHINode>(II)); ++II) {
00373       int IDX = PN->getBasicBlockIndex(this);
00374       while (IDX != -1) {
00375         PN->setIncomingBlock((unsigned)IDX, New);
00376         IDX = PN->getBasicBlockIndex(this);
00377       }
00378     }
00379   }
00380   return New;
00381 }
00382 
00383 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
00384   TerminatorInst *TI = getTerminator();
00385   if (!TI)
00386     // Cope with being called on a BasicBlock that doesn't have a terminator
00387     // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
00388     return;
00389   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
00390     BasicBlock *Succ = TI->getSuccessor(i);
00391     // N.B. Succ might not be a complete BasicBlock, so don't assume
00392     // that it ends with a non-phi instruction.
00393     for (iterator II = Succ->begin(), IE = Succ->end(); II != IE; ++II) {
00394       PHINode *PN = dyn_cast<PHINode>(II);
00395       if (!PN)
00396         break;
00397       int i;
00398       while ((i = PN->getBasicBlockIndex(this)) >= 0)
00399         PN->setIncomingBlock(i, New);
00400     }
00401   }
00402 }
00403 
00404 /// Return true if this basic block is a landing pad. I.e., it's
00405 /// the destination of the 'unwind' edge of an invoke instruction.
00406 bool BasicBlock::isLandingPad() const {
00407   return isa<LandingPadInst>(getFirstNonPHI());
00408 }
00409 
00410 /// Return the landingpad instruction associated with the landing pad.
00411 LandingPadInst *BasicBlock::getLandingPadInst() {
00412   return dyn_cast<LandingPadInst>(getFirstNonPHI());
00413 }
00414 const LandingPadInst *BasicBlock::getLandingPadInst() const {
00415   return dyn_cast<LandingPadInst>(getFirstNonPHI());
00416 }