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