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