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