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