Home | History | Annotate | Download | only in Scalar
      1 //===- EarlyCSE.cpp - Simple and fast CSE pass ----------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This pass performs a simple dominator tree walk that eliminates trivially
     11 // redundant instructions.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #define DEBUG_TYPE "early-cse"
     16 #include "llvm/Transforms/Scalar.h"
     17 #include "llvm/ADT/Hashing.h"
     18 #include "llvm/ADT/ScopedHashTable.h"
     19 #include "llvm/ADT/Statistic.h"
     20 #include "llvm/Analysis/Dominators.h"
     21 #include "llvm/Analysis/InstructionSimplify.h"
     22 #include "llvm/IR/DataLayout.h"
     23 #include "llvm/IR/Instructions.h"
     24 #include "llvm/Pass.h"
     25 #include "llvm/Support/Debug.h"
     26 #include "llvm/Support/RecyclingAllocator.h"
     27 #include "llvm/Target/TargetLibraryInfo.h"
     28 #include "llvm/Transforms/Utils/Local.h"
     29 #include <deque>
     30 using namespace llvm;
     31 
     32 STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
     33 STATISTIC(NumCSE,      "Number of instructions CSE'd");
     34 STATISTIC(NumCSELoad,  "Number of load instructions CSE'd");
     35 STATISTIC(NumCSECall,  "Number of call instructions CSE'd");
     36 STATISTIC(NumDSE,      "Number of trivial dead stores removed");
     37 
     38 static unsigned getHash(const void *V) {
     39   return DenseMapInfo<const void*>::getHashValue(V);
     40 }
     41 
     42 //===----------------------------------------------------------------------===//
     43 // SimpleValue
     44 //===----------------------------------------------------------------------===//
     45 
     46 namespace {
     47   /// SimpleValue - Instances of this struct represent available values in the
     48   /// scoped hash table.
     49   struct SimpleValue {
     50     Instruction *Inst;
     51 
     52     SimpleValue(Instruction *I) : Inst(I) {
     53       assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
     54     }
     55 
     56     bool isSentinel() const {
     57       return Inst == DenseMapInfo<Instruction*>::getEmptyKey() ||
     58              Inst == DenseMapInfo<Instruction*>::getTombstoneKey();
     59     }
     60 
     61     static bool canHandle(Instruction *Inst) {
     62       // This can only handle non-void readnone functions.
     63       if (CallInst *CI = dyn_cast<CallInst>(Inst))
     64         return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
     65       return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
     66              isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
     67              isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
     68              isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
     69              isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
     70     }
     71   };
     72 }
     73 
     74 namespace llvm {
     75 // SimpleValue is POD.
     76 template<> struct isPodLike<SimpleValue> {
     77   static const bool value = true;
     78 };
     79 
     80 template<> struct DenseMapInfo<SimpleValue> {
     81   static inline SimpleValue getEmptyKey() {
     82     return DenseMapInfo<Instruction*>::getEmptyKey();
     83   }
     84   static inline SimpleValue getTombstoneKey() {
     85     return DenseMapInfo<Instruction*>::getTombstoneKey();
     86   }
     87   static unsigned getHashValue(SimpleValue Val);
     88   static bool isEqual(SimpleValue LHS, SimpleValue RHS);
     89 };
     90 }
     91 
     92 unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
     93   Instruction *Inst = Val.Inst;
     94   // Hash in all of the operands as pointers.
     95   if (BinaryOperator* BinOp = dyn_cast<BinaryOperator>(Inst)) {
     96     Value *LHS = BinOp->getOperand(0);
     97     Value *RHS = BinOp->getOperand(1);
     98     if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
     99       std::swap(LHS, RHS);
    100 
    101     if (isa<OverflowingBinaryOperator>(BinOp)) {
    102       // Hash the overflow behavior
    103       unsigned Overflow =
    104         BinOp->hasNoSignedWrap()   * OverflowingBinaryOperator::NoSignedWrap |
    105         BinOp->hasNoUnsignedWrap() * OverflowingBinaryOperator::NoUnsignedWrap;
    106       return hash_combine(BinOp->getOpcode(), Overflow, LHS, RHS);
    107     }
    108 
    109     return hash_combine(BinOp->getOpcode(), LHS, RHS);
    110   }
    111 
    112   if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
    113     Value *LHS = CI->getOperand(0);
    114     Value *RHS = CI->getOperand(1);
    115     CmpInst::Predicate Pred = CI->getPredicate();
    116     if (Inst->getOperand(0) > Inst->getOperand(1)) {
    117       std::swap(LHS, RHS);
    118       Pred = CI->getSwappedPredicate();
    119     }
    120     return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
    121   }
    122 
    123   if (CastInst *CI = dyn_cast<CastInst>(Inst))
    124     return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
    125 
    126   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
    127     return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
    128                         hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
    129 
    130   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
    131     return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
    132                         IVI->getOperand(1),
    133                         hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
    134 
    135   assert((isa<CallInst>(Inst) || isa<BinaryOperator>(Inst) ||
    136           isa<GetElementPtrInst>(Inst) || isa<SelectInst>(Inst) ||
    137           isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
    138           isa<ShuffleVectorInst>(Inst)) && "Invalid/unknown instruction");
    139 
    140   // Mix in the opcode.
    141   return hash_combine(Inst->getOpcode(),
    142                       hash_combine_range(Inst->value_op_begin(),
    143                                          Inst->value_op_end()));
    144 }
    145 
    146 bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
    147   Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
    148 
    149   if (LHS.isSentinel() || RHS.isSentinel())
    150     return LHSI == RHSI;
    151 
    152   if (LHSI->getOpcode() != RHSI->getOpcode()) return false;
    153   if (LHSI->isIdenticalTo(RHSI)) return true;
    154 
    155   // If we're not strictly identical, we still might be a commutable instruction
    156   if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
    157     if (!LHSBinOp->isCommutative())
    158       return false;
    159 
    160     assert(isa<BinaryOperator>(RHSI)
    161            && "same opcode, but different instruction type?");
    162     BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
    163 
    164     // Check overflow attributes
    165     if (isa<OverflowingBinaryOperator>(LHSBinOp)) {
    166       assert(isa<OverflowingBinaryOperator>(RHSBinOp)
    167              && "same opcode, but different operator type?");
    168       if (LHSBinOp->hasNoUnsignedWrap() != RHSBinOp->hasNoUnsignedWrap() ||
    169           LHSBinOp->hasNoSignedWrap() != RHSBinOp->hasNoSignedWrap())
    170         return false;
    171     }
    172 
    173     // Commuted equality
    174     return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
    175       LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
    176   }
    177   if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
    178     assert(isa<CmpInst>(RHSI)
    179            && "same opcode, but different instruction type?");
    180     CmpInst *RHSCmp = cast<CmpInst>(RHSI);
    181     // Commuted equality
    182     return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
    183       LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
    184       LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
    185   }
    186 
    187   return false;
    188 }
    189 
    190 //===----------------------------------------------------------------------===//
    191 // CallValue
    192 //===----------------------------------------------------------------------===//
    193 
    194 namespace {
    195   /// CallValue - Instances of this struct represent available call values in
    196   /// the scoped hash table.
    197   struct CallValue {
    198     Instruction *Inst;
    199 
    200     CallValue(Instruction *I) : Inst(I) {
    201       assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
    202     }
    203 
    204     bool isSentinel() const {
    205       return Inst == DenseMapInfo<Instruction*>::getEmptyKey() ||
    206              Inst == DenseMapInfo<Instruction*>::getTombstoneKey();
    207     }
    208 
    209     static bool canHandle(Instruction *Inst) {
    210       // Don't value number anything that returns void.
    211       if (Inst->getType()->isVoidTy())
    212         return false;
    213 
    214       CallInst *CI = dyn_cast<CallInst>(Inst);
    215       if (CI == 0 || !CI->onlyReadsMemory())
    216         return false;
    217       return true;
    218     }
    219   };
    220 }
    221 
    222 namespace llvm {
    223   // CallValue is POD.
    224   template<> struct isPodLike<CallValue> {
    225     static const bool value = true;
    226   };
    227 
    228   template<> struct DenseMapInfo<CallValue> {
    229     static inline CallValue getEmptyKey() {
    230       return DenseMapInfo<Instruction*>::getEmptyKey();
    231     }
    232     static inline CallValue getTombstoneKey() {
    233       return DenseMapInfo<Instruction*>::getTombstoneKey();
    234     }
    235     static unsigned getHashValue(CallValue Val);
    236     static bool isEqual(CallValue LHS, CallValue RHS);
    237   };
    238 }
    239 unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
    240   Instruction *Inst = Val.Inst;
    241   // Hash in all of the operands as pointers.
    242   unsigned Res = 0;
    243   for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i) {
    244     assert(!Inst->getOperand(i)->getType()->isMetadataTy() &&
    245            "Cannot value number calls with metadata operands");
    246     Res ^= getHash(Inst->getOperand(i)) << (i & 0xF);
    247   }
    248 
    249   // Mix in the opcode.
    250   return (Res << 1) ^ Inst->getOpcode();
    251 }
    252 
    253 bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
    254   Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
    255   if (LHS.isSentinel() || RHS.isSentinel())
    256     return LHSI == RHSI;
    257   return LHSI->isIdenticalTo(RHSI);
    258 }
    259 
    260 
    261 //===----------------------------------------------------------------------===//
    262 // EarlyCSE pass.
    263 //===----------------------------------------------------------------------===//
    264 
    265 namespace {
    266 
    267 /// EarlyCSE - This pass does a simple depth-first walk over the dominator
    268 /// tree, eliminating trivially redundant instructions and using instsimplify
    269 /// to canonicalize things as it goes.  It is intended to be fast and catch
    270 /// obvious cases so that instcombine and other passes are more effective.  It
    271 /// is expected that a later pass of GVN will catch the interesting/hard
    272 /// cases.
    273 class EarlyCSE : public FunctionPass {
    274 public:
    275   const DataLayout *TD;
    276   const TargetLibraryInfo *TLI;
    277   DominatorTree *DT;
    278   typedef RecyclingAllocator<BumpPtrAllocator,
    279                       ScopedHashTableVal<SimpleValue, Value*> > AllocatorTy;
    280   typedef ScopedHashTable<SimpleValue, Value*, DenseMapInfo<SimpleValue>,
    281                           AllocatorTy> ScopedHTType;
    282 
    283   /// AvailableValues - This scoped hash table contains the current values of
    284   /// all of our simple scalar expressions.  As we walk down the domtree, we
    285   /// look to see if instructions are in this: if so, we replace them with what
    286   /// we find, otherwise we insert them so that dominated values can succeed in
    287   /// their lookup.
    288   ScopedHTType *AvailableValues;
    289 
    290   /// AvailableLoads - This scoped hash table contains the current values
    291   /// of loads.  This allows us to get efficient access to dominating loads when
    292   /// we have a fully redundant load.  In addition to the most recent load, we
    293   /// keep track of a generation count of the read, which is compared against
    294   /// the current generation count.  The current generation count is
    295   /// incremented after every possibly writing memory operation, which ensures
    296   /// that we only CSE loads with other loads that have no intervening store.
    297   typedef RecyclingAllocator<BumpPtrAllocator,
    298     ScopedHashTableVal<Value*, std::pair<Value*, unsigned> > > LoadMapAllocator;
    299   typedef ScopedHashTable<Value*, std::pair<Value*, unsigned>,
    300                           DenseMapInfo<Value*>, LoadMapAllocator> LoadHTType;
    301   LoadHTType *AvailableLoads;
    302 
    303   /// AvailableCalls - This scoped hash table contains the current values
    304   /// of read-only call values.  It uses the same generation count as loads.
    305   typedef ScopedHashTable<CallValue, std::pair<Value*, unsigned> > CallHTType;
    306   CallHTType *AvailableCalls;
    307 
    308   /// CurrentGeneration - This is the current generation of the memory value.
    309   unsigned CurrentGeneration;
    310 
    311   static char ID;
    312   explicit EarlyCSE() : FunctionPass(ID) {
    313     initializeEarlyCSEPass(*PassRegistry::getPassRegistry());
    314   }
    315 
    316   bool runOnFunction(Function &F);
    317 
    318 private:
    319 
    320   // NodeScope - almost a POD, but needs to call the constructors for the
    321   // scoped hash tables so that a new scope gets pushed on. These are RAII so
    322   // that the scope gets popped when the NodeScope is destroyed.
    323   class NodeScope {
    324    public:
    325     NodeScope(ScopedHTType *availableValues,
    326               LoadHTType *availableLoads,
    327               CallHTType *availableCalls) :
    328         Scope(*availableValues),
    329         LoadScope(*availableLoads),
    330         CallScope(*availableCalls) {}
    331 
    332    private:
    333     NodeScope(const NodeScope&) LLVM_DELETED_FUNCTION;
    334     void operator=(const NodeScope&) LLVM_DELETED_FUNCTION;
    335 
    336     ScopedHTType::ScopeTy Scope;
    337     LoadHTType::ScopeTy LoadScope;
    338     CallHTType::ScopeTy CallScope;
    339   };
    340 
    341   // StackNode - contains all the needed information to create a stack for
    342   // doing a depth first tranversal of the tree. This includes scopes for
    343   // values, loads, and calls as well as the generation. There is a child
    344   // iterator so that the children do not need to be store spearately.
    345   class StackNode {
    346    public:
    347     StackNode(ScopedHTType *availableValues,
    348               LoadHTType *availableLoads,
    349               CallHTType *availableCalls,
    350               unsigned cg, DomTreeNode *n,
    351               DomTreeNode::iterator child, DomTreeNode::iterator end) :
    352         CurrentGeneration(cg), ChildGeneration(cg), Node(n),
    353         ChildIter(child), EndIter(end),
    354         Scopes(availableValues, availableLoads, availableCalls),
    355         Processed(false) {}
    356 
    357     // Accessors.
    358     unsigned currentGeneration() { return CurrentGeneration; }
    359     unsigned childGeneration() { return ChildGeneration; }
    360     void childGeneration(unsigned generation) { ChildGeneration = generation; }
    361     DomTreeNode *node() { return Node; }
    362     DomTreeNode::iterator childIter() { return ChildIter; }
    363     DomTreeNode *nextChild() {
    364       DomTreeNode *child = *ChildIter;
    365       ++ChildIter;
    366       return child;
    367     }
    368     DomTreeNode::iterator end() { return EndIter; }
    369     bool isProcessed() { return Processed; }
    370     void process() { Processed = true; }
    371 
    372    private:
    373     StackNode(const StackNode&) LLVM_DELETED_FUNCTION;
    374     void operator=(const StackNode&) LLVM_DELETED_FUNCTION;
    375 
    376     // Members.
    377     unsigned CurrentGeneration;
    378     unsigned ChildGeneration;
    379     DomTreeNode *Node;
    380     DomTreeNode::iterator ChildIter;
    381     DomTreeNode::iterator EndIter;
    382     NodeScope Scopes;
    383     bool Processed;
    384   };
    385 
    386   bool processNode(DomTreeNode *Node);
    387 
    388   // This transformation requires dominator postdominator info
    389   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
    390     AU.addRequired<DominatorTree>();
    391     AU.addRequired<TargetLibraryInfo>();
    392     AU.setPreservesCFG();
    393   }
    394 };
    395 }
    396 
    397 char EarlyCSE::ID = 0;
    398 
    399 // createEarlyCSEPass - The public interface to this file.
    400 FunctionPass *llvm::createEarlyCSEPass() {
    401   return new EarlyCSE();
    402 }
    403 
    404 INITIALIZE_PASS_BEGIN(EarlyCSE, "early-cse", "Early CSE", false, false)
    405 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
    406 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
    407 INITIALIZE_PASS_END(EarlyCSE, "early-cse", "Early CSE", false, false)
    408 
    409 bool EarlyCSE::processNode(DomTreeNode *Node) {
    410   BasicBlock *BB = Node->getBlock();
    411 
    412   // If this block has a single predecessor, then the predecessor is the parent
    413   // of the domtree node and all of the live out memory values are still current
    414   // in this block.  If this block has multiple predecessors, then they could
    415   // have invalidated the live-out memory values of our parent value.  For now,
    416   // just be conservative and invalidate memory if this block has multiple
    417   // predecessors.
    418   if (BB->getSinglePredecessor() == 0)
    419     ++CurrentGeneration;
    420 
    421   /// LastStore - Keep track of the last non-volatile store that we saw... for
    422   /// as long as there in no instruction that reads memory.  If we see a store
    423   /// to the same location, we delete the dead store.  This zaps trivial dead
    424   /// stores which can occur in bitfield code among other things.
    425   StoreInst *LastStore = 0;
    426 
    427   bool Changed = false;
    428 
    429   // See if any instructions in the block can be eliminated.  If so, do it.  If
    430   // not, add them to AvailableValues.
    431   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
    432     Instruction *Inst = I++;
    433 
    434     // Dead instructions should just be removed.
    435     if (isInstructionTriviallyDead(Inst, TLI)) {
    436       DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
    437       Inst->eraseFromParent();
    438       Changed = true;
    439       ++NumSimplify;
    440       continue;
    441     }
    442 
    443     // If the instruction can be simplified (e.g. X+0 = X) then replace it with
    444     // its simpler value.
    445     if (Value *V = SimplifyInstruction(Inst, TD, TLI, DT)) {
    446       DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << "  to: " << *V << '\n');
    447       Inst->replaceAllUsesWith(V);
    448       Inst->eraseFromParent();
    449       Changed = true;
    450       ++NumSimplify;
    451       continue;
    452     }
    453 
    454     // If this is a simple instruction that we can value number, process it.
    455     if (SimpleValue::canHandle(Inst)) {
    456       // See if the instruction has an available value.  If so, use it.
    457       if (Value *V = AvailableValues->lookup(Inst)) {
    458         DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << "  to: " << *V << '\n');
    459         Inst->replaceAllUsesWith(V);
    460         Inst->eraseFromParent();
    461         Changed = true;
    462         ++NumCSE;
    463         continue;
    464       }
    465 
    466       // Otherwise, just remember that this value is available.
    467       AvailableValues->insert(Inst, Inst);
    468       continue;
    469     }
    470 
    471     // If this is a non-volatile load, process it.
    472     if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
    473       // Ignore volatile loads.
    474       if (!LI->isSimple()) {
    475         LastStore = 0;
    476         continue;
    477       }
    478 
    479       // If we have an available version of this load, and if it is the right
    480       // generation, replace this instruction.
    481       std::pair<Value*, unsigned> InVal =
    482         AvailableLoads->lookup(Inst->getOperand(0));
    483       if (InVal.first != 0 && InVal.second == CurrentGeneration) {
    484         DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst << "  to: "
    485               << *InVal.first << '\n');
    486         if (!Inst->use_empty()) Inst->replaceAllUsesWith(InVal.first);
    487         Inst->eraseFromParent();
    488         Changed = true;
    489         ++NumCSELoad;
    490         continue;
    491       }
    492 
    493       // Otherwise, remember that we have this instruction.
    494       AvailableLoads->insert(Inst->getOperand(0),
    495                           std::pair<Value*, unsigned>(Inst, CurrentGeneration));
    496       LastStore = 0;
    497       continue;
    498     }
    499 
    500     // If this instruction may read from memory, forget LastStore.
    501     if (Inst->mayReadFromMemory())
    502       LastStore = 0;
    503 
    504     // If this is a read-only call, process it.
    505     if (CallValue::canHandle(Inst)) {
    506       // If we have an available version of this call, and if it is the right
    507       // generation, replace this instruction.
    508       std::pair<Value*, unsigned> InVal = AvailableCalls->lookup(Inst);
    509       if (InVal.first != 0 && InVal.second == CurrentGeneration) {
    510         DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst << "  to: "
    511                      << *InVal.first << '\n');
    512         if (!Inst->use_empty()) Inst->replaceAllUsesWith(InVal.first);
    513         Inst->eraseFromParent();
    514         Changed = true;
    515         ++NumCSECall;
    516         continue;
    517       }
    518 
    519       // Otherwise, remember that we have this instruction.
    520       AvailableCalls->insert(Inst,
    521                          std::pair<Value*, unsigned>(Inst, CurrentGeneration));
    522       continue;
    523     }
    524 
    525     // Okay, this isn't something we can CSE at all.  Check to see if it is
    526     // something that could modify memory.  If so, our available memory values
    527     // cannot be used so bump the generation count.
    528     if (Inst->mayWriteToMemory()) {
    529       ++CurrentGeneration;
    530 
    531       if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
    532         // We do a trivial form of DSE if there are two stores to the same
    533         // location with no intervening loads.  Delete the earlier store.
    534         if (LastStore &&
    535             LastStore->getPointerOperand() == SI->getPointerOperand()) {
    536           DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore << "  due to: "
    537                        << *Inst << '\n');
    538           LastStore->eraseFromParent();
    539           Changed = true;
    540           ++NumDSE;
    541           LastStore = 0;
    542           continue;
    543         }
    544 
    545         // Okay, we just invalidated anything we knew about loaded values.  Try
    546         // to salvage *something* by remembering that the stored value is a live
    547         // version of the pointer.  It is safe to forward from volatile stores
    548         // to non-volatile loads, so we don't have to check for volatility of
    549         // the store.
    550         AvailableLoads->insert(SI->getPointerOperand(),
    551          std::pair<Value*, unsigned>(SI->getValueOperand(), CurrentGeneration));
    552 
    553         // Remember that this was the last store we saw for DSE.
    554         if (SI->isSimple())
    555           LastStore = SI;
    556       }
    557     }
    558   }
    559 
    560   return Changed;
    561 }
    562 
    563 
    564 bool EarlyCSE::runOnFunction(Function &F) {
    565   std::deque<StackNode *> nodesToProcess;
    566 
    567   TD = getAnalysisIfAvailable<DataLayout>();
    568   TLI = &getAnalysis<TargetLibraryInfo>();
    569   DT = &getAnalysis<DominatorTree>();
    570 
    571   // Tables that the pass uses when walking the domtree.
    572   ScopedHTType AVTable;
    573   AvailableValues = &AVTable;
    574   LoadHTType LoadTable;
    575   AvailableLoads = &LoadTable;
    576   CallHTType CallTable;
    577   AvailableCalls = &CallTable;
    578 
    579   CurrentGeneration = 0;
    580   bool Changed = false;
    581 
    582   // Process the root node.
    583   nodesToProcess.push_front(
    584       new StackNode(AvailableValues, AvailableLoads, AvailableCalls,
    585                     CurrentGeneration, DT->getRootNode(),
    586                     DT->getRootNode()->begin(),
    587                     DT->getRootNode()->end()));
    588 
    589   // Save the current generation.
    590   unsigned LiveOutGeneration = CurrentGeneration;
    591 
    592   // Process the stack.
    593   while (!nodesToProcess.empty()) {
    594     // Grab the first item off the stack. Set the current generation, remove
    595     // the node from the stack, and process it.
    596     StackNode *NodeToProcess = nodesToProcess.front();
    597 
    598     // Initialize class members.
    599     CurrentGeneration = NodeToProcess->currentGeneration();
    600 
    601     // Check if the node needs to be processed.
    602     if (!NodeToProcess->isProcessed()) {
    603       // Process the node.
    604       Changed |= processNode(NodeToProcess->node());
    605       NodeToProcess->childGeneration(CurrentGeneration);
    606       NodeToProcess->process();
    607     } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
    608       // Push the next child onto the stack.
    609       DomTreeNode *child = NodeToProcess->nextChild();
    610       nodesToProcess.push_front(
    611           new StackNode(AvailableValues,
    612                         AvailableLoads,
    613                         AvailableCalls,
    614                         NodeToProcess->childGeneration(), child,
    615                         child->begin(), child->end()));
    616     } else {
    617       // It has been processed, and there are no more children to process,
    618       // so delete it and pop it off the stack.
    619       delete NodeToProcess;
    620       nodesToProcess.pop_front();
    621     }
    622   } // while (!nodes...)
    623 
    624   // Reset the current generation.
    625   CurrentGeneration = LiveOutGeneration;
    626 
    627   return Changed;
    628 }
    629