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