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