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