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