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 VMCore library.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/BasicBlock.h"
00015 #include "llvm/Constants.h"
00016 #include "llvm/Instructions.h"
00017 #include "llvm/Type.h"
00018 #include "llvm/ADT/STLExtras.h"
00019 #include "llvm/Support/CFG.h"
00020 #include "llvm/Support/LeakDetector.h"
00021 #include "llvm/Support/Compiler.h"
00022 #include "SymbolTableListTraitsImpl.h"
00023 #include <algorithm>
00024 using namespace llvm;
00025 
00026 inline ValueSymbolTable *
00027 ilist_traits<Instruction>::getSymTab(BasicBlock *BB) {
00028   if (BB)
00029     if (Function *F = BB->getParent())
00030       return &F->getValueSymbolTable();
00031   return 0;
00032 }
00033 
00034 
00035 namespace {
00036   /// DummyInst - An instance of this class is used to mark the end of the
00037   /// instruction list.  This is not a real instruction.
00038   struct VISIBILITY_HIDDEN DummyInst : public Instruction {
00039     // allocate space for exactly zero operands
00040     void *operator new(size_t s) {
00041       return User::operator new(s, 0);
00042     }
00043     DummyInst() : Instruction(Type::VoidTy, OtherOpsEnd, 0, 0) {
00044       // This should not be garbage monitored.
00045       LeakDetector::removeGarbageObject(this);
00046     }
00047 
00048     Instruction *clone() const {
00049       assert(0 && "Cannot clone EOL");abort();
00050       return 0;
00051     }
00052     const char *getOpcodeName() const { return "*end-of-list-inst*"; }
00053 
00054     // Methods for support type inquiry through isa, cast, and dyn_cast...
00055     static inline bool classof(const DummyInst *) { return true; }
00056     static inline bool classof(const Instruction *I) {
00057       return I->getOpcode() == OtherOpsEnd;
00058     }
00059     static inline bool classof(const Value *V) {
00060       return isa<Instruction>(V) && classof(cast<Instruction>(V));
00061     }
00062   };
00063 }
00064 
00065 Instruction *ilist_traits<Instruction>::createSentinel() {
00066   return new DummyInst();
00067 }
00068 iplist<Instruction> &ilist_traits<Instruction>::getList(BasicBlock *BB) {
00069   return BB->getInstList();
00070 }
00071 
00072 // Explicit instantiation of SymbolTableListTraits since some of the methods
00073 // are not in the public header file...
00074 template class SymbolTableListTraits<Instruction, BasicBlock>;
00075 
00076 
00077 BasicBlock::BasicBlock(const std::string &Name, Function *NewParent,
00078                        BasicBlock *InsertBefore)
00079   : Value(Type::LabelTy, Value::BasicBlockVal), Parent(0) {
00080 
00081   // Make sure that we get added to a function
00082   LeakDetector::addGarbageObject(this);
00083 
00084   if (InsertBefore) {
00085     assert(NewParent &&
00086            "Cannot insert block before another block with no function!");
00087     NewParent->getBasicBlockList().insert(InsertBefore, this);
00088   } else if (NewParent) {
00089     NewParent->getBasicBlockList().push_back(this);
00090   }
00091   
00092   setName(Name);
00093 }
00094 
00095 
00096 BasicBlock::~BasicBlock() {
00097   assert(getParent() == 0 && "BasicBlock still linked into the program!");
00098   dropAllReferences();
00099   InstList.clear();
00100 }
00101 
00102 void BasicBlock::setParent(Function *parent) {
00103   if (getParent())
00104     LeakDetector::addGarbageObject(this);
00105 
00106   // Set Parent=parent, updating instruction symtab entries as appropriate.
00107   InstList.setSymTabObject(&Parent, parent);
00108 
00109   if (getParent())
00110     LeakDetector::removeGarbageObject(this);
00111 }
00112 
00113 void BasicBlock::removeFromParent() {
00114   getParent()->getBasicBlockList().remove(this);
00115 }
00116 
00117 void BasicBlock::eraseFromParent() {
00118   getParent()->getBasicBlockList().erase(this);
00119 }
00120 
00121 /// moveBefore - Unlink this basic block from its current function and
00122 /// insert it into the function that MovePos lives in, right before MovePos.
00123 void BasicBlock::moveBefore(BasicBlock *MovePos) {
00124   MovePos->getParent()->getBasicBlockList().splice(MovePos,
00125                        getParent()->getBasicBlockList(), this);
00126 }
00127 
00128 /// moveAfter - Unlink this basic block from its current function and
00129 /// insert it into the function that MovePos lives in, right after MovePos.
00130 void BasicBlock::moveAfter(BasicBlock *MovePos) {
00131   Function::iterator I = MovePos;
00132   MovePos->getParent()->getBasicBlockList().splice(++I,
00133                                        getParent()->getBasicBlockList(), this);
00134 }
00135 
00136 
00137 TerminatorInst *BasicBlock::getTerminator() {
00138   if (InstList.empty()) return 0;
00139   return dyn_cast<TerminatorInst>(&InstList.back());
00140 }
00141 
00142 const TerminatorInst *BasicBlock::getTerminator() const {
00143   if (InstList.empty()) return 0;
00144   return dyn_cast<TerminatorInst>(&InstList.back());
00145 }
00146 
00147 Instruction* BasicBlock::getFirstNonPHI() {
00148   BasicBlock::iterator i = begin();
00149   // All valid basic blocks should have a terminator,
00150   // which is not a PHINode. If we have an invalid basic
00151   // block we'll get an assertion failure when dereferencing
00152   // a past-the-end iterator.
00153   while (isa<PHINode>(i)) ++i;
00154   return &*i;
00155 }
00156 
00157 void BasicBlock::dropAllReferences() {
00158   for(iterator I = begin(), E = end(); I != E; ++I)
00159     I->dropAllReferences();
00160 }
00161 
00162 /// getSinglePredecessor - If this basic block has a single predecessor block,
00163 /// return the block, otherwise return a null pointer.
00164 BasicBlock *BasicBlock::getSinglePredecessor() {
00165   pred_iterator PI = pred_begin(this), E = pred_end(this);
00166   if (PI == E) return 0;         // No preds.
00167   BasicBlock *ThePred = *PI;
00168   ++PI;
00169   return (PI == E) ? ThePred : 0 /*multiple preds*/;
00170 }
00171 
00172 /// getUniquePredecessor - If this basic block has a unique predecessor block,
00173 /// return the block, otherwise return a null pointer.
00174 /// Note that unique predecessor doesn't mean single edge, there can be 
00175 /// multiple edges from the unique predecessor to this block (for example 
00176 /// a switch statement with multiple cases having the same destination).
00177 BasicBlock *BasicBlock::getUniquePredecessor() {
00178   pred_iterator PI = pred_begin(this), E = pred_end(this);
00179   if (PI == E) return 0; // No preds.
00180   BasicBlock *PredBB = *PI;
00181   ++PI;
00182   for (;PI != E; ++PI) {
00183     if (*PI != PredBB)
00184       return 0;
00185     // The same predecessor appears multiple times in the predecessor list.
00186     // This is OK.
00187   }
00188   return PredBB;
00189 }
00190 
00191 /// removePredecessor - This method is used to notify a BasicBlock that the
00192 /// specified Predecessor of the block is no longer able to reach it.  This is
00193 /// actually not used to update the Predecessor list, but is actually used to
00194 /// update the PHI nodes that reside in the block.  Note that this should be
00195 /// called while the predecessor still refers to this block.
00196 ///
00197 void BasicBlock::removePredecessor(BasicBlock *Pred,
00198                                    bool DontDeleteUselessPHIs) {
00199   assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
00200           find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
00201          "removePredecessor: BB is not a predecessor!");
00202 
00203   if (InstList.empty()) return;
00204   PHINode *APN = dyn_cast<PHINode>(&front());
00205   if (!APN) return;   // Quick exit.
00206 
00207   // If there are exactly two predecessors, then we want to nuke the PHI nodes
00208   // altogether.  However, we cannot do this, if this in this case:
00209   //
00210   //  Loop:
00211   //    %x = phi [X, Loop]
00212   //    %x2 = add %x, 1         ;; This would become %x2 = add %x2, 1
00213   //    br Loop                 ;; %x2 does not dominate all uses
00214   //
00215   // This is because the PHI node input is actually taken from the predecessor
00216   // basic block.  The only case this can happen is with a self loop, so we
00217   // check for this case explicitly now.
00218   //
00219   unsigned max_idx = APN->getNumIncomingValues();
00220   assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
00221   if (max_idx == 2) {
00222     BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
00223 
00224     // Disable PHI elimination!
00225     if (this == Other) max_idx = 3;
00226   }
00227 
00228   // <= Two predecessors BEFORE I remove one?
00229   if (max_idx <= 2 && !DontDeleteUselessPHIs) {
00230     // Yup, loop through and nuke the PHI nodes
00231     while (PHINode *PN = dyn_cast<PHINode>(&front())) {
00232       // Remove the predecessor first.
00233       PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
00234 
00235       // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
00236       if (max_idx == 2) {
00237         if (PN->getOperand(0) != PN)
00238           PN->replaceAllUsesWith(PN->getOperand(0));
00239         else
00240           // We are left with an infinite loop with no entries: kill the PHI.
00241           PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
00242         getInstList().pop_front();    // Remove the PHI node
00243       }
00244 
00245       // If the PHI node already only had one entry, it got deleted by
00246       // removeIncomingValue.
00247     }
00248   } else {
00249     // Okay, now we know that we need to remove predecessor #pred_idx from all
00250     // PHI nodes.  Iterate over each PHI node fixing them up
00251     PHINode *PN;
00252     for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
00253       ++II;
00254       PN->removeIncomingValue(Pred, false);
00255       // If all incoming values to the Phi are the same, we can replace the Phi
00256       // with that value.
00257       Value* PNV = 0;
00258       if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue())) {
00259         PN->replaceAllUsesWith(PNV);
00260         PN->eraseFromParent();
00261       }
00262     }
00263   }
00264 }
00265 
00266 
00267 /// splitBasicBlock - This splits a basic block into two at the specified
00268 /// instruction.  Note that all instructions BEFORE the specified iterator stay
00269 /// as part of the original basic block, an unconditional branch is added to
00270 /// the new BB, and the rest of the instructions in the BB are moved to the new
00271 /// BB, including the old terminator.  This invalidates the iterator.
00272 ///
00273 /// Note that this only works on well formed basic blocks (must have a
00274 /// terminator), and 'I' must not be the end of instruction list (which would
00275 /// cause a degenerate basic block to be formed, having a terminator inside of
00276 /// the basic block).
00277 ///
00278 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const std::string &BBName) {
00279   assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
00280   assert(I != InstList.end() &&
00281          "Trying to get me to create degenerate basic block!");
00282 
00283   BasicBlock *InsertBefore = next(Function::iterator(this))
00284                                .getNodePtrUnchecked();
00285   BasicBlock *New = BasicBlock::Create(BBName, getParent(), InsertBefore);
00286 
00287   // Move all of the specified instructions from the original basic block into
00288   // the new basic block.
00289   New->getInstList().splice(New->end(), this->getInstList(), I, end());
00290 
00291   // Add a branch instruction to the newly formed basic block.
00292   BranchInst::Create(New, this);
00293 
00294   // Now we must loop through all of the successors of the New block (which
00295   // _were_ the successors of the 'this' block), and update any PHI nodes in
00296   // successors.  If there were PHI nodes in the successors, then they need to
00297   // know that incoming branches will be from New, not from Old.
00298   //
00299   for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
00300     // Loop over any phi nodes in the basic block, updating the BB field of
00301     // incoming values...
00302     BasicBlock *Successor = *I;
00303     PHINode *PN;
00304     for (BasicBlock::iterator II = Successor->begin();
00305          (PN = dyn_cast<PHINode>(II)); ++II) {
00306       int IDX = PN->getBasicBlockIndex(this);
00307       while (IDX != -1) {
00308         PN->setIncomingBlock((unsigned)IDX, New);
00309         IDX = PN->getBasicBlockIndex(this);
00310       }
00311     }
00312   }
00313   return New;
00314 }



This web site is hosted by the Computer Science Department at the University of Illinois at Urbana-Champaign.