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