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