LLVM API Documentation

GVN.cpp
Go to the documentation of this file.
00001 //===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
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 pass performs global value numbering to eliminate fully redundant
00011 // instructions.  It also performs simple dead load elimination.
00012 //
00013 // Note that this pass does the value numbering itself; it does not use the
00014 // ValueNumbering analysis passes.
00015 //
00016 //===----------------------------------------------------------------------===//
00017 
00018 #define DEBUG_TYPE "gvn"
00019 #include "llvm/Transforms/Scalar.h"
00020 #include "llvm/ADT/DenseMap.h"
00021 #include "llvm/ADT/DepthFirstIterator.h"
00022 #include "llvm/ADT/Hashing.h"
00023 #include "llvm/ADT/SetVector.h"
00024 #include "llvm/ADT/SmallPtrSet.h"
00025 #include "llvm/ADT/Statistic.h"
00026 #include "llvm/Analysis/AliasAnalysis.h"
00027 #include "llvm/Analysis/CFG.h"
00028 #include "llvm/Analysis/ConstantFolding.h"
00029 #include "llvm/Analysis/InstructionSimplify.h"
00030 #include "llvm/Analysis/Loads.h"
00031 #include "llvm/Analysis/MemoryBuiltins.h"
00032 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
00033 #include "llvm/Analysis/PHITransAddr.h"
00034 #include "llvm/Analysis/ValueTracking.h"
00035 #include "llvm/IR/DataLayout.h"
00036 #include "llvm/IR/Dominators.h"
00037 #include "llvm/IR/GlobalVariable.h"
00038 #include "llvm/IR/IRBuilder.h"
00039 #include "llvm/IR/IntrinsicInst.h"
00040 #include "llvm/IR/LLVMContext.h"
00041 #include "llvm/IR/Metadata.h"
00042 #include "llvm/IR/PatternMatch.h"
00043 #include "llvm/Support/Allocator.h"
00044 #include "llvm/Support/CommandLine.h"
00045 #include "llvm/Support/Debug.h"
00046 #include "llvm/Target/TargetLibraryInfo.h"
00047 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00048 #include "llvm/Transforms/Utils/SSAUpdater.h"
00049 #include <vector>
00050 using namespace llvm;
00051 using namespace PatternMatch;
00052 
00053 STATISTIC(NumGVNInstr,  "Number of instructions deleted");
00054 STATISTIC(NumGVNLoad,   "Number of loads deleted");
00055 STATISTIC(NumGVNPRE,    "Number of instructions PRE'd");
00056 STATISTIC(NumGVNBlocks, "Number of blocks merged");
00057 STATISTIC(NumGVNSimpl,  "Number of instructions simplified");
00058 STATISTIC(NumGVNEqProp, "Number of equalities propagated");
00059 STATISTIC(NumPRELoad,   "Number of loads PRE'd");
00060 
00061 static cl::opt<bool> EnablePRE("enable-pre",
00062                                cl::init(true), cl::Hidden);
00063 static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
00064 
00065 // Maximum allowed recursion depth.
00066 static cl::opt<uint32_t>
00067 MaxRecurseDepth("max-recurse-depth", cl::Hidden, cl::init(1000), cl::ZeroOrMore,
00068                 cl::desc("Max recurse depth (default = 1000)"));
00069 
00070 //===----------------------------------------------------------------------===//
00071 //                         ValueTable Class
00072 //===----------------------------------------------------------------------===//
00073 
00074 /// This class holds the mapping between values and value numbers.  It is used
00075 /// as an efficient mechanism to determine the expression-wise equivalence of
00076 /// two values.
00077 namespace {
00078   struct Expression {
00079     uint32_t opcode;
00080     Type *type;
00081     SmallVector<uint32_t, 4> varargs;
00082 
00083     Expression(uint32_t o = ~2U) : opcode(o) { }
00084 
00085     bool operator==(const Expression &other) const {
00086       if (opcode != other.opcode)
00087         return false;
00088       if (opcode == ~0U || opcode == ~1U)
00089         return true;
00090       if (type != other.type)
00091         return false;
00092       if (varargs != other.varargs)
00093         return false;
00094       return true;
00095     }
00096 
00097     friend hash_code hash_value(const Expression &Value) {
00098       return hash_combine(Value.opcode, Value.type,
00099                           hash_combine_range(Value.varargs.begin(),
00100                                              Value.varargs.end()));
00101     }
00102   };
00103 
00104   class ValueTable {
00105     DenseMap<Value*, uint32_t> valueNumbering;
00106     DenseMap<Expression, uint32_t> expressionNumbering;
00107     AliasAnalysis *AA;
00108     MemoryDependenceAnalysis *MD;
00109     DominatorTree *DT;
00110 
00111     uint32_t nextValueNumber;
00112 
00113     Expression create_expression(Instruction* I);
00114     Expression create_cmp_expression(unsigned Opcode,
00115                                      CmpInst::Predicate Predicate,
00116                                      Value *LHS, Value *RHS);
00117     Expression create_extractvalue_expression(ExtractValueInst* EI);
00118     uint32_t lookup_or_add_call(CallInst* C);
00119   public:
00120     ValueTable() : nextValueNumber(1) { }
00121     uint32_t lookup_or_add(Value *V);
00122     uint32_t lookup(Value *V) const;
00123     uint32_t lookup_or_add_cmp(unsigned Opcode, CmpInst::Predicate Pred,
00124                                Value *LHS, Value *RHS);
00125     void add(Value *V, uint32_t num);
00126     void clear();
00127     void erase(Value *v);
00128     void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
00129     AliasAnalysis *getAliasAnalysis() const { return AA; }
00130     void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
00131     void setDomTree(DominatorTree* D) { DT = D; }
00132     uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
00133     void verifyRemoved(const Value *) const;
00134   };
00135 }
00136 
00137 namespace llvm {
00138 template <> struct DenseMapInfo<Expression> {
00139   static inline Expression getEmptyKey() {
00140     return ~0U;
00141   }
00142 
00143   static inline Expression getTombstoneKey() {
00144     return ~1U;
00145   }
00146 
00147   static unsigned getHashValue(const Expression e) {
00148     using llvm::hash_value;
00149     return static_cast<unsigned>(hash_value(e));
00150   }
00151   static bool isEqual(const Expression &LHS, const Expression &RHS) {
00152     return LHS == RHS;
00153   }
00154 };
00155 
00156 }
00157 
00158 //===----------------------------------------------------------------------===//
00159 //                     ValueTable Internal Functions
00160 //===----------------------------------------------------------------------===//
00161 
00162 Expression ValueTable::create_expression(Instruction *I) {
00163   Expression e;
00164   e.type = I->getType();
00165   e.opcode = I->getOpcode();
00166   for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
00167        OI != OE; ++OI)
00168     e.varargs.push_back(lookup_or_add(*OI));
00169   if (I->isCommutative()) {
00170     // Ensure that commutative instructions that only differ by a permutation
00171     // of their operands get the same value number by sorting the operand value
00172     // numbers.  Since all commutative instructions have two operands it is more
00173     // efficient to sort by hand rather than using, say, std::sort.
00174     assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
00175     if (e.varargs[0] > e.varargs[1])
00176       std::swap(e.varargs[0], e.varargs[1]);
00177   }
00178 
00179   if (CmpInst *C = dyn_cast<CmpInst>(I)) {
00180     // Sort the operand value numbers so x<y and y>x get the same value number.
00181     CmpInst::Predicate Predicate = C->getPredicate();
00182     if (e.varargs[0] > e.varargs[1]) {
00183       std::swap(e.varargs[0], e.varargs[1]);
00184       Predicate = CmpInst::getSwappedPredicate(Predicate);
00185     }
00186     e.opcode = (C->getOpcode() << 8) | Predicate;
00187   } else if (InsertValueInst *E = dyn_cast<InsertValueInst>(I)) {
00188     for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
00189          II != IE; ++II)
00190       e.varargs.push_back(*II);
00191   }
00192 
00193   return e;
00194 }
00195 
00196 Expression ValueTable::create_cmp_expression(unsigned Opcode,
00197                                              CmpInst::Predicate Predicate,
00198                                              Value *LHS, Value *RHS) {
00199   assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
00200          "Not a comparison!");
00201   Expression e;
00202   e.type = CmpInst::makeCmpResultType(LHS->getType());
00203   e.varargs.push_back(lookup_or_add(LHS));
00204   e.varargs.push_back(lookup_or_add(RHS));
00205 
00206   // Sort the operand value numbers so x<y and y>x get the same value number.
00207   if (e.varargs[0] > e.varargs[1]) {
00208     std::swap(e.varargs[0], e.varargs[1]);
00209     Predicate = CmpInst::getSwappedPredicate(Predicate);
00210   }
00211   e.opcode = (Opcode << 8) | Predicate;
00212   return e;
00213 }
00214 
00215 Expression ValueTable::create_extractvalue_expression(ExtractValueInst *EI) {
00216   assert(EI != 0 && "Not an ExtractValueInst?");
00217   Expression e;
00218   e.type = EI->getType();
00219   e.opcode = 0;
00220 
00221   IntrinsicInst *I = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
00222   if (I != 0 && EI->getNumIndices() == 1 && *EI->idx_begin() == 0 ) {
00223     // EI might be an extract from one of our recognised intrinsics. If it
00224     // is we'll synthesize a semantically equivalent expression instead on
00225     // an extract value expression.
00226     switch (I->getIntrinsicID()) {
00227       case Intrinsic::sadd_with_overflow:
00228       case Intrinsic::uadd_with_overflow:
00229         e.opcode = Instruction::Add;
00230         break;
00231       case Intrinsic::ssub_with_overflow:
00232       case Intrinsic::usub_with_overflow:
00233         e.opcode = Instruction::Sub;
00234         break;
00235       case Intrinsic::smul_with_overflow:
00236       case Intrinsic::umul_with_overflow:
00237         e.opcode = Instruction::Mul;
00238         break;
00239       default:
00240         break;
00241     }
00242 
00243     if (e.opcode != 0) {
00244       // Intrinsic recognized. Grab its args to finish building the expression.
00245       assert(I->getNumArgOperands() == 2 &&
00246              "Expect two args for recognised intrinsics.");
00247       e.varargs.push_back(lookup_or_add(I->getArgOperand(0)));
00248       e.varargs.push_back(lookup_or_add(I->getArgOperand(1)));
00249       return e;
00250     }
00251   }
00252 
00253   // Not a recognised intrinsic. Fall back to producing an extract value
00254   // expression.
00255   e.opcode = EI->getOpcode();
00256   for (Instruction::op_iterator OI = EI->op_begin(), OE = EI->op_end();
00257        OI != OE; ++OI)
00258     e.varargs.push_back(lookup_or_add(*OI));
00259 
00260   for (ExtractValueInst::idx_iterator II = EI->idx_begin(), IE = EI->idx_end();
00261          II != IE; ++II)
00262     e.varargs.push_back(*II);
00263 
00264   return e;
00265 }
00266 
00267 //===----------------------------------------------------------------------===//
00268 //                     ValueTable External Functions
00269 //===----------------------------------------------------------------------===//
00270 
00271 /// add - Insert a value into the table with a specified value number.
00272 void ValueTable::add(Value *V, uint32_t num) {
00273   valueNumbering.insert(std::make_pair(V, num));
00274 }
00275 
00276 uint32_t ValueTable::lookup_or_add_call(CallInst *C) {
00277   if (AA->doesNotAccessMemory(C)) {
00278     Expression exp = create_expression(C);
00279     uint32_t &e = expressionNumbering[exp];
00280     if (!e) e = nextValueNumber++;
00281     valueNumbering[C] = e;
00282     return e;
00283   } else if (AA->onlyReadsMemory(C)) {
00284     Expression exp = create_expression(C);
00285     uint32_t &e = expressionNumbering[exp];
00286     if (!e) {
00287       e = nextValueNumber++;
00288       valueNumbering[C] = e;
00289       return e;
00290     }
00291     if (!MD) {
00292       e = nextValueNumber++;
00293       valueNumbering[C] = e;
00294       return e;
00295     }
00296 
00297     MemDepResult local_dep = MD->getDependency(C);
00298 
00299     if (!local_dep.isDef() && !local_dep.isNonLocal()) {
00300       valueNumbering[C] =  nextValueNumber;
00301       return nextValueNumber++;
00302     }
00303 
00304     if (local_dep.isDef()) {
00305       CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
00306 
00307       if (local_cdep->getNumArgOperands() != C->getNumArgOperands()) {
00308         valueNumbering[C] = nextValueNumber;
00309         return nextValueNumber++;
00310       }
00311 
00312       for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
00313         uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
00314         uint32_t cd_vn = lookup_or_add(local_cdep->getArgOperand(i));
00315         if (c_vn != cd_vn) {
00316           valueNumbering[C] = nextValueNumber;
00317           return nextValueNumber++;
00318         }
00319       }
00320 
00321       uint32_t v = lookup_or_add(local_cdep);
00322       valueNumbering[C] = v;
00323       return v;
00324     }
00325 
00326     // Non-local case.
00327     const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
00328       MD->getNonLocalCallDependency(CallSite(C));
00329     // FIXME: Move the checking logic to MemDep!
00330     CallInst* cdep = 0;
00331 
00332     // Check to see if we have a single dominating call instruction that is
00333     // identical to C.
00334     for (unsigned i = 0, e = deps.size(); i != e; ++i) {
00335       const NonLocalDepEntry *I = &deps[i];
00336       if (I->getResult().isNonLocal())
00337         continue;
00338 
00339       // We don't handle non-definitions.  If we already have a call, reject
00340       // instruction dependencies.
00341       if (!I->getResult().isDef() || cdep != 0) {
00342         cdep = 0;
00343         break;
00344       }
00345 
00346       CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst());
00347       // FIXME: All duplicated with non-local case.
00348       if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){
00349         cdep = NonLocalDepCall;
00350         continue;
00351       }
00352 
00353       cdep = 0;
00354       break;
00355     }
00356 
00357     if (!cdep) {
00358       valueNumbering[C] = nextValueNumber;
00359       return nextValueNumber++;
00360     }
00361 
00362     if (cdep->getNumArgOperands() != C->getNumArgOperands()) {
00363       valueNumbering[C] = nextValueNumber;
00364       return nextValueNumber++;
00365     }
00366     for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
00367       uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
00368       uint32_t cd_vn = lookup_or_add(cdep->getArgOperand(i));
00369       if (c_vn != cd_vn) {
00370         valueNumbering[C] = nextValueNumber;
00371         return nextValueNumber++;
00372       }
00373     }
00374 
00375     uint32_t v = lookup_or_add(cdep);
00376     valueNumbering[C] = v;
00377     return v;
00378 
00379   } else {
00380     valueNumbering[C] = nextValueNumber;
00381     return nextValueNumber++;
00382   }
00383 }
00384 
00385 /// lookup_or_add - Returns the value number for the specified value, assigning
00386 /// it a new number if it did not have one before.
00387 uint32_t ValueTable::lookup_or_add(Value *V) {
00388   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
00389   if (VI != valueNumbering.end())
00390     return VI->second;
00391 
00392   if (!isa<Instruction>(V)) {
00393     valueNumbering[V] = nextValueNumber;
00394     return nextValueNumber++;
00395   }
00396 
00397   Instruction* I = cast<Instruction>(V);
00398   Expression exp;
00399   switch (I->getOpcode()) {
00400     case Instruction::Call:
00401       return lookup_or_add_call(cast<CallInst>(I));
00402     case Instruction::Add:
00403     case Instruction::FAdd:
00404     case Instruction::Sub:
00405     case Instruction::FSub:
00406     case Instruction::Mul:
00407     case Instruction::FMul:
00408     case Instruction::UDiv:
00409     case Instruction::SDiv:
00410     case Instruction::FDiv:
00411     case Instruction::URem:
00412     case Instruction::SRem:
00413     case Instruction::FRem:
00414     case Instruction::Shl:
00415     case Instruction::LShr:
00416     case Instruction::AShr:
00417     case Instruction::And:
00418     case Instruction::Or:
00419     case Instruction::Xor:
00420     case Instruction::ICmp:
00421     case Instruction::FCmp:
00422     case Instruction::Trunc:
00423     case Instruction::ZExt:
00424     case Instruction::SExt:
00425     case Instruction::FPToUI:
00426     case Instruction::FPToSI:
00427     case Instruction::UIToFP:
00428     case Instruction::SIToFP:
00429     case Instruction::FPTrunc:
00430     case Instruction::FPExt:
00431     case Instruction::PtrToInt:
00432     case Instruction::IntToPtr:
00433     case Instruction::BitCast:
00434     case Instruction::Select:
00435     case Instruction::ExtractElement:
00436     case Instruction::InsertElement:
00437     case Instruction::ShuffleVector:
00438     case Instruction::InsertValue:
00439     case Instruction::GetElementPtr:
00440       exp = create_expression(I);
00441       break;
00442     case Instruction::ExtractValue:
00443       exp = create_extractvalue_expression(cast<ExtractValueInst>(I));
00444       break;
00445     default:
00446       valueNumbering[V] = nextValueNumber;
00447       return nextValueNumber++;
00448   }
00449 
00450   uint32_t& e = expressionNumbering[exp];
00451   if (!e) e = nextValueNumber++;
00452   valueNumbering[V] = e;
00453   return e;
00454 }
00455 
00456 /// lookup - Returns the value number of the specified value. Fails if
00457 /// the value has not yet been numbered.
00458 uint32_t ValueTable::lookup(Value *V) const {
00459   DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
00460   assert(VI != valueNumbering.end() && "Value not numbered?");
00461   return VI->second;
00462 }
00463 
00464 /// lookup_or_add_cmp - Returns the value number of the given comparison,
00465 /// assigning it a new number if it did not have one before.  Useful when
00466 /// we deduced the result of a comparison, but don't immediately have an
00467 /// instruction realizing that comparison to hand.
00468 uint32_t ValueTable::lookup_or_add_cmp(unsigned Opcode,
00469                                        CmpInst::Predicate Predicate,
00470                                        Value *LHS, Value *RHS) {
00471   Expression exp = create_cmp_expression(Opcode, Predicate, LHS, RHS);
00472   uint32_t& e = expressionNumbering[exp];
00473   if (!e) e = nextValueNumber++;
00474   return e;
00475 }
00476 
00477 /// clear - Remove all entries from the ValueTable.
00478 void ValueTable::clear() {
00479   valueNumbering.clear();
00480   expressionNumbering.clear();
00481   nextValueNumber = 1;
00482 }
00483 
00484 /// erase - Remove a value from the value numbering.
00485 void ValueTable::erase(Value *V) {
00486   valueNumbering.erase(V);
00487 }
00488 
00489 /// verifyRemoved - Verify that the value is removed from all internal data
00490 /// structures.
00491 void ValueTable::verifyRemoved(const Value *V) const {
00492   for (DenseMap<Value*, uint32_t>::const_iterator
00493          I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
00494     assert(I->first != V && "Inst still occurs in value numbering map!");
00495   }
00496 }
00497 
00498 //===----------------------------------------------------------------------===//
00499 //                                GVN Pass
00500 //===----------------------------------------------------------------------===//
00501 
00502 namespace {
00503   class GVN;
00504   struct AvailableValueInBlock {
00505     /// BB - The basic block in question.
00506     BasicBlock *BB;
00507     enum ValType {
00508       SimpleVal,  // A simple offsetted value that is accessed.
00509       LoadVal,    // A value produced by a load.
00510       MemIntrin,  // A memory intrinsic which is loaded from.
00511       UndefVal    // A UndefValue representing a value from dead block (which
00512                   // is not yet physically removed from the CFG). 
00513     };
00514   
00515     /// V - The value that is live out of the block.
00516     PointerIntPair<Value *, 2, ValType> Val;
00517   
00518     /// Offset - The byte offset in Val that is interesting for the load query.
00519     unsigned Offset;
00520   
00521     static AvailableValueInBlock get(BasicBlock *BB, Value *V,
00522                                      unsigned Offset = 0) {
00523       AvailableValueInBlock Res;
00524       Res.BB = BB;
00525       Res.Val.setPointer(V);
00526       Res.Val.setInt(SimpleVal);
00527       Res.Offset = Offset;
00528       return Res;
00529     }
00530   
00531     static AvailableValueInBlock getMI(BasicBlock *BB, MemIntrinsic *MI,
00532                                        unsigned Offset = 0) {
00533       AvailableValueInBlock Res;
00534       Res.BB = BB;
00535       Res.Val.setPointer(MI);
00536       Res.Val.setInt(MemIntrin);
00537       Res.Offset = Offset;
00538       return Res;
00539     }
00540   
00541     static AvailableValueInBlock getLoad(BasicBlock *BB, LoadInst *LI,
00542                                          unsigned Offset = 0) {
00543       AvailableValueInBlock Res;
00544       Res.BB = BB;
00545       Res.Val.setPointer(LI);
00546       Res.Val.setInt(LoadVal);
00547       Res.Offset = Offset;
00548       return Res;
00549     }
00550 
00551     static AvailableValueInBlock getUndef(BasicBlock *BB) {
00552       AvailableValueInBlock Res;
00553       Res.BB = BB;
00554       Res.Val.setPointer(0);
00555       Res.Val.setInt(UndefVal);
00556       Res.Offset = 0;
00557       return Res;
00558     }
00559 
00560     bool isSimpleValue() const { return Val.getInt() == SimpleVal; }
00561     bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; }
00562     bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; }
00563     bool isUndefValue() const { return Val.getInt() == UndefVal; }
00564   
00565     Value *getSimpleValue() const {
00566       assert(isSimpleValue() && "Wrong accessor");
00567       return Val.getPointer();
00568     }
00569   
00570     LoadInst *getCoercedLoadValue() const {
00571       assert(isCoercedLoadValue() && "Wrong accessor");
00572       return cast<LoadInst>(Val.getPointer());
00573     }
00574   
00575     MemIntrinsic *getMemIntrinValue() const {
00576       assert(isMemIntrinValue() && "Wrong accessor");
00577       return cast<MemIntrinsic>(Val.getPointer());
00578     }
00579   
00580     /// MaterializeAdjustedValue - Emit code into this block to adjust the value
00581     /// defined here to the specified type.  This handles various coercion cases.
00582     Value *MaterializeAdjustedValue(Type *LoadTy, GVN &gvn) const;
00583   };
00584 
00585   class GVN : public FunctionPass {
00586     bool NoLoads;
00587     MemoryDependenceAnalysis *MD;
00588     DominatorTree *DT;
00589     const DataLayout *DL;
00590     const TargetLibraryInfo *TLI;
00591     SetVector<BasicBlock *> DeadBlocks;
00592 
00593     ValueTable VN;
00594 
00595     /// LeaderTable - A mapping from value numbers to lists of Value*'s that
00596     /// have that value number.  Use findLeader to query it.
00597     struct LeaderTableEntry {
00598       Value *Val;
00599       const BasicBlock *BB;
00600       LeaderTableEntry *Next;
00601     };
00602     DenseMap<uint32_t, LeaderTableEntry> LeaderTable;
00603     BumpPtrAllocator TableAllocator;
00604 
00605     SmallVector<Instruction*, 8> InstrsToErase;
00606 
00607     typedef SmallVector<NonLocalDepResult, 64> LoadDepVect;
00608     typedef SmallVector<AvailableValueInBlock, 64> AvailValInBlkVect;
00609     typedef SmallVector<BasicBlock*, 64> UnavailBlkVect;
00610 
00611   public:
00612     static char ID; // Pass identification, replacement for typeid
00613     explicit GVN(bool noloads = false)
00614         : FunctionPass(ID), NoLoads(noloads), MD(0) {
00615       initializeGVNPass(*PassRegistry::getPassRegistry());
00616     }
00617 
00618     bool runOnFunction(Function &F) override;
00619 
00620     /// markInstructionForDeletion - This removes the specified instruction from
00621     /// our various maps and marks it for deletion.
00622     void markInstructionForDeletion(Instruction *I) {
00623       VN.erase(I);
00624       InstrsToErase.push_back(I);
00625     }
00626 
00627     const DataLayout *getDataLayout() const { return DL; }
00628     DominatorTree &getDominatorTree() const { return *DT; }
00629     AliasAnalysis *getAliasAnalysis() const { return VN.getAliasAnalysis(); }
00630     MemoryDependenceAnalysis &getMemDep() const { return *MD; }
00631   private:
00632     /// addToLeaderTable - Push a new Value to the LeaderTable onto the list for
00633     /// its value number.
00634     void addToLeaderTable(uint32_t N, Value *V, const BasicBlock *BB) {
00635       LeaderTableEntry &Curr = LeaderTable[N];
00636       if (!Curr.Val) {
00637         Curr.Val = V;
00638         Curr.BB = BB;
00639         return;
00640       }
00641 
00642       LeaderTableEntry *Node = TableAllocator.Allocate<LeaderTableEntry>();
00643       Node->Val = V;
00644       Node->BB = BB;
00645       Node->Next = Curr.Next;
00646       Curr.Next = Node;
00647     }
00648 
00649     /// removeFromLeaderTable - Scan the list of values corresponding to a given
00650     /// value number, and remove the given instruction if encountered.
00651     void removeFromLeaderTable(uint32_t N, Instruction *I, BasicBlock *BB) {
00652       LeaderTableEntry* Prev = 0;
00653       LeaderTableEntry* Curr = &LeaderTable[N];
00654 
00655       while (Curr->Val != I || Curr->BB != BB) {
00656         Prev = Curr;
00657         Curr = Curr->Next;
00658       }
00659 
00660       if (Prev) {
00661         Prev->Next = Curr->Next;
00662       } else {
00663         if (!Curr->Next) {
00664           Curr->Val = 0;
00665           Curr->BB = 0;
00666         } else {
00667           LeaderTableEntry* Next = Curr->Next;
00668           Curr->Val = Next->Val;
00669           Curr->BB = Next->BB;
00670           Curr->Next = Next->Next;
00671         }
00672       }
00673     }
00674 
00675     // List of critical edges to be split between iterations.
00676     SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
00677 
00678     // This transformation requires dominator postdominator info
00679     void getAnalysisUsage(AnalysisUsage &AU) const override {
00680       AU.addRequired<DominatorTreeWrapperPass>();
00681       AU.addRequired<TargetLibraryInfo>();
00682       if (!NoLoads)
00683         AU.addRequired<MemoryDependenceAnalysis>();
00684       AU.addRequired<AliasAnalysis>();
00685 
00686       AU.addPreserved<DominatorTreeWrapperPass>();
00687       AU.addPreserved<AliasAnalysis>();
00688     }
00689 
00690 
00691     // Helper fuctions of redundant load elimination 
00692     bool processLoad(LoadInst *L);
00693     bool processNonLocalLoad(LoadInst *L);
00694     void AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps, 
00695                                  AvailValInBlkVect &ValuesPerBlock,
00696                                  UnavailBlkVect &UnavailableBlocks);
00697     bool PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock, 
00698                         UnavailBlkVect &UnavailableBlocks);
00699 
00700     // Other helper routines
00701     bool processInstruction(Instruction *I);
00702     bool processBlock(BasicBlock *BB);
00703     void dump(DenseMap<uint32_t, Value*> &d);
00704     bool iterateOnFunction(Function &F);
00705     bool performPRE(Function &F);
00706     Value *findLeader(const BasicBlock *BB, uint32_t num);
00707     void cleanupGlobalSets();
00708     void verifyRemoved(const Instruction *I) const;
00709     bool splitCriticalEdges();
00710     BasicBlock *splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ);
00711     unsigned replaceAllDominatedUsesWith(Value *From, Value *To,
00712                                          const BasicBlockEdge &Root);
00713     bool propagateEquality(Value *LHS, Value *RHS, const BasicBlockEdge &Root);
00714     bool processFoldableCondBr(BranchInst *BI);
00715     void addDeadBlock(BasicBlock *BB);
00716     void assignValNumForDeadCode();
00717   };
00718 
00719   char GVN::ID = 0;
00720 }
00721 
00722 // createGVNPass - The public interface to this file...
00723 FunctionPass *llvm::createGVNPass(bool NoLoads) {
00724   return new GVN(NoLoads);
00725 }
00726 
00727 INITIALIZE_PASS_BEGIN(GVN, "gvn", "Global Value Numbering", false, false)
00728 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
00729 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00730 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
00731 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
00732 INITIALIZE_PASS_END(GVN, "gvn", "Global Value Numbering", false, false)
00733 
00734 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00735 void GVN::dump(DenseMap<uint32_t, Value*>& d) {
00736   errs() << "{\n";
00737   for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
00738        E = d.end(); I != E; ++I) {
00739       errs() << I->first << "\n";
00740       I->second->dump();
00741   }
00742   errs() << "}\n";
00743 }
00744 #endif
00745 
00746 /// IsValueFullyAvailableInBlock - Return true if we can prove that the value
00747 /// we're analyzing is fully available in the specified block.  As we go, keep
00748 /// track of which blocks we know are fully alive in FullyAvailableBlocks.  This
00749 /// map is actually a tri-state map with the following values:
00750 ///   0) we know the block *is not* fully available.
00751 ///   1) we know the block *is* fully available.
00752 ///   2) we do not know whether the block is fully available or not, but we are
00753 ///      currently speculating that it will be.
00754 ///   3) we are speculating for this block and have used that to speculate for
00755 ///      other blocks.
00756 static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
00757                             DenseMap<BasicBlock*, char> &FullyAvailableBlocks,
00758                             uint32_t RecurseDepth) {
00759   if (RecurseDepth > MaxRecurseDepth)
00760     return false;
00761 
00762   // Optimistically assume that the block is fully available and check to see
00763   // if we already know about this block in one lookup.
00764   std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
00765     FullyAvailableBlocks.insert(std::make_pair(BB, 2));
00766 
00767   // If the entry already existed for this block, return the precomputed value.
00768   if (!IV.second) {
00769     // If this is a speculative "available" value, mark it as being used for
00770     // speculation of other blocks.
00771     if (IV.first->second == 2)
00772       IV.first->second = 3;
00773     return IV.first->second != 0;
00774   }
00775 
00776   // Otherwise, see if it is fully available in all predecessors.
00777   pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
00778 
00779   // If this block has no predecessors, it isn't live-in here.
00780   if (PI == PE)
00781     goto SpeculationFailure;
00782 
00783   for (; PI != PE; ++PI)
00784     // If the value isn't fully available in one of our predecessors, then it
00785     // isn't fully available in this block either.  Undo our previous
00786     // optimistic assumption and bail out.
00787     if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks,RecurseDepth+1))
00788       goto SpeculationFailure;
00789 
00790   return true;
00791 
00792 // SpeculationFailure - If we get here, we found out that this is not, after
00793 // all, a fully-available block.  We have a problem if we speculated on this and
00794 // used the speculation to mark other blocks as available.
00795 SpeculationFailure:
00796   char &BBVal = FullyAvailableBlocks[BB];
00797 
00798   // If we didn't speculate on this, just return with it set to false.
00799   if (BBVal == 2) {
00800     BBVal = 0;
00801     return false;
00802   }
00803 
00804   // If we did speculate on this value, we could have blocks set to 1 that are
00805   // incorrect.  Walk the (transitive) successors of this block and mark them as
00806   // 0 if set to one.
00807   SmallVector<BasicBlock*, 32> BBWorklist;
00808   BBWorklist.push_back(BB);
00809 
00810   do {
00811     BasicBlock *Entry = BBWorklist.pop_back_val();
00812     // Note that this sets blocks to 0 (unavailable) if they happen to not
00813     // already be in FullyAvailableBlocks.  This is safe.
00814     char &EntryVal = FullyAvailableBlocks[Entry];
00815     if (EntryVal == 0) continue;  // Already unavailable.
00816 
00817     // Mark as unavailable.
00818     EntryVal = 0;
00819 
00820     BBWorklist.append(succ_begin(Entry), succ_end(Entry));
00821   } while (!BBWorklist.empty());
00822 
00823   return false;
00824 }
00825 
00826 
00827 /// CanCoerceMustAliasedValueToLoad - Return true if
00828 /// CoerceAvailableValueToLoadType will succeed.
00829 static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
00830                                             Type *LoadTy,
00831                                             const DataLayout &DL) {
00832   // If the loaded or stored value is an first class array or struct, don't try
00833   // to transform them.  We need to be able to bitcast to integer.
00834   if (LoadTy->isStructTy() || LoadTy->isArrayTy() ||
00835       StoredVal->getType()->isStructTy() ||
00836       StoredVal->getType()->isArrayTy())
00837     return false;
00838 
00839   // The store has to be at least as big as the load.
00840   if (DL.getTypeSizeInBits(StoredVal->getType()) <
00841         DL.getTypeSizeInBits(LoadTy))
00842     return false;
00843 
00844   return true;
00845 }
00846 
00847 /// CoerceAvailableValueToLoadType - If we saw a store of a value to memory, and
00848 /// then a load from a must-aliased pointer of a different type, try to coerce
00849 /// the stored value.  LoadedTy is the type of the load we want to replace and
00850 /// InsertPt is the place to insert new instructions.
00851 ///
00852 /// If we can't do it, return null.
00853 static Value *CoerceAvailableValueToLoadType(Value *StoredVal,
00854                                              Type *LoadedTy,
00855                                              Instruction *InsertPt,
00856                                              const DataLayout &DL) {
00857   if (!CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, DL))
00858     return 0;
00859 
00860   // If this is already the right type, just return it.
00861   Type *StoredValTy = StoredVal->getType();
00862 
00863   uint64_t StoreSize = DL.getTypeSizeInBits(StoredValTy);
00864   uint64_t LoadSize = DL.getTypeSizeInBits(LoadedTy);
00865 
00866   // If the store and reload are the same size, we can always reuse it.
00867   if (StoreSize == LoadSize) {
00868     // Pointer to Pointer -> use bitcast.
00869     if (StoredValTy->getScalarType()->isPointerTy() &&
00870         LoadedTy->getScalarType()->isPointerTy())
00871       return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
00872 
00873     // Convert source pointers to integers, which can be bitcast.
00874     if (StoredValTy->getScalarType()->isPointerTy()) {
00875       StoredValTy = DL.getIntPtrType(StoredValTy);
00876       StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
00877     }
00878 
00879     Type *TypeToCastTo = LoadedTy;
00880     if (TypeToCastTo->getScalarType()->isPointerTy())
00881       TypeToCastTo = DL.getIntPtrType(TypeToCastTo);
00882 
00883     if (StoredValTy != TypeToCastTo)
00884       StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
00885 
00886     // Cast to pointer if the load needs a pointer type.
00887     if (LoadedTy->getScalarType()->isPointerTy())
00888       StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
00889 
00890     return StoredVal;
00891   }
00892 
00893   // If the loaded value is smaller than the available value, then we can
00894   // extract out a piece from it.  If the available value is too small, then we
00895   // can't do anything.
00896   assert(StoreSize >= LoadSize && "CanCoerceMustAliasedValueToLoad fail");
00897 
00898   // Convert source pointers to integers, which can be manipulated.
00899   if (StoredValTy->getScalarType()->isPointerTy()) {
00900     StoredValTy = DL.getIntPtrType(StoredValTy);
00901     StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
00902   }
00903 
00904   // Convert vectors and fp to integer, which can be manipulated.
00905   if (!StoredValTy->isIntegerTy()) {
00906     StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
00907     StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
00908   }
00909 
00910   // If this is a big-endian system, we need to shift the value down to the low
00911   // bits so that a truncate will work.
00912   if (DL.isBigEndian()) {
00913     Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
00914     StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
00915   }
00916 
00917   // Truncate the integer to the right size now.
00918   Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
00919   StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
00920 
00921   if (LoadedTy == NewIntTy)
00922     return StoredVal;
00923 
00924   // If the result is a pointer, inttoptr.
00925   if (LoadedTy->getScalarType()->isPointerTy())
00926     return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
00927 
00928   // Otherwise, bitcast.
00929   return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
00930 }
00931 
00932 /// AnalyzeLoadFromClobberingWrite - This function is called when we have a
00933 /// memdep query of a load that ends up being a clobbering memory write (store,
00934 /// memset, memcpy, memmove).  This means that the write *may* provide bits used
00935 /// by the load but we can't be sure because the pointers don't mustalias.
00936 ///
00937 /// Check this case to see if there is anything more we can do before we give
00938 /// up.  This returns -1 if we have to give up, or a byte number in the stored
00939 /// value of the piece that feeds the load.
00940 static int AnalyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr,
00941                                           Value *WritePtr,
00942                                           uint64_t WriteSizeInBits,
00943                                           const DataLayout &DL) {
00944   // If the loaded or stored value is a first class array or struct, don't try
00945   // to transform them.  We need to be able to bitcast to integer.
00946   if (LoadTy->isStructTy() || LoadTy->isArrayTy())
00947     return -1;
00948 
00949   int64_t StoreOffset = 0, LoadOffset = 0;
00950   Value *StoreBase = GetPointerBaseWithConstantOffset(WritePtr,StoreOffset,&DL);
00951   Value *LoadBase = GetPointerBaseWithConstantOffset(LoadPtr, LoadOffset, &DL);
00952   if (StoreBase != LoadBase)
00953     return -1;
00954 
00955   // If the load and store are to the exact same address, they should have been
00956   // a must alias.  AA must have gotten confused.
00957   // FIXME: Study to see if/when this happens.  One case is forwarding a memset
00958   // to a load from the base of the memset.
00959 #if 0
00960   if (LoadOffset == StoreOffset) {
00961     dbgs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
00962     << "Base       = " << *StoreBase << "\n"
00963     << "Store Ptr  = " << *WritePtr << "\n"
00964     << "Store Offs = " << StoreOffset << "\n"
00965     << "Load Ptr   = " << *LoadPtr << "\n";
00966     abort();
00967   }
00968 #endif
00969 
00970   // If the load and store don't overlap at all, the store doesn't provide
00971   // anything to the load.  In this case, they really don't alias at all, AA
00972   // must have gotten confused.
00973   uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy);
00974 
00975   if ((WriteSizeInBits & 7) | (LoadSize & 7))
00976     return -1;
00977   uint64_t StoreSize = WriteSizeInBits >> 3;  // Convert to bytes.
00978   LoadSize >>= 3;
00979 
00980 
00981   bool isAAFailure = false;
00982   if (StoreOffset < LoadOffset)
00983     isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
00984   else
00985     isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
00986 
00987   if (isAAFailure) {
00988 #if 0
00989     dbgs() << "STORE LOAD DEP WITH COMMON BASE:\n"
00990     << "Base       = " << *StoreBase << "\n"
00991     << "Store Ptr  = " << *WritePtr << "\n"
00992     << "Store Offs = " << StoreOffset << "\n"
00993     << "Load Ptr   = " << *LoadPtr << "\n";
00994     abort();
00995 #endif
00996     return -1;
00997   }
00998 
00999   // If the Load isn't completely contained within the stored bits, we don't
01000   // have all the bits to feed it.  We could do something crazy in the future
01001   // (issue a smaller load then merge the bits in) but this seems unlikely to be
01002   // valuable.
01003   if (StoreOffset > LoadOffset ||
01004       StoreOffset+StoreSize < LoadOffset+LoadSize)
01005     return -1;
01006 
01007   // Okay, we can do this transformation.  Return the number of bytes into the
01008   // store that the load is.
01009   return LoadOffset-StoreOffset;
01010 }
01011 
01012 /// AnalyzeLoadFromClobberingStore - This function is called when we have a
01013 /// memdep query of a load that ends up being a clobbering store.
01014 static int AnalyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr,
01015                                           StoreInst *DepSI,
01016                                           const DataLayout &DL) {
01017   // Cannot handle reading from store of first-class aggregate yet.
01018   if (DepSI->getValueOperand()->getType()->isStructTy() ||
01019       DepSI->getValueOperand()->getType()->isArrayTy())
01020     return -1;
01021 
01022   Value *StorePtr = DepSI->getPointerOperand();
01023   uint64_t StoreSize =DL.getTypeSizeInBits(DepSI->getValueOperand()->getType());
01024   return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
01025                                         StorePtr, StoreSize, DL);
01026 }
01027 
01028 /// AnalyzeLoadFromClobberingLoad - This function is called when we have a
01029 /// memdep query of a load that ends up being clobbered by another load.  See if
01030 /// the other load can feed into the second load.
01031 static int AnalyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr,
01032                                          LoadInst *DepLI, const DataLayout &DL){
01033   // Cannot handle reading from store of first-class aggregate yet.
01034   if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy())
01035     return -1;
01036 
01037   Value *DepPtr = DepLI->getPointerOperand();
01038   uint64_t DepSize = DL.getTypeSizeInBits(DepLI->getType());
01039   int R = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, DL);
01040   if (R != -1) return R;
01041 
01042   // If we have a load/load clobber an DepLI can be widened to cover this load,
01043   // then we should widen it!
01044   int64_t LoadOffs = 0;
01045   const Value *LoadBase =
01046     GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, &DL);
01047   unsigned LoadSize = DL.getTypeStoreSize(LoadTy);
01048 
01049   unsigned Size = MemoryDependenceAnalysis::
01050     getLoadLoadClobberFullWidthSize(LoadBase, LoadOffs, LoadSize, DepLI, DL);
01051   if (Size == 0) return -1;
01052 
01053   return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size*8, DL);
01054 }
01055 
01056 
01057 
01058 static int AnalyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr,
01059                                             MemIntrinsic *MI,
01060                                             const DataLayout &DL) {
01061   // If the mem operation is a non-constant size, we can't handle it.
01062   ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength());
01063   if (SizeCst == 0) return -1;
01064   uint64_t MemSizeInBits = SizeCst->getZExtValue()*8;
01065 
01066   // If this is memset, we just need to see if the offset is valid in the size
01067   // of the memset..
01068   if (MI->getIntrinsicID() == Intrinsic::memset)
01069     return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
01070                                           MemSizeInBits, DL);
01071 
01072   // If we have a memcpy/memmove, the only case we can handle is if this is a
01073   // copy from constant memory.  In that case, we can read directly from the
01074   // constant memory.
01075   MemTransferInst *MTI = cast<MemTransferInst>(MI);
01076 
01077   Constant *Src = dyn_cast<Constant>(MTI->getSource());
01078   if (Src == 0) return -1;
01079 
01080   GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Src, &DL));
01081   if (GV == 0 || !GV->isConstant()) return -1;
01082 
01083   // See if the access is within the bounds of the transfer.
01084   int Offset = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
01085                                               MI->getDest(), MemSizeInBits, DL);
01086   if (Offset == -1)
01087     return Offset;
01088 
01089   unsigned AS = Src->getType()->getPointerAddressSpace();
01090   // Otherwise, see if we can constant fold a load from the constant with the
01091   // offset applied as appropriate.
01092   Src = ConstantExpr::getBitCast(Src,
01093                                  Type::getInt8PtrTy(Src->getContext(), AS));
01094   Constant *OffsetCst =
01095     ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
01096   Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
01097   Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
01098   if (ConstantFoldLoadFromConstPtr(Src, &DL))
01099     return Offset;
01100   return -1;
01101 }
01102 
01103 
01104 /// GetStoreValueForLoad - This function is called when we have a
01105 /// memdep query of a load that ends up being a clobbering store.  This means
01106 /// that the store provides bits used by the load but we the pointers don't
01107 /// mustalias.  Check this case to see if there is anything more we can do
01108 /// before we give up.
01109 static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
01110                                    Type *LoadTy,
01111                                    Instruction *InsertPt, const DataLayout &DL){
01112   LLVMContext &Ctx = SrcVal->getType()->getContext();
01113 
01114   uint64_t StoreSize = (DL.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
01115   uint64_t LoadSize = (DL.getTypeSizeInBits(LoadTy) + 7) / 8;
01116 
01117   IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
01118 
01119   // Compute which bits of the stored value are being used by the load.  Convert
01120   // to an integer type to start with.
01121   if (SrcVal->getType()->getScalarType()->isPointerTy())
01122     SrcVal = Builder.CreatePtrToInt(SrcVal,
01123         DL.getIntPtrType(SrcVal->getType()));
01124   if (!SrcVal->getType()->isIntegerTy())
01125     SrcVal = Builder.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize*8));
01126 
01127   // Shift the bits to the least significant depending on endianness.
01128   unsigned ShiftAmt;
01129   if (DL.isLittleEndian())
01130     ShiftAmt = Offset*8;
01131   else
01132     ShiftAmt = (StoreSize-LoadSize-Offset)*8;
01133 
01134   if (ShiftAmt)
01135     SrcVal = Builder.CreateLShr(SrcVal, ShiftAmt);
01136 
01137   if (LoadSize != StoreSize)
01138     SrcVal = Builder.CreateTrunc(SrcVal, IntegerType::get(Ctx, LoadSize*8));
01139 
01140   return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, DL);
01141 }
01142 
01143 /// GetLoadValueForLoad - This function is called when we have a
01144 /// memdep query of a load that ends up being a clobbering load.  This means
01145 /// that the load *may* provide bits used by the load but we can't be sure
01146 /// because the pointers don't mustalias.  Check this case to see if there is
01147 /// anything more we can do before we give up.
01148 static Value *GetLoadValueForLoad(LoadInst *SrcVal, unsigned Offset,
01149                                   Type *LoadTy, Instruction *InsertPt,
01150                                   GVN &gvn) {
01151   const DataLayout &DL = *gvn.getDataLayout();
01152   // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to
01153   // widen SrcVal out to a larger load.
01154   unsigned SrcValSize = DL.getTypeStoreSize(SrcVal->getType());
01155   unsigned LoadSize = DL.getTypeStoreSize(LoadTy);
01156   if (Offset+LoadSize > SrcValSize) {
01157     assert(SrcVal->isSimple() && "Cannot widen volatile/atomic load!");
01158     assert(SrcVal->getType()->isIntegerTy() && "Can't widen non-integer load");
01159     // If we have a load/load clobber an DepLI can be widened to cover this
01160     // load, then we should widen it to the next power of 2 size big enough!
01161     unsigned NewLoadSize = Offset+LoadSize;
01162     if (!isPowerOf2_32(NewLoadSize))
01163       NewLoadSize = NextPowerOf2(NewLoadSize);
01164 
01165     Value *PtrVal = SrcVal->getPointerOperand();
01166 
01167     // Insert the new load after the old load.  This ensures that subsequent
01168     // memdep queries will find the new load.  We can't easily remove the old
01169     // load completely because it is already in the value numbering table.
01170     IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal));
01171     Type *DestPTy =
01172       IntegerType::get(LoadTy->getContext(), NewLoadSize*8);
01173     DestPTy = PointerType::get(DestPTy,
01174                                PtrVal->getType()->getPointerAddressSpace());
01175     Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc());
01176     PtrVal = Builder.CreateBitCast(PtrVal, DestPTy);
01177     LoadInst *NewLoad = Builder.CreateLoad(PtrVal);
01178     NewLoad->takeName(SrcVal);
01179     NewLoad->setAlignment(SrcVal->getAlignment());
01180 
01181     DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n");
01182     DEBUG(dbgs() << "TO: " << *NewLoad << "\n");
01183 
01184     // Replace uses of the original load with the wider load.  On a big endian
01185     // system, we need to shift down to get the relevant bits.
01186     Value *RV = NewLoad;
01187     if (DL.isBigEndian())
01188       RV = Builder.CreateLShr(RV,
01189                     NewLoadSize*8-SrcVal->getType()->getPrimitiveSizeInBits());
01190     RV = Builder.CreateTrunc(RV, SrcVal->getType());
01191     SrcVal->replaceAllUsesWith(RV);
01192 
01193     // We would like to use gvn.markInstructionForDeletion here, but we can't
01194     // because the load is already memoized into the leader map table that GVN
01195     // tracks.  It is potentially possible to remove the load from the table,
01196     // but then there all of the operations based on it would need to be
01197     // rehashed.  Just leave the dead load around.
01198     gvn.getMemDep().removeInstruction(SrcVal);
01199     SrcVal = NewLoad;
01200   }
01201 
01202   return GetStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, DL);
01203 }
01204 
01205 
01206 /// GetMemInstValueForLoad - This function is called when we have a
01207 /// memdep query of a load that ends up being a clobbering mem intrinsic.
01208 static Value *GetMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
01209                                      Type *LoadTy, Instruction *InsertPt,
01210                                      const DataLayout &DL){
01211   LLVMContext &Ctx = LoadTy->getContext();
01212   uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy)/8;
01213 
01214   IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
01215 
01216   // We know that this method is only called when the mem transfer fully
01217   // provides the bits for the load.
01218   if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) {
01219     // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
01220     // independently of what the offset is.
01221     Value *Val = MSI->getValue();
01222     if (LoadSize != 1)
01223       Val = Builder.CreateZExt(Val, IntegerType::get(Ctx, LoadSize*8));
01224 
01225     Value *OneElt = Val;
01226 
01227     // Splat the value out to the right number of bits.
01228     for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize; ) {
01229       // If we can double the number of bytes set, do it.
01230       if (NumBytesSet*2 <= LoadSize) {
01231         Value *ShVal = Builder.CreateShl(Val, NumBytesSet*8);
01232         Val = Builder.CreateOr(Val, ShVal);
01233         NumBytesSet <<= 1;
01234         continue;
01235       }
01236 
01237       // Otherwise insert one byte at a time.
01238       Value *ShVal = Builder.CreateShl(Val, 1*8);
01239       Val = Builder.CreateOr(OneElt, ShVal);
01240       ++NumBytesSet;
01241     }
01242 
01243     return CoerceAvailableValueToLoadType(Val, LoadTy, InsertPt, DL);
01244   }
01245 
01246   // Otherwise, this is a memcpy/memmove from a constant global.
01247   MemTransferInst *MTI = cast<MemTransferInst>(SrcInst);
01248   Constant *Src = cast<Constant>(MTI->getSource());
01249   unsigned AS = Src->getType()->getPointerAddressSpace();
01250 
01251   // Otherwise, see if we can constant fold a load from the constant with the
01252   // offset applied as appropriate.
01253   Src = ConstantExpr::getBitCast(Src,
01254                                  Type::getInt8PtrTy(Src->getContext(), AS));
01255   Constant *OffsetCst =
01256     ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
01257   Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
01258   Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
01259   return ConstantFoldLoadFromConstPtr(Src, &DL);
01260 }
01261 
01262 
01263 /// ConstructSSAForLoadSet - Given a set of loads specified by ValuesPerBlock,
01264 /// construct SSA form, allowing us to eliminate LI.  This returns the value
01265 /// that should be used at LI's definition site.
01266 static Value *ConstructSSAForLoadSet(LoadInst *LI,
01267                          SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
01268                                      GVN &gvn) {
01269   // Check for the fully redundant, dominating load case.  In this case, we can
01270   // just use the dominating value directly.
01271   if (ValuesPerBlock.size() == 1 &&
01272       gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
01273                                                LI->getParent())) {
01274     assert(!ValuesPerBlock[0].isUndefValue() && "Dead BB dominate this block");
01275     return ValuesPerBlock[0].MaterializeAdjustedValue(LI->getType(), gvn);
01276   }
01277 
01278   // Otherwise, we have to construct SSA form.
01279   SmallVector<PHINode*, 8> NewPHIs;
01280   SSAUpdater SSAUpdate(&NewPHIs);
01281   SSAUpdate.Initialize(LI->getType(), LI->getName());
01282 
01283   Type *LoadTy = LI->getType();
01284 
01285   for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
01286     const AvailableValueInBlock &AV = ValuesPerBlock[i];
01287     BasicBlock *BB = AV.BB;
01288 
01289     if (SSAUpdate.HasValueForBlock(BB))
01290       continue;
01291 
01292     SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LoadTy, gvn));
01293   }
01294 
01295   // Perform PHI construction.
01296   Value *V = SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
01297 
01298   // If new PHI nodes were created, notify alias analysis.
01299   if (V->getType()->getScalarType()->isPointerTy()) {
01300     AliasAnalysis *AA = gvn.getAliasAnalysis();
01301 
01302     for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
01303       AA->copyValue(LI, NewPHIs[i]);
01304 
01305     // Now that we've copied information to the new PHIs, scan through
01306     // them again and inform alias analysis that we've added potentially
01307     // escaping uses to any values that are operands to these PHIs.
01308     for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i) {
01309       PHINode *P = NewPHIs[i];
01310       for (unsigned ii = 0, ee = P->getNumIncomingValues(); ii != ee; ++ii) {
01311         unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
01312         AA->addEscapingUse(P->getOperandUse(jj));
01313       }
01314     }
01315   }
01316 
01317   return V;
01318 }
01319 
01320 Value *AvailableValueInBlock::MaterializeAdjustedValue(Type *LoadTy, GVN &gvn) const {
01321   Value *Res;
01322   if (isSimpleValue()) {
01323     Res = getSimpleValue();
01324     if (Res->getType() != LoadTy) {
01325       const DataLayout *DL = gvn.getDataLayout();
01326       assert(DL && "Need target data to handle type mismatch case");
01327       Res = GetStoreValueForLoad(Res, Offset, LoadTy, BB->getTerminator(),
01328                                  *DL);
01329   
01330       DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset << "  "
01331                    << *getSimpleValue() << '\n'
01332                    << *Res << '\n' << "\n\n\n");
01333     }
01334   } else if (isCoercedLoadValue()) {
01335     LoadInst *Load = getCoercedLoadValue();
01336     if (Load->getType() == LoadTy && Offset == 0) {
01337       Res = Load;
01338     } else {
01339       Res = GetLoadValueForLoad(Load, Offset, LoadTy, BB->getTerminator(),
01340                                 gvn);
01341   
01342       DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset << "  "
01343                    << *getCoercedLoadValue() << '\n'
01344                    << *Res << '\n' << "\n\n\n");
01345     }
01346   } else if (isMemIntrinValue()) {
01347     const DataLayout *DL = gvn.getDataLayout();
01348     assert(DL && "Need target data to handle type mismatch case");
01349     Res = GetMemInstValueForLoad(getMemIntrinValue(), Offset,
01350                                  LoadTy, BB->getTerminator(), *DL);
01351     DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
01352                  << "  " << *getMemIntrinValue() << '\n'
01353                  << *Res << '\n' << "\n\n\n");
01354   } else {
01355     assert(isUndefValue() && "Should be UndefVal");
01356     DEBUG(dbgs() << "GVN COERCED NONLOCAL Undef:\n";);
01357     return UndefValue::get(LoadTy);
01358   }
01359   return Res;
01360 }
01361 
01362 static bool isLifetimeStart(const Instruction *Inst) {
01363   if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
01364     return II->getIntrinsicID() == Intrinsic::lifetime_start;
01365   return false;
01366 }
01367 
01368 void GVN::AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps, 
01369                                   AvailValInBlkVect &ValuesPerBlock,
01370                                   UnavailBlkVect &UnavailableBlocks) {
01371 
01372   // Filter out useless results (non-locals, etc).  Keep track of the blocks
01373   // where we have a value available in repl, also keep track of whether we see
01374   // dependencies that produce an unknown value for the load (such as a call
01375   // that could potentially clobber the load).
01376   unsigned NumDeps = Deps.size();
01377   for (unsigned i = 0, e = NumDeps; i != e; ++i) {
01378     BasicBlock *DepBB = Deps[i].getBB();
01379     MemDepResult DepInfo = Deps[i].getResult();
01380 
01381     if (DeadBlocks.count(DepBB)) {
01382       // Dead dependent mem-op disguise as a load evaluating the same value
01383       // as the load in question.
01384       ValuesPerBlock.push_back(AvailableValueInBlock::getUndef(DepBB));
01385       continue;
01386     }
01387 
01388     if (!DepInfo.isDef() && !DepInfo.isClobber()) {
01389       UnavailableBlocks.push_back(DepBB);
01390       continue;
01391     }
01392 
01393     if (DepInfo.isClobber()) {
01394       // The address being loaded in this non-local block may not be the same as
01395       // the pointer operand of the load if PHI translation occurs.  Make sure
01396       // to consider the right address.
01397       Value *Address = Deps[i].getAddress();
01398 
01399       // If the dependence is to a store that writes to a superset of the bits
01400       // read by the load, we can extract the bits we need for the load from the
01401       // stored value.
01402       if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
01403         if (DL && Address) {
01404           int Offset = AnalyzeLoadFromClobberingStore(LI->getType(), Address,
01405                                                       DepSI, *DL);
01406           if (Offset != -1) {
01407             ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
01408                                                        DepSI->getValueOperand(),
01409                                                                 Offset));
01410             continue;
01411           }
01412         }
01413       }
01414 
01415       // Check to see if we have something like this:
01416       //    load i32* P
01417       //    load i8* (P+1)
01418       // if we have this, replace the later with an extraction from the former.
01419       if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInfo.getInst())) {
01420         // If this is a clobber and L is the first instruction in its block, then
01421         // we have the first instruction in the entry block.
01422         if (DepLI != LI && Address && DL) {
01423           int Offset = AnalyzeLoadFromClobberingLoad(LI->getType(),
01424                                                      LI->getPointerOperand(),
01425                                                      DepLI, *DL);
01426 
01427           if (Offset != -1) {
01428             ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB,DepLI,
01429                                                                     Offset));
01430             continue;
01431           }
01432         }
01433       }
01434 
01435       // If the clobbering value is a memset/memcpy/memmove, see if we can
01436       // forward a value on from it.
01437       if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInfo.getInst())) {
01438         if (DL && Address) {
01439           int Offset = AnalyzeLoadFromClobberingMemInst(LI->getType(), Address,
01440                                                         DepMI, *DL);
01441           if (Offset != -1) {
01442             ValuesPerBlock.push_back(AvailableValueInBlock::getMI(DepBB, DepMI,
01443                                                                   Offset));
01444             continue;
01445           }
01446         }
01447       }
01448 
01449       UnavailableBlocks.push_back(DepBB);
01450       continue;
01451     }
01452 
01453     // DepInfo.isDef() here
01454 
01455     Instruction *DepInst = DepInfo.getInst();
01456 
01457     // Loading the allocation -> undef.
01458     if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI) ||
01459         // Loading immediately after lifetime begin -> undef.
01460         isLifetimeStart(DepInst)) {
01461       ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
01462                                              UndefValue::get(LI->getType())));
01463       continue;
01464     }
01465 
01466     if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
01467       // Reject loads and stores that are to the same address but are of
01468       // different types if we have to.
01469       if (S->getValueOperand()->getType() != LI->getType()) {
01470         // If the stored value is larger or equal to the loaded value, we can
01471         // reuse it.
01472         if (DL == 0 || !CanCoerceMustAliasedValueToLoad(S->getValueOperand(),
01473                                                         LI->getType(), *DL)) {
01474           UnavailableBlocks.push_back(DepBB);
01475           continue;
01476         }
01477       }
01478 
01479       ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
01480                                                          S->getValueOperand()));
01481       continue;
01482     }
01483 
01484     if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
01485       // If the types mismatch and we can't handle it, reject reuse of the load.
01486       if (LD->getType() != LI->getType()) {
01487         // If the stored value is larger or equal to the loaded value, we can
01488         // reuse it.
01489         if (DL == 0 || !CanCoerceMustAliasedValueToLoad(LD, LI->getType(),*DL)){
01490           UnavailableBlocks.push_back(DepBB);
01491           continue;
01492         }
01493       }
01494       ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB, LD));
01495       continue;
01496     }
01497 
01498     UnavailableBlocks.push_back(DepBB);
01499   }
01500 }
01501 
01502 bool GVN::PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock, 
01503                          UnavailBlkVect &UnavailableBlocks) {
01504   // Okay, we have *some* definitions of the value.  This means that the value
01505   // is available in some of our (transitive) predecessors.  Lets think about
01506   // doing PRE of this load.  This will involve inserting a new load into the
01507   // predecessor when it's not available.  We could do this in general, but
01508   // prefer to not increase code size.  As such, we only do this when we know
01509   // that we only have to insert *one* load (which means we're basically moving
01510   // the load, not inserting a new one).
01511 
01512   SmallPtrSet<BasicBlock *, 4> Blockers;
01513   for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
01514     Blockers.insert(UnavailableBlocks[i]);
01515 
01516   // Let's find the first basic block with more than one predecessor.  Walk
01517   // backwards through predecessors if needed.
01518   BasicBlock *LoadBB = LI->getParent();
01519   BasicBlock *TmpBB = LoadBB;
01520 
01521   while (TmpBB->getSinglePredecessor()) {
01522     TmpBB = TmpBB->getSinglePredecessor();
01523     if (TmpBB == LoadBB) // Infinite (unreachable) loop.
01524       return false;
01525     if (Blockers.count(TmpBB))
01526       return false;
01527 
01528     // If any of these blocks has more than one successor (i.e. if the edge we
01529     // just traversed was critical), then there are other paths through this
01530     // block along which the load may not be anticipated.  Hoisting the load
01531     // above this block would be adding the load to execution paths along
01532     // which it was not previously executed.
01533     if (TmpBB->getTerminator()->getNumSuccessors() != 1)
01534       return false;
01535   }
01536 
01537   assert(TmpBB);
01538   LoadBB = TmpBB;
01539 
01540   // Check to see how many predecessors have the loaded value fully
01541   // available.
01542   DenseMap<BasicBlock*, Value*> PredLoads;
01543   DenseMap<BasicBlock*, char> FullyAvailableBlocks;
01544   for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
01545     FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
01546   for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
01547     FullyAvailableBlocks[UnavailableBlocks[i]] = false;
01548 
01549   SmallVector<BasicBlock *, 4> CriticalEdgePred;
01550   for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
01551        PI != E; ++PI) {
01552     BasicBlock *Pred = *PI;
01553     if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks, 0)) {
01554       continue;
01555     }
01556     PredLoads[Pred] = 0;
01557 
01558     if (Pred->getTerminator()->getNumSuccessors() != 1) {
01559       if (isa<IndirectBrInst>(Pred->getTerminator())) {
01560         DEBUG(dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
01561               << Pred->getName() << "': " << *LI << '\n');
01562         return false;
01563       }
01564 
01565       if (LoadBB->isLandingPad()) {
01566         DEBUG(dbgs()
01567               << "COULD NOT PRE LOAD BECAUSE OF LANDING PAD CRITICAL EDGE '"
01568               << Pred->getName() << "': " << *LI << '\n');
01569         return false;
01570       }
01571 
01572       CriticalEdgePred.push_back(Pred);
01573     }
01574   }
01575 
01576   // Decide whether PRE is profitable for this load.
01577   unsigned NumUnavailablePreds = PredLoads.size();
01578   assert(NumUnavailablePreds != 0 &&
01579          "Fully available value should already be eliminated!");
01580 
01581   // If this load is unavailable in multiple predecessors, reject it.
01582   // FIXME: If we could restructure the CFG, we could make a common pred with
01583   // all the preds that don't have an available LI and insert a new load into
01584   // that one block.
01585   if (NumUnavailablePreds != 1)
01586       return false;
01587 
01588   // Split critical edges, and update the unavailable predecessors accordingly.
01589   for (SmallVectorImpl<BasicBlock *>::iterator I = CriticalEdgePred.begin(),
01590          E = CriticalEdgePred.end(); I != E; I++) {
01591     BasicBlock *OrigPred = *I;
01592     BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB);
01593     PredLoads.erase(OrigPred);
01594     PredLoads[NewPred] = 0;
01595     DEBUG(dbgs() << "Split critical edge " << OrigPred->getName() << "->"
01596                  << LoadBB->getName() << '\n');
01597   }
01598 
01599   // Check if the load can safely be moved to all the unavailable predecessors.
01600   bool CanDoPRE = true;
01601   SmallVector<Instruction*, 8> NewInsts;
01602   for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
01603          E = PredLoads.end(); I != E; ++I) {
01604     BasicBlock *UnavailablePred = I->first;
01605 
01606     // Do PHI translation to get its value in the predecessor if necessary.  The
01607     // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
01608 
01609     // If all preds have a single successor, then we know it is safe to insert
01610     // the load on the pred (?!?), so we can insert code to materialize the
01611     // pointer if it is not available.
01612     PHITransAddr Address(LI->getPointerOperand(), DL);
01613     Value *LoadPtr = 0;
01614     LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred,
01615                                                 *DT, NewInsts);
01616 
01617     // If we couldn't find or insert a computation of this phi translated value,
01618     // we fail PRE.
01619     if (LoadPtr == 0) {
01620       DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
01621             << *LI->getPointerOperand() << "\n");
01622       CanDoPRE = false;
01623       break;
01624     }
01625 
01626     I->second = LoadPtr;
01627   }
01628 
01629   if (!CanDoPRE) {
01630     while (!NewInsts.empty()) {
01631       Instruction *I = NewInsts.pop_back_val();
01632       if (MD) MD->removeInstruction(I);
01633       I->eraseFromParent();
01634     }
01635     // HINT:Don't revert the edge-splitting as following transformation may 
01636     // also need to split these critial edges.
01637     return !CriticalEdgePred.empty();
01638   }
01639 
01640   // Okay, we can eliminate this load by inserting a reload in the predecessor
01641   // and using PHI construction to get the value in the other predecessors, do
01642   // it.
01643   DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
01644   DEBUG(if (!NewInsts.empty())
01645           dbgs() << "INSERTED " << NewInsts.size() << " INSTS: "
01646                  << *NewInsts.back() << '\n');
01647 
01648   // Assign value numbers to the new instructions.
01649   for (unsigned i = 0, e = NewInsts.size(); i != e; ++i) {
01650     // FIXME: We really _ought_ to insert these value numbers into their
01651     // parent's availability map.  However, in doing so, we risk getting into
01652     // ordering issues.  If a block hasn't been processed yet, we would be
01653     // marking a value as AVAIL-IN, which isn't what we intend.
01654     VN.lookup_or_add(NewInsts[i]);
01655   }
01656 
01657   for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
01658          E = PredLoads.end(); I != E; ++I) {
01659     BasicBlock *UnavailablePred = I->first;
01660     Value *LoadPtr = I->second;
01661 
01662     Instruction *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
01663                                         LI->getAlignment(),
01664                                         UnavailablePred->getTerminator());
01665 
01666     // Transfer the old load's TBAA tag to the new load.
01667     if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa))
01668       NewLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
01669 
01670     // Transfer DebugLoc.
01671     NewLoad->setDebugLoc(LI->getDebugLoc());
01672 
01673     // Add the newly created load.
01674     ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,
01675                                                         NewLoad));
01676     MD->invalidateCachedPointerInfo(LoadPtr);
01677     DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
01678   }
01679 
01680   // Perform PHI construction.
01681   Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
01682   LI->replaceAllUsesWith(V);
01683   if (isa<PHINode>(V))
01684     V->takeName(LI);
01685   if (V->getType()->getScalarType()->isPointerTy())
01686     MD->invalidateCachedPointerInfo(V);
01687   markInstructionForDeletion(LI);
01688   ++NumPRELoad;
01689   return true;
01690 }
01691 
01692 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
01693 /// non-local by performing PHI construction.
01694 bool GVN::processNonLocalLoad(LoadInst *LI) {
01695   // Step 1: Find the non-local dependencies of the load.
01696   LoadDepVect Deps;
01697   AliasAnalysis::Location Loc = VN.getAliasAnalysis()->getLocation(LI);
01698   MD->getNonLocalPointerDependency(Loc, true, LI->getParent(), Deps);
01699 
01700   // If we had to process more than one hundred blocks to find the
01701   // dependencies, this load isn't worth worrying about.  Optimizing
01702   // it will be too expensive.
01703   unsigned NumDeps = Deps.size();
01704   if (NumDeps > 100)
01705     return false;
01706 
01707   // If we had a phi translation failure, we'll have a single entry which is a
01708   // clobber in the current block.  Reject this early.
01709   if (NumDeps == 1 &&
01710       !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
01711     DEBUG(
01712       dbgs() << "GVN: non-local load ";
01713       LI->printAsOperand(dbgs());
01714       dbgs() << " has unknown dependencies\n";
01715     );
01716     return false;
01717   }
01718 
01719   // Step 2: Analyze the availability of the load
01720   AvailValInBlkVect ValuesPerBlock;
01721   UnavailBlkVect UnavailableBlocks;
01722   AnalyzeLoadAvailability(LI, Deps, ValuesPerBlock, UnavailableBlocks);
01723 
01724   // If we have no predecessors that produce a known value for this load, exit
01725   // early.
01726   if (ValuesPerBlock.empty())
01727     return false;
01728 
01729   // Step 3: Eliminate fully redundancy.
01730   //
01731   // If all of the instructions we depend on produce a known value for this
01732   // load, then it is fully redundant and we can use PHI insertion to compute
01733   // its value.  Insert PHIs and remove the fully redundant value now.
01734   if (UnavailableBlocks.empty()) {
01735     DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
01736 
01737     // Perform PHI construction.
01738     Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
01739     LI->replaceAllUsesWith(V);
01740 
01741     if (isa<PHINode>(V))
01742       V->takeName(LI);
01743     if (V->getType()->getScalarType()->isPointerTy())
01744       MD->invalidateCachedPointerInfo(V);
01745     markInstructionForDeletion(LI);
01746     ++NumGVNLoad;
01747     return true;
01748   }
01749 
01750   // Step 4: Eliminate partial redundancy.
01751   if (!EnablePRE || !EnableLoadPRE)
01752     return false;
01753 
01754   return PerformLoadPRE(LI, ValuesPerBlock, UnavailableBlocks);
01755 }
01756 
01757 
01758 static void patchReplacementInstruction(Instruction *I, Value *Repl) {
01759   // Patch the replacement so that it is not more restrictive than the value
01760   // being replaced.
01761   BinaryOperator *Op = dyn_cast<BinaryOperator>(I);
01762   BinaryOperator *ReplOp = dyn_cast<BinaryOperator>(Repl);
01763   if (Op && ReplOp && isa<OverflowingBinaryOperator>(Op) &&
01764       isa<OverflowingBinaryOperator>(ReplOp)) {
01765     if (ReplOp->hasNoSignedWrap() && !Op->hasNoSignedWrap())
01766       ReplOp->setHasNoSignedWrap(false);
01767     if (ReplOp->hasNoUnsignedWrap() && !Op->hasNoUnsignedWrap())
01768       ReplOp->setHasNoUnsignedWrap(false);
01769   }
01770   if (Instruction *ReplInst = dyn_cast<Instruction>(Repl)) {
01771     SmallVector<std::pair<unsigned, MDNode*>, 4> Metadata;
01772     ReplInst->getAllMetadataOtherThanDebugLoc(Metadata);
01773     for (int i = 0, n = Metadata.size(); i < n; ++i) {
01774       unsigned Kind = Metadata[i].first;
01775       MDNode *IMD = I->getMetadata(Kind);
01776       MDNode *ReplMD = Metadata[i].second;
01777       switch(Kind) {
01778       default:
01779         ReplInst->setMetadata(Kind, NULL); // Remove unknown metadata
01780         break;
01781       case LLVMContext::MD_dbg:
01782         llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
01783       case LLVMContext::MD_tbaa:
01784         ReplInst->setMetadata(Kind, MDNode::getMostGenericTBAA(IMD, ReplMD));
01785         break;
01786       case LLVMContext::MD_range:
01787         ReplInst->setMetadata(Kind, MDNode::getMostGenericRange(IMD, ReplMD));
01788         break;
01789       case LLVMContext::MD_prof:
01790         llvm_unreachable("MD_prof in a non-terminator instruction");
01791         break;
01792       case LLVMContext::MD_fpmath:
01793         ReplInst->setMetadata(Kind, MDNode::getMostGenericFPMath(IMD, ReplMD));
01794         break;
01795       }
01796     }
01797   }
01798 }
01799 
01800 static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
01801   patchReplacementInstruction(I, Repl);
01802   I->replaceAllUsesWith(Repl);
01803 }
01804 
01805 /// processLoad - Attempt to eliminate a load, first by eliminating it
01806 /// locally, and then attempting non-local elimination if that fails.
01807 bool GVN::processLoad(LoadInst *L) {
01808   if (!MD)
01809     return false;
01810 
01811   if (!L->isSimple())
01812     return false;
01813 
01814   if (L->use_empty()) {
01815     markInstructionForDeletion(L);
01816     return true;
01817   }
01818 
01819   // ... to a pointer that has been loaded from before...
01820   MemDepResult Dep = MD->getDependency(L);
01821 
01822   // If we have a clobber and target data is around, see if this is a clobber
01823   // that we can fix up through code synthesis.
01824   if (Dep.isClobber() && DL) {
01825     // Check to see if we have something like this:
01826     //   store i32 123, i32* %P
01827     //   %A = bitcast i32* %P to i8*
01828     //   %B = gep i8* %A, i32 1
01829     //   %C = load i8* %B
01830     //
01831     // We could do that by recognizing if the clobber instructions are obviously
01832     // a common base + constant offset, and if the previous store (or memset)
01833     // completely covers this load.  This sort of thing can happen in bitfield
01834     // access code.
01835     Value *AvailVal = 0;
01836     if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst())) {
01837       int Offset = AnalyzeLoadFromClobberingStore(L->getType(),
01838                                                   L->getPointerOperand(),
01839                                                   DepSI, *DL);
01840       if (Offset != -1)
01841         AvailVal = GetStoreValueForLoad(DepSI->getValueOperand(), Offset,
01842                                         L->getType(), L, *DL);
01843     }
01844 
01845     // Check to see if we have something like this:
01846     //    load i32* P
01847     //    load i8* (P+1)
01848     // if we have this, replace the later with an extraction from the former.
01849     if (LoadInst *DepLI = dyn_cast<LoadInst>(Dep.getInst())) {
01850       // If this is a clobber and L is the first instruction in its block, then
01851       // we have the first instruction in the entry block.
01852       if (DepLI == L)
01853         return false;
01854 
01855       int Offset = AnalyzeLoadFromClobberingLoad(L->getType(),
01856                                                  L->getPointerOperand(),
01857                                                  DepLI, *DL);
01858       if (Offset != -1)
01859         AvailVal = GetLoadValueForLoad(DepLI, Offset, L->getType(), L, *this);
01860     }
01861 
01862     // If the clobbering value is a memset/memcpy/memmove, see if we can forward
01863     // a value on from it.
01864     if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(Dep.getInst())) {
01865       int Offset = AnalyzeLoadFromClobberingMemInst(L->getType(),
01866                                                     L->getPointerOperand(),
01867                                                     DepMI, *DL);
01868       if (Offset != -1)
01869         AvailVal = GetMemInstValueForLoad(DepMI, Offset, L->getType(), L, *DL);
01870     }
01871 
01872     if (AvailVal) {
01873       DEBUG(dbgs() << "GVN COERCED INST:\n" << *Dep.getInst() << '\n'
01874             << *AvailVal << '\n' << *L << "\n\n\n");
01875 
01876       // Replace the load!
01877       L->replaceAllUsesWith(AvailVal);
01878       if (AvailVal->getType()->getScalarType()->isPointerTy())
01879         MD->invalidateCachedPointerInfo(AvailVal);
01880       markInstructionForDeletion(L);
01881       ++NumGVNLoad;
01882       return true;
01883     }
01884   }
01885 
01886   // If the value isn't available, don't do anything!
01887   if (Dep.isClobber()) {
01888     DEBUG(
01889       // fast print dep, using operator<< on instruction is too slow.
01890       dbgs() << "GVN: load ";
01891       L->printAsOperand(dbgs());
01892       Instruction *I = Dep.getInst();
01893       dbgs() << " is clobbered by " << *I << '\n';
01894     );
01895     return false;
01896   }
01897 
01898   // If it is defined in another block, try harder.
01899   if (Dep.isNonLocal())
01900     return processNonLocalLoad(L);
01901 
01902   if (!Dep.isDef()) {
01903     DEBUG(
01904       // fast print dep, using operator<< on instruction is too slow.
01905       dbgs() << "GVN: load ";
01906       L->printAsOperand(dbgs());
01907       dbgs() << " has unknown dependence\n";
01908     );
01909     return false;
01910   }
01911 
01912   Instruction *DepInst = Dep.getInst();
01913   if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
01914     Value *StoredVal = DepSI->getValueOperand();
01915 
01916     // The store and load are to a must-aliased pointer, but they may not
01917     // actually have the same type.  See if we know how to reuse the stored
01918     // value (depending on its type).
01919     if (StoredVal->getType() != L->getType()) {
01920       if (DL) {
01921         StoredVal = CoerceAvailableValueToLoadType(StoredVal, L->getType(),
01922                                                    L, *DL);
01923         if (StoredVal == 0)
01924           return false;
01925 
01926         DEBUG(dbgs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
01927                      << '\n' << *L << "\n\n\n");
01928       }
01929       else
01930         return false;
01931     }
01932 
01933     // Remove it!
01934     L->replaceAllUsesWith(StoredVal);
01935     if (StoredVal->getType()->getScalarType()->isPointerTy())
01936       MD->invalidateCachedPointerInfo(StoredVal);
01937     markInstructionForDeletion(L);
01938     ++NumGVNLoad;
01939     return true;
01940   }
01941 
01942   if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
01943     Value *AvailableVal = DepLI;
01944 
01945     // The loads are of a must-aliased pointer, but they may not actually have
01946     // the same type.  See if we know how to reuse the previously loaded value
01947     // (depending on its type).
01948     if (DepLI->getType() != L->getType()) {
01949       if (DL) {
01950         AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(),
01951                                                       L, *DL);
01952         if (AvailableVal == 0)
01953           return false;
01954 
01955         DEBUG(dbgs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
01956                      << "\n" << *L << "\n\n\n");
01957       }
01958       else
01959         return false;
01960     }
01961 
01962     // Remove it!
01963     patchAndReplaceAllUsesWith(L, AvailableVal);
01964     if (DepLI->getType()->getScalarType()->isPointerTy())
01965       MD->invalidateCachedPointerInfo(DepLI);
01966     markInstructionForDeletion(L);
01967     ++NumGVNLoad;
01968     return true;
01969   }
01970 
01971   // If this load really doesn't depend on anything, then we must be loading an
01972   // undef value.  This can happen when loading for a fresh allocation with no
01973   // intervening stores, for example.
01974   if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
01975     L->replaceAllUsesWith(UndefValue::get(L->getType()));
01976     markInstructionForDeletion(L);
01977     ++NumGVNLoad;
01978     return true;
01979   }
01980 
01981   // If this load occurs either right after a lifetime begin,
01982   // then the loaded value is undefined.
01983   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(DepInst)) {
01984     if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
01985       L->replaceAllUsesWith(UndefValue::get(L->getType()));
01986       markInstructionForDeletion(L);
01987       ++NumGVNLoad;
01988       return true;
01989     }
01990   }
01991 
01992   return false;
01993 }
01994 
01995 // findLeader - In order to find a leader for a given value number at a
01996 // specific basic block, we first obtain the list of all Values for that number,
01997 // and then scan the list to find one whose block dominates the block in
01998 // question.  This is fast because dominator tree queries consist of only
01999 // a few comparisons of DFS numbers.
02000 Value *GVN::findLeader(const BasicBlock *BB, uint32_t num) {
02001   LeaderTableEntry Vals = LeaderTable[num];
02002   if (!Vals.Val) return 0;
02003 
02004   Value *Val = 0;
02005   if (DT->dominates(Vals.BB, BB)) {
02006     Val = Vals.Val;
02007     if (isa<Constant>(Val)) return Val;
02008   }
02009 
02010   LeaderTableEntry* Next = Vals.Next;
02011   while (Next) {
02012     if (DT->dominates(Next->BB, BB)) {
02013       if (isa<Constant>(Next->Val)) return Next->Val;
02014       if (!Val) Val = Next->Val;
02015     }
02016 
02017     Next = Next->Next;
02018   }
02019 
02020   return Val;
02021 }
02022 
02023 /// replaceAllDominatedUsesWith - Replace all uses of 'From' with 'To' if the
02024 /// use is dominated by the given basic block.  Returns the number of uses that
02025 /// were replaced.
02026 unsigned GVN::replaceAllDominatedUsesWith(Value *From, Value *To,
02027                                           const BasicBlockEdge &Root) {
02028   unsigned Count = 0;
02029   for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
02030        UI != UE; ) {
02031     Use &U = *UI++;
02032 
02033     if (DT->dominates(Root, U)) {
02034       U.set(To);
02035       ++Count;
02036     }
02037   }
02038   return Count;
02039 }
02040 
02041 /// isOnlyReachableViaThisEdge - There is an edge from 'Src' to 'Dst'.  Return
02042 /// true if every path from the entry block to 'Dst' passes via this edge.  In
02043 /// particular 'Dst' must not be reachable via another edge from 'Src'.
02044 static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E,
02045                                        DominatorTree *DT) {
02046   // While in theory it is interesting to consider the case in which Dst has
02047   // more than one predecessor, because Dst might be part of a loop which is
02048   // only reachable from Src, in practice it is pointless since at the time
02049   // GVN runs all such loops have preheaders, which means that Dst will have
02050   // been changed to have only one predecessor, namely Src.
02051   const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
02052   const BasicBlock *Src = E.getStart();
02053   assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
02054   (void)Src;
02055   return Pred != 0;
02056 }
02057 
02058 /// propagateEquality - The given values are known to be equal in every block
02059 /// dominated by 'Root'.  Exploit this, for example by replacing 'LHS' with
02060 /// 'RHS' everywhere in the scope.  Returns whether a change was made.
02061 bool GVN::propagateEquality(Value *LHS, Value *RHS,
02062                             const BasicBlockEdge &Root) {
02063   SmallVector<std::pair<Value*, Value*>, 4> Worklist;
02064   Worklist.push_back(std::make_pair(LHS, RHS));
02065   bool Changed = false;
02066   // For speed, compute a conservative fast approximation to
02067   // DT->dominates(Root, Root.getEnd());
02068   bool RootDominatesEnd = isOnlyReachableViaThisEdge(Root, DT);
02069 
02070   while (!Worklist.empty()) {
02071     std::pair<Value*, Value*> Item = Worklist.pop_back_val();
02072     LHS = Item.first; RHS = Item.second;
02073 
02074     if (LHS == RHS) continue;
02075     assert(LHS->getType() == RHS->getType() && "Equality but unequal types!");
02076 
02077     // Don't try to propagate equalities between constants.
02078     if (isa<Constant>(LHS) && isa<Constant>(RHS)) continue;
02079 
02080     // Prefer a constant on the right-hand side, or an Argument if no constants.
02081     if (isa<Constant>(LHS) || (isa<Argument>(LHS) && !isa<Constant>(RHS)))
02082       std::swap(LHS, RHS);
02083     assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) && "Unexpected value!");
02084 
02085     // If there is no obvious reason to prefer the left-hand side over the right-
02086     // hand side, ensure the longest lived term is on the right-hand side, so the
02087     // shortest lived term will be replaced by the longest lived.  This tends to
02088     // expose more simplifications.
02089     uint32_t LVN = VN.lookup_or_add(LHS);
02090     if ((isa<Argument>(LHS) && isa<Argument>(RHS)) ||
02091         (isa<Instruction>(LHS) && isa<Instruction>(RHS))) {
02092       // Move the 'oldest' value to the right-hand side, using the value number as
02093       // a proxy for age.
02094       uint32_t RVN = VN.lookup_or_add(RHS);
02095       if (LVN < RVN) {
02096         std::swap(LHS, RHS);
02097         LVN = RVN;
02098       }
02099     }
02100 
02101     // If value numbering later sees that an instruction in the scope is equal
02102     // to 'LHS' then ensure it will be turned into 'RHS'.  In order to preserve
02103     // the invariant that instructions only occur in the leader table for their
02104     // own value number (this is used by removeFromLeaderTable), do not do this
02105     // if RHS is an instruction (if an instruction in the scope is morphed into
02106     // LHS then it will be turned into RHS by the next GVN iteration anyway, so
02107     // using the leader table is about compiling faster, not optimizing better).
02108     // The leader table only tracks basic blocks, not edges. Only add to if we
02109     // have the simple case where the edge dominates the end.
02110     if (RootDominatesEnd && !isa<Instruction>(RHS))
02111       addToLeaderTable(LVN, RHS, Root.getEnd());
02112 
02113     // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope.  As
02114     // LHS always has at least one use that is not dominated by Root, this will
02115     // never do anything if LHS has only one use.
02116     if (!LHS->hasOneUse()) {
02117       unsigned NumReplacements = replaceAllDominatedUsesWith(LHS, RHS, Root);
02118       Changed |= NumReplacements > 0;
02119       NumGVNEqProp += NumReplacements;
02120     }
02121 
02122     // Now try to deduce additional equalities from this one.  For example, if the
02123     // known equality was "(A != B)" == "false" then it follows that A and B are
02124     // equal in the scope.  Only boolean equalities with an explicit true or false
02125     // RHS are currently supported.
02126     if (!RHS->getType()->isIntegerTy(1))
02127       // Not a boolean equality - bail out.
02128       continue;
02129     ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
02130     if (!CI)
02131       // RHS neither 'true' nor 'false' - bail out.
02132       continue;
02133     // Whether RHS equals 'true'.  Otherwise it equals 'false'.
02134     bool isKnownTrue = CI->isAllOnesValue();
02135     bool isKnownFalse = !isKnownTrue;
02136 
02137     // If "A && B" is known true then both A and B are known true.  If "A || B"
02138     // is known false then both A and B are known false.
02139     Value *A, *B;
02140     if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) ||
02141         (isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) {
02142       Worklist.push_back(std::make_pair(A, RHS));
02143       Worklist.push_back(std::make_pair(B, RHS));
02144       continue;
02145     }
02146 
02147     // If we are propagating an equality like "(A == B)" == "true" then also
02148     // propagate the equality A == B.  When propagating a comparison such as
02149     // "(A >= B)" == "true", replace all instances of "A < B" with "false".
02150     if (ICmpInst *Cmp = dyn_cast<ICmpInst>(LHS)) {
02151       Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
02152 
02153       // If "A == B" is known true, or "A != B" is known false, then replace
02154       // A with B everywhere in the scope.
02155       if ((isKnownTrue && Cmp->getPredicate() == CmpInst::ICMP_EQ) ||
02156           (isKnownFalse && Cmp->getPredicate() == CmpInst::ICMP_NE))
02157         Worklist.push_back(std::make_pair(Op0, Op1));
02158 
02159       // If "A >= B" is known true, replace "A < B" with false everywhere.
02160       CmpInst::Predicate NotPred = Cmp->getInversePredicate();
02161       Constant *NotVal = ConstantInt::get(Cmp->getType(), isKnownFalse);
02162       // Since we don't have the instruction "A < B" immediately to hand, work out
02163       // the value number that it would have and use that to find an appropriate
02164       // instruction (if any).
02165       uint32_t NextNum = VN.getNextUnusedValueNumber();
02166       uint32_t Num = VN.lookup_or_add_cmp(Cmp->getOpcode(), NotPred, Op0, Op1);
02167       // If the number we were assigned was brand new then there is no point in
02168       // looking for an instruction realizing it: there cannot be one!
02169       if (Num < NextNum) {
02170         Value *NotCmp = findLeader(Root.getEnd(), Num);
02171         if (NotCmp && isa<Instruction>(NotCmp)) {
02172           unsigned NumReplacements =
02173             replaceAllDominatedUsesWith(NotCmp, NotVal, Root);
02174           Changed |= NumReplacements > 0;
02175           NumGVNEqProp += NumReplacements;
02176         }
02177       }
02178       // Ensure that any instruction in scope that gets the "A < B" value number
02179       // is replaced with false.
02180       // The leader table only tracks basic blocks, not edges. Only add to if we
02181       // have the simple case where the edge dominates the end.
02182       if (RootDominatesEnd)
02183         addToLeaderTable(Num, NotVal, Root.getEnd());
02184 
02185       continue;
02186     }
02187   }
02188 
02189   return Changed;
02190 }
02191 
02192 /// processInstruction - When calculating availability, handle an instruction
02193 /// by inserting it into the appropriate sets
02194 bool GVN::processInstruction(Instruction *I) {
02195   // Ignore dbg info intrinsics.
02196   if (isa<DbgInfoIntrinsic>(I))
02197     return false;
02198 
02199   // If the instruction can be easily simplified then do so now in preference
02200   // to value numbering it.  Value numbering often exposes redundancies, for
02201   // example if it determines that %y is equal to %x then the instruction
02202   // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
02203   if (Value *V = SimplifyInstruction(I, DL, TLI, DT)) {
02204     I->replaceAllUsesWith(V);
02205     if (MD && V->getType()->getScalarType()->isPointerTy())
02206       MD->invalidateCachedPointerInfo(V);
02207     markInstructionForDeletion(I);
02208     ++NumGVNSimpl;
02209     return true;
02210   }
02211 
02212   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
02213     if (processLoad(LI))
02214       return true;
02215 
02216     unsigned Num = VN.lookup_or_add(LI);
02217     addToLeaderTable(Num, LI, LI->getParent());
02218     return false;
02219   }
02220 
02221   // For conditional branches, we can perform simple conditional propagation on
02222   // the condition value itself.
02223   if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
02224     if (!BI->isConditional())
02225       return false;
02226 
02227     if (isa<Constant>(BI->getCondition()))
02228       return processFoldableCondBr(BI);
02229 
02230     Value *BranchCond = BI->getCondition();
02231     BasicBlock *TrueSucc = BI->getSuccessor(0);
02232     BasicBlock *FalseSucc = BI->getSuccessor(1);
02233     // Avoid multiple edges early.
02234     if (TrueSucc == FalseSucc)
02235       return false;
02236 
02237     BasicBlock *Parent = BI->getParent();
02238     bool Changed = false;
02239 
02240     Value *TrueVal = ConstantInt::getTrue(TrueSucc->getContext());
02241     BasicBlockEdge TrueE(Parent, TrueSucc);
02242     Changed |= propagateEquality(BranchCond, TrueVal, TrueE);
02243 
02244     Value *FalseVal = ConstantInt::getFalse(FalseSucc->getContext());
02245     BasicBlockEdge FalseE(Parent, FalseSucc);
02246     Changed |= propagateEquality(BranchCond, FalseVal, FalseE);
02247 
02248     return Changed;
02249   }
02250 
02251   // For switches, propagate the case values into the case destinations.
02252   if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
02253     Value *SwitchCond = SI->getCondition();
02254     BasicBlock *Parent = SI->getParent();
02255     bool Changed = false;
02256 
02257     // Remember how many outgoing edges there are to every successor.
02258     SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
02259     for (unsigned i = 0, n = SI->getNumSuccessors(); i != n; ++i)
02260       ++SwitchEdges[SI->getSuccessor(i)];
02261 
02262     for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
02263          i != e; ++i) {
02264       BasicBlock *Dst = i.getCaseSuccessor();
02265       // If there is only a single edge, propagate the case value into it.
02266       if (SwitchEdges.lookup(Dst) == 1) {
02267         BasicBlockEdge E(Parent, Dst);
02268         Changed |= propagateEquality(SwitchCond, i.getCaseValue(), E);
02269       }
02270     }
02271     return Changed;
02272   }
02273 
02274   // Instructions with void type don't return a value, so there's
02275   // no point in trying to find redundancies in them.
02276   if (I->getType()->isVoidTy()) return false;
02277 
02278   uint32_t NextNum = VN.getNextUnusedValueNumber();
02279   unsigned Num = VN.lookup_or_add(I);
02280 
02281   // Allocations are always uniquely numbered, so we can save time and memory
02282   // by fast failing them.
02283   if (isa<AllocaInst>(I) || isa<TerminatorInst>(I) || isa<PHINode>(I)) {
02284     addToLeaderTable(Num, I, I->getParent());
02285     return false;
02286   }
02287 
02288   // If the number we were assigned was a brand new VN, then we don't
02289   // need to do a lookup to see if the number already exists
02290   // somewhere in the domtree: it can't!
02291   if (Num >= NextNum) {
02292     addToLeaderTable(Num, I, I->getParent());
02293     return false;
02294   }
02295 
02296   // Perform fast-path value-number based elimination of values inherited from
02297   // dominators.
02298   Value *repl = findLeader(I->getParent(), Num);
02299   if (repl == 0) {
02300     // Failure, just remember this instance for future use.
02301     addToLeaderTable(Num, I, I->getParent());
02302     return false;
02303   }
02304 
02305   // Remove it!
02306   patchAndReplaceAllUsesWith(I, repl);
02307   if (MD && repl->getType()->getScalarType()->isPointerTy())
02308     MD->invalidateCachedPointerInfo(repl);
02309   markInstructionForDeletion(I);
02310   return true;
02311 }
02312 
02313 /// runOnFunction - This is the main transformation entry point for a function.
02314 bool GVN::runOnFunction(Function& F) {
02315   if (skipOptnoneFunction(F))
02316     return false;
02317 
02318   if (!NoLoads)
02319     MD = &getAnalysis<MemoryDependenceAnalysis>();
02320   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
02321   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
02322   DL = DLP ? &DLP->getDataLayout() : 0;
02323   TLI = &getAnalysis<TargetLibraryInfo>();
02324   VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
02325   VN.setMemDep(MD);
02326   VN.setDomTree(DT);
02327 
02328   bool Changed = false;
02329   bool ShouldContinue = true;
02330 
02331   // Merge unconditional branches, allowing PRE to catch more
02332   // optimization opportunities.
02333   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
02334     BasicBlock *BB = FI++;
02335 
02336     bool removedBlock = MergeBlockIntoPredecessor(BB, this);
02337     if (removedBlock) ++NumGVNBlocks;
02338 
02339     Changed |= removedBlock;
02340   }
02341 
02342   unsigned Iteration = 0;
02343   while (ShouldContinue) {
02344     DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
02345     ShouldContinue = iterateOnFunction(F);
02346     Changed |= ShouldContinue;
02347     ++Iteration;
02348   }
02349 
02350   if (EnablePRE) {
02351     // Fabricate val-num for dead-code in order to suppress assertion in
02352     // performPRE().
02353     assignValNumForDeadCode();
02354     bool PREChanged = true;
02355     while (PREChanged) {
02356       PREChanged = performPRE(F);
02357       Changed |= PREChanged;
02358     }
02359   }
02360 
02361   // FIXME: Should perform GVN again after PRE does something.  PRE can move
02362   // computations into blocks where they become fully redundant.  Note that
02363   // we can't do this until PRE's critical edge splitting updates memdep.
02364   // Actually, when this happens, we should just fully integrate PRE into GVN.
02365 
02366   cleanupGlobalSets();
02367   // Do not cleanup DeadBlocks in cleanupGlobalSets() as it's called for each
02368   // iteration. 
02369   DeadBlocks.clear();
02370 
02371   return Changed;
02372 }
02373 
02374 
02375 bool GVN::processBlock(BasicBlock *BB) {
02376   // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function
02377   // (and incrementing BI before processing an instruction).
02378   assert(InstrsToErase.empty() &&
02379          "We expect InstrsToErase to be empty across iterations");
02380   if (DeadBlocks.count(BB))
02381     return false;
02382 
02383   bool ChangedFunction = false;
02384 
02385   for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
02386        BI != BE;) {
02387     ChangedFunction |= processInstruction(BI);
02388     if (InstrsToErase.empty()) {
02389       ++BI;
02390       continue;
02391     }
02392 
02393     // If we need some instructions deleted, do it now.
02394     NumGVNInstr += InstrsToErase.size();
02395 
02396     // Avoid iterator invalidation.
02397     bool AtStart = BI == BB->begin();
02398     if (!AtStart)
02399       --BI;
02400 
02401     for (SmallVectorImpl<Instruction *>::iterator I = InstrsToErase.begin(),
02402          E = InstrsToErase.end(); I != E; ++I) {
02403       DEBUG(dbgs() << "GVN removed: " << **I << '\n');
02404       if (MD) MD->removeInstruction(*I);
02405       DEBUG(verifyRemoved(*I));
02406       (*I)->eraseFromParent();
02407     }
02408     InstrsToErase.clear();
02409 
02410     if (AtStart)
02411       BI = BB->begin();
02412     else
02413       ++BI;
02414   }
02415 
02416   return ChangedFunction;
02417 }
02418 
02419 /// performPRE - Perform a purely local form of PRE that looks for diamond
02420 /// control flow patterns and attempts to perform simple PRE at the join point.
02421 bool GVN::performPRE(Function &F) {
02422   bool Changed = false;
02423   SmallVector<std::pair<Value*, BasicBlock*>, 8> predMap;
02424   for (BasicBlock *CurrentBlock : depth_first(&F.getEntryBlock())) {
02425     // Nothing to PRE in the entry block.
02426     if (CurrentBlock == &F.getEntryBlock()) continue;
02427 
02428     // Don't perform PRE on a landing pad.
02429     if (CurrentBlock->isLandingPad()) continue;
02430 
02431     for (BasicBlock::iterator BI = CurrentBlock->begin(),
02432          BE = CurrentBlock->end(); BI != BE; ) {
02433       Instruction *CurInst = BI++;
02434 
02435       if (isa<AllocaInst>(CurInst) ||
02436           isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
02437           CurInst->getType()->isVoidTy() ||
02438           CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
02439           isa<DbgInfoIntrinsic>(CurInst))
02440         continue;
02441 
02442       // Don't do PRE on compares. The PHI would prevent CodeGenPrepare from
02443       // sinking the compare again, and it would force the code generator to
02444       // move the i1 from processor flags or predicate registers into a general
02445       // purpose register.
02446       if (isa<CmpInst>(CurInst))
02447         continue;
02448 
02449       // We don't currently value number ANY inline asm calls.
02450       if (CallInst *CallI = dyn_cast<CallInst>(CurInst))
02451         if (CallI->isInlineAsm())
02452           continue;
02453 
02454       uint32_t ValNo = VN.lookup(CurInst);
02455 
02456       // Look for the predecessors for PRE opportunities.  We're
02457       // only trying to solve the basic diamond case, where
02458       // a value is computed in the successor and one predecessor,
02459       // but not the other.  We also explicitly disallow cases
02460       // where the successor is its own predecessor, because they're
02461       // more complicated to get right.
02462       unsigned NumWith = 0;
02463       unsigned NumWithout = 0;
02464       BasicBlock *PREPred = 0;
02465       predMap.clear();
02466 
02467       for (pred_iterator PI = pred_begin(CurrentBlock),
02468            PE = pred_end(CurrentBlock); PI != PE; ++PI) {
02469         BasicBlock *P = *PI;
02470         // We're not interested in PRE where the block is its
02471         // own predecessor, or in blocks with predecessors
02472         // that are not reachable.
02473         if (P == CurrentBlock) {
02474           NumWithout = 2;
02475           break;
02476         } else if (!DT->isReachableFromEntry(P))  {
02477           NumWithout = 2;
02478           break;
02479         }
02480 
02481         Value* predV = findLeader(P, ValNo);
02482         if (predV == 0) {
02483           predMap.push_back(std::make_pair(static_cast<Value *>(0), P));
02484           PREPred = P;
02485           ++NumWithout;
02486         } else if (predV == CurInst) {
02487           /* CurInst dominates this predecessor. */
02488           NumWithout = 2;
02489           break;
02490         } else {
02491           predMap.push_back(std::make_pair(predV, P));
02492           ++NumWith;
02493         }
02494       }
02495 
02496       // Don't do PRE when it might increase code size, i.e. when
02497       // we would need to insert instructions in more than one pred.
02498       if (NumWithout != 1 || NumWith == 0)
02499         continue;
02500 
02501       // Don't do PRE across indirect branch.
02502       if (isa<IndirectBrInst>(PREPred->getTerminator()))
02503         continue;
02504 
02505       // We can't do PRE safely on a critical edge, so instead we schedule
02506       // the edge to be split and perform the PRE the next time we iterate
02507       // on the function.
02508       unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
02509       if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
02510         toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
02511         continue;
02512       }
02513 
02514       // Instantiate the expression in the predecessor that lacked it.
02515       // Because we are going top-down through the block, all value numbers
02516       // will be available in the predecessor by the time we need them.  Any
02517       // that weren't originally present will have been instantiated earlier
02518       // in this loop.
02519       Instruction *PREInstr = CurInst->clone();
02520       bool success = true;
02521       for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
02522         Value *Op = PREInstr->getOperand(i);
02523         if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
02524           continue;
02525 
02526         if (Value *V = findLeader(PREPred, VN.lookup(Op))) {
02527           PREInstr->setOperand(i, V);
02528         } else {
02529           success = false;
02530           break;
02531         }
02532       }
02533 
02534       // Fail out if we encounter an operand that is not available in
02535       // the PRE predecessor.  This is typically because of loads which
02536       // are not value numbered precisely.
02537       if (!success) {
02538         DEBUG(verifyRemoved(PREInstr));
02539         delete PREInstr;
02540         continue;
02541       }
02542 
02543       PREInstr->insertBefore(PREPred->getTerminator());
02544       PREInstr->setName(CurInst->getName() + ".pre");
02545       PREInstr->setDebugLoc(CurInst->getDebugLoc());
02546       VN.add(PREInstr, ValNo);
02547       ++NumGVNPRE;
02548 
02549       // Update the availability map to include the new instruction.
02550       addToLeaderTable(ValNo, PREInstr, PREPred);
02551 
02552       // Create a PHI to make the value available in this block.
02553       PHINode* Phi = PHINode::Create(CurInst->getType(), predMap.size(),
02554                                      CurInst->getName() + ".pre-phi",
02555                                      CurrentBlock->begin());
02556       for (unsigned i = 0, e = predMap.size(); i != e; ++i) {
02557         if (Value *V = predMap[i].first)
02558           Phi->addIncoming(V, predMap[i].second);
02559         else
02560           Phi->addIncoming(PREInstr, PREPred);
02561       }
02562 
02563       VN.add(Phi, ValNo);
02564       addToLeaderTable(ValNo, Phi, CurrentBlock);
02565       Phi->setDebugLoc(CurInst->getDebugLoc());
02566       CurInst->replaceAllUsesWith(Phi);
02567       if (Phi->getType()->getScalarType()->isPointerTy()) {
02568         // Because we have added a PHI-use of the pointer value, it has now
02569         // "escaped" from alias analysis' perspective.  We need to inform
02570         // AA of this.
02571         for (unsigned ii = 0, ee = Phi->getNumIncomingValues(); ii != ee;
02572              ++ii) {
02573           unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
02574           VN.getAliasAnalysis()->addEscapingUse(Phi->getOperandUse(jj));
02575         }
02576 
02577         if (MD)
02578           MD->invalidateCachedPointerInfo(Phi);
02579       }
02580       VN.erase(CurInst);
02581       removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
02582 
02583       DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
02584       if (MD) MD->removeInstruction(CurInst);
02585       DEBUG(verifyRemoved(CurInst));
02586       CurInst->eraseFromParent();
02587       Changed = true;
02588     }
02589   }
02590 
02591   if (splitCriticalEdges())
02592     Changed = true;
02593 
02594   return Changed;
02595 }
02596 
02597 /// Split the critical edge connecting the given two blocks, and return
02598 /// the block inserted to the critical edge.
02599 BasicBlock *GVN::splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ) {
02600   BasicBlock *BB = SplitCriticalEdge(Pred, Succ, this);
02601   if (MD)
02602     MD->invalidateCachedPredecessors();
02603   return BB;
02604 }
02605 
02606 /// splitCriticalEdges - Split critical edges found during the previous
02607 /// iteration that may enable further optimization.
02608 bool GVN::splitCriticalEdges() {
02609   if (toSplit.empty())
02610     return false;
02611   do {
02612     std::pair<TerminatorInst*, unsigned> Edge = toSplit.pop_back_val();
02613     SplitCriticalEdge(Edge.first, Edge.second, this);
02614   } while (!toSplit.empty());
02615   if (MD) MD->invalidateCachedPredecessors();
02616   return true;
02617 }
02618 
02619 /// iterateOnFunction - Executes one iteration of GVN
02620 bool GVN::iterateOnFunction(Function &F) {
02621   cleanupGlobalSets();
02622 
02623   // Top-down walk of the dominator tree
02624   bool Changed = false;
02625 #if 0
02626   // Needed for value numbering with phi construction to work.
02627   ReversePostOrderTraversal<Function*> RPOT(&F);
02628   for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
02629        RE = RPOT.end(); RI != RE; ++RI)
02630     Changed |= processBlock(*RI);
02631 #else
02632   // Save the blocks this function have before transformation begins. GVN may
02633   // split critical edge, and hence may invalidate the RPO/DT iterator.
02634   //
02635   std::vector<BasicBlock *> BBVect;
02636   BBVect.reserve(256);
02637   for (DomTreeNode *x : depth_first(DT->getRootNode()))
02638     BBVect.push_back(x->getBlock());
02639 
02640   for (std::vector<BasicBlock *>::iterator I = BBVect.begin(), E = BBVect.end();
02641        I != E; I++)
02642     Changed |= processBlock(*I);
02643 #endif
02644 
02645   return Changed;
02646 }
02647 
02648 void GVN::cleanupGlobalSets() {
02649   VN.clear();
02650   LeaderTable.clear();
02651   TableAllocator.Reset();
02652 }
02653 
02654 /// verifyRemoved - Verify that the specified instruction does not occur in our
02655 /// internal data structures.
02656 void GVN::verifyRemoved(const Instruction *Inst) const {
02657   VN.verifyRemoved(Inst);
02658 
02659   // Walk through the value number scope to make sure the instruction isn't
02660   // ferreted away in it.
02661   for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator
02662        I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) {
02663     const LeaderTableEntry *Node = &I->second;
02664     assert(Node->Val != Inst && "Inst still in value numbering scope!");
02665 
02666     while (Node->Next) {
02667       Node = Node->Next;
02668       assert(Node->Val != Inst && "Inst still in value numbering scope!");
02669     }
02670   }
02671 }
02672 
02673 // BB is declared dead, which implied other blocks become dead as well. This
02674 // function is to add all these blocks to "DeadBlocks". For the dead blocks'
02675 // live successors, update their phi nodes by replacing the operands
02676 // corresponding to dead blocks with UndefVal.
02677 //
02678 void GVN::addDeadBlock(BasicBlock *BB) {
02679   SmallVector<BasicBlock *, 4> NewDead;
02680   SmallSetVector<BasicBlock *, 4> DF;
02681 
02682   NewDead.push_back(BB);
02683   while (!NewDead.empty()) {
02684     BasicBlock *D = NewDead.pop_back_val();
02685     if (DeadBlocks.count(D))
02686       continue;
02687 
02688     // All blocks dominated by D are dead.
02689     SmallVector<BasicBlock *, 8> Dom;
02690     DT->getDescendants(D, Dom);
02691     DeadBlocks.insert(Dom.begin(), Dom.end());
02692     
02693     // Figure out the dominance-frontier(D).
02694     for (SmallVectorImpl<BasicBlock *>::iterator I = Dom.begin(),
02695            E = Dom.end(); I != E; I++) {
02696       BasicBlock *B = *I;
02697       for (succ_iterator SI = succ_begin(B), SE = succ_end(B); SI != SE; SI++) {
02698         BasicBlock *S = *SI;
02699         if (DeadBlocks.count(S))
02700           continue;
02701 
02702         bool AllPredDead = true;
02703         for (pred_iterator PI = pred_begin(S), PE = pred_end(S); PI != PE; PI++)
02704           if (!DeadBlocks.count(*PI)) {
02705             AllPredDead = false;
02706             break;
02707           }
02708 
02709         if (!AllPredDead) {
02710           // S could be proved dead later on. That is why we don't update phi
02711           // operands at this moment.
02712           DF.insert(S);
02713         } else {
02714           // While S is not dominated by D, it is dead by now. This could take
02715           // place if S already have a dead predecessor before D is declared
02716           // dead.
02717           NewDead.push_back(S);
02718         }
02719       }
02720     }
02721   }
02722 
02723   // For the dead blocks' live successors, update their phi nodes by replacing
02724   // the operands corresponding to dead blocks with UndefVal.
02725   for(SmallSetVector<BasicBlock *, 4>::iterator I = DF.begin(), E = DF.end();
02726         I != E; I++) {
02727     BasicBlock *B = *I;
02728     if (DeadBlocks.count(B))
02729       continue;
02730 
02731     SmallVector<BasicBlock *, 4> Preds(pred_begin(B), pred_end(B));
02732     for (SmallVectorImpl<BasicBlock *>::iterator PI = Preds.begin(),
02733            PE = Preds.end(); PI != PE; PI++) {
02734       BasicBlock *P = *PI;
02735 
02736       if (!DeadBlocks.count(P))
02737         continue;
02738 
02739       if (isCriticalEdge(P->getTerminator(), GetSuccessorNumber(P, B))) {
02740         if (BasicBlock *S = splitCriticalEdges(P, B))
02741           DeadBlocks.insert(P = S);
02742       }
02743 
02744       for (BasicBlock::iterator II = B->begin(); isa<PHINode>(II); ++II) {
02745         PHINode &Phi = cast<PHINode>(*II);
02746         Phi.setIncomingValue(Phi.getBasicBlockIndex(P),
02747                              UndefValue::get(Phi.getType()));
02748       }
02749     }
02750   }
02751 }
02752 
02753 // If the given branch is recognized as a foldable branch (i.e. conditional
02754 // branch with constant condition), it will perform following analyses and
02755 // transformation.
02756 //  1) If the dead out-coming edge is a critical-edge, split it. Let 
02757 //     R be the target of the dead out-coming edge.
02758 //  1) Identify the set of dead blocks implied by the branch's dead outcoming
02759 //     edge. The result of this step will be {X| X is dominated by R}
02760 //  2) Identify those blocks which haves at least one dead prodecessor. The
02761 //     result of this step will be dominance-frontier(R).
02762 //  3) Update the PHIs in DF(R) by replacing the operands corresponding to 
02763 //     dead blocks with "UndefVal" in an hope these PHIs will optimized away.
02764 //
02765 // Return true iff *NEW* dead code are found.
02766 bool GVN::processFoldableCondBr(BranchInst *BI) {
02767   if (!BI || BI->isUnconditional())
02768     return false;
02769 
02770   ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
02771   if (!Cond)
02772     return false;
02773 
02774   BasicBlock *DeadRoot = Cond->getZExtValue() ? 
02775                          BI->getSuccessor(1) : BI->getSuccessor(0);
02776   if (DeadBlocks.count(DeadRoot))
02777     return false;
02778 
02779   if (!DeadRoot->getSinglePredecessor())
02780     DeadRoot = splitCriticalEdges(BI->getParent(), DeadRoot);
02781 
02782   addDeadBlock(DeadRoot);
02783   return true;
02784 }
02785 
02786 // performPRE() will trigger assert if it come across an instruciton without
02787 // associated val-num. As it normally has far more live instructions than dead
02788 // instructions, it makes more sense just to "fabricate" a val-number for the
02789 // dead code than checking if instruction involved is dead or not.
02790 void GVN::assignValNumForDeadCode() {
02791   for (SetVector<BasicBlock *>::iterator I = DeadBlocks.begin(),
02792         E = DeadBlocks.end(); I != E; I++) {
02793     BasicBlock *BB = *I;
02794     for (BasicBlock::iterator II = BB->begin(), EE = BB->end();
02795           II != EE; II++) {
02796       Instruction *Inst = &*II;
02797       unsigned ValNum = VN.lookup_or_add(Inst);
02798       addToLeaderTable(ValNum, Inst, BB);
02799     }
02800   }
02801 }