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