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