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