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