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