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