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