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