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 Module *BasicBlock::getModule() {
00121   return getParent()->getParent();
00122 }
00123 
00124 TerminatorInst *BasicBlock::getTerminator() {
00125   if (InstList.empty()) return nullptr;
00126   return dyn_cast<TerminatorInst>(&InstList.back());
00127 }
00128 
00129 const TerminatorInst *BasicBlock::getTerminator() const {
00130   if (InstList.empty()) return nullptr;
00131   return dyn_cast<TerminatorInst>(&InstList.back());
00132 }
00133 
00134 CallInst *BasicBlock::getTerminatingMustTailCall() {
00135   if (InstList.empty())
00136     return nullptr;
00137   ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
00138   if (!RI || RI == &InstList.front())
00139     return nullptr;
00140 
00141   Instruction *Prev = RI->getPrevNode();
00142   if (!Prev)
00143     return nullptr;
00144 
00145   if (Value *RV = RI->getReturnValue()) {
00146     if (RV != Prev)
00147       return nullptr;
00148 
00149     // Look through the optional bitcast.
00150     if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
00151       RV = BI->getOperand(0);
00152       Prev = BI->getPrevNode();
00153       if (!Prev || RV != Prev)
00154         return nullptr;
00155     }
00156   }
00157 
00158   if (auto *CI = dyn_cast<CallInst>(Prev)) {
00159     if (CI->isMustTailCall())
00160       return CI;
00161   }
00162   return nullptr;
00163 }
00164 
00165 Instruction* BasicBlock::getFirstNonPHI() {
00166   BasicBlock::iterator i = begin();
00167   // All valid basic blocks should have a terminator,
00168   // which is not a PHINode. If we have an invalid basic
00169   // block we'll get an assertion failure when dereferencing
00170   // a past-the-end iterator.
00171   while (isa<PHINode>(i)) ++i;
00172   return &*i;
00173 }
00174 
00175 Instruction* BasicBlock::getFirstNonPHIOrDbg() {
00176   BasicBlock::iterator i = begin();
00177   // All valid basic blocks should have a terminator,
00178   // which is not a PHINode. If we have an invalid basic
00179   // block we'll get an assertion failure when dereferencing
00180   // a past-the-end iterator.
00181   while (isa<PHINode>(i) || isa<DbgInfoIntrinsic>(i)) ++i;
00182   return &*i;
00183 }
00184 
00185 Instruction* BasicBlock::getFirstNonPHIOrDbgOrLifetime() {
00186   // All valid basic blocks should have a terminator,
00187   // which is not a PHINode. If we have an invalid basic
00188   // block we'll get an assertion failure when dereferencing
00189   // a past-the-end iterator.
00190   BasicBlock::iterator i = begin();
00191   for (;; ++i) {
00192     if (isa<PHINode>(i) || isa<DbgInfoIntrinsic>(i))
00193       continue;
00194 
00195     const IntrinsicInst *II = dyn_cast<IntrinsicInst>(i);
00196     if (!II)
00197       break;
00198     if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
00199         II->getIntrinsicID() != Intrinsic::lifetime_end)
00200       break;
00201   }
00202   return &*i;
00203 }
00204 
00205 BasicBlock::iterator BasicBlock::getFirstInsertionPt() {
00206   iterator InsertPt = getFirstNonPHI();
00207   if (isa<LandingPadInst>(InsertPt)) ++InsertPt;
00208   return InsertPt;
00209 }
00210 
00211 void BasicBlock::dropAllReferences() {
00212   for(iterator I = begin(), E = end(); I != E; ++I)
00213     I->dropAllReferences();
00214 }
00215 
00216 /// If this basic block has a single predecessor block,
00217 /// return the block, otherwise return a null pointer.
00218 BasicBlock *BasicBlock::getSinglePredecessor() {
00219   pred_iterator PI = pred_begin(this), E = pred_end(this);
00220   if (PI == E) return nullptr;         // No preds.
00221   BasicBlock *ThePred = *PI;
00222   ++PI;
00223   return (PI == E) ? ThePred : nullptr /*multiple preds*/;
00224 }
00225 
00226 /// If this basic block has a unique predecessor block,
00227 /// return the block, otherwise return a null pointer.
00228 /// Note that unique predecessor doesn't mean single edge, there can be
00229 /// multiple edges from the unique predecessor to this block (for example
00230 /// a switch statement with multiple cases having the same destination).
00231 BasicBlock *BasicBlock::getUniquePredecessor() {
00232   pred_iterator PI = pred_begin(this), E = pred_end(this);
00233   if (PI == E) return nullptr; // No preds.
00234   BasicBlock *PredBB = *PI;
00235   ++PI;
00236   for (;PI != E; ++PI) {
00237     if (*PI != PredBB)
00238       return nullptr;
00239     // The same predecessor appears multiple times in the predecessor list.
00240     // This is OK.
00241   }
00242   return PredBB;
00243 }
00244 
00245 BasicBlock *BasicBlock::getSingleSuccessor() {
00246   succ_iterator SI = succ_begin(this), E = succ_end(this);
00247   if (SI == E) return nullptr; // no successors
00248   BasicBlock *TheSucc = *SI;
00249   ++SI;
00250   return (SI == E) ? TheSucc : nullptr /* multiple successors */;
00251 }
00252 
00253 BasicBlock *BasicBlock::getUniqueSuccessor() {
00254   succ_iterator SI = succ_begin(this), E = succ_end(this);
00255   if (SI == E) return NULL; // No successors
00256   BasicBlock *SuccBB = *SI;
00257   ++SI;
00258   for (;SI != E; ++SI) {
00259     if (*SI != SuccBB)
00260       return NULL;
00261     // The same successor appears multiple times in the successor list.
00262     // This is OK.
00263   }
00264   return SuccBB;
00265 }
00266 
00267 /// This method is used to notify a BasicBlock that the
00268 /// specified Predecessor of the block is no longer able to reach it.  This is
00269 /// actually not used to update the Predecessor list, but is actually used to
00270 /// update the PHI nodes that reside in the block.  Note that this should be
00271 /// called while the predecessor still refers to this block.
00272 ///
00273 void BasicBlock::removePredecessor(BasicBlock *Pred,
00274                                    bool DontDeleteUselessPHIs) {
00275   assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
00276           find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
00277          "removePredecessor: BB is not a predecessor!");
00278 
00279   if (InstList.empty()) return;
00280   PHINode *APN = dyn_cast<PHINode>(&front());
00281   if (!APN) return;   // Quick exit.
00282 
00283   // If there are exactly two predecessors, then we want to nuke the PHI nodes
00284   // altogether.  However, we cannot do this, if this in this case:
00285   //
00286   //  Loop:
00287   //    %x = phi [X, Loop]
00288   //    %x2 = add %x, 1         ;; This would become %x2 = add %x2, 1
00289   //    br Loop                 ;; %x2 does not dominate all uses
00290   //
00291   // This is because the PHI node input is actually taken from the predecessor
00292   // basic block.  The only case this can happen is with a self loop, so we
00293   // check for this case explicitly now.
00294   //
00295   unsigned max_idx = APN->getNumIncomingValues();
00296   assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
00297   if (max_idx == 2) {
00298     BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
00299 
00300     // Disable PHI elimination!
00301     if (this == Other) max_idx = 3;
00302   }
00303 
00304   // <= Two predecessors BEFORE I remove one?
00305   if (max_idx <= 2 && !DontDeleteUselessPHIs) {
00306     // Yup, loop through and nuke the PHI nodes
00307     while (PHINode *PN = dyn_cast<PHINode>(&front())) {
00308       // Remove the predecessor first.
00309       PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
00310 
00311       // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
00312       if (max_idx == 2) {
00313         if (PN->getIncomingValue(0) != PN)
00314           PN->replaceAllUsesWith(PN->getIncomingValue(0));
00315         else
00316           // We are left with an infinite loop with no entries: kill the PHI.
00317           PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
00318         getInstList().pop_front();    // Remove the PHI node
00319       }
00320 
00321       // If the PHI node already only had one entry, it got deleted by
00322       // removeIncomingValue.
00323     }
00324   } else {
00325     // Okay, now we know that we need to remove predecessor #pred_idx from all
00326     // PHI nodes.  Iterate over each PHI node fixing them up
00327     PHINode *PN;
00328     for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
00329       ++II;
00330       PN->removeIncomingValue(Pred, false);
00331       // If all incoming values to the Phi are the same, we can replace the Phi
00332       // with that value.
00333       Value* PNV = nullptr;
00334       if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue()))
00335         if (PNV != PN) {
00336           PN->replaceAllUsesWith(PNV);
00337           PN->eraseFromParent();
00338         }
00339     }
00340   }
00341 }
00342 
00343 
00344 /// This splits a basic block into two at the specified
00345 /// instruction.  Note that all instructions BEFORE the specified iterator stay
00346 /// as part of the original basic block, an unconditional branch is added to
00347 /// the new BB, and the rest of the instructions in the BB are moved to the new
00348 /// BB, including the old terminator.  This invalidates the iterator.
00349 ///
00350 /// Note that this only works on well formed basic blocks (must have a
00351 /// terminator), and 'I' must not be the end of instruction list (which would
00352 /// cause a degenerate basic block to be formed, having a terminator inside of
00353 /// the basic block).
00354 ///
00355 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
00356   assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
00357   assert(I != InstList.end() &&
00358          "Trying to get me to create degenerate basic block!");
00359 
00360   BasicBlock *InsertBefore = std::next(Function::iterator(this))
00361                                .getNodePtrUnchecked();
00362   BasicBlock *New = BasicBlock::Create(getContext(), BBName,
00363                                        getParent(), InsertBefore);
00364 
00365   // Save DebugLoc of split point before invalidating iterator.
00366   DebugLoc Loc = I->getDebugLoc();
00367   // Move all of the specified instructions from the original basic block into
00368   // the new basic block.
00369   New->getInstList().splice(New->end(), this->getInstList(), I, end());
00370 
00371   // Add a branch instruction to the newly formed basic block.
00372   BranchInst *BI = BranchInst::Create(New, this);
00373   BI->setDebugLoc(Loc);
00374 
00375   // Now we must loop through all of the successors of the New block (which
00376   // _were_ the successors of the 'this' block), and update any PHI nodes in
00377   // successors.  If there were PHI nodes in the successors, then they need to
00378   // know that incoming branches will be from New, not from Old.
00379   //
00380   for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
00381     // Loop over any phi nodes in the basic block, updating the BB field of
00382     // incoming values...
00383     BasicBlock *Successor = *I;
00384     PHINode *PN;
00385     for (BasicBlock::iterator II = Successor->begin();
00386          (PN = dyn_cast<PHINode>(II)); ++II) {
00387       int IDX = PN->getBasicBlockIndex(this);
00388       while (IDX != -1) {
00389         PN->setIncomingBlock((unsigned)IDX, New);
00390         IDX = PN->getBasicBlockIndex(this);
00391       }
00392     }
00393   }
00394   return New;
00395 }
00396 
00397 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
00398   TerminatorInst *TI = getTerminator();
00399   if (!TI)
00400     // Cope with being called on a BasicBlock that doesn't have a terminator
00401     // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
00402     return;
00403   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
00404     BasicBlock *Succ = TI->getSuccessor(i);
00405     // N.B. Succ might not be a complete BasicBlock, so don't assume
00406     // that it ends with a non-phi instruction.
00407     for (iterator II = Succ->begin(), IE = Succ->end(); II != IE; ++II) {
00408       PHINode *PN = dyn_cast<PHINode>(II);
00409       if (!PN)
00410         break;
00411       int i;
00412       while ((i = PN->getBasicBlockIndex(this)) >= 0)
00413         PN->setIncomingBlock(i, New);
00414     }
00415   }
00416 }
00417 
00418 /// Return true if this basic block is a landing pad. I.e., it's
00419 /// the destination of the 'unwind' edge of an invoke instruction.
00420 bool BasicBlock::isLandingPad() const {
00421   return isa<LandingPadInst>(getFirstNonPHI());
00422 }
00423 
00424 /// Return the landingpad instruction associated with the landing pad.
00425 LandingPadInst *BasicBlock::getLandingPadInst() {
00426   return dyn_cast<LandingPadInst>(getFirstNonPHI());
00427 }
00428 const LandingPadInst *BasicBlock::getLandingPadInst() const {
00429   return dyn_cast<LandingPadInst>(getFirstNonPHI());
00430 }