1 //===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass performs global value numbering to eliminate fully redundant
11 // instructions.  It also performs simple dead load elimination.
12 //
13 // Note that this pass does the value numbering itself; it does not use the
14 // ValueNumbering analysis passes.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/Transforms/Scalar/GVN.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/DepthFirstIterator.h"
21 #include "llvm/ADT/Hashing.h"
22 #include "llvm/ADT/MapVector.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Analysis/AssumptionCache.h"
29 #include "llvm/Analysis/CFG.h"
30 #include "llvm/Analysis/ConstantFolding.h"
31 #include "llvm/Analysis/GlobalsModRef.h"
32 #include "llvm/Analysis/InstructionSimplify.h"
33 #include "llvm/Analysis/Loads.h"
34 #include "llvm/Analysis/MemoryBuiltins.h"
35 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
36 #include "llvm/Analysis/OptimizationDiagnosticInfo.h"
37 #include "llvm/Analysis/PHITransAddr.h"
38 #include "llvm/Analysis/TargetLibraryInfo.h"
39 #include "llvm/Analysis/ValueTracking.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/Dominators.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/IRBuilder.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/LLVMContext.h"
46 #include "llvm/IR/Metadata.h"
47 #include "llvm/IR/PatternMatch.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
52 #include "llvm/Transforms/Utils/Local.h"
53 #include "llvm/Transforms/Utils/SSAUpdater.h"
54 #include <vector>
55 using namespace llvm;
56 using namespace llvm::gvn;
57 using namespace PatternMatch;
58 
59 #define DEBUG_TYPE "gvn"
60 
61 STATISTIC(NumGVNInstr,  "Number of instructions deleted");
62 STATISTIC(NumGVNLoad,   "Number of loads deleted");
63 STATISTIC(NumGVNPRE,    "Number of instructions PRE'd");
64 STATISTIC(NumGVNBlocks, "Number of blocks merged");
65 STATISTIC(NumGVNSimpl,  "Number of instructions simplified");
66 STATISTIC(NumGVNEqProp, "Number of equalities propagated");
67 STATISTIC(NumPRELoad,   "Number of loads PRE'd");
68 
69 static cl::opt<bool> EnablePRE("enable-pre",
70                                cl::init(true), cl::Hidden);
71 static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
72 
73 // Maximum allowed recursion depth.
74 static cl::opt<uint32_t>
75 MaxRecurseDepth("max-recurse-depth", cl::Hidden, cl::init(1000), cl::ZeroOrMore,
76                 cl::desc("Max recurse depth (default = 1000)"));
77 
78 struct llvm::GVN::Expression {
79   uint32_t opcode;
80   Type *type;
81   SmallVector<uint32_t, 4> varargs;
82 
83   Expression(uint32_t o = ~2U) : opcode(o) {}
84 
85   bool operator==(const Expression &other) const {
86     if (opcode != other.opcode)
87       return false;
88     if (opcode == ~0U || opcode == ~1U)
89       return true;
90     if (type != other.type)
91       return false;
92     if (varargs != other.varargs)
93       return false;
94     return true;
95   }
96 
97   friend hash_code hash_value(const Expression &Value) {
98     return hash_combine(
99         Value.opcode, Value.type,
100         hash_combine_range(Value.varargs.begin(), Value.varargs.end()));
101   }
102 };
103 
104 namespace llvm {
105 template <> struct DenseMapInfo<GVN::Expression> {
106   static inline GVN::Expression getEmptyKey() { return ~0U; }
107 
108   static inline GVN::Expression getTombstoneKey() { return ~1U; }
109 
110   static unsigned getHashValue(const GVN::Expression &e) {
111     using llvm::hash_value;
112     return static_cast<unsigned>(hash_value(e));
113   }
114   static bool isEqual(const GVN::Expression &LHS, const GVN::Expression &RHS) {
115     return LHS == RHS;
116   }
117 };
118 } // End llvm namespace.
119 
120 /// Represents a particular available value that we know how to materialize.
121 /// Materialization of an AvailableValue never fails.  An AvailableValue is
122 /// implicitly associated with a rematerialization point which is the
123 /// location of the instruction from which it was formed.
124 struct llvm::gvn::AvailableValue {
125   enum ValType {
126     SimpleVal, // A simple offsetted value that is accessed.
127     LoadVal,   // A value produced by a load.
128     MemIntrin, // A memory intrinsic which is loaded from.
129     UndefVal   // A UndefValue representing a value from dead block (which
130                // is not yet physically removed from the CFG).
131   };
132 
133   /// V - The value that is live out of the block.
134   PointerIntPair<Value *, 2, ValType> Val;
135 
136   /// Offset - The byte offset in Val that is interesting for the load query.
137   unsigned Offset;
138 
139   static AvailableValue get(Value *V, unsigned Offset = 0) {
140     AvailableValue Res;
141     Res.Val.setPointer(V);
142     Res.Val.setInt(SimpleVal);
143     Res.Offset = Offset;
144     return Res;
145   }
146 
147   static AvailableValue getMI(MemIntrinsic *MI, unsigned Offset = 0) {
148     AvailableValue Res;
149     Res.Val.setPointer(MI);
150     Res.Val.setInt(MemIntrin);
151     Res.Offset = Offset;
152     return Res;
153   }
154 
155   static AvailableValue getLoad(LoadInst *LI, unsigned Offset = 0) {
156     AvailableValue Res;
157     Res.Val.setPointer(LI);
158     Res.Val.setInt(LoadVal);
159     Res.Offset = Offset;
160     return Res;
161   }
162 
163   static AvailableValue getUndef() {
164     AvailableValue Res;
165     Res.Val.setPointer(nullptr);
166     Res.Val.setInt(UndefVal);
167     Res.Offset = 0;
168     return Res;
169   }
170 
171   bool isSimpleValue() const { return Val.getInt() == SimpleVal; }
172   bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; }
173   bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; }
174   bool isUndefValue() const { return Val.getInt() == UndefVal; }
175 
176   Value *getSimpleValue() const {
177     assert(isSimpleValue() && "Wrong accessor");
178     return Val.getPointer();
179   }
180 
181   LoadInst *getCoercedLoadValue() const {
182     assert(isCoercedLoadValue() && "Wrong accessor");
183     return cast<LoadInst>(Val.getPointer());
184   }
185 
186   MemIntrinsic *getMemIntrinValue() const {
187     assert(isMemIntrinValue() && "Wrong accessor");
188     return cast<MemIntrinsic>(Val.getPointer());
189   }
190 
191   /// Emit code at the specified insertion point to adjust the value defined
192   /// here to the specified type. This handles various coercion cases.
193   Value *MaterializeAdjustedValue(LoadInst *LI, Instruction *InsertPt,
194                                   GVN &gvn) const;
195 };
196 
197 /// Represents an AvailableValue which can be rematerialized at the end of
198 /// the associated BasicBlock.
199 struct llvm::gvn::AvailableValueInBlock {
200   /// BB - The basic block in question.
201   BasicBlock *BB;
202 
203   /// AV - The actual available value
204   AvailableValue AV;
205 
206   static AvailableValueInBlock get(BasicBlock *BB, AvailableValue &&AV) {
207     AvailableValueInBlock Res;
208     Res.BB = BB;
209     Res.AV = std::move(AV);
210     return Res;
211   }
212 
213   static AvailableValueInBlock get(BasicBlock *BB, Value *V,
214                                    unsigned Offset = 0) {
215     return get(BB, AvailableValue::get(V, Offset));
216   }
217   static AvailableValueInBlock getUndef(BasicBlock *BB) {
218     return get(BB, AvailableValue::getUndef());
219   }
220 
221   /// Emit code at the end of this block to adjust the value defined here to
222   /// the specified type. This handles various coercion cases.
223   Value *MaterializeAdjustedValue(LoadInst *LI, GVN &gvn) const {
224     return AV.MaterializeAdjustedValue(LI, BB->getTerminator(), gvn);
225   }
226 };
227 
228 //===----------------------------------------------------------------------===//
229 //                     ValueTable Internal Functions
230 //===----------------------------------------------------------------------===//
231 
232 GVN::Expression GVN::ValueTable::createExpr(Instruction *I) {
233   Expression e;
234   e.type = I->getType();
235   e.opcode = I->getOpcode();
236   for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
237        OI != OE; ++OI)
238     e.varargs.push_back(lookupOrAdd(*OI));
239   if (I->isCommutative()) {
240     // Ensure that commutative instructions that only differ by a permutation
241     // of their operands get the same value number by sorting the operand value
242     // numbers.  Since all commutative instructions have two operands it is more
243     // efficient to sort by hand rather than using, say, std::sort.
244     assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
245     if (e.varargs[0] > e.varargs[1])
246       std::swap(e.varargs[0], e.varargs[1]);
247   }
248 
249   if (CmpInst *C = dyn_cast<CmpInst>(I)) {
250     // Sort the operand value numbers so x<y and y>x get the same value number.
251     CmpInst::Predicate Predicate = C->getPredicate();
252     if (e.varargs[0] > e.varargs[1]) {
253       std::swap(e.varargs[0], e.varargs[1]);
254       Predicate = CmpInst::getSwappedPredicate(Predicate);
255     }
256     e.opcode = (C->getOpcode() << 8) | Predicate;
257   } else if (InsertValueInst *E = dyn_cast<InsertValueInst>(I)) {
258     for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
259          II != IE; ++II)
260       e.varargs.push_back(*II);
261   }
262 
263   return e;
264 }
265 
266 GVN::Expression GVN::ValueTable::createCmpExpr(unsigned Opcode,
267                                                CmpInst::Predicate Predicate,
268                                                Value *LHS, Value *RHS) {
269   assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
270          "Not a comparison!");
271   Expression e;
272   e.type = CmpInst::makeCmpResultType(LHS->getType());
273   e.varargs.push_back(lookupOrAdd(LHS));
274   e.varargs.push_back(lookupOrAdd(RHS));
275 
276   // Sort the operand value numbers so x<y and y>x get the same value number.
277   if (e.varargs[0] > e.varargs[1]) {
278     std::swap(e.varargs[0], e.varargs[1]);
279     Predicate = CmpInst::getSwappedPredicate(Predicate);
280   }
281   e.opcode = (Opcode << 8) | Predicate;
282   return e;
283 }
284 
285 GVN::Expression GVN::ValueTable::createExtractvalueExpr(ExtractValueInst *EI) {
286   assert(EI && "Not an ExtractValueInst?");
287   Expression e;
288   e.type = EI->getType();
289   e.opcode = 0;
290 
291   IntrinsicInst *I = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
292   if (I != nullptr && EI->getNumIndices() == 1 && *EI->idx_begin() == 0 ) {
293     // EI might be an extract from one of our recognised intrinsics. If it
294     // is we'll synthesize a semantically equivalent expression instead on
295     // an extract value expression.
296     switch (I->getIntrinsicID()) {
297       case Intrinsic::sadd_with_overflow:
298       case Intrinsic::uadd_with_overflow:
299         e.opcode = Instruction::Add;
300         break;
301       case Intrinsic::ssub_with_overflow:
302       case Intrinsic::usub_with_overflow:
303         e.opcode = Instruction::Sub;
304         break;
305       case Intrinsic::smul_with_overflow:
306       case Intrinsic::umul_with_overflow:
307         e.opcode = Instruction::Mul;
308         break;
309       default:
310         break;
311     }
312 
313     if (e.opcode != 0) {
314       // Intrinsic recognized. Grab its args to finish building the expression.
315       assert(I->getNumArgOperands() == 2 &&
316              "Expect two args for recognised intrinsics.");
317       e.varargs.push_back(lookupOrAdd(I->getArgOperand(0)));
318       e.varargs.push_back(lookupOrAdd(I->getArgOperand(1)));
319       return e;
320     }
321   }
322 
323   // Not a recognised intrinsic. Fall back to producing an extract value
324   // expression.
325   e.opcode = EI->getOpcode();
326   for (Instruction::op_iterator OI = EI->op_begin(), OE = EI->op_end();
327        OI != OE; ++OI)
328     e.varargs.push_back(lookupOrAdd(*OI));
329 
330   for (ExtractValueInst::idx_iterator II = EI->idx_begin(), IE = EI->idx_end();
331          II != IE; ++II)
332     e.varargs.push_back(*II);
333 
334   return e;
335 }
336 
337 //===----------------------------------------------------------------------===//
338 //                     ValueTable External Functions
339 //===----------------------------------------------------------------------===//
340 
341 GVN::ValueTable::ValueTable() : nextValueNumber(1) {}
342 GVN::ValueTable::ValueTable(const ValueTable &) = default;
343 GVN::ValueTable::ValueTable(ValueTable &&) = default;
344 GVN::ValueTable::~ValueTable() = default;
345 
346 /// add - Insert a value into the table with a specified value number.
347 void GVN::ValueTable::add(Value *V, uint32_t num) {
348   valueNumbering.insert(std::make_pair(V, num));
349 }
350 
351 uint32_t GVN::ValueTable::lookupOrAddCall(CallInst *C) {
352   if (AA->doesNotAccessMemory(C)) {
353     Expression exp = createExpr(C);
354     uint32_t &e = expressionNumbering[exp];
355     if (!e) e = nextValueNumber++;
356     valueNumbering[C] = e;
357     return e;
358   } else if (AA->onlyReadsMemory(C)) {
359     Expression exp = createExpr(C);
360     uint32_t &e = expressionNumbering[exp];
361     if (!e) {
362       e = nextValueNumber++;
363       valueNumbering[C] = e;
364       return e;
365     }
366     if (!MD) {
367       e = nextValueNumber++;
368       valueNumbering[C] = e;
369       return e;
370     }
371 
372     MemDepResult local_dep = MD->getDependency(C);
373 
374     if (!local_dep.isDef() && !local_dep.isNonLocal()) {
375       valueNumbering[C] =  nextValueNumber;
376       return nextValueNumber++;
377     }
378 
379     if (local_dep.isDef()) {
380       CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
381 
382       if (local_cdep->getNumArgOperands() != C->getNumArgOperands()) {
383         valueNumbering[C] = nextValueNumber;
384         return nextValueNumber++;
385       }
386 
387       for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
388         uint32_t c_vn = lookupOrAdd(C->getArgOperand(i));
389         uint32_t cd_vn = lookupOrAdd(local_cdep->getArgOperand(i));
390         if (c_vn != cd_vn) {
391           valueNumbering[C] = nextValueNumber;
392           return nextValueNumber++;
393         }
394       }
395 
396       uint32_t v = lookupOrAdd(local_cdep);
397       valueNumbering[C] = v;
398       return v;
399     }
400 
401     // Non-local case.
402     const MemoryDependenceResults::NonLocalDepInfo &deps =
403       MD->getNonLocalCallDependency(CallSite(C));
404     // FIXME: Move the checking logic to MemDep!
405     CallInst* cdep = nullptr;
406 
407     // Check to see if we have a single dominating call instruction that is
408     // identical to C.
409     for (unsigned i = 0, e = deps.size(); i != e; ++i) {
410       const NonLocalDepEntry *I = &deps[i];
411       if (I->getResult().isNonLocal())
412         continue;
413 
414       // We don't handle non-definitions.  If we already have a call, reject
415       // instruction dependencies.
416       if (!I->getResult().isDef() || cdep != nullptr) {
417         cdep = nullptr;
418         break;
419       }
420 
421       CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst());
422       // FIXME: All duplicated with non-local case.
423       if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){
424         cdep = NonLocalDepCall;
425         continue;
426       }
427 
428       cdep = nullptr;
429       break;
430     }
431 
432     if (!cdep) {
433       valueNumbering[C] = nextValueNumber;
434       return nextValueNumber++;
435     }
436 
437     if (cdep->getNumArgOperands() != C->getNumArgOperands()) {
438       valueNumbering[C] = nextValueNumber;
439       return nextValueNumber++;
440     }
441     for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
442       uint32_t c_vn = lookupOrAdd(C->getArgOperand(i));
443       uint32_t cd_vn = lookupOrAdd(cdep->getArgOperand(i));
444       if (c_vn != cd_vn) {
445         valueNumbering[C] = nextValueNumber;
446         return nextValueNumber++;
447       }
448     }
449 
450     uint32_t v = lookupOrAdd(cdep);
451     valueNumbering[C] = v;
452     return v;
453 
454   } else {
455     valueNumbering[C] = nextValueNumber;
456     return nextValueNumber++;
457   }
458 }
459 
460 /// Returns true if a value number exists for the specified value.
461 bool GVN::ValueTable::exists(Value *V) const { return valueNumbering.count(V) != 0; }
462 
463 /// lookup_or_add - Returns the value number for the specified value, assigning
464 /// it a new number if it did not have one before.
465 uint32_t GVN::ValueTable::lookupOrAdd(Value *V) {
466   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
467   if (VI != valueNumbering.end())
468     return VI->second;
469 
470   if (!isa<Instruction>(V)) {
471     valueNumbering[V] = nextValueNumber;
472     return nextValueNumber++;
473   }
474 
475   Instruction* I = cast<Instruction>(V);
476   Expression exp;
477   switch (I->getOpcode()) {
478     case Instruction::Call:
479       return lookupOrAddCall(cast<CallInst>(I));
480     case Instruction::Add:
481     case Instruction::FAdd:
482     case Instruction::Sub:
483     case Instruction::FSub:
484     case Instruction::Mul:
485     case Instruction::FMul:
486     case Instruction::UDiv:
487     case Instruction::SDiv:
488     case Instruction::FDiv:
489     case Instruction::URem:
490     case Instruction::SRem:
491     case Instruction::FRem:
492     case Instruction::Shl:
493     case Instruction::LShr:
494     case Instruction::AShr:
495     case Instruction::And:
496     case Instruction::Or:
497     case Instruction::Xor:
498     case Instruction::ICmp:
499     case Instruction::FCmp:
500     case Instruction::Trunc:
501     case Instruction::ZExt:
502     case Instruction::SExt:
503     case Instruction::FPToUI:
504     case Instruction::FPToSI:
505     case Instruction::UIToFP:
506     case Instruction::SIToFP:
507     case Instruction::FPTrunc:
508     case Instruction::FPExt:
509     case Instruction::PtrToInt:
510     case Instruction::IntToPtr:
511     case Instruction::BitCast:
512     case Instruction::Select:
513     case Instruction::ExtractElement:
514     case Instruction::InsertElement:
515     case Instruction::ShuffleVector:
516     case Instruction::InsertValue:
517     case Instruction::GetElementPtr:
518       exp = createExpr(I);
519       break;
520     case Instruction::ExtractValue:
521       exp = createExtractvalueExpr(cast<ExtractValueInst>(I));
522       break;
523     default:
524       valueNumbering[V] = nextValueNumber;
525       return nextValueNumber++;
526   }
527 
528   uint32_t& e = expressionNumbering[exp];
529   if (!e) e = nextValueNumber++;
530   valueNumbering[V] = e;
531   return e;
532 }
533 
534 /// Returns the value number of the specified value. Fails if
535 /// the value has not yet been numbered.
536 uint32_t GVN::ValueTable::lookup(Value *V) const {
537   DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
538   assert(VI != valueNumbering.end() && "Value not numbered?");
539   return VI->second;
540 }
541 
542 /// Returns the value number of the given comparison,
543 /// assigning it a new number if it did not have one before.  Useful when
544 /// we deduced the result of a comparison, but don't immediately have an
545 /// instruction realizing that comparison to hand.
546 uint32_t GVN::ValueTable::lookupOrAddCmp(unsigned Opcode,
547                                          CmpInst::Predicate Predicate,
548                                          Value *LHS, Value *RHS) {
549   Expression exp = createCmpExpr(Opcode, Predicate, LHS, RHS);
550   uint32_t& e = expressionNumbering[exp];
551   if (!e) e = nextValueNumber++;
552   return e;
553 }
554 
555 /// Remove all entries from the ValueTable.
556 void GVN::ValueTable::clear() {
557   valueNumbering.clear();
558   expressionNumbering.clear();
559   nextValueNumber = 1;
560 }
561 
562 /// Remove a value from the value numbering.
563 void GVN::ValueTable::erase(Value *V) {
564   valueNumbering.erase(V);
565 }
566 
567 /// verifyRemoved - Verify that the value is removed from all internal data
568 /// structures.
569 void GVN::ValueTable::verifyRemoved(const Value *V) const {
570   for (DenseMap<Value*, uint32_t>::const_iterator
571          I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
572     assert(I->first != V && "Inst still occurs in value numbering map!");
573   }
574 }
575 
576 //===----------------------------------------------------------------------===//
577 //                                GVN Pass
578 //===----------------------------------------------------------------------===//
579 
580 PreservedAnalyses GVN::run(Function &F, FunctionAnalysisManager &AM) {
581   // FIXME: The order of evaluation of these 'getResult' calls is very
582   // significant! Re-ordering these variables will cause GVN when run alone to
583   // be less effective! We should fix memdep and basic-aa to not exhibit this
584   // behavior, but until then don't change the order here.
585   auto &AC = AM.getResult<AssumptionAnalysis>(F);
586   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
587   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
588   auto &AA = AM.getResult<AAManager>(F);
589   auto &MemDep = AM.getResult<MemoryDependenceAnalysis>(F);
590   auto *LI = AM.getCachedResult<LoopAnalysis>(F);
591   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
592   bool Changed = runImpl(F, AC, DT, TLI, AA, &MemDep, LI, &ORE);
593   if (!Changed)
594     return PreservedAnalyses::all();
595   PreservedAnalyses PA;
596   PA.preserve<DominatorTreeAnalysis>();
597   PA.preserve<GlobalsAA>();
598   PA.preserve<TargetLibraryAnalysis>();
599   return PA;
600 }
601 
602 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
603 LLVM_DUMP_METHOD void GVN::dump(DenseMap<uint32_t, Value*>& d) {
604   errs() << "{\n";
605   for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
606        E = d.end(); I != E; ++I) {
607       errs() << I->first << "\n";
608       I->second->dump();
609   }
610   errs() << "}\n";
611 }
612 #endif
613 
614 /// Return true if we can prove that the value
615 /// we're analyzing is fully available in the specified block.  As we go, keep
616 /// track of which blocks we know are fully alive in FullyAvailableBlocks.  This
617 /// map is actually a tri-state map with the following values:
618 ///   0) we know the block *is not* fully available.
619 ///   1) we know the block *is* fully available.
620 ///   2) we do not know whether the block is fully available or not, but we are
621 ///      currently speculating that it will be.
622 ///   3) we are speculating for this block and have used that to speculate for
623 ///      other blocks.
624 static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
625                             DenseMap<BasicBlock*, char> &FullyAvailableBlocks,
626                             uint32_t RecurseDepth) {
627   if (RecurseDepth > MaxRecurseDepth)
628     return false;
629 
630   // Optimistically assume that the block is fully available and check to see
631   // if we already know about this block in one lookup.
632   std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
633     FullyAvailableBlocks.insert(std::make_pair(BB, 2));
634 
635   // If the entry already existed for this block, return the precomputed value.
636   if (!IV.second) {
637     // If this is a speculative "available" value, mark it as being used for
638     // speculation of other blocks.
639     if (IV.first->second == 2)
640       IV.first->second = 3;
641     return IV.first->second != 0;
642   }
643 
644   // Otherwise, see if it is fully available in all predecessors.
645   pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
646 
647   // If this block has no predecessors, it isn't live-in here.
648   if (PI == PE)
649     goto SpeculationFailure;
650 
651   for (; PI != PE; ++PI)
652     // If the value isn't fully available in one of our predecessors, then it
653     // isn't fully available in this block either.  Undo our previous
654     // optimistic assumption and bail out.
655     if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks,RecurseDepth+1))
656       goto SpeculationFailure;
657 
658   return true;
659 
660 // If we get here, we found out that this is not, after
661 // all, a fully-available block.  We have a problem if we speculated on this and
662 // used the speculation to mark other blocks as available.
663 SpeculationFailure:
664   char &BBVal = FullyAvailableBlocks[BB];
665 
666   // If we didn't speculate on this, just return with it set to false.
667   if (BBVal == 2) {
668     BBVal = 0;
669     return false;
670   }
671 
672   // If we did speculate on this value, we could have blocks set to 1 that are
673   // incorrect.  Walk the (transitive) successors of this block and mark them as
674   // 0 if set to one.
675   SmallVector<BasicBlock*, 32> BBWorklist;
676   BBWorklist.push_back(BB);
677 
678   do {
679     BasicBlock *Entry = BBWorklist.pop_back_val();
680     // Note that this sets blocks to 0 (unavailable) if they happen to not
681     // already be in FullyAvailableBlocks.  This is safe.
682     char &EntryVal = FullyAvailableBlocks[Entry];
683     if (EntryVal == 0) continue;  // Already unavailable.
684 
685     // Mark as unavailable.
686     EntryVal = 0;
687 
688     BBWorklist.append(succ_begin(Entry), succ_end(Entry));
689   } while (!BBWorklist.empty());
690 
691   return false;
692 }
693 
694 
695 /// Return true if CoerceAvailableValueToLoadType will succeed.
696 static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
697                                             Type *LoadTy,
698                                             const DataLayout &DL) {
699   // If the loaded or stored value is an first class array or struct, don't try
700   // to transform them.  We need to be able to bitcast to integer.
701   if (LoadTy->isStructTy() || LoadTy->isArrayTy() ||
702       StoredVal->getType()->isStructTy() ||
703       StoredVal->getType()->isArrayTy())
704     return false;
705 
706   // The store has to be at least as big as the load.
707   if (DL.getTypeSizeInBits(StoredVal->getType()) <
708         DL.getTypeSizeInBits(LoadTy))
709     return false;
710 
711   return true;
712 }
713 
714 /// If we saw a store of a value to memory, and
715 /// then a load from a must-aliased pointer of a different type, try to coerce
716 /// the stored value.  LoadedTy is the type of the load we want to replace.
717 /// IRB is IRBuilder used to insert new instructions.
718 ///
719 /// If we can't do it, return null.
720 static Value *CoerceAvailableValueToLoadType(Value *StoredVal, Type *LoadedTy,
721                                              IRBuilder<> &IRB,
722                                              const DataLayout &DL) {
723   assert(CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, DL) &&
724          "precondition violation - materialization can't fail");
725 
726   if (auto *C = dyn_cast<Constant>(StoredVal))
727     if (auto *FoldedStoredVal = ConstantFoldConstant(C, DL))
728       StoredVal = FoldedStoredVal;
729 
730   // If this is already the right type, just return it.
731   Type *StoredValTy = StoredVal->getType();
732 
733   uint64_t StoredValSize = DL.getTypeSizeInBits(StoredValTy);
734   uint64_t LoadedValSize = DL.getTypeSizeInBits(LoadedTy);
735 
736   // If the store and reload are the same size, we can always reuse it.
737   if (StoredValSize == LoadedValSize) {
738     // Pointer to Pointer -> use bitcast.
739     if (StoredValTy->getScalarType()->isPointerTy() &&
740         LoadedTy->getScalarType()->isPointerTy()) {
741       StoredVal = IRB.CreateBitCast(StoredVal, LoadedTy);
742     } else {
743       // Convert source pointers to integers, which can be bitcast.
744       if (StoredValTy->getScalarType()->isPointerTy()) {
745         StoredValTy = DL.getIntPtrType(StoredValTy);
746         StoredVal = IRB.CreatePtrToInt(StoredVal, StoredValTy);
747       }
748 
749       Type *TypeToCastTo = LoadedTy;
750       if (TypeToCastTo->getScalarType()->isPointerTy())
751         TypeToCastTo = DL.getIntPtrType(TypeToCastTo);
752 
753       if (StoredValTy != TypeToCastTo)
754         StoredVal = IRB.CreateBitCast(StoredVal, TypeToCastTo);
755 
756       // Cast to pointer if the load needs a pointer type.
757       if (LoadedTy->getScalarType()->isPointerTy())
758         StoredVal = IRB.CreateIntToPtr(StoredVal, LoadedTy);
759     }
760 
761     if (auto *C = dyn_cast<ConstantExpr>(StoredVal))
762       if (auto *FoldedStoredVal = ConstantFoldConstant(C, DL))
763         StoredVal = FoldedStoredVal;
764 
765     return StoredVal;
766   }
767 
768   // If the loaded value is smaller than the available value, then we can
769   // extract out a piece from it.  If the available value is too small, then we
770   // can't do anything.
771   assert(StoredValSize >= LoadedValSize &&
772          "CanCoerceMustAliasedValueToLoad fail");
773 
774   // Convert source pointers to integers, which can be manipulated.
775   if (StoredValTy->getScalarType()->isPointerTy()) {
776     StoredValTy = DL.getIntPtrType(StoredValTy);
777     StoredVal = IRB.CreatePtrToInt(StoredVal, StoredValTy);
778   }
779 
780   // Convert vectors and fp to integer, which can be manipulated.
781   if (!StoredValTy->isIntegerTy()) {
782     StoredValTy = IntegerType::get(StoredValTy->getContext(), StoredValSize);
783     StoredVal = IRB.CreateBitCast(StoredVal, StoredValTy);
784   }
785 
786   // If this is a big-endian system, we need to shift the value down to the low
787   // bits so that a truncate will work.
788   if (DL.isBigEndian()) {
789     uint64_t ShiftAmt = DL.getTypeStoreSizeInBits(StoredValTy) -
790                         DL.getTypeStoreSizeInBits(LoadedTy);
791     StoredVal = IRB.CreateLShr(StoredVal, ShiftAmt, "tmp");
792   }
793 
794   // Truncate the integer to the right size now.
795   Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadedValSize);
796   StoredVal  = IRB.CreateTrunc(StoredVal, NewIntTy, "trunc");
797 
798   if (LoadedTy != NewIntTy) {
799     // If the result is a pointer, inttoptr.
800     if (LoadedTy->getScalarType()->isPointerTy())
801       StoredVal = IRB.CreateIntToPtr(StoredVal, LoadedTy, "inttoptr");
802     else
803       // Otherwise, bitcast.
804       StoredVal = IRB.CreateBitCast(StoredVal, LoadedTy, "bitcast");
805   }
806 
807   if (auto *C = dyn_cast<Constant>(StoredVal))
808     if (auto *FoldedStoredVal = ConstantFoldConstant(C, DL))
809       StoredVal = FoldedStoredVal;
810 
811   return StoredVal;
812 }
813 
814 /// This function is called when we have a
815 /// memdep query of a load that ends up being a clobbering memory write (store,
816 /// memset, memcpy, memmove).  This means that the write *may* provide bits used
817 /// by the load but we can't be sure because the pointers don't mustalias.
818 ///
819 /// Check this case to see if there is anything more we can do before we give
820 /// up.  This returns -1 if we have to give up, or a byte number in the stored
821 /// value of the piece that feeds the load.
822 static int AnalyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr,
823                                           Value *WritePtr,
824                                           uint64_t WriteSizeInBits,
825                                           const DataLayout &DL) {
826   // If the loaded or stored value is a first class array or struct, don't try
827   // to transform them.  We need to be able to bitcast to integer.
828   if (LoadTy->isStructTy() || LoadTy->isArrayTy())
829     return -1;
830 
831   int64_t StoreOffset = 0, LoadOffset = 0;
832   Value *StoreBase =
833       GetPointerBaseWithConstantOffset(WritePtr, StoreOffset, DL);
834   Value *LoadBase = GetPointerBaseWithConstantOffset(LoadPtr, LoadOffset, DL);
835   if (StoreBase != LoadBase)
836     return -1;
837 
838   // If the load and store are to the exact same address, they should have been
839   // a must alias.  AA must have gotten confused.
840   // FIXME: Study to see if/when this happens.  One case is forwarding a memset
841   // to a load from the base of the memset.
842 
843   // If the load and store don't overlap at all, the store doesn't provide
844   // anything to the load.  In this case, they really don't alias at all, AA
845   // must have gotten confused.
846   uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy);
847 
848   if ((WriteSizeInBits & 7) | (LoadSize & 7))
849     return -1;
850   uint64_t StoreSize = WriteSizeInBits / 8;  // Convert to bytes.
851   LoadSize /= 8;
852 
853 
854   bool isAAFailure = false;
855   if (StoreOffset < LoadOffset)
856     isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
857   else
858     isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
859 
860   if (isAAFailure)
861     return -1;
862 
863   // If the Load isn't completely contained within the stored bits, we don't
864   // have all the bits to feed it.  We could do something crazy in the future
865   // (issue a smaller load then merge the bits in) but this seems unlikely to be
866   // valuable.
867   if (StoreOffset > LoadOffset ||
868       StoreOffset+StoreSize < LoadOffset+LoadSize)
869     return -1;
870 
871   // Okay, we can do this transformation.  Return the number of bytes into the
872   // store that the load is.
873   return LoadOffset-StoreOffset;
874 }
875 
876 /// This function is called when we have a
877 /// memdep query of a load that ends up being a clobbering store.
878 static int AnalyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr,
879                                           StoreInst *DepSI) {
880   // Cannot handle reading from store of first-class aggregate yet.
881   if (DepSI->getValueOperand()->getType()->isStructTy() ||
882       DepSI->getValueOperand()->getType()->isArrayTy())
883     return -1;
884 
885   const DataLayout &DL = DepSI->getModule()->getDataLayout();
886   Value *StorePtr = DepSI->getPointerOperand();
887   uint64_t StoreSize =DL.getTypeSizeInBits(DepSI->getValueOperand()->getType());
888   return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
889                                         StorePtr, StoreSize, DL);
890 }
891 
892 /// This function is called when we have a
893 /// memdep query of a load that ends up being clobbered by another load.  See if
894 /// the other load can feed into the second load.
895 static int AnalyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr,
896                                          LoadInst *DepLI, const DataLayout &DL){
897   // Cannot handle reading from store of first-class aggregate yet.
898   if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy())
899     return -1;
900 
901   Value *DepPtr = DepLI->getPointerOperand();
902   uint64_t DepSize = DL.getTypeSizeInBits(DepLI->getType());
903   int R = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, DL);
904   if (R != -1) return R;
905 
906   // If we have a load/load clobber an DepLI can be widened to cover this load,
907   // then we should widen it!
908   int64_t LoadOffs = 0;
909   const Value *LoadBase =
910       GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, DL);
911   unsigned LoadSize = DL.getTypeStoreSize(LoadTy);
912 
913   unsigned Size = MemoryDependenceResults::getLoadLoadClobberFullWidthSize(
914       LoadBase, LoadOffs, LoadSize, DepLI);
915   if (Size == 0) return -1;
916 
917   // Check non-obvious conditions enforced by MDA which we rely on for being
918   // able to materialize this potentially available value
919   assert(DepLI->isSimple() && "Cannot widen volatile/atomic load!");
920   assert(DepLI->getType()->isIntegerTy() && "Can't widen non-integer load");
921 
922   return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size*8, DL);
923 }
924 
925 
926 
927 static int AnalyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr,
928                                             MemIntrinsic *MI,
929                                             const DataLayout &DL) {
930   // If the mem operation is a non-constant size, we can't handle it.
931   ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength());
932   if (!SizeCst) return -1;
933   uint64_t MemSizeInBits = SizeCst->getZExtValue()*8;
934 
935   // If this is memset, we just need to see if the offset is valid in the size
936   // of the memset..
937   if (MI->getIntrinsicID() == Intrinsic::memset)
938     return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
939                                           MemSizeInBits, DL);
940 
941   // If we have a memcpy/memmove, the only case we can handle is if this is a
942   // copy from constant memory.  In that case, we can read directly from the
943   // constant memory.
944   MemTransferInst *MTI = cast<MemTransferInst>(MI);
945 
946   Constant *Src = dyn_cast<Constant>(MTI->getSource());
947   if (!Src) return -1;
948 
949   GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Src, DL));
950   if (!GV || !GV->isConstant()) return -1;
951 
952   // See if the access is within the bounds of the transfer.
953   int Offset = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
954                                               MI->getDest(), MemSizeInBits, DL);
955   if (Offset == -1)
956     return Offset;
957 
958   unsigned AS = Src->getType()->getPointerAddressSpace();
959   // Otherwise, see if we can constant fold a load from the constant with the
960   // offset applied as appropriate.
961   Src = ConstantExpr::getBitCast(Src,
962                                  Type::getInt8PtrTy(Src->getContext(), AS));
963   Constant *OffsetCst =
964     ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
965   Src = ConstantExpr::getGetElementPtr(Type::getInt8Ty(Src->getContext()), Src,
966                                        OffsetCst);
967   Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
968   if (ConstantFoldLoadFromConstPtr(Src, LoadTy, DL))
969     return Offset;
970   return -1;
971 }
972 
973 
974 /// This function is called when we have a
975 /// memdep query of a load that ends up being a clobbering store.  This means
976 /// that the store provides bits used by the load but we the pointers don't
977 /// mustalias.  Check this case to see if there is anything more we can do
978 /// before we give up.
979 static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
980                                    Type *LoadTy,
981                                    Instruction *InsertPt, const DataLayout &DL){
982   LLVMContext &Ctx = SrcVal->getType()->getContext();
983 
984   uint64_t StoreSize = (DL.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
985   uint64_t LoadSize = (DL.getTypeSizeInBits(LoadTy) + 7) / 8;
986 
987   IRBuilder<> Builder(InsertPt);
988 
989   // Compute which bits of the stored value are being used by the load.  Convert
990   // to an integer type to start with.
991   if (SrcVal->getType()->getScalarType()->isPointerTy())
992     SrcVal = Builder.CreatePtrToInt(SrcVal,
993         DL.getIntPtrType(SrcVal->getType()));
994   if (!SrcVal->getType()->isIntegerTy())
995     SrcVal = Builder.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize*8));
996 
997   // Shift the bits to the least significant depending on endianness.
998   unsigned ShiftAmt;
999   if (DL.isLittleEndian())
1000     ShiftAmt = Offset*8;
1001   else
1002     ShiftAmt = (StoreSize-LoadSize-Offset)*8;
1003 
1004   if (ShiftAmt)
1005     SrcVal = Builder.CreateLShr(SrcVal, ShiftAmt);
1006 
1007   if (LoadSize != StoreSize)
1008     SrcVal = Builder.CreateTrunc(SrcVal, IntegerType::get(Ctx, LoadSize*8));
1009 
1010   return CoerceAvailableValueToLoadType(SrcVal, LoadTy, Builder, DL);
1011 }
1012 
1013 /// This function is called when we have a
1014 /// memdep query of a load that ends up being a clobbering load.  This means
1015 /// that the load *may* provide bits used by the load but we can't be sure
1016 /// because the pointers don't mustalias.  Check this case to see if there is
1017 /// anything more we can do before we give up.
1018 static Value *GetLoadValueForLoad(LoadInst *SrcVal, unsigned Offset,
1019                                   Type *LoadTy, Instruction *InsertPt,
1020                                   GVN &gvn) {
1021   const DataLayout &DL = SrcVal->getModule()->getDataLayout();
1022   // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to
1023   // widen SrcVal out to a larger load.
1024   unsigned SrcValStoreSize = DL.getTypeStoreSize(SrcVal->getType());
1025   unsigned LoadSize = DL.getTypeStoreSize(LoadTy);
1026   if (Offset+LoadSize > SrcValStoreSize) {
1027     assert(SrcVal->isSimple() && "Cannot widen volatile/atomic load!");
1028     assert(SrcVal->getType()->isIntegerTy() && "Can't widen non-integer load");
1029     // If we have a load/load clobber an DepLI can be widened to cover this
1030     // load, then we should widen it to the next power of 2 size big enough!
1031     unsigned NewLoadSize = Offset+LoadSize;
1032     if (!isPowerOf2_32(NewLoadSize))
1033       NewLoadSize = NextPowerOf2(NewLoadSize);
1034 
1035     Value *PtrVal = SrcVal->getPointerOperand();
1036 
1037     // Insert the new load after the old load.  This ensures that subsequent
1038     // memdep queries will find the new load.  We can't easily remove the old
1039     // load completely because it is already in the value numbering table.
1040     IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal));
1041     Type *DestPTy =
1042       IntegerType::get(LoadTy->getContext(), NewLoadSize*8);
1043     DestPTy = PointerType::get(DestPTy,
1044                                PtrVal->getType()->getPointerAddressSpace());
1045     Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc());
1046     PtrVal = Builder.CreateBitCast(PtrVal, DestPTy);
1047     LoadInst *NewLoad = Builder.CreateLoad(PtrVal);
1048     NewLoad->takeName(SrcVal);
1049     NewLoad->setAlignment(SrcVal->getAlignment());
1050 
1051     DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n");
1052     DEBUG(dbgs() << "TO: " << *NewLoad << "\n");
1053 
1054     // Replace uses of the original load with the wider load.  On a big endian
1055     // system, we need to shift down to get the relevant bits.
1056     Value *RV = NewLoad;
1057     if (DL.isBigEndian())
1058       RV = Builder.CreateLShr(RV, (NewLoadSize - SrcValStoreSize) * 8);
1059     RV = Builder.CreateTrunc(RV, SrcVal->getType());
1060     SrcVal->replaceAllUsesWith(RV);
1061 
1062     // We would like to use gvn.markInstructionForDeletion here, but we can't
1063     // because the load is already memoized into the leader map table that GVN
1064     // tracks.  It is potentially possible to remove the load from the table,
1065     // but then there all of the operations based on it would need to be
1066     // rehashed.  Just leave the dead load around.
1067     gvn.getMemDep().removeInstruction(SrcVal);
1068     SrcVal = NewLoad;
1069   }
1070 
1071   return GetStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, DL);
1072 }
1073 
1074 
1075 /// This function is called when we have a
1076 /// memdep query of a load that ends up being a clobbering mem intrinsic.
1077 static Value *GetMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
1078                                      Type *LoadTy, Instruction *InsertPt,
1079                                      const DataLayout &DL){
1080   LLVMContext &Ctx = LoadTy->getContext();
1081   uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy)/8;
1082 
1083   IRBuilder<> Builder(InsertPt);
1084 
1085   // We know that this method is only called when the mem transfer fully
1086   // provides the bits for the load.
1087   if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) {
1088     // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
1089     // independently of what the offset is.
1090     Value *Val = MSI->getValue();
1091     if (LoadSize != 1)
1092       Val = Builder.CreateZExt(Val, IntegerType::get(Ctx, LoadSize*8));
1093 
1094     Value *OneElt = Val;
1095 
1096     // Splat the value out to the right number of bits.
1097     for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize; ) {
1098       // If we can double the number of bytes set, do it.
1099       if (NumBytesSet*2 <= LoadSize) {
1100         Value *ShVal = Builder.CreateShl(Val, NumBytesSet*8);
1101         Val = Builder.CreateOr(Val, ShVal);
1102         NumBytesSet <<= 1;
1103         continue;
1104       }
1105 
1106       // Otherwise insert one byte at a time.
1107       Value *ShVal = Builder.CreateShl(Val, 1*8);
1108       Val = Builder.CreateOr(OneElt, ShVal);
1109       ++NumBytesSet;
1110     }
1111 
1112     return CoerceAvailableValueToLoadType(Val, LoadTy, Builder, DL);
1113   }
1114 
1115   // Otherwise, this is a memcpy/memmove from a constant global.
1116   MemTransferInst *MTI = cast<MemTransferInst>(SrcInst);
1117   Constant *Src = cast<Constant>(MTI->getSource());
1118   unsigned AS = Src->getType()->getPointerAddressSpace();
1119 
1120   // Otherwise, see if we can constant fold a load from the constant with the
1121   // offset applied as appropriate.
1122   Src = ConstantExpr::getBitCast(Src,
1123                                  Type::getInt8PtrTy(Src->getContext(), AS));
1124   Constant *OffsetCst =
1125     ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
1126   Src = ConstantExpr::getGetElementPtr(Type::getInt8Ty(Src->getContext()), Src,
1127                                        OffsetCst);
1128   Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
1129   return ConstantFoldLoadFromConstPtr(Src, LoadTy, DL);
1130 }
1131 
1132 
1133 /// Given a set of loads specified by ValuesPerBlock,
1134 /// construct SSA form, allowing us to eliminate LI.  This returns the value
1135 /// that should be used at LI's definition site.
1136 static Value *ConstructSSAForLoadSet(LoadInst *LI,
1137                          SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
1138                                      GVN &gvn) {
1139   // Check for the fully redundant, dominating load case.  In this case, we can
1140   // just use the dominating value directly.
1141   if (ValuesPerBlock.size() == 1 &&
1142       gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
1143                                                LI->getParent())) {
1144     assert(!ValuesPerBlock[0].AV.isUndefValue() &&
1145            "Dead BB dominate this block");
1146     return ValuesPerBlock[0].MaterializeAdjustedValue(LI, gvn);
1147   }
1148 
1149   // Otherwise, we have to construct SSA form.
1150   SmallVector<PHINode*, 8> NewPHIs;
1151   SSAUpdater SSAUpdate(&NewPHIs);
1152   SSAUpdate.Initialize(LI->getType(), LI->getName());
1153 
1154   for (const AvailableValueInBlock &AV : ValuesPerBlock) {
1155     BasicBlock *BB = AV.BB;
1156 
1157     if (SSAUpdate.HasValueForBlock(BB))
1158       continue;
1159 
1160     SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LI, gvn));
1161   }
1162 
1163   // Perform PHI construction.
1164   return SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
1165 }
1166 
1167 Value *AvailableValue::MaterializeAdjustedValue(LoadInst *LI,
1168                                                 Instruction *InsertPt,
1169                                                 GVN &gvn) const {
1170   Value *Res;
1171   Type *LoadTy = LI->getType();
1172   const DataLayout &DL = LI->getModule()->getDataLayout();
1173   if (isSimpleValue()) {
1174     Res = getSimpleValue();
1175     if (Res->getType() != LoadTy) {
1176       Res = GetStoreValueForLoad(Res, Offset, LoadTy, InsertPt, DL);
1177 
1178       DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset << "  "
1179                    << *getSimpleValue() << '\n'
1180                    << *Res << '\n' << "\n\n\n");
1181     }
1182   } else if (isCoercedLoadValue()) {
1183     LoadInst *Load = getCoercedLoadValue();
1184     if (Load->getType() == LoadTy && Offset == 0) {
1185       Res = Load;
1186     } else {
1187       Res = GetLoadValueForLoad(Load, Offset, LoadTy, InsertPt, gvn);
1188 
1189       DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset << "  "
1190                    << *getCoercedLoadValue() << '\n'
1191                    << *Res << '\n' << "\n\n\n");
1192     }
1193   } else if (isMemIntrinValue()) {
1194     Res = GetMemInstValueForLoad(getMemIntrinValue(), Offset, LoadTy,
1195                                  InsertPt, DL);
1196     DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
1197                  << "  " << *getMemIntrinValue() << '\n'
1198                  << *Res << '\n' << "\n\n\n");
1199   } else {
1200     assert(isUndefValue() && "Should be UndefVal");
1201     DEBUG(dbgs() << "GVN COERCED NONLOCAL Undef:\n";);
1202     return UndefValue::get(LoadTy);
1203   }
1204   assert(Res && "failed to materialize?");
1205   return Res;
1206 }
1207 
1208 static bool isLifetimeStart(const Instruction *Inst) {
1209   if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
1210     return II->getIntrinsicID() == Intrinsic::lifetime_start;
1211   return false;
1212 }
1213 
1214 /// \brief Try to locate the three instruction involved in a missed
1215 /// load-elimination case that is due to an intervening store.
1216 static void reportMayClobberedLoad(LoadInst *LI, MemDepResult DepInfo,
1217                                    DominatorTree *DT,
1218                                    OptimizationRemarkEmitter *ORE) {
1219   using namespace ore;
1220   User *OtherAccess = nullptr;
1221 
1222   OptimizationRemarkMissed R(DEBUG_TYPE, "LoadClobbered", LI);
1223   R << "load of type " << NV("Type", LI->getType()) << " not eliminated"
1224     << setExtraArgs();
1225 
1226   for (auto *U : LI->getPointerOperand()->users())
1227     if (U != LI && (isa<LoadInst>(U) || isa<StoreInst>(U)) &&
1228         DT->dominates(cast<Instruction>(U), LI)) {
1229       // FIXME: for now give up if there are multiple memory accesses that
1230       // dominate the load.  We need further analysis to decide which one is
1231       // that we're forwarding from.
1232       if (OtherAccess)
1233         OtherAccess = nullptr;
1234       else
1235         OtherAccess = U;
1236     }
1237 
1238   if (OtherAccess)
1239     R << " in favor of " << NV("OtherAccess", OtherAccess);
1240 
1241   R << " because it is clobbered by " << NV("ClobberedBy", DepInfo.getInst());
1242 
1243   ORE->emit(R);
1244 }
1245 
1246 bool GVN::AnalyzeLoadAvailability(LoadInst *LI, MemDepResult DepInfo,
1247                                   Value *Address, AvailableValue &Res) {
1248 
1249   assert((DepInfo.isDef() || DepInfo.isClobber()) &&
1250          "expected a local dependence");
1251   assert(LI->isUnordered() && "rules below are incorrect for ordered access");
1252 
1253   const DataLayout &DL = LI->getModule()->getDataLayout();
1254 
1255   if (DepInfo.isClobber()) {
1256     // If the dependence is to a store that writes to a superset of the bits
1257     // read by the load, we can extract the bits we need for the load from the
1258     // stored value.
1259     if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
1260       // Can't forward from non-atomic to atomic without violating memory model.
1261       if (Address && LI->isAtomic() <= DepSI->isAtomic()) {
1262         int Offset =
1263           AnalyzeLoadFromClobberingStore(LI->getType(), Address, DepSI);
1264         if (Offset != -1) {
1265           Res = AvailableValue::get(DepSI->getValueOperand(), Offset);
1266           return true;
1267         }
1268       }
1269     }
1270 
1271     // Check to see if we have something like this:
1272     //    load i32* P
1273     //    load i8* (P+1)
1274     // if we have this, replace the later with an extraction from the former.
1275     if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInfo.getInst())) {
1276       // If this is a clobber and L is the first instruction in its block, then
1277       // we have the first instruction in the entry block.
1278       // Can't forward from non-atomic to atomic without violating memory model.
1279       if (DepLI != LI && Address && LI->isAtomic() <= DepLI->isAtomic()) {
1280         int Offset =
1281           AnalyzeLoadFromClobberingLoad(LI->getType(), Address, DepLI, DL);
1282 
1283         if (Offset != -1) {
1284           Res = AvailableValue::getLoad(DepLI, Offset);
1285           return true;
1286         }
1287       }
1288     }
1289 
1290     // If the clobbering value is a memset/memcpy/memmove, see if we can
1291     // forward a value on from it.
1292     if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInfo.getInst())) {
1293       if (Address && !LI->isAtomic()) {
1294         int Offset = AnalyzeLoadFromClobberingMemInst(LI->getType(), Address,
1295                                                       DepMI, DL);
1296         if (Offset != -1) {
1297           Res = AvailableValue::getMI(DepMI, Offset);
1298           return true;
1299         }
1300       }
1301     }
1302     // Nothing known about this clobber, have to be conservative
1303     DEBUG(
1304       // fast print dep, using operator<< on instruction is too slow.
1305       dbgs() << "GVN: load ";
1306       LI->printAsOperand(dbgs());
1307       Instruction *I = DepInfo.getInst();
1308       dbgs() << " is clobbered by " << *I << '\n';
1309     );
1310 
1311     if (ORE->allowExtraAnalysis())
1312       reportMayClobberedLoad(LI, DepInfo, DT, ORE);
1313 
1314     return false;
1315   }
1316   assert(DepInfo.isDef() && "follows from above");
1317 
1318   Instruction *DepInst = DepInfo.getInst();
1319 
1320   // Loading the allocation -> undef.
1321   if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI) ||
1322       // Loading immediately after lifetime begin -> undef.
1323       isLifetimeStart(DepInst)) {
1324     Res = AvailableValue::get(UndefValue::get(LI->getType()));
1325     return true;
1326   }
1327 
1328   // Loading from calloc (which zero initializes memory) -> zero
1329   if (isCallocLikeFn(DepInst, TLI)) {
1330     Res = AvailableValue::get(Constant::getNullValue(LI->getType()));
1331     return true;
1332   }
1333 
1334   if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
1335     // Reject loads and stores that are to the same address but are of
1336     // different types if we have to. If the stored value is larger or equal to
1337     // the loaded value, we can reuse it.
1338     if (S->getValueOperand()->getType() != LI->getType() &&
1339         !CanCoerceMustAliasedValueToLoad(S->getValueOperand(),
1340                                          LI->getType(), DL))
1341       return false;
1342 
1343     // Can't forward from non-atomic to atomic without violating memory model.
1344     if (S->isAtomic() < LI->isAtomic())
1345       return false;
1346 
1347     Res = AvailableValue::get(S->getValueOperand());
1348     return true;
1349   }
1350 
1351   if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
1352     // If the types mismatch and we can't handle it, reject reuse of the load.
1353     // If the stored value is larger or equal to the loaded value, we can reuse
1354     // it.
1355     if (LD->getType() != LI->getType() &&
1356         !CanCoerceMustAliasedValueToLoad(LD, LI->getType(), DL))
1357       return false;
1358 
1359     // Can't forward from non-atomic to atomic without violating memory model.
1360     if (LD->isAtomic() < LI->isAtomic())
1361       return false;
1362 
1363     Res = AvailableValue::getLoad(LD);
1364     return true;
1365   }
1366 
1367   // Unknown def - must be conservative
1368   DEBUG(
1369     // fast print dep, using operator<< on instruction is too slow.
1370     dbgs() << "GVN: load ";
1371     LI->printAsOperand(dbgs());
1372     dbgs() << " has unknown def " << *DepInst << '\n';
1373   );
1374   return false;
1375 }
1376 
1377 void GVN::AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps,
1378                                   AvailValInBlkVect &ValuesPerBlock,
1379                                   UnavailBlkVect &UnavailableBlocks) {
1380 
1381   // Filter out useless results (non-locals, etc).  Keep track of the blocks
1382   // where we have a value available in repl, also keep track of whether we see
1383   // dependencies that produce an unknown value for the load (such as a call
1384   // that could potentially clobber the load).
1385   unsigned NumDeps = Deps.size();
1386   for (unsigned i = 0, e = NumDeps; i != e; ++i) {
1387     BasicBlock *DepBB = Deps[i].getBB();
1388     MemDepResult DepInfo = Deps[i].getResult();
1389 
1390     if (DeadBlocks.count(DepBB)) {
1391       // Dead dependent mem-op disguise as a load evaluating the same value
1392       // as the load in question.
1393       ValuesPerBlock.push_back(AvailableValueInBlock::getUndef(DepBB));
1394       continue;
1395     }
1396 
1397     if (!DepInfo.isDef() && !DepInfo.isClobber()) {
1398       UnavailableBlocks.push_back(DepBB);
1399       continue;
1400     }
1401 
1402     // The address being loaded in this non-local block may not be the same as
1403     // the pointer operand of the load if PHI translation occurs.  Make sure
1404     // to consider the right address.
1405     Value *Address = Deps[i].getAddress();
1406 
1407     AvailableValue AV;
1408     if (AnalyzeLoadAvailability(LI, DepInfo, Address, AV)) {
1409       // subtlety: because we know this was a non-local dependency, we know
1410       // it's safe to materialize anywhere between the instruction within
1411       // DepInfo and the end of it's block.
1412       ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1413                                                           std::move(AV)));
1414     } else {
1415       UnavailableBlocks.push_back(DepBB);
1416     }
1417   }
1418 
1419   assert(NumDeps == ValuesPerBlock.size() + UnavailableBlocks.size() &&
1420          "post condition violation");
1421 }
1422 
1423 bool GVN::PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock,
1424                          UnavailBlkVect &UnavailableBlocks) {
1425   // Okay, we have *some* definitions of the value.  This means that the value
1426   // is available in some of our (transitive) predecessors.  Lets think about
1427   // doing PRE of this load.  This will involve inserting a new load into the
1428   // predecessor when it's not available.  We could do this in general, but
1429   // prefer to not increase code size.  As such, we only do this when we know
1430   // that we only have to insert *one* load (which means we're basically moving
1431   // the load, not inserting a new one).
1432 
1433   SmallPtrSet<BasicBlock *, 4> Blockers(UnavailableBlocks.begin(),
1434                                         UnavailableBlocks.end());
1435 
1436   // Let's find the first basic block with more than one predecessor.  Walk
1437   // backwards through predecessors if needed.
1438   BasicBlock *LoadBB = LI->getParent();
1439   BasicBlock *TmpBB = LoadBB;
1440 
1441   while (TmpBB->getSinglePredecessor()) {
1442     TmpBB = TmpBB->getSinglePredecessor();
1443     if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1444       return false;
1445     if (Blockers.count(TmpBB))
1446       return false;
1447 
1448     // If any of these blocks has more than one successor (i.e. if the edge we
1449     // just traversed was critical), then there are other paths through this
1450     // block along which the load may not be anticipated.  Hoisting the load
1451     // above this block would be adding the load to execution paths along
1452     // which it was not previously executed.
1453     if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1454       return false;
1455   }
1456 
1457   assert(TmpBB);
1458   LoadBB = TmpBB;
1459 
1460   // Check to see how many predecessors have the loaded value fully
1461   // available.
1462   MapVector<BasicBlock *, Value *> PredLoads;
1463   DenseMap<BasicBlock*, char> FullyAvailableBlocks;
1464   for (const AvailableValueInBlock &AV : ValuesPerBlock)
1465     FullyAvailableBlocks[AV.BB] = true;
1466   for (BasicBlock *UnavailableBB : UnavailableBlocks)
1467     FullyAvailableBlocks[UnavailableBB] = false;
1468 
1469   SmallVector<BasicBlock *, 4> CriticalEdgePred;
1470   for (BasicBlock *Pred : predecessors(LoadBB)) {
1471     // If any predecessor block is an EH pad that does not allow non-PHI
1472     // instructions before the terminator, we can't PRE the load.
1473     if (Pred->getTerminator()->isEHPad()) {
1474       DEBUG(dbgs()
1475             << "COULD NOT PRE LOAD BECAUSE OF AN EH PAD PREDECESSOR '"
1476             << Pred->getName() << "': " << *LI << '\n');
1477       return false;
1478     }
1479 
1480     if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks, 0)) {
1481       continue;
1482     }
1483 
1484     if (Pred->getTerminator()->getNumSuccessors() != 1) {
1485       if (isa<IndirectBrInst>(Pred->getTerminator())) {
1486         DEBUG(dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
1487               << Pred->getName() << "': " << *LI << '\n');
1488         return false;
1489       }
1490 
1491       if (LoadBB->isEHPad()) {
1492         DEBUG(dbgs()
1493               << "COULD NOT PRE LOAD BECAUSE OF AN EH PAD CRITICAL EDGE '"
1494               << Pred->getName() << "': " << *LI << '\n');
1495         return false;
1496       }
1497 
1498       CriticalEdgePred.push_back(Pred);
1499     } else {
1500       // Only add the predecessors that will not be split for now.
1501       PredLoads[Pred] = nullptr;
1502     }
1503   }
1504 
1505   // Decide whether PRE is profitable for this load.
1506   unsigned NumUnavailablePreds = PredLoads.size() + CriticalEdgePred.size();
1507   assert(NumUnavailablePreds != 0 &&
1508          "Fully available value should already be eliminated!");
1509 
1510   // If this load is unavailable in multiple predecessors, reject it.
1511   // FIXME: If we could restructure the CFG, we could make a common pred with
1512   // all the preds that don't have an available LI and insert a new load into
1513   // that one block.
1514   if (NumUnavailablePreds != 1)
1515       return false;
1516 
1517   // Split critical edges, and update the unavailable predecessors accordingly.
1518   for (BasicBlock *OrigPred : CriticalEdgePred) {
1519     BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB);
1520     assert(!PredLoads.count(OrigPred) && "Split edges shouldn't be in map!");
1521     PredLoads[NewPred] = nullptr;
1522     DEBUG(dbgs() << "Split critical edge " << OrigPred->getName() << "->"
1523                  << LoadBB->getName() << '\n');
1524   }
1525 
1526   // Check if the load can safely be moved to all the unavailable predecessors.
1527   bool CanDoPRE = true;
1528   const DataLayout &DL = LI->getModule()->getDataLayout();
1529   SmallVector<Instruction*, 8> NewInsts;
1530   for (auto &PredLoad : PredLoads) {
1531     BasicBlock *UnavailablePred = PredLoad.first;
1532 
1533     // Do PHI translation to get its value in the predecessor if necessary.  The
1534     // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
1535 
1536     // If all preds have a single successor, then we know it is safe to insert
1537     // the load on the pred (?!?), so we can insert code to materialize the
1538     // pointer if it is not available.
1539     PHITransAddr Address(LI->getPointerOperand(), DL, AC);
1540     Value *LoadPtr = nullptr;
1541     LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred,
1542                                                 *DT, NewInsts);
1543 
1544     // If we couldn't find or insert a computation of this phi translated value,
1545     // we fail PRE.
1546     if (!LoadPtr) {
1547       DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
1548             << *LI->getPointerOperand() << "\n");
1549       CanDoPRE = false;
1550       break;
1551     }
1552 
1553     PredLoad.second = LoadPtr;
1554   }
1555 
1556   if (!CanDoPRE) {
1557     while (!NewInsts.empty()) {
1558       Instruction *I = NewInsts.pop_back_val();
1559       if (MD) MD->removeInstruction(I);
1560       I->eraseFromParent();
1561     }
1562     // HINT: Don't revert the edge-splitting as following transformation may
1563     // also need to split these critical edges.
1564     return !CriticalEdgePred.empty();
1565   }
1566 
1567   // Okay, we can eliminate this load by inserting a reload in the predecessor
1568   // and using PHI construction to get the value in the other predecessors, do
1569   // it.
1570   DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
1571   DEBUG(if (!NewInsts.empty())
1572           dbgs() << "INSERTED " << NewInsts.size() << " INSTS: "
1573                  << *NewInsts.back() << '\n');
1574 
1575   // Assign value numbers to the new instructions.
1576   for (Instruction *I : NewInsts) {
1577     // Instructions that have been inserted in predecessor(s) to materialize
1578     // the load address do not retain their original debug locations. Doing
1579     // so could lead to confusing (but correct) source attributions.
1580     // FIXME: How do we retain source locations without causing poor debugging
1581     // behavior?
1582     I->setDebugLoc(DebugLoc());
1583 
1584     // FIXME: We really _ought_ to insert these value numbers into their
1585     // parent's availability map.  However, in doing so, we risk getting into
1586     // ordering issues.  If a block hasn't been processed yet, we would be
1587     // marking a value as AVAIL-IN, which isn't what we intend.
1588     VN.lookupOrAdd(I);
1589   }
1590 
1591   for (const auto &PredLoad : PredLoads) {
1592     BasicBlock *UnavailablePred = PredLoad.first;
1593     Value *LoadPtr = PredLoad.second;
1594 
1595     auto *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre",
1596                                  LI->isVolatile(), LI->getAlignment(),
1597                                  LI->getOrdering(), LI->getSynchScope(),
1598                                  UnavailablePred->getTerminator());
1599 
1600     // Transfer the old load's AA tags to the new load.
1601     AAMDNodes Tags;
1602     LI->getAAMetadata(Tags);
1603     if (Tags)
1604       NewLoad->setAAMetadata(Tags);
1605 
1606     if (auto *MD = LI->getMetadata(LLVMContext::MD_invariant_load))
1607       NewLoad->setMetadata(LLVMContext::MD_invariant_load, MD);
1608     if (auto *InvGroupMD = LI->getMetadata(LLVMContext::MD_invariant_group))
1609       NewLoad->setMetadata(LLVMContext::MD_invariant_group, InvGroupMD);
1610     if (auto *RangeMD = LI->getMetadata(LLVMContext::MD_range))
1611       NewLoad->setMetadata(LLVMContext::MD_range, RangeMD);
1612 
1613     // We do not propagate the old load's debug location, because the new
1614     // load now lives in a different BB, and we want to avoid a jumpy line
1615     // table.
1616     // FIXME: How do we retain source locations without causing poor debugging
1617     // behavior?
1618 
1619     // Add the newly created load.
1620     ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,
1621                                                         NewLoad));
1622     MD->invalidateCachedPointerInfo(LoadPtr);
1623     DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
1624   }
1625 
1626   // Perform PHI construction.
1627   Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1628   LI->replaceAllUsesWith(V);
1629   if (isa<PHINode>(V))
1630     V->takeName(LI);
1631   if (Instruction *I = dyn_cast<Instruction>(V))
1632     I->setDebugLoc(LI->getDebugLoc());
1633   if (V->getType()->getScalarType()->isPointerTy())
1634     MD->invalidateCachedPointerInfo(V);
1635   markInstructionForDeletion(LI);
1636   ORE->emit(OptimizationRemark(DEBUG_TYPE, "LoadPRE", LI)
1637             << "load eliminated by PRE");
1638   ++NumPRELoad;
1639   return true;
1640 }
1641 
1642 static void reportLoadElim(LoadInst *LI, Value *AvailableValue,
1643                            OptimizationRemarkEmitter *ORE) {
1644   using namespace ore;
1645   ORE->emit(OptimizationRemark(DEBUG_TYPE, "LoadElim", LI)
1646             << "load of type " << NV("Type", LI->getType()) << " eliminated"
1647             << setExtraArgs() << " in favor of "
1648             << NV("InfavorOfValue", AvailableValue));
1649 }
1650 
1651 /// Attempt to eliminate a load whose dependencies are
1652 /// non-local by performing PHI construction.
1653 bool GVN::processNonLocalLoad(LoadInst *LI) {
1654   // non-local speculations are not allowed under asan.
1655   if (LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeAddress))
1656     return false;
1657 
1658   // Step 1: Find the non-local dependencies of the load.
1659   LoadDepVect Deps;
1660   MD->getNonLocalPointerDependency(LI, Deps);
1661 
1662   // If we had to process more than one hundred blocks to find the
1663   // dependencies, this load isn't worth worrying about.  Optimizing
1664   // it will be too expensive.
1665   unsigned NumDeps = Deps.size();
1666   if (NumDeps > 100)
1667     return false;
1668 
1669   // If we had a phi translation failure, we'll have a single entry which is a
1670   // clobber in the current block.  Reject this early.
1671   if (NumDeps == 1 &&
1672       !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
1673     DEBUG(
1674       dbgs() << "GVN: non-local load ";
1675       LI->printAsOperand(dbgs());
1676       dbgs() << " has unknown dependencies\n";
1677     );
1678     return false;
1679   }
1680 
1681   // If this load follows a GEP, see if we can PRE the indices before analyzing.
1682   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0))) {
1683     for (GetElementPtrInst::op_iterator OI = GEP->idx_begin(),
1684                                         OE = GEP->idx_end();
1685          OI != OE; ++OI)
1686       if (Instruction *I = dyn_cast<Instruction>(OI->get()))
1687         performScalarPRE(I);
1688   }
1689 
1690   // Step 2: Analyze the availability of the load
1691   AvailValInBlkVect ValuesPerBlock;
1692   UnavailBlkVect UnavailableBlocks;
1693   AnalyzeLoadAvailability(LI, Deps, ValuesPerBlock, UnavailableBlocks);
1694 
1695   // If we have no predecessors that produce a known value for this load, exit
1696   // early.
1697   if (ValuesPerBlock.empty())
1698     return false;
1699 
1700   // Step 3: Eliminate fully redundancy.
1701   //
1702   // If all of the instructions we depend on produce a known value for this
1703   // load, then it is fully redundant and we can use PHI insertion to compute
1704   // its value.  Insert PHIs and remove the fully redundant value now.
1705   if (UnavailableBlocks.empty()) {
1706     DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
1707 
1708     // Perform PHI construction.
1709     Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1710     LI->replaceAllUsesWith(V);
1711 
1712     if (isa<PHINode>(V))
1713       V->takeName(LI);
1714     if (Instruction *I = dyn_cast<Instruction>(V))
1715       // If instruction I has debug info, then we should not update it.
1716       // Also, if I has a null DebugLoc, then it is still potentially incorrect
1717       // to propagate LI's DebugLoc because LI may not post-dominate I.
1718       if (LI->getDebugLoc() && LI->getParent() == I->getParent())
1719         I->setDebugLoc(LI->getDebugLoc());
1720     if (V->getType()->getScalarType()->isPointerTy())
1721       MD->invalidateCachedPointerInfo(V);
1722     markInstructionForDeletion(LI);
1723     ++NumGVNLoad;
1724     reportLoadElim(LI, V, ORE);
1725     return true;
1726   }
1727 
1728   // Step 4: Eliminate partial redundancy.
1729   if (!EnablePRE || !EnableLoadPRE)
1730     return false;
1731 
1732   return PerformLoadPRE(LI, ValuesPerBlock, UnavailableBlocks);
1733 }
1734 
1735 bool GVN::processAssumeIntrinsic(IntrinsicInst *IntrinsicI) {
1736   assert(IntrinsicI->getIntrinsicID() == Intrinsic::assume &&
1737          "This function can only be called with llvm.assume intrinsic");
1738   Value *V = IntrinsicI->getArgOperand(0);
1739 
1740   if (ConstantInt *Cond = dyn_cast<ConstantInt>(V)) {
1741     if (Cond->isZero()) {
1742       Type *Int8Ty = Type::getInt8Ty(V->getContext());
1743       // Insert a new store to null instruction before the load to indicate that
1744       // this code is not reachable.  FIXME: We could insert unreachable
1745       // instruction directly because we can modify the CFG.
1746       new StoreInst(UndefValue::get(Int8Ty),
1747                     Constant::getNullValue(Int8Ty->getPointerTo()),
1748                     IntrinsicI);
1749     }
1750     markInstructionForDeletion(IntrinsicI);
1751     return false;
1752   }
1753 
1754   Constant *True = ConstantInt::getTrue(V->getContext());
1755   bool Changed = false;
1756 
1757   for (BasicBlock *Successor : successors(IntrinsicI->getParent())) {
1758     BasicBlockEdge Edge(IntrinsicI->getParent(), Successor);
1759 
1760     // This property is only true in dominated successors, propagateEquality
1761     // will check dominance for us.
1762     Changed |= propagateEquality(V, True, Edge, false);
1763   }
1764 
1765   // We can replace assume value with true, which covers cases like this:
1766   // call void @llvm.assume(i1 %cmp)
1767   // br i1 %cmp, label %bb1, label %bb2 ; will change %cmp to true
1768   ReplaceWithConstMap[V] = True;
1769 
1770   // If one of *cmp *eq operand is const, adding it to map will cover this:
1771   // %cmp = fcmp oeq float 3.000000e+00, %0 ; const on lhs could happen
1772   // call void @llvm.assume(i1 %cmp)
1773   // ret float %0 ; will change it to ret float 3.000000e+00
1774   if (auto *CmpI = dyn_cast<CmpInst>(V)) {
1775     if (CmpI->getPredicate() == CmpInst::Predicate::ICMP_EQ ||
1776         CmpI->getPredicate() == CmpInst::Predicate::FCMP_OEQ ||
1777         (CmpI->getPredicate() == CmpInst::Predicate::FCMP_UEQ &&
1778          CmpI->getFastMathFlags().noNaNs())) {
1779       Value *CmpLHS = CmpI->getOperand(0);
1780       Value *CmpRHS = CmpI->getOperand(1);
1781       if (isa<Constant>(CmpLHS))
1782         std::swap(CmpLHS, CmpRHS);
1783       auto *RHSConst = dyn_cast<Constant>(CmpRHS);
1784 
1785       // If only one operand is constant.
1786       if (RHSConst != nullptr && !isa<Constant>(CmpLHS))
1787         ReplaceWithConstMap[CmpLHS] = RHSConst;
1788     }
1789   }
1790   return Changed;
1791 }
1792 
1793 static void patchReplacementInstruction(Instruction *I, Value *Repl) {
1794   auto *ReplInst = dyn_cast<Instruction>(Repl);
1795   if (!ReplInst)
1796     return;
1797 
1798   // Patch the replacement so that it is not more restrictive than the value
1799   // being replaced.
1800   // Note that if 'I' is a load being replaced by some operation,
1801   // for example, by an arithmetic operation, then andIRFlags()
1802   // would just erase all math flags from the original arithmetic
1803   // operation, which is clearly not wanted and not needed.
1804   if (!isa<LoadInst>(I))
1805     ReplInst->andIRFlags(I);
1806 
1807   // FIXME: If both the original and replacement value are part of the
1808   // same control-flow region (meaning that the execution of one
1809   // guarantees the execution of the other), then we can combine the
1810   // noalias scopes here and do better than the general conservative
1811   // answer used in combineMetadata().
1812 
1813   // In general, GVN unifies expressions over different control-flow
1814   // regions, and so we need a conservative combination of the noalias
1815   // scopes.
1816   static const unsigned KnownIDs[] = {
1817       LLVMContext::MD_tbaa,           LLVMContext::MD_alias_scope,
1818       LLVMContext::MD_noalias,        LLVMContext::MD_range,
1819       LLVMContext::MD_fpmath,         LLVMContext::MD_invariant_load,
1820       LLVMContext::MD_invariant_group};
1821   combineMetadata(ReplInst, I, KnownIDs);
1822 }
1823 
1824 static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
1825   patchReplacementInstruction(I, Repl);
1826   I->replaceAllUsesWith(Repl);
1827 }
1828 
1829 /// Attempt to eliminate a load, first by eliminating it
1830 /// locally, and then attempting non-local elimination if that fails.
1831 bool GVN::processLoad(LoadInst *L) {
1832   if (!MD)
1833     return false;
1834 
1835   // This code hasn't been audited for ordered or volatile memory access
1836   if (!L->isUnordered())
1837     return false;
1838 
1839   if (L->use_empty()) {
1840     markInstructionForDeletion(L);
1841     return true;
1842   }
1843 
1844   // ... to a pointer that has been loaded from before...
1845   MemDepResult Dep = MD->getDependency(L);
1846 
1847   // If it is defined in another block, try harder.
1848   if (Dep.isNonLocal())
1849     return processNonLocalLoad(L);
1850 
1851   // Only handle the local case below
1852   if (!Dep.isDef() && !Dep.isClobber()) {
1853     // This might be a NonFuncLocal or an Unknown
1854     DEBUG(
1855       // fast print dep, using operator<< on instruction is too slow.
1856       dbgs() << "GVN: load ";
1857       L->printAsOperand(dbgs());
1858       dbgs() << " has unknown dependence\n";
1859     );
1860     return false;
1861   }
1862 
1863   AvailableValue AV;
1864   if (AnalyzeLoadAvailability(L, Dep, L->getPointerOperand(), AV)) {
1865     Value *AvailableValue = AV.MaterializeAdjustedValue(L, L, *this);
1866 
1867     // Replace the load!
1868     patchAndReplaceAllUsesWith(L, AvailableValue);
1869     markInstructionForDeletion(L);
1870     ++NumGVNLoad;
1871     reportLoadElim(L, AvailableValue, ORE);
1872     // Tell MDA to rexamine the reused pointer since we might have more
1873     // information after forwarding it.
1874     if (MD && AvailableValue->getType()->getScalarType()->isPointerTy())
1875       MD->invalidateCachedPointerInfo(AvailableValue);
1876     return true;
1877   }
1878 
1879   return false;
1880 }
1881 
1882 // In order to find a leader for a given value number at a
1883 // specific basic block, we first obtain the list of all Values for that number,
1884 // and then scan the list to find one whose block dominates the block in
1885 // question.  This is fast because dominator tree queries consist of only
1886 // a few comparisons of DFS numbers.
1887 Value *GVN::findLeader(const BasicBlock *BB, uint32_t num) {
1888   LeaderTableEntry Vals = LeaderTable[num];
1889   if (!Vals.Val) return nullptr;
1890 
1891   Value *Val = nullptr;
1892   if (DT->dominates(Vals.BB, BB)) {
1893     Val = Vals.Val;
1894     if (isa<Constant>(Val)) return Val;
1895   }
1896 
1897   LeaderTableEntry* Next = Vals.Next;
1898   while (Next) {
1899     if (DT->dominates(Next->BB, BB)) {
1900       if (isa<Constant>(Next->Val)) return Next->Val;
1901       if (!Val) Val = Next->Val;
1902     }
1903 
1904     Next = Next->Next;
1905   }
1906 
1907   return Val;
1908 }
1909 
1910 /// There is an edge from 'Src' to 'Dst'.  Return
1911 /// true if every path from the entry block to 'Dst' passes via this edge.  In
1912 /// particular 'Dst' must not be reachable via another edge from 'Src'.
1913 static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E,
1914                                        DominatorTree *DT) {
1915   // While in theory it is interesting to consider the case in which Dst has
1916   // more than one predecessor, because Dst might be part of a loop which is
1917   // only reachable from Src, in practice it is pointless since at the time
1918   // GVN runs all such loops have preheaders, which means that Dst will have
1919   // been changed to have only one predecessor, namely Src.
1920   const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
1921   assert((!Pred || Pred == E.getStart()) &&
1922          "No edge between these basic blocks!");
1923   return Pred != nullptr;
1924 }
1925 
1926 // Tries to replace instruction with const, using information from
1927 // ReplaceWithConstMap.
1928 bool GVN::replaceOperandsWithConsts(Instruction *Instr) const {
1929   bool Changed = false;
1930   for (unsigned OpNum = 0; OpNum < Instr->getNumOperands(); ++OpNum) {
1931     Value *Operand = Instr->getOperand(OpNum);
1932     auto it = ReplaceWithConstMap.find(Operand);
1933     if (it != ReplaceWithConstMap.end()) {
1934       assert(!isa<Constant>(Operand) &&
1935              "Replacing constants with constants is invalid");
1936       DEBUG(dbgs() << "GVN replacing: " << *Operand << " with " << *it->second
1937                    << " in instruction " << *Instr << '\n');
1938       Instr->setOperand(OpNum, it->second);
1939       Changed = true;
1940     }
1941   }
1942   return Changed;
1943 }
1944 
1945 /// The given values are known to be equal in every block
1946 /// dominated by 'Root'.  Exploit this, for example by replacing 'LHS' with
1947 /// 'RHS' everywhere in the scope.  Returns whether a change was made.
1948 /// If DominatesByEdge is false, then it means that we will propagate the RHS
1949 /// value starting from the end of Root.Start.
1950 bool GVN::propagateEquality(Value *LHS, Value *RHS, const BasicBlockEdge &Root,
1951                             bool DominatesByEdge) {
1952   SmallVector<std::pair<Value*, Value*>, 4> Worklist;
1953   Worklist.push_back(std::make_pair(LHS, RHS));
1954   bool Changed = false;
1955   // For speed, compute a conservative fast approximation to
1956   // DT->dominates(Root, Root.getEnd());
1957   const bool RootDominatesEnd = isOnlyReachableViaThisEdge(Root, DT);
1958 
1959   while (!Worklist.empty()) {
1960     std::pair<Value*, Value*> Item = Worklist.pop_back_val();
1961     LHS = Item.first; RHS = Item.second;
1962 
1963     if (LHS == RHS)
1964       continue;
1965     assert(LHS->getType() == RHS->getType() && "Equality but unequal types!");
1966 
1967     // Don't try to propagate equalities between constants.
1968     if (isa<Constant>(LHS) && isa<Constant>(RHS))
1969       continue;
1970 
1971     // Prefer a constant on the right-hand side, or an Argument if no constants.
1972     if (isa<Constant>(LHS) || (isa<Argument>(LHS) && !isa<Constant>(RHS)))
1973       std::swap(LHS, RHS);
1974     assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) && "Unexpected value!");
1975 
1976     // If there is no obvious reason to prefer the left-hand side over the
1977     // right-hand side, ensure the longest lived term is on the right-hand side,
1978     // so the shortest lived term will be replaced by the longest lived.
1979     // This tends to expose more simplifications.
1980     uint32_t LVN = VN.lookupOrAdd(LHS);
1981     if ((isa<Argument>(LHS) && isa<Argument>(RHS)) ||
1982         (isa<Instruction>(LHS) && isa<Instruction>(RHS))) {
1983       // Move the 'oldest' value to the right-hand side, using the value number
1984       // as a proxy for age.
1985       uint32_t RVN = VN.lookupOrAdd(RHS);
1986       if (LVN < RVN) {
1987         std::swap(LHS, RHS);
1988         LVN = RVN;
1989       }
1990     }
1991 
1992     // If value numbering later sees that an instruction in the scope is equal
1993     // to 'LHS' then ensure it will be turned into 'RHS'.  In order to preserve
1994     // the invariant that instructions only occur in the leader table for their
1995     // own value number (this is used by removeFromLeaderTable), do not do this
1996     // if RHS is an instruction (if an instruction in the scope is morphed into
1997     // LHS then it will be turned into RHS by the next GVN iteration anyway, so
1998     // using the leader table is about compiling faster, not optimizing better).
1999     // The leader table only tracks basic blocks, not edges. Only add to if we
2000     // have the simple case where the edge dominates the end.
2001     if (RootDominatesEnd && !isa<Instruction>(RHS))
2002       addToLeaderTable(LVN, RHS, Root.getEnd());
2003 
2004     // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope.  As
2005     // LHS always has at least one use that is not dominated by Root, this will
2006     // never do anything if LHS has only one use.
2007     if (!LHS->hasOneUse()) {
2008       unsigned NumReplacements =
2009           DominatesByEdge
2010               ? replaceDominatedUsesWith(LHS, RHS, *DT, Root)
2011               : replaceDominatedUsesWith(LHS, RHS, *DT, Root.getStart());
2012 
2013       Changed |= NumReplacements > 0;
2014       NumGVNEqProp += NumReplacements;
2015     }
2016 
2017     // Now try to deduce additional equalities from this one. For example, if
2018     // the known equality was "(A != B)" == "false" then it follows that A and B
2019     // are equal in the scope. Only boolean equalities with an explicit true or
2020     // false RHS are currently supported.
2021     if (!RHS->getType()->isIntegerTy(1))
2022       // Not a boolean equality - bail out.
2023       continue;
2024     ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
2025     if (!CI)
2026       // RHS neither 'true' nor 'false' - bail out.
2027       continue;
2028     // Whether RHS equals 'true'.  Otherwise it equals 'false'.
2029     bool isKnownTrue = CI->isAllOnesValue();
2030     bool isKnownFalse = !isKnownTrue;
2031 
2032     // If "A && B" is known true then both A and B are known true.  If "A || B"
2033     // is known false then both A and B are known false.
2034     Value *A, *B;
2035     if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) ||
2036         (isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) {
2037       Worklist.push_back(std::make_pair(A, RHS));
2038       Worklist.push_back(std::make_pair(B, RHS));
2039       continue;
2040     }
2041 
2042     // If we are propagating an equality like "(A == B)" == "true" then also
2043     // propagate the equality A == B.  When propagating a comparison such as
2044     // "(A >= B)" == "true", replace all instances of "A < B" with "false".
2045     if (CmpInst *Cmp = dyn_cast<CmpInst>(LHS)) {
2046       Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
2047 
2048       // If "A == B" is known true, or "A != B" is known false, then replace
2049       // A with B everywhere in the scope.
2050       if ((isKnownTrue && Cmp->getPredicate() == CmpInst::ICMP_EQ) ||
2051           (isKnownFalse && Cmp->getPredicate() == CmpInst::ICMP_NE))
2052         Worklist.push_back(std::make_pair(Op0, Op1));
2053 
2054       // Handle the floating point versions of equality comparisons too.
2055       if ((isKnownTrue && Cmp->getPredicate() == CmpInst::FCMP_OEQ) ||
2056           (isKnownFalse && Cmp->getPredicate() == CmpInst::FCMP_UNE)) {
2057 
2058         // Floating point -0.0 and 0.0 compare equal, so we can only
2059         // propagate values if we know that we have a constant and that
2060         // its value is non-zero.
2061 
2062         // FIXME: We should do this optimization if 'no signed zeros' is
2063         // applicable via an instruction-level fast-math-flag or some other
2064         // indicator that relaxed FP semantics are being used.
2065 
2066         if (isa<ConstantFP>(Op1) && !cast<ConstantFP>(Op1)->isZero())
2067           Worklist.push_back(std::make_pair(Op0, Op1));
2068       }
2069 
2070       // If "A >= B" is known true, replace "A < B" with false everywhere.
2071       CmpInst::Predicate NotPred = Cmp->getInversePredicate();
2072       Constant *NotVal = ConstantInt::get(Cmp->getType(), isKnownFalse);
2073       // Since we don't have the instruction "A < B" immediately to hand, work
2074       // out the value number that it would have and use that to find an
2075       // appropriate instruction (if any).
2076       uint32_t NextNum = VN.getNextUnusedValueNumber();
2077       uint32_t Num = VN.lookupOrAddCmp(Cmp->getOpcode(), NotPred, Op0, Op1);
2078       // If the number we were assigned was brand new then there is no point in
2079       // looking for an instruction realizing it: there cannot be one!
2080       if (Num < NextNum) {
2081         Value *NotCmp = findLeader(Root.getEnd(), Num);
2082         if (NotCmp && isa<Instruction>(NotCmp)) {
2083           unsigned NumReplacements =
2084               DominatesByEdge
2085                   ? replaceDominatedUsesWith(NotCmp, NotVal, *DT, Root)
2086                   : replaceDominatedUsesWith(NotCmp, NotVal, *DT,
2087                                              Root.getStart());
2088           Changed |= NumReplacements > 0;
2089           NumGVNEqProp += NumReplacements;
2090         }
2091       }
2092       // Ensure that any instruction in scope that gets the "A < B" value number
2093       // is replaced with false.
2094       // The leader table only tracks basic blocks, not edges. Only add to if we
2095       // have the simple case where the edge dominates the end.
2096       if (RootDominatesEnd)
2097         addToLeaderTable(Num, NotVal, Root.getEnd());
2098 
2099       continue;
2100     }
2101   }
2102 
2103   return Changed;
2104 }
2105 
2106 /// When calculating availability, handle an instruction
2107 /// by inserting it into the appropriate sets
2108 bool GVN::processInstruction(Instruction *I) {
2109   // Ignore dbg info intrinsics.
2110   if (isa<DbgInfoIntrinsic>(I))
2111     return false;
2112 
2113   // If the instruction can be easily simplified then do so now in preference
2114   // to value numbering it.  Value numbering often exposes redundancies, for
2115   // example if it determines that %y is equal to %x then the instruction
2116   // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
2117   const DataLayout &DL = I->getModule()->getDataLayout();
2118   if (Value *V = SimplifyInstruction(I, DL, TLI, DT, AC)) {
2119     bool Changed = false;
2120     if (!I->use_empty()) {
2121       I->replaceAllUsesWith(V);
2122       Changed = true;
2123     }
2124     if (isInstructionTriviallyDead(I, TLI)) {
2125       markInstructionForDeletion(I);
2126       Changed = true;
2127     }
2128     if (Changed) {
2129       if (MD && V->getType()->getScalarType()->isPointerTy())
2130         MD->invalidateCachedPointerInfo(V);
2131       ++NumGVNSimpl;
2132       return true;
2133     }
2134   }
2135 
2136   if (IntrinsicInst *IntrinsicI = dyn_cast<IntrinsicInst>(I))
2137     if (IntrinsicI->getIntrinsicID() == Intrinsic::assume)
2138       return processAssumeIntrinsic(IntrinsicI);
2139 
2140   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
2141     if (processLoad(LI))
2142       return true;
2143 
2144     unsigned Num = VN.lookupOrAdd(LI);
2145     addToLeaderTable(Num, LI, LI->getParent());
2146     return false;
2147   }
2148 
2149   // For conditional branches, we can perform simple conditional propagation on
2150   // the condition value itself.
2151   if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
2152     if (!BI->isConditional())
2153       return false;
2154 
2155     if (isa<Constant>(BI->getCondition()))
2156       return processFoldableCondBr(BI);
2157 
2158     Value *BranchCond = BI->getCondition();
2159     BasicBlock *TrueSucc = BI->getSuccessor(0);
2160     BasicBlock *FalseSucc = BI->getSuccessor(1);
2161     // Avoid multiple edges early.
2162     if (TrueSucc == FalseSucc)
2163       return false;
2164 
2165     BasicBlock *Parent = BI->getParent();
2166     bool Changed = false;
2167 
2168     Value *TrueVal = ConstantInt::getTrue(TrueSucc->getContext());
2169     BasicBlockEdge TrueE(Parent, TrueSucc);
2170     Changed |= propagateEquality(BranchCond, TrueVal, TrueE, true);
2171 
2172     Value *FalseVal = ConstantInt::getFalse(FalseSucc->getContext());
2173     BasicBlockEdge FalseE(Parent, FalseSucc);
2174     Changed |= propagateEquality(BranchCond, FalseVal, FalseE, true);
2175 
2176     return Changed;
2177   }
2178 
2179   // For switches, propagate the case values into the case destinations.
2180   if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
2181     Value *SwitchCond = SI->getCondition();
2182     BasicBlock *Parent = SI->getParent();
2183     bool Changed = false;
2184 
2185     // Remember how many outgoing edges there are to every successor.
2186     SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
2187     for (unsigned i = 0, n = SI->getNumSuccessors(); i != n; ++i)
2188       ++SwitchEdges[SI->getSuccessor(i)];
2189 
2190     for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2191          i != e; ++i) {
2192       BasicBlock *Dst = i.getCaseSuccessor();
2193       // If there is only a single edge, propagate the case value into it.
2194       if (SwitchEdges.lookup(Dst) == 1) {
2195         BasicBlockEdge E(Parent, Dst);
2196         Changed |= propagateEquality(SwitchCond, i.getCaseValue(), E, true);
2197       }
2198     }
2199     return Changed;
2200   }
2201 
2202   // Instructions with void type don't return a value, so there's
2203   // no point in trying to find redundancies in them.
2204   if (I->getType()->isVoidTy())
2205     return false;
2206 
2207   uint32_t NextNum = VN.getNextUnusedValueNumber();
2208   unsigned Num = VN.lookupOrAdd(I);
2209 
2210   // Allocations are always uniquely numbered, so we can save time and memory
2211   // by fast failing them.
2212   if (isa<AllocaInst>(I) || isa<TerminatorInst>(I) || isa<PHINode>(I)) {
2213     addToLeaderTable(Num, I, I->getParent());
2214     return false;
2215   }
2216 
2217   // If the number we were assigned was a brand new VN, then we don't
2218   // need to do a lookup to see if the number already exists
2219   // somewhere in the domtree: it can't!
2220   if (Num >= NextNum) {
2221     addToLeaderTable(Num, I, I->getParent());
2222     return false;
2223   }
2224 
2225   // Perform fast-path value-number based elimination of values inherited from
2226   // dominators.
2227   Value *Repl = findLeader(I->getParent(), Num);
2228   if (!Repl) {
2229     // Failure, just remember this instance for future use.
2230     addToLeaderTable(Num, I, I->getParent());
2231     return false;
2232   } else if (Repl == I) {
2233     // If I was the result of a shortcut PRE, it might already be in the table
2234     // and the best replacement for itself. Nothing to do.
2235     return false;
2236   }
2237 
2238   // Remove it!
2239   patchAndReplaceAllUsesWith(I, Repl);
2240   if (MD && Repl->getType()->getScalarType()->isPointerTy())
2241     MD->invalidateCachedPointerInfo(Repl);
2242   markInstructionForDeletion(I);
2243   return true;
2244 }
2245 
2246 /// runOnFunction - This is the main transformation entry point for a function.
2247 bool GVN::runImpl(Function &F, AssumptionCache &RunAC, DominatorTree &RunDT,
2248                   const TargetLibraryInfo &RunTLI, AAResults &RunAA,
2249                   MemoryDependenceResults *RunMD, LoopInfo *LI,
2250                   OptimizationRemarkEmitter *RunORE) {
2251   AC = &RunAC;
2252   DT = &RunDT;
2253   VN.setDomTree(DT);
2254   TLI = &RunTLI;
2255   VN.setAliasAnalysis(&RunAA);
2256   MD = RunMD;
2257   VN.setMemDep(MD);
2258   ORE = RunORE;
2259 
2260   bool Changed = false;
2261   bool ShouldContinue = true;
2262 
2263   // Merge unconditional branches, allowing PRE to catch more
2264   // optimization opportunities.
2265   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
2266     BasicBlock *BB = &*FI++;
2267 
2268     bool removedBlock = MergeBlockIntoPredecessor(BB, DT, LI, MD);
2269     if (removedBlock)
2270       ++NumGVNBlocks;
2271 
2272     Changed |= removedBlock;
2273   }
2274 
2275   unsigned Iteration = 0;
2276   while (ShouldContinue) {
2277     DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
2278     ShouldContinue = iterateOnFunction(F);
2279     Changed |= ShouldContinue;
2280     ++Iteration;
2281   }
2282 
2283   if (EnablePRE) {
2284     // Fabricate val-num for dead-code in order to suppress assertion in
2285     // performPRE().
2286     assignValNumForDeadCode();
2287     bool PREChanged = true;
2288     while (PREChanged) {
2289       PREChanged = performPRE(F);
2290       Changed |= PREChanged;
2291     }
2292   }
2293 
2294   // FIXME: Should perform GVN again after PRE does something.  PRE can move
2295   // computations into blocks where they become fully redundant.  Note that
2296   // we can't do this until PRE's critical edge splitting updates memdep.
2297   // Actually, when this happens, we should just fully integrate PRE into GVN.
2298 
2299   cleanupGlobalSets();
2300   // Do not cleanup DeadBlocks in cleanupGlobalSets() as it's called for each
2301   // iteration.
2302   DeadBlocks.clear();
2303 
2304   return Changed;
2305 }
2306 
2307 bool GVN::processBlock(BasicBlock *BB) {
2308   // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function
2309   // (and incrementing BI before processing an instruction).
2310   assert(InstrsToErase.empty() &&
2311          "We expect InstrsToErase to be empty across iterations");
2312   if (DeadBlocks.count(BB))
2313     return false;
2314 
2315   // Clearing map before every BB because it can be used only for single BB.
2316   ReplaceWithConstMap.clear();
2317   bool ChangedFunction = false;
2318 
2319   for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
2320        BI != BE;) {
2321     if (!ReplaceWithConstMap.empty())
2322       ChangedFunction |= replaceOperandsWithConsts(&*BI);
2323     ChangedFunction |= processInstruction(&*BI);
2324 
2325     if (InstrsToErase.empty()) {
2326       ++BI;
2327       continue;
2328     }
2329 
2330     // If we need some instructions deleted, do it now.
2331     NumGVNInstr += InstrsToErase.size();
2332 
2333     // Avoid iterator invalidation.
2334     bool AtStart = BI == BB->begin();
2335     if (!AtStart)
2336       --BI;
2337 
2338     for (SmallVectorImpl<Instruction *>::iterator I = InstrsToErase.begin(),
2339          E = InstrsToErase.end(); I != E; ++I) {
2340       DEBUG(dbgs() << "GVN removed: " << **I << '\n');
2341       if (MD) MD->removeInstruction(*I);
2342       DEBUG(verifyRemoved(*I));
2343       (*I)->eraseFromParent();
2344     }
2345     InstrsToErase.clear();
2346 
2347     if (AtStart)
2348       BI = BB->begin();
2349     else
2350       ++BI;
2351   }
2352 
2353   return ChangedFunction;
2354 }
2355 
2356 // Instantiate an expression in a predecessor that lacked it.
2357 bool GVN::performScalarPREInsertion(Instruction *Instr, BasicBlock *Pred,
2358                                     unsigned int ValNo) {
2359   // Because we are going top-down through the block, all value numbers
2360   // will be available in the predecessor by the time we need them.  Any
2361   // that weren't originally present will have been instantiated earlier
2362   // in this loop.
2363   bool success = true;
2364   for (unsigned i = 0, e = Instr->getNumOperands(); i != e; ++i) {
2365     Value *Op = Instr->getOperand(i);
2366     if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
2367       continue;
2368     // This could be a newly inserted instruction, in which case, we won't
2369     // find a value number, and should give up before we hurt ourselves.
2370     // FIXME: Rewrite the infrastructure to let it easier to value number
2371     // and process newly inserted instructions.
2372     if (!VN.exists(Op)) {
2373       success = false;
2374       break;
2375     }
2376     if (Value *V = findLeader(Pred, VN.lookup(Op))) {
2377       Instr->setOperand(i, V);
2378     } else {
2379       success = false;
2380       break;
2381     }
2382   }
2383 
2384   // Fail out if we encounter an operand that is not available in
2385   // the PRE predecessor.  This is typically because of loads which
2386   // are not value numbered precisely.
2387   if (!success)
2388     return false;
2389 
2390   Instr->insertBefore(Pred->getTerminator());
2391   Instr->setName(Instr->getName() + ".pre");
2392   Instr->setDebugLoc(Instr->getDebugLoc());
2393   VN.add(Instr, ValNo);
2394 
2395   // Update the availability map to include the new instruction.
2396   addToLeaderTable(ValNo, Instr, Pred);
2397   return true;
2398 }
2399 
2400 bool GVN::performScalarPRE(Instruction *CurInst) {
2401   if (isa<AllocaInst>(CurInst) || isa<TerminatorInst>(CurInst) ||
2402       isa<PHINode>(CurInst) || CurInst->getType()->isVoidTy() ||
2403       CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
2404       isa<DbgInfoIntrinsic>(CurInst))
2405     return false;
2406 
2407   // Don't do PRE on compares. The PHI would prevent CodeGenPrepare from
2408   // sinking the compare again, and it would force the code generator to
2409   // move the i1 from processor flags or predicate registers into a general
2410   // purpose register.
2411   if (isa<CmpInst>(CurInst))
2412     return false;
2413 
2414   // We don't currently value number ANY inline asm calls.
2415   if (CallInst *CallI = dyn_cast<CallInst>(CurInst))
2416     if (CallI->isInlineAsm())
2417       return false;
2418 
2419   uint32_t ValNo = VN.lookup(CurInst);
2420 
2421   // Look for the predecessors for PRE opportunities.  We're
2422   // only trying to solve the basic diamond case, where
2423   // a value is computed in the successor and one predecessor,
2424   // but not the other.  We also explicitly disallow cases
2425   // where the successor is its own predecessor, because they're
2426   // more complicated to get right.
2427   unsigned NumWith = 0;
2428   unsigned NumWithout = 0;
2429   BasicBlock *PREPred = nullptr;
2430   BasicBlock *CurrentBlock = CurInst->getParent();
2431 
2432   SmallVector<std::pair<Value *, BasicBlock *>, 8> predMap;
2433   for (BasicBlock *P : predecessors(CurrentBlock)) {
2434     // We're not interested in PRE where the block is its
2435     // own predecessor, or in blocks with predecessors
2436     // that are not reachable.
2437     if (P == CurrentBlock) {
2438       NumWithout = 2;
2439       break;
2440     } else if (!DT->isReachableFromEntry(P)) {
2441       NumWithout = 2;
2442       break;
2443     }
2444 
2445     Value *predV = findLeader(P, ValNo);
2446     if (!predV) {
2447       predMap.push_back(std::make_pair(static_cast<Value *>(nullptr), P));
2448       PREPred = P;
2449       ++NumWithout;
2450     } else if (predV == CurInst) {
2451       /* CurInst dominates this predecessor. */
2452       NumWithout = 2;
2453       break;
2454     } else {
2455       predMap.push_back(std::make_pair(predV, P));
2456       ++NumWith;
2457     }
2458   }
2459 
2460   // Don't do PRE when it might increase code size, i.e. when
2461   // we would need to insert instructions in more than one pred.
2462   if (NumWithout > 1 || NumWith == 0)
2463     return false;
2464 
2465   // We may have a case where all predecessors have the instruction,
2466   // and we just need to insert a phi node. Otherwise, perform
2467   // insertion.
2468   Instruction *PREInstr = nullptr;
2469 
2470   if (NumWithout != 0) {
2471     // Don't do PRE across indirect branch.
2472     if (isa<IndirectBrInst>(PREPred->getTerminator()))
2473       return false;
2474 
2475     // We can't do PRE safely on a critical edge, so instead we schedule
2476     // the edge to be split and perform the PRE the next time we iterate
2477     // on the function.
2478     unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
2479     if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
2480       toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
2481       return false;
2482     }
2483     // We need to insert somewhere, so let's give it a shot
2484     PREInstr = CurInst->clone();
2485     if (!performScalarPREInsertion(PREInstr, PREPred, ValNo)) {
2486       // If we failed insertion, make sure we remove the instruction.
2487       DEBUG(verifyRemoved(PREInstr));
2488       delete PREInstr;
2489       return false;
2490     }
2491   }
2492 
2493   // Either we should have filled in the PRE instruction, or we should
2494   // not have needed insertions.
2495   assert (PREInstr != nullptr || NumWithout == 0);
2496 
2497   ++NumGVNPRE;
2498 
2499   // Create a PHI to make the value available in this block.
2500   PHINode *Phi =
2501       PHINode::Create(CurInst->getType(), predMap.size(),
2502                       CurInst->getName() + ".pre-phi", &CurrentBlock->front());
2503   for (unsigned i = 0, e = predMap.size(); i != e; ++i) {
2504     if (Value *V = predMap[i].first)
2505       Phi->addIncoming(V, predMap[i].second);
2506     else
2507       Phi->addIncoming(PREInstr, PREPred);
2508   }
2509 
2510   VN.add(Phi, ValNo);
2511   addToLeaderTable(ValNo, Phi, CurrentBlock);
2512   Phi->setDebugLoc(CurInst->getDebugLoc());
2513   CurInst->replaceAllUsesWith(Phi);
2514   if (MD && Phi->getType()->getScalarType()->isPointerTy())
2515     MD->invalidateCachedPointerInfo(Phi);
2516   VN.erase(CurInst);
2517   removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
2518 
2519   DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
2520   if (MD)
2521     MD->removeInstruction(CurInst);
2522   DEBUG(verifyRemoved(CurInst));
2523   CurInst->eraseFromParent();
2524   ++NumGVNInstr;
2525 
2526   return true;
2527 }
2528 
2529 /// Perform a purely local form of PRE that looks for diamond
2530 /// control flow patterns and attempts to perform simple PRE at the join point.
2531 bool GVN::performPRE(Function &F) {
2532   bool Changed = false;
2533   for (BasicBlock *CurrentBlock : depth_first(&F.getEntryBlock())) {
2534     // Nothing to PRE in the entry block.
2535     if (CurrentBlock == &F.getEntryBlock())
2536       continue;
2537 
2538     // Don't perform PRE on an EH pad.
2539     if (CurrentBlock->isEHPad())
2540       continue;
2541 
2542     for (BasicBlock::iterator BI = CurrentBlock->begin(),
2543                               BE = CurrentBlock->end();
2544          BI != BE;) {
2545       Instruction *CurInst = &*BI++;
2546       Changed |= performScalarPRE(CurInst);
2547     }
2548   }
2549 
2550   if (splitCriticalEdges())
2551     Changed = true;
2552 
2553   return Changed;
2554 }
2555 
2556 /// Split the critical edge connecting the given two blocks, and return
2557 /// the block inserted to the critical edge.
2558 BasicBlock *GVN::splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ) {
2559   BasicBlock *BB =
2560       SplitCriticalEdge(Pred, Succ, CriticalEdgeSplittingOptions(DT));
2561   if (MD)
2562     MD->invalidateCachedPredecessors();
2563   return BB;
2564 }
2565 
2566 /// Split critical edges found during the previous
2567 /// iteration that may enable further optimization.
2568 bool GVN::splitCriticalEdges() {
2569   if (toSplit.empty())
2570     return false;
2571   do {
2572     std::pair<TerminatorInst*, unsigned> Edge = toSplit.pop_back_val();
2573     SplitCriticalEdge(Edge.first, Edge.second,
2574                       CriticalEdgeSplittingOptions(DT));
2575   } while (!toSplit.empty());
2576   if (MD) MD->invalidateCachedPredecessors();
2577   return true;
2578 }
2579 
2580 /// Executes one iteration of GVN
2581 bool GVN::iterateOnFunction(Function &F) {
2582   cleanupGlobalSets();
2583 
2584   // Top-down walk of the dominator tree
2585   bool Changed = false;
2586   // Save the blocks this function have before transformation begins. GVN may
2587   // split critical edge, and hence may invalidate the RPO/DT iterator.
2588   //
2589   std::vector<BasicBlock *> BBVect;
2590   BBVect.reserve(256);
2591   // Needed for value numbering with phi construction to work.
2592   ReversePostOrderTraversal<Function *> RPOT(&F);
2593   for (ReversePostOrderTraversal<Function *>::rpo_iterator RI = RPOT.begin(),
2594                                                            RE = RPOT.end();
2595        RI != RE; ++RI)
2596     BBVect.push_back(*RI);
2597 
2598   for (std::vector<BasicBlock *>::iterator I = BBVect.begin(), E = BBVect.end();
2599        I != E; I++)
2600     Changed |= processBlock(*I);
2601 
2602   return Changed;
2603 }
2604 
2605 void GVN::cleanupGlobalSets() {
2606   VN.clear();
2607   LeaderTable.clear();
2608   TableAllocator.Reset();
2609 }
2610 
2611 /// Verify that the specified instruction does not occur in our
2612 /// internal data structures.
2613 void GVN::verifyRemoved(const Instruction *Inst) const {
2614   VN.verifyRemoved(Inst);
2615 
2616   // Walk through the value number scope to make sure the instruction isn't
2617   // ferreted away in it.
2618   for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator
2619        I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) {
2620     const LeaderTableEntry *Node = &I->second;
2621     assert(Node->Val != Inst && "Inst still in value numbering scope!");
2622 
2623     while (Node->Next) {
2624       Node = Node->Next;
2625       assert(Node->Val != Inst && "Inst still in value numbering scope!");
2626     }
2627   }
2628 }
2629 
2630 /// BB is declared dead, which implied other blocks become dead as well. This
2631 /// function is to add all these blocks to "DeadBlocks". For the dead blocks'
2632 /// live successors, update their phi nodes by replacing the operands
2633 /// corresponding to dead blocks with UndefVal.
2634 void GVN::addDeadBlock(BasicBlock *BB) {
2635   SmallVector<BasicBlock *, 4> NewDead;
2636   SmallSetVector<BasicBlock *, 4> DF;
2637 
2638   NewDead.push_back(BB);
2639   while (!NewDead.empty()) {
2640     BasicBlock *D = NewDead.pop_back_val();
2641     if (DeadBlocks.count(D))
2642       continue;
2643 
2644     // All blocks dominated by D are dead.
2645     SmallVector<BasicBlock *, 8> Dom;
2646     DT->getDescendants(D, Dom);
2647     DeadBlocks.insert(Dom.begin(), Dom.end());
2648 
2649     // Figure out the dominance-frontier(D).
2650     for (BasicBlock *B : Dom) {
2651       for (BasicBlock *S : successors(B)) {
2652         if (DeadBlocks.count(S))
2653           continue;
2654 
2655         bool AllPredDead = true;
2656         for (BasicBlock *P : predecessors(S))
2657           if (!DeadBlocks.count(P)) {
2658             AllPredDead = false;
2659             break;
2660           }
2661 
2662         if (!AllPredDead) {
2663           // S could be proved dead later on. That is why we don't update phi
2664           // operands at this moment.
2665           DF.insert(S);
2666         } else {
2667           // While S is not dominated by D, it is dead by now. This could take
2668           // place if S already have a dead predecessor before D is declared
2669           // dead.
2670           NewDead.push_back(S);
2671         }
2672       }
2673     }
2674   }
2675 
2676   // For the dead blocks' live successors, update their phi nodes by replacing
2677   // the operands corresponding to dead blocks with UndefVal.
2678   for(SmallSetVector<BasicBlock *, 4>::iterator I = DF.begin(), E = DF.end();
2679         I != E; I++) {
2680     BasicBlock *B = *I;
2681     if (DeadBlocks.count(B))
2682       continue;
2683 
2684     SmallVector<BasicBlock *, 4> Preds(pred_begin(B), pred_end(B));
2685     for (BasicBlock *P : Preds) {
2686       if (!DeadBlocks.count(P))
2687         continue;
2688 
2689       if (isCriticalEdge(P->getTerminator(), GetSuccessorNumber(P, B))) {
2690         if (BasicBlock *S = splitCriticalEdges(P, B))
2691           DeadBlocks.insert(P = S);
2692       }
2693 
2694       for (BasicBlock::iterator II = B->begin(); isa<PHINode>(II); ++II) {
2695         PHINode &Phi = cast<PHINode>(*II);
2696         Phi.setIncomingValue(Phi.getBasicBlockIndex(P),
2697                              UndefValue::get(Phi.getType()));
2698       }
2699     }
2700   }
2701 }
2702 
2703 // If the given branch is recognized as a foldable branch (i.e. conditional
2704 // branch with constant condition), it will perform following analyses and
2705 // transformation.
2706 //  1) If the dead out-coming edge is a critical-edge, split it. Let
2707 //     R be the target of the dead out-coming edge.
2708 //  1) Identify the set of dead blocks implied by the branch's dead outcoming
2709 //     edge. The result of this step will be {X| X is dominated by R}
2710 //  2) Identify those blocks which haves at least one dead predecessor. The
2711 //     result of this step will be dominance-frontier(R).
2712 //  3) Update the PHIs in DF(R) by replacing the operands corresponding to
2713 //     dead blocks with "UndefVal" in an hope these PHIs will optimized away.
2714 //
2715 // Return true iff *NEW* dead code are found.
2716 bool GVN::processFoldableCondBr(BranchInst *BI) {
2717   if (!BI || BI->isUnconditional())
2718     return false;
2719 
2720   // If a branch has two identical successors, we cannot declare either dead.
2721   if (BI->getSuccessor(0) == BI->getSuccessor(1))
2722     return false;
2723 
2724   ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
2725   if (!Cond)
2726     return false;
2727 
2728   BasicBlock *DeadRoot =
2729       Cond->getZExtValue() ? BI->getSuccessor(1) : BI->getSuccessor(0);
2730   if (DeadBlocks.count(DeadRoot))
2731     return false;
2732 
2733   if (!DeadRoot->getSinglePredecessor())
2734     DeadRoot = splitCriticalEdges(BI->getParent(), DeadRoot);
2735 
2736   addDeadBlock(DeadRoot);
2737   return true;
2738 }
2739 
2740 // performPRE() will trigger assert if it comes across an instruction without
2741 // associated val-num. As it normally has far more live instructions than dead
2742 // instructions, it makes more sense just to "fabricate" a val-number for the
2743 // dead code than checking if instruction involved is dead or not.
2744 void GVN::assignValNumForDeadCode() {
2745   for (BasicBlock *BB : DeadBlocks) {
2746     for (Instruction &Inst : *BB) {
2747       unsigned ValNum = VN.lookupOrAdd(&Inst);
2748       addToLeaderTable(ValNum, &Inst, BB);
2749     }
2750   }
2751 }
2752 
2753 class llvm::gvn::GVNLegacyPass : public FunctionPass {
2754 public:
2755   static char ID; // Pass identification, replacement for typeid
2756   explicit GVNLegacyPass(bool NoLoads = false)
2757       : FunctionPass(ID), NoLoads(NoLoads) {
2758     initializeGVNLegacyPassPass(*PassRegistry::getPassRegistry());
2759   }
2760 
2761   bool runOnFunction(Function &F) override {
2762     if (skipFunction(F))
2763       return false;
2764 
2765     auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
2766 
2767     return Impl.runImpl(
2768         F, getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
2769         getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
2770         getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
2771         getAnalysis<AAResultsWrapperPass>().getAAResults(),
2772         NoLoads ? nullptr
2773                 : &getAnalysis<MemoryDependenceWrapperPass>().getMemDep(),
2774         LIWP ? &LIWP->getLoopInfo() : nullptr,
2775         &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE());
2776   }
2777 
2778   void getAnalysisUsage(AnalysisUsage &AU) const override {
2779     AU.addRequired<AssumptionCacheTracker>();
2780     AU.addRequired<DominatorTreeWrapperPass>();
2781     AU.addRequired<TargetLibraryInfoWrapperPass>();
2782     if (!NoLoads)
2783       AU.addRequired<MemoryDependenceWrapperPass>();
2784     AU.addRequired<AAResultsWrapperPass>();
2785 
2786     AU.addPreserved<DominatorTreeWrapperPass>();
2787     AU.addPreserved<GlobalsAAWrapperPass>();
2788     AU.addPreserved<TargetLibraryInfoWrapperPass>();
2789     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2790   }
2791 
2792 private:
2793   bool NoLoads;
2794   GVN Impl;
2795 };
2796 
2797 char GVNLegacyPass::ID = 0;
2798 
2799 // The public interface to this file...
2800 FunctionPass *llvm::createGVNPass(bool NoLoads) {
2801   return new GVNLegacyPass(NoLoads);
2802 }
2803 
2804 INITIALIZE_PASS_BEGIN(GVNLegacyPass, "gvn", "Global Value Numbering", false, false)
2805 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
2806 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
2807 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2808 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2809 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2810 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
2811 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
2812 INITIALIZE_PASS_END(GVNLegacyPass, "gvn", "Global Value Numbering", false, false)
2813