LLVM API Documentation

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