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