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