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