LLVM API Documentation

Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members | Related Pages

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 was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source 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/Constant.h"
00016 #include "llvm/Instructions.h"
00017 #include "llvm/Type.h"
00018 #include "llvm/Support/CFG.h"
00019 #include "llvm/SymbolTable.h"
00020 #include "llvm/Support/LeakDetector.h"
00021 #include "SymbolTableListTraitsImpl.h"
00022 #include <algorithm>
00023 using namespace llvm;
00024 
00025 namespace {
00026   /// DummyInst - An instance of this class is used to mark the end of the
00027   /// instruction list.  This is not a real instruction.
00028   struct DummyInst : public Instruction {
00029     DummyInst() : Instruction(Type::VoidTy, OtherOpsEnd) {
00030       // This should not be garbage monitored.
00031       LeakDetector::removeGarbageObject(this);
00032     }
00033 
00034     virtual Instruction *clone() const {
00035       assert(0 && "Cannot clone EOL");abort();
00036       return 0;
00037     }
00038     virtual const char *getOpcodeName() const { return "*end-of-list-inst*"; }
00039 
00040     // Methods for support type inquiry through isa, cast, and dyn_cast...
00041     static inline bool classof(const DummyInst *) { return true; }
00042     static inline bool classof(const Instruction *I) {
00043       return I->getOpcode() == OtherOpsEnd;
00044     }
00045     static inline bool classof(const Value *V) {
00046       return isa<Instruction>(V) && classof(cast<Instruction>(V));
00047     }
00048   };
00049 }
00050 
00051 Instruction *ilist_traits<Instruction>::createNode() {
00052   return new DummyInst();
00053 }
00054 iplist<Instruction> &ilist_traits<Instruction>::getList(BasicBlock *BB) {
00055   return BB->getInstList();
00056 }
00057 
00058 // Explicit instantiation of SymbolTableListTraits since some of the methods
00059 // are not in the public header file...
00060 template class SymbolTableListTraits<Instruction, BasicBlock, Function>;
00061 
00062 
00063 BasicBlock::BasicBlock(const std::string &Name, Function *Parent,
00064                        BasicBlock *InsertBefore)
00065   : Value(Type::LabelTy, Value::BasicBlockVal, Name) {
00066   // Initialize the instlist...
00067   InstList.setItemParent(this);
00068 
00069   // Make sure that we get added to a function
00070   LeakDetector::addGarbageObject(this);
00071 
00072   if (InsertBefore) {
00073     assert(Parent &&
00074            "Cannot insert block before another block with no function!");
00075     Parent->getBasicBlockList().insert(InsertBefore, this);
00076   } else if (Parent) {
00077     Parent->getBasicBlockList().push_back(this);
00078   }
00079 }
00080 
00081 
00082 BasicBlock::~BasicBlock() {
00083   assert(getParent() == 0 && "BasicBlock still linked into the program!");
00084   dropAllReferences();
00085   InstList.clear();
00086 }
00087 
00088 void BasicBlock::setParent(Function *parent) {
00089   if (getParent())
00090     LeakDetector::addGarbageObject(this);
00091 
00092   InstList.setParent(parent);
00093 
00094   if (getParent())
00095     LeakDetector::removeGarbageObject(this);
00096 }
00097 
00098 // Specialize setName to take care of symbol table majik
00099 void BasicBlock::setName(const std::string &name, SymbolTable *ST) {
00100   Function *P;
00101   assert((ST == 0 || (!getParent() || ST == &getParent()->getSymbolTable())) &&
00102    "Invalid symtab argument!");
00103   if ((P = getParent()) && hasName()) P->getSymbolTable().remove(this);
00104   Value::setName(name);
00105   if (P && hasName()) P->getSymbolTable().insert(this);
00106 }
00107 
00108 void BasicBlock::removeFromParent() {
00109   getParent()->getBasicBlockList().remove(this);
00110 }
00111 
00112 void BasicBlock::eraseFromParent() {
00113   getParent()->getBasicBlockList().erase(this);
00114 }
00115 
00116 
00117 TerminatorInst *BasicBlock::getTerminator() {
00118   if (InstList.empty()) return 0;
00119   return dyn_cast<TerminatorInst>(&InstList.back());
00120 }
00121 
00122 const TerminatorInst *const BasicBlock::getTerminator() const {
00123   if (InstList.empty()) return 0;
00124   return dyn_cast<TerminatorInst>(&InstList.back());
00125 }
00126 
00127 void BasicBlock::dropAllReferences() {
00128   for(iterator I = begin(), E = end(); I != E; ++I)
00129     I->dropAllReferences();
00130 }
00131 
00132 // removePredecessor - This method is used to notify a BasicBlock that the
00133 // specified Predecessor of the block is no longer able to reach it.  This is
00134 // actually not used to update the Predecessor list, but is actually used to 
00135 // update the PHI nodes that reside in the block.  Note that this should be
00136 // called while the predecessor still refers to this block.
00137 //
00138 void BasicBlock::removePredecessor(BasicBlock *Pred) {
00139   assert(find(pred_begin(this), pred_end(this), Pred) != pred_end(this) &&
00140    "removePredecessor: BB is not a predecessor!");
00141   PHINode *APN = dyn_cast<PHINode>(&front());
00142   if (!APN) return;   // Quick exit.
00143 
00144   // If there are exactly two predecessors, then we want to nuke the PHI nodes
00145   // altogether.  However, we cannot do this, if this in this case:
00146   //
00147   //  Loop:
00148   //    %x = phi [X, Loop]
00149   //    %x2 = add %x, 1         ;; This would become %x2 = add %x2, 1
00150   //    br Loop                 ;; %x2 does not dominate all uses
00151   //
00152   // This is because the PHI node input is actually taken from the predecessor
00153   // basic block.  The only case this can happen is with a self loop, so we 
00154   // check for this case explicitly now.
00155   // 
00156   unsigned max_idx = APN->getNumIncomingValues();
00157   assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
00158   if (max_idx == 2) {
00159     BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
00160 
00161     // Disable PHI elimination!
00162     if (this == Other) max_idx = 3;
00163   }
00164 
00165   if (max_idx <= 2) {                // <= Two predecessors BEFORE I remove one?
00166     // Yup, loop through and nuke the PHI nodes
00167     while (PHINode *PN = dyn_cast<PHINode>(&front())) {
00168       PN->removeIncomingValue(Pred); // Remove the predecessor first...
00169 
00170       // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
00171       if (max_idx == 2) {
00172         if (PN->getOperand(0) != PN)
00173           PN->replaceAllUsesWith(PN->getOperand(0));
00174         else
00175           // We are left with an infinite loop with no entries: kill the PHI.
00176           PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
00177         getInstList().pop_front();    // Remove the PHI node
00178       }
00179 
00180       // If the PHI node already only had one entry, it got deleted by
00181       // removeIncomingValue.
00182     }
00183   } else {
00184     // Okay, now we know that we need to remove predecessor #pred_idx from all
00185     // PHI nodes.  Iterate over each PHI node fixing them up
00186     PHINode *PN;
00187     for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ++II)
00188       PN->removeIncomingValue(Pred);
00189   }
00190 }
00191 
00192 
00193 // splitBasicBlock - This splits a basic block into two at the specified
00194 // instruction.  Note that all instructions BEFORE the specified iterator stay
00195 // as part of the original basic block, an unconditional branch is added to 
00196 // the new BB, and the rest of the instructions in the BB are moved to the new
00197 // BB, including the old terminator.  This invalidates the iterator.
00198 //
00199 // Note that this only works on well formed basic blocks (must have a 
00200 // terminator), and 'I' must not be the end of instruction list (which would
00201 // cause a degenerate basic block to be formed, having a terminator inside of
00202 // the basic block). 
00203 //
00204 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const std::string &BBName) {
00205   assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
00206   assert(I != InstList.end() && 
00207    "Trying to get me to create degenerate basic block!");
00208 
00209   BasicBlock *New = new BasicBlock(BBName, getParent(), getNext());
00210 
00211   // Move all of the specified instructions from the original basic block into
00212   // the new basic block.
00213   New->getInstList().splice(New->end(), this->getInstList(), I, end());
00214 
00215   // Add a branch instruction to the newly formed basic block.
00216   new BranchInst(New, this);
00217 
00218   // Now we must loop through all of the successors of the New block (which
00219   // _were_ the successors of the 'this' block), and update any PHI nodes in
00220   // successors.  If there were PHI nodes in the successors, then they need to
00221   // know that incoming branches will be from New, not from Old.
00222   //
00223   for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
00224     // Loop over any phi nodes in the basic block, updating the BB field of
00225     // incoming values...
00226     BasicBlock *Successor = *I;
00227     PHINode *PN;
00228     for (BasicBlock::iterator II = Successor->begin();
00229          (PN = dyn_cast<PHINode>(II)); ++II) {
00230       int IDX = PN->getBasicBlockIndex(this);
00231       while (IDX != -1) {
00232         PN->setIncomingBlock((unsigned)IDX, New);
00233         IDX = PN->getBasicBlockIndex(this);
00234       }
00235     }
00236   }
00237   return New;
00238 }