xref: /llvm-project/llvm/lib/Transforms/Scalar/EarlyCSE.cpp (revision 6972e39d47eccc3e5fc3ded4a1e1b78f74d10af6)
1 //===- EarlyCSE.cpp - Simple and fast CSE pass ----------------------------===//
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 a simple dominator tree walk that eliminates trivially
10 // redundant instructions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Scalar/EarlyCSE.h"
15 #include "llvm/ADT/DenseMapInfo.h"
16 #include "llvm/ADT/Hashing.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/ScopedHashTable.h"
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AssumptionCache.h"
23 #include "llvm/Analysis/GlobalsModRef.h"
24 #include "llvm/Analysis/GuardUtils.h"
25 #include "llvm/Analysis/InstructionSimplify.h"
26 #include "llvm/Analysis/MemorySSA.h"
27 #include "llvm/Analysis/MemorySSAUpdater.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/Analysis/TargetTransformInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/InstrTypes.h"
37 #include "llvm/IR/Instruction.h"
38 #include "llvm/IR/Instructions.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/IR/PassManager.h"
43 #include "llvm/IR/PatternMatch.h"
44 #include "llvm/IR/Statepoint.h"
45 #include "llvm/IR/Type.h"
46 #include "llvm/IR/Use.h"
47 #include "llvm/IR/Value.h"
48 #include "llvm/InitializePasses.h"
49 #include "llvm/Pass.h"
50 #include "llvm/Support/Allocator.h"
51 #include "llvm/Support/AtomicOrdering.h"
52 #include "llvm/Support/Casting.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/DebugCounter.h"
55 #include "llvm/Support/RecyclingAllocator.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include "llvm/Transforms/Scalar.h"
58 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
59 #include "llvm/Transforms/Utils/GuardUtils.h"
60 #include "llvm/Transforms/Utils/Local.h"
61 #include <cassert>
62 #include <deque>
63 #include <memory>
64 #include <utility>
65 
66 using namespace llvm;
67 using namespace llvm::PatternMatch;
68 
69 #define DEBUG_TYPE "early-cse"
70 
71 STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
72 STATISTIC(NumCSE,      "Number of instructions CSE'd");
73 STATISTIC(NumCSECVP,   "Number of compare instructions CVP'd");
74 STATISTIC(NumCSELoad,  "Number of load instructions CSE'd");
75 STATISTIC(NumCSECall,  "Number of call instructions CSE'd");
76 STATISTIC(NumDSE,      "Number of trivial dead stores removed");
77 
78 DEBUG_COUNTER(CSECounter, "early-cse",
79               "Controls which instructions are removed");
80 
81 static cl::opt<unsigned> EarlyCSEMssaOptCap(
82     "earlycse-mssa-optimization-cap", cl::init(500), cl::Hidden,
83     cl::desc("Enable imprecision in EarlyCSE in pathological cases, in exchange "
84              "for faster compile. Caps the MemorySSA clobbering calls."));
85 
86 static cl::opt<bool> EarlyCSEDebugHash(
87     "earlycse-debug-hash", cl::init(false), cl::Hidden,
88     cl::desc("Perform extra assertion checking to verify that SimpleValue's hash "
89              "function is well-behaved w.r.t. its isEqual predicate"));
90 
91 //===----------------------------------------------------------------------===//
92 // SimpleValue
93 //===----------------------------------------------------------------------===//
94 
95 namespace {
96 
97 /// Struct representing the available values in the scoped hash table.
98 struct SimpleValue {
99   Instruction *Inst;
100 
101   SimpleValue(Instruction *I) : Inst(I) {
102     assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
103   }
104 
105   bool isSentinel() const {
106     return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
107            Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
108   }
109 
110   static bool canHandle(Instruction *Inst) {
111     // This can only handle non-void readnone functions.
112     if (isa<GCRelocateInst>(Inst))
113       // Migration assistant for PR49607, to be removed once complete
114       return true;
115     if (CallInst *CI = dyn_cast<CallInst>(Inst))
116       return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
117     return isa<CastInst>(Inst) || isa<UnaryOperator>(Inst) ||
118            isa<BinaryOperator>(Inst) || isa<GetElementPtrInst>(Inst) ||
119            isa<CmpInst>(Inst) || isa<SelectInst>(Inst) ||
120            isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
121            isa<ShuffleVectorInst>(Inst) || isa<ExtractValueInst>(Inst) ||
122            isa<InsertValueInst>(Inst) || isa<FreezeInst>(Inst);
123   }
124 };
125 
126 } // end anonymous namespace
127 
128 namespace llvm {
129 
130 template <> struct DenseMapInfo<SimpleValue> {
131   static inline SimpleValue getEmptyKey() {
132     return DenseMapInfo<Instruction *>::getEmptyKey();
133   }
134 
135   static inline SimpleValue getTombstoneKey() {
136     return DenseMapInfo<Instruction *>::getTombstoneKey();
137   }
138 
139   static unsigned getHashValue(SimpleValue Val);
140   static bool isEqual(SimpleValue LHS, SimpleValue RHS);
141 };
142 
143 } // end namespace llvm
144 
145 /// Match a 'select' including an optional 'not's of the condition.
146 static bool matchSelectWithOptionalNotCond(Value *V, Value *&Cond, Value *&A,
147                                            Value *&B,
148                                            SelectPatternFlavor &Flavor) {
149   // Return false if V is not even a select.
150   if (!match(V, m_Select(m_Value(Cond), m_Value(A), m_Value(B))))
151     return false;
152 
153   // Look through a 'not' of the condition operand by swapping A/B.
154   Value *CondNot;
155   if (match(Cond, m_Not(m_Value(CondNot)))) {
156     Cond = CondNot;
157     std::swap(A, B);
158   }
159 
160   // Match canonical forms of min/max. We are not using ValueTracking's
161   // more powerful matchSelectPattern() because it may rely on instruction flags
162   // such as "nsw". That would be incompatible with the current hashing
163   // mechanism that may remove flags to increase the likelihood of CSE.
164 
165   Flavor = SPF_UNKNOWN;
166   CmpInst::Predicate Pred;
167 
168   if (!match(Cond, m_ICmp(Pred, m_Specific(A), m_Specific(B)))) {
169     // Check for commuted variants of min/max by swapping predicate.
170     // If we do not match the standard or commuted patterns, this is not a
171     // recognized form of min/max, but it is still a select, so return true.
172     if (!match(Cond, m_ICmp(Pred, m_Specific(B), m_Specific(A))))
173       return true;
174     Pred = ICmpInst::getSwappedPredicate(Pred);
175   }
176 
177   switch (Pred) {
178   case CmpInst::ICMP_UGT: Flavor = SPF_UMAX; break;
179   case CmpInst::ICMP_ULT: Flavor = SPF_UMIN; break;
180   case CmpInst::ICMP_SGT: Flavor = SPF_SMAX; break;
181   case CmpInst::ICMP_SLT: Flavor = SPF_SMIN; break;
182   // Non-strict inequalities.
183   case CmpInst::ICMP_ULE: Flavor = SPF_UMIN; break;
184   case CmpInst::ICMP_UGE: Flavor = SPF_UMAX; break;
185   case CmpInst::ICMP_SLE: Flavor = SPF_SMIN; break;
186   case CmpInst::ICMP_SGE: Flavor = SPF_SMAX; break;
187   default: break;
188   }
189 
190   return true;
191 }
192 
193 static unsigned getHashValueImpl(SimpleValue Val) {
194   Instruction *Inst = Val.Inst;
195   // Hash in all of the operands as pointers.
196   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
197     Value *LHS = BinOp->getOperand(0);
198     Value *RHS = BinOp->getOperand(1);
199     if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
200       std::swap(LHS, RHS);
201 
202     return hash_combine(BinOp->getOpcode(), LHS, RHS);
203   }
204 
205   if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
206     // Compares can be commuted by swapping the comparands and
207     // updating the predicate.  Choose the form that has the
208     // comparands in sorted order, or in the case of a tie, the
209     // one with the lower predicate.
210     Value *LHS = CI->getOperand(0);
211     Value *RHS = CI->getOperand(1);
212     CmpInst::Predicate Pred = CI->getPredicate();
213     CmpInst::Predicate SwappedPred = CI->getSwappedPredicate();
214     if (std::tie(LHS, Pred) > std::tie(RHS, SwappedPred)) {
215       std::swap(LHS, RHS);
216       Pred = SwappedPred;
217     }
218     return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
219   }
220 
221   // Hash general selects to allow matching commuted true/false operands.
222   SelectPatternFlavor SPF;
223   Value *Cond, *A, *B;
224   if (matchSelectWithOptionalNotCond(Inst, Cond, A, B, SPF)) {
225     // Hash min/max (cmp + select) to allow for commuted operands.
226     // Min/max may also have non-canonical compare predicate (eg, the compare for
227     // smin may use 'sgt' rather than 'slt'), and non-canonical operands in the
228     // compare.
229     // TODO: We should also detect FP min/max.
230     if (SPF == SPF_SMIN || SPF == SPF_SMAX ||
231         SPF == SPF_UMIN || SPF == SPF_UMAX) {
232       if (A > B)
233         std::swap(A, B);
234       return hash_combine(Inst->getOpcode(), SPF, A, B);
235     }
236 
237     // Hash general selects to allow matching commuted true/false operands.
238 
239     // If we do not have a compare as the condition, just hash in the condition.
240     CmpInst::Predicate Pred;
241     Value *X, *Y;
242     if (!match(Cond, m_Cmp(Pred, m_Value(X), m_Value(Y))))
243       return hash_combine(Inst->getOpcode(), Cond, A, B);
244 
245     // Similar to cmp normalization (above) - canonicalize the predicate value:
246     // select (icmp Pred, X, Y), A, B --> select (icmp InvPred, X, Y), B, A
247     if (CmpInst::getInversePredicate(Pred) < Pred) {
248       Pred = CmpInst::getInversePredicate(Pred);
249       std::swap(A, B);
250     }
251     return hash_combine(Inst->getOpcode(), Pred, X, Y, A, B);
252   }
253 
254   if (CastInst *CI = dyn_cast<CastInst>(Inst))
255     return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
256 
257   if (FreezeInst *FI = dyn_cast<FreezeInst>(Inst))
258     return hash_combine(FI->getOpcode(), FI->getOperand(0));
259 
260   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
261     return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
262                         hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
263 
264   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
265     return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
266                         IVI->getOperand(1),
267                         hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
268 
269   assert((isa<CallInst>(Inst) || isa<GetElementPtrInst>(Inst) ||
270           isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
271           isa<ShuffleVectorInst>(Inst) || isa<UnaryOperator>(Inst) ||
272           isa<FreezeInst>(Inst)) &&
273          "Invalid/unknown instruction");
274 
275   // Handle intrinsics with commutative operands.
276   // TODO: Extend this to handle intrinsics with >2 operands where the 1st
277   //       2 operands are commutative.
278   auto *II = dyn_cast<IntrinsicInst>(Inst);
279   if (II && II->isCommutative() && II->getNumArgOperands() == 2) {
280     Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
281     if (LHS > RHS)
282       std::swap(LHS, RHS);
283     return hash_combine(II->getOpcode(), LHS, RHS);
284   }
285 
286   // gc.relocate is 'special' call: its second and third operands are
287   // not real values, but indices into statepoint's argument list.
288   // Get values they point to.
289   if (const GCRelocateInst *GCR = dyn_cast<GCRelocateInst>(Inst))
290     return hash_combine(GCR->getOpcode(), GCR->getOperand(0),
291                         GCR->getBasePtr(), GCR->getDerivedPtr());
292 
293   // Mix in the opcode.
294   return hash_combine(
295       Inst->getOpcode(),
296       hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
297 }
298 
299 unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
300 #ifndef NDEBUG
301   // If -earlycse-debug-hash was specified, return a constant -- this
302   // will force all hashing to collide, so we'll exhaustively search
303   // the table for a match, and the assertion in isEqual will fire if
304   // there's a bug causing equal keys to hash differently.
305   if (EarlyCSEDebugHash)
306     return 0;
307 #endif
308   return getHashValueImpl(Val);
309 }
310 
311 static bool isEqualImpl(SimpleValue LHS, SimpleValue RHS) {
312   Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
313 
314   if (LHS.isSentinel() || RHS.isSentinel())
315     return LHSI == RHSI;
316 
317   if (LHSI->getOpcode() != RHSI->getOpcode())
318     return false;
319   if (LHSI->isIdenticalToWhenDefined(RHSI))
320     return true;
321 
322   // If we're not strictly identical, we still might be a commutable instruction
323   if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
324     if (!LHSBinOp->isCommutative())
325       return false;
326 
327     assert(isa<BinaryOperator>(RHSI) &&
328            "same opcode, but different instruction type?");
329     BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
330 
331     // Commuted equality
332     return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
333            LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
334   }
335   if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
336     assert(isa<CmpInst>(RHSI) &&
337            "same opcode, but different instruction type?");
338     CmpInst *RHSCmp = cast<CmpInst>(RHSI);
339     // Commuted equality
340     return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
341            LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
342            LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
343   }
344 
345   // TODO: Extend this for >2 args by matching the trailing N-2 args.
346   auto *LII = dyn_cast<IntrinsicInst>(LHSI);
347   auto *RII = dyn_cast<IntrinsicInst>(RHSI);
348   if (LII && RII && LII->getIntrinsicID() == RII->getIntrinsicID() &&
349       LII->isCommutative() && LII->getNumArgOperands() == 2) {
350     return LII->getArgOperand(0) == RII->getArgOperand(1) &&
351            LII->getArgOperand(1) == RII->getArgOperand(0);
352   }
353 
354   // See comment above in `getHashValue()`.
355   if (const GCRelocateInst *GCR1 = dyn_cast<GCRelocateInst>(LHSI))
356     if (const GCRelocateInst *GCR2 = dyn_cast<GCRelocateInst>(RHSI))
357       return GCR1->getOperand(0) == GCR2->getOperand(0) &&
358              GCR1->getBasePtr() == GCR2->getBasePtr() &&
359              GCR1->getDerivedPtr() == GCR2->getDerivedPtr();
360 
361   // Min/max can occur with commuted operands, non-canonical predicates,
362   // and/or non-canonical operands.
363   // Selects can be non-trivially equivalent via inverted conditions and swaps.
364   SelectPatternFlavor LSPF, RSPF;
365   Value *CondL, *CondR, *LHSA, *RHSA, *LHSB, *RHSB;
366   if (matchSelectWithOptionalNotCond(LHSI, CondL, LHSA, LHSB, LSPF) &&
367       matchSelectWithOptionalNotCond(RHSI, CondR, RHSA, RHSB, RSPF)) {
368     if (LSPF == RSPF) {
369       // TODO: We should also detect FP min/max.
370       if (LSPF == SPF_SMIN || LSPF == SPF_SMAX ||
371           LSPF == SPF_UMIN || LSPF == SPF_UMAX)
372         return ((LHSA == RHSA && LHSB == RHSB) ||
373                 (LHSA == RHSB && LHSB == RHSA));
374 
375       // select Cond, A, B <--> select not(Cond), B, A
376       if (CondL == CondR && LHSA == RHSA && LHSB == RHSB)
377         return true;
378     }
379 
380     // If the true/false operands are swapped and the conditions are compares
381     // with inverted predicates, the selects are equal:
382     // select (icmp Pred, X, Y), A, B <--> select (icmp InvPred, X, Y), B, A
383     //
384     // This also handles patterns with a double-negation in the sense of not +
385     // inverse, because we looked through a 'not' in the matching function and
386     // swapped A/B:
387     // select (cmp Pred, X, Y), A, B <--> select (not (cmp InvPred, X, Y)), B, A
388     //
389     // This intentionally does NOT handle patterns with a double-negation in
390     // the sense of not + not, because doing so could result in values
391     // comparing
392     // as equal that hash differently in the min/max cases like:
393     // select (cmp slt, X, Y), X, Y <--> select (not (not (cmp slt, X, Y))), X, Y
394     //   ^ hashes as min                  ^ would not hash as min
395     // In the context of the EarlyCSE pass, however, such cases never reach
396     // this code, as we simplify the double-negation before hashing the second
397     // select (and so still succeed at CSEing them).
398     if (LHSA == RHSB && LHSB == RHSA) {
399       CmpInst::Predicate PredL, PredR;
400       Value *X, *Y;
401       if (match(CondL, m_Cmp(PredL, m_Value(X), m_Value(Y))) &&
402           match(CondR, m_Cmp(PredR, m_Specific(X), m_Specific(Y))) &&
403           CmpInst::getInversePredicate(PredL) == PredR)
404         return true;
405     }
406   }
407 
408   return false;
409 }
410 
411 bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
412   // These comparisons are nontrivial, so assert that equality implies
413   // hash equality (DenseMap demands this as an invariant).
414   bool Result = isEqualImpl(LHS, RHS);
415   assert(!Result || (LHS.isSentinel() && LHS.Inst == RHS.Inst) ||
416          getHashValueImpl(LHS) == getHashValueImpl(RHS));
417   return Result;
418 }
419 
420 //===----------------------------------------------------------------------===//
421 // CallValue
422 //===----------------------------------------------------------------------===//
423 
424 namespace {
425 
426 /// Struct representing the available call values in the scoped hash
427 /// table.
428 struct CallValue {
429   Instruction *Inst;
430 
431   CallValue(Instruction *I) : Inst(I) {
432     assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
433   }
434 
435   bool isSentinel() const {
436     return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
437            Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
438   }
439 
440   static bool canHandle(Instruction *Inst) {
441     // Don't value number anything that returns void.
442     if (Inst->getType()->isVoidTy())
443       return false;
444 
445     CallInst *CI = dyn_cast<CallInst>(Inst);
446     if (!CI || !CI->onlyReadsMemory())
447       return false;
448     return true;
449   }
450 };
451 
452 } // end anonymous namespace
453 
454 namespace llvm {
455 
456 template <> struct DenseMapInfo<CallValue> {
457   static inline CallValue getEmptyKey() {
458     return DenseMapInfo<Instruction *>::getEmptyKey();
459   }
460 
461   static inline CallValue getTombstoneKey() {
462     return DenseMapInfo<Instruction *>::getTombstoneKey();
463   }
464 
465   static unsigned getHashValue(CallValue Val);
466   static bool isEqual(CallValue LHS, CallValue RHS);
467 };
468 
469 } // end namespace llvm
470 
471 unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
472   Instruction *Inst = Val.Inst;
473 
474   // Hash all of the operands as pointers and mix in the opcode.
475   return hash_combine(
476       Inst->getOpcode(),
477       hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
478 }
479 
480 bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
481   Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
482   if (LHS.isSentinel() || RHS.isSentinel())
483     return LHSI == RHSI;
484 
485   return LHSI->isIdenticalTo(RHSI);
486 }
487 
488 //===----------------------------------------------------------------------===//
489 // EarlyCSE implementation
490 //===----------------------------------------------------------------------===//
491 
492 namespace {
493 
494 /// A simple and fast domtree-based CSE pass.
495 ///
496 /// This pass does a simple depth-first walk over the dominator tree,
497 /// eliminating trivially redundant instructions and using instsimplify to
498 /// canonicalize things as it goes. It is intended to be fast and catch obvious
499 /// cases so that instcombine and other passes are more effective. It is
500 /// expected that a later pass of GVN will catch the interesting/hard cases.
501 class EarlyCSE {
502 public:
503   const TargetLibraryInfo &TLI;
504   const TargetTransformInfo &TTI;
505   DominatorTree &DT;
506   AssumptionCache &AC;
507   const SimplifyQuery SQ;
508   MemorySSA *MSSA;
509   std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
510 
511   using AllocatorTy =
512       RecyclingAllocator<BumpPtrAllocator,
513                          ScopedHashTableVal<SimpleValue, Value *>>;
514   using ScopedHTType =
515       ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
516                       AllocatorTy>;
517 
518   /// A scoped hash table of the current values of all of our simple
519   /// scalar expressions.
520   ///
521   /// As we walk down the domtree, we look to see if instructions are in this:
522   /// if so, we replace them with what we find, otherwise we insert them so
523   /// that dominated values can succeed in their lookup.
524   ScopedHTType AvailableValues;
525 
526   /// A scoped hash table of the current values of previously encountered
527   /// memory locations.
528   ///
529   /// This allows us to get efficient access to dominating loads or stores when
530   /// we have a fully redundant load.  In addition to the most recent load, we
531   /// keep track of a generation count of the read, which is compared against
532   /// the current generation count.  The current generation count is incremented
533   /// after every possibly writing memory operation, which ensures that we only
534   /// CSE loads with other loads that have no intervening store.  Ordering
535   /// events (such as fences or atomic instructions) increment the generation
536   /// count as well; essentially, we model these as writes to all possible
537   /// locations.  Note that atomic and/or volatile loads and stores can be
538   /// present the table; it is the responsibility of the consumer to inspect
539   /// the atomicity/volatility if needed.
540   struct LoadValue {
541     Instruction *DefInst = nullptr;
542     unsigned Generation = 0;
543     int MatchingId = -1;
544     bool IsAtomic = false;
545 
546     LoadValue() = default;
547     LoadValue(Instruction *Inst, unsigned Generation, unsigned MatchingId,
548               bool IsAtomic)
549         : DefInst(Inst), Generation(Generation), MatchingId(MatchingId),
550           IsAtomic(IsAtomic) {}
551   };
552 
553   using LoadMapAllocator =
554       RecyclingAllocator<BumpPtrAllocator,
555                          ScopedHashTableVal<Value *, LoadValue>>;
556   using LoadHTType =
557       ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>,
558                       LoadMapAllocator>;
559 
560   LoadHTType AvailableLoads;
561 
562   // A scoped hash table mapping memory locations (represented as typed
563   // addresses) to generation numbers at which that memory location became
564   // (henceforth indefinitely) invariant.
565   using InvariantMapAllocator =
566       RecyclingAllocator<BumpPtrAllocator,
567                          ScopedHashTableVal<MemoryLocation, unsigned>>;
568   using InvariantHTType =
569       ScopedHashTable<MemoryLocation, unsigned, DenseMapInfo<MemoryLocation>,
570                       InvariantMapAllocator>;
571   InvariantHTType AvailableInvariants;
572 
573   /// A scoped hash table of the current values of read-only call
574   /// values.
575   ///
576   /// It uses the same generation count as loads.
577   using CallHTType =
578       ScopedHashTable<CallValue, std::pair<Instruction *, unsigned>>;
579   CallHTType AvailableCalls;
580 
581   /// This is the current generation of the memory value.
582   unsigned CurrentGeneration = 0;
583 
584   /// Set up the EarlyCSE runner for a particular function.
585   EarlyCSE(const DataLayout &DL, const TargetLibraryInfo &TLI,
586            const TargetTransformInfo &TTI, DominatorTree &DT,
587            AssumptionCache &AC, MemorySSA *MSSA)
588       : TLI(TLI), TTI(TTI), DT(DT), AC(AC), SQ(DL, &TLI, &DT, &AC), MSSA(MSSA),
589         MSSAUpdater(std::make_unique<MemorySSAUpdater>(MSSA)) {}
590 
591   bool run();
592 
593 private:
594   unsigned ClobberCounter = 0;
595   // Almost a POD, but needs to call the constructors for the scoped hash
596   // tables so that a new scope gets pushed on. These are RAII so that the
597   // scope gets popped when the NodeScope is destroyed.
598   class NodeScope {
599   public:
600     NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
601               InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls)
602       : Scope(AvailableValues), LoadScope(AvailableLoads),
603         InvariantScope(AvailableInvariants), CallScope(AvailableCalls) {}
604     NodeScope(const NodeScope &) = delete;
605     NodeScope &operator=(const NodeScope &) = delete;
606 
607   private:
608     ScopedHTType::ScopeTy Scope;
609     LoadHTType::ScopeTy LoadScope;
610     InvariantHTType::ScopeTy InvariantScope;
611     CallHTType::ScopeTy CallScope;
612   };
613 
614   // Contains all the needed information to create a stack for doing a depth
615   // first traversal of the tree. This includes scopes for values, loads, and
616   // calls as well as the generation. There is a child iterator so that the
617   // children do not need to be store separately.
618   class StackNode {
619   public:
620     StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
621               InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls,
622               unsigned cg, DomTreeNode *n, DomTreeNode::const_iterator child,
623               DomTreeNode::const_iterator end)
624         : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
625           EndIter(end),
626           Scopes(AvailableValues, AvailableLoads, AvailableInvariants,
627                  AvailableCalls)
628           {}
629     StackNode(const StackNode &) = delete;
630     StackNode &operator=(const StackNode &) = delete;
631 
632     // Accessors.
633     unsigned currentGeneration() const { return CurrentGeneration; }
634     unsigned childGeneration() const { return ChildGeneration; }
635     void childGeneration(unsigned generation) { ChildGeneration = generation; }
636     DomTreeNode *node() { return Node; }
637     DomTreeNode::const_iterator childIter() const { return ChildIter; }
638 
639     DomTreeNode *nextChild() {
640       DomTreeNode *child = *ChildIter;
641       ++ChildIter;
642       return child;
643     }
644 
645     DomTreeNode::const_iterator end() const { return EndIter; }
646     bool isProcessed() const { return Processed; }
647     void process() { Processed = true; }
648 
649   private:
650     unsigned CurrentGeneration;
651     unsigned ChildGeneration;
652     DomTreeNode *Node;
653     DomTreeNode::const_iterator ChildIter;
654     DomTreeNode::const_iterator EndIter;
655     NodeScope Scopes;
656     bool Processed = false;
657   };
658 
659   /// Wrapper class to handle memory instructions, including loads,
660   /// stores and intrinsic loads and stores defined by the target.
661   class ParseMemoryInst {
662   public:
663     ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
664       : Inst(Inst) {
665       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
666         IntrID = II->getIntrinsicID();
667         if (TTI.getTgtMemIntrinsic(II, Info))
668           return;
669         if (isHandledNonTargetIntrinsic(IntrID)) {
670           switch (IntrID) {
671           case Intrinsic::masked_load:
672             Info.PtrVal = Inst->getOperand(0);
673             Info.MatchingId = Intrinsic::masked_load;
674             Info.ReadMem = true;
675             Info.WriteMem = false;
676             Info.IsVolatile = false;
677             break;
678           case Intrinsic::masked_store:
679             Info.PtrVal = Inst->getOperand(1);
680             // Use the ID of masked load as the "matching id". This will
681             // prevent matching non-masked loads/stores with masked ones
682             // (which could be done), but at the moment, the code here
683             // does not support matching intrinsics with non-intrinsics,
684             // so keep the MatchingIds specific to masked instructions
685             // for now (TODO).
686             Info.MatchingId = Intrinsic::masked_load;
687             Info.ReadMem = false;
688             Info.WriteMem = true;
689             Info.IsVolatile = false;
690             break;
691           }
692         }
693       }
694     }
695 
696     Instruction *get() { return Inst; }
697     const Instruction *get() const { return Inst; }
698 
699     bool isLoad() const {
700       if (IntrID != 0)
701         return Info.ReadMem;
702       return isa<LoadInst>(Inst);
703     }
704 
705     bool isStore() const {
706       if (IntrID != 0)
707         return Info.WriteMem;
708       return isa<StoreInst>(Inst);
709     }
710 
711     bool isAtomic() const {
712       if (IntrID != 0)
713         return Info.Ordering != AtomicOrdering::NotAtomic;
714       return Inst->isAtomic();
715     }
716 
717     bool isUnordered() const {
718       if (IntrID != 0)
719         return Info.isUnordered();
720 
721       if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
722         return LI->isUnordered();
723       } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
724         return SI->isUnordered();
725       }
726       // Conservative answer
727       return !Inst->isAtomic();
728     }
729 
730     bool isVolatile() const {
731       if (IntrID != 0)
732         return Info.IsVolatile;
733 
734       if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
735         return LI->isVolatile();
736       } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
737         return SI->isVolatile();
738       }
739       // Conservative answer
740       return true;
741     }
742 
743     bool isInvariantLoad() const {
744       if (auto *LI = dyn_cast<LoadInst>(Inst))
745         return LI->hasMetadata(LLVMContext::MD_invariant_load);
746       return false;
747     }
748 
749     bool isValid() const { return getPointerOperand() != nullptr; }
750 
751     // For regular (non-intrinsic) loads/stores, this is set to -1. For
752     // intrinsic loads/stores, the id is retrieved from the corresponding
753     // field in the MemIntrinsicInfo structure.  That field contains
754     // non-negative values only.
755     int getMatchingId() const {
756       if (IntrID != 0)
757         return Info.MatchingId;
758       return -1;
759     }
760 
761     Value *getPointerOperand() const {
762       if (IntrID != 0)
763         return Info.PtrVal;
764       return getLoadStorePointerOperand(Inst);
765     }
766 
767     bool mayReadFromMemory() const {
768       if (IntrID != 0)
769         return Info.ReadMem;
770       return Inst->mayReadFromMemory();
771     }
772 
773     bool mayWriteToMemory() const {
774       if (IntrID != 0)
775         return Info.WriteMem;
776       return Inst->mayWriteToMemory();
777     }
778 
779   private:
780     Intrinsic::ID IntrID = 0;
781     MemIntrinsicInfo Info;
782     Instruction *Inst;
783   };
784 
785   // This function is to prevent accidentally passing a non-target
786   // intrinsic ID to TargetTransformInfo.
787   static bool isHandledNonTargetIntrinsic(Intrinsic::ID ID) {
788     switch (ID) {
789     case Intrinsic::masked_load:
790     case Intrinsic::masked_store:
791       return true;
792     }
793     return false;
794   }
795   static bool isHandledNonTargetIntrinsic(const Value *V) {
796     if (auto *II = dyn_cast<IntrinsicInst>(V))
797       return isHandledNonTargetIntrinsic(II->getIntrinsicID());
798     return false;
799   }
800 
801   bool processNode(DomTreeNode *Node);
802 
803   bool handleBranchCondition(Instruction *CondInst, const BranchInst *BI,
804                              const BasicBlock *BB, const BasicBlock *Pred);
805 
806   Value *getMatchingValue(LoadValue &InVal, ParseMemoryInst &MemInst,
807                           unsigned CurrentGeneration);
808 
809   bool overridingStores(const ParseMemoryInst &Earlier,
810                         const ParseMemoryInst &Later);
811 
812   Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const {
813     if (auto *LI = dyn_cast<LoadInst>(Inst))
814       return LI;
815     if (auto *SI = dyn_cast<StoreInst>(Inst))
816       return SI->getValueOperand();
817     assert(isa<IntrinsicInst>(Inst) && "Instruction not supported");
818     auto *II = cast<IntrinsicInst>(Inst);
819     if (isHandledNonTargetIntrinsic(II->getIntrinsicID()))
820       return getOrCreateResultNonTargetMemIntrinsic(II, ExpectedType);
821     return TTI.getOrCreateResultFromMemIntrinsic(II, ExpectedType);
822   }
823 
824   Value *getOrCreateResultNonTargetMemIntrinsic(IntrinsicInst *II,
825                                                 Type *ExpectedType) const {
826     switch (II->getIntrinsicID()) {
827     case Intrinsic::masked_load:
828       return II;
829     case Intrinsic::masked_store:
830       return II->getOperand(0);
831     }
832     return nullptr;
833   }
834 
835   /// Return true if the instruction is known to only operate on memory
836   /// provably invariant in the given "generation".
837   bool isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt);
838 
839   bool isSameMemGeneration(unsigned EarlierGeneration, unsigned LaterGeneration,
840                            Instruction *EarlierInst, Instruction *LaterInst);
841 
842   bool isNonTargetIntrinsicMatch(const IntrinsicInst *Earlier,
843                                  const IntrinsicInst *Later) {
844     auto IsSubmask = [](const Value *Mask0, const Value *Mask1) {
845       // Is Mask0 a submask of Mask1?
846       if (Mask0 == Mask1)
847         return true;
848       if (isa<UndefValue>(Mask0) || isa<UndefValue>(Mask1))
849         return false;
850       auto *Vec0 = dyn_cast<ConstantVector>(Mask0);
851       auto *Vec1 = dyn_cast<ConstantVector>(Mask1);
852       if (!Vec0 || !Vec1)
853         return false;
854       assert(Vec0->getType() == Vec1->getType() &&
855              "Masks should have the same type");
856       for (int i = 0, e = Vec0->getNumOperands(); i != e; ++i) {
857         Constant *Elem0 = Vec0->getOperand(i);
858         Constant *Elem1 = Vec1->getOperand(i);
859         auto *Int0 = dyn_cast<ConstantInt>(Elem0);
860         if (Int0 && Int0->isZero())
861           continue;
862         auto *Int1 = dyn_cast<ConstantInt>(Elem1);
863         if (Int1 && !Int1->isZero())
864           continue;
865         if (isa<UndefValue>(Elem0) || isa<UndefValue>(Elem1))
866           return false;
867         if (Elem0 == Elem1)
868           continue;
869         return false;
870       }
871       return true;
872     };
873     auto PtrOp = [](const IntrinsicInst *II) {
874       if (II->getIntrinsicID() == Intrinsic::masked_load)
875         return II->getOperand(0);
876       if (II->getIntrinsicID() == Intrinsic::masked_store)
877         return II->getOperand(1);
878       llvm_unreachable("Unexpected IntrinsicInst");
879     };
880     auto MaskOp = [](const IntrinsicInst *II) {
881       if (II->getIntrinsicID() == Intrinsic::masked_load)
882         return II->getOperand(2);
883       if (II->getIntrinsicID() == Intrinsic::masked_store)
884         return II->getOperand(3);
885       llvm_unreachable("Unexpected IntrinsicInst");
886     };
887     auto ThruOp = [](const IntrinsicInst *II) {
888       if (II->getIntrinsicID() == Intrinsic::masked_load)
889         return II->getOperand(3);
890       llvm_unreachable("Unexpected IntrinsicInst");
891     };
892 
893     if (PtrOp(Earlier) != PtrOp(Later))
894       return false;
895 
896     Intrinsic::ID IDE = Earlier->getIntrinsicID();
897     Intrinsic::ID IDL = Later->getIntrinsicID();
898     // We could really use specific intrinsic classes for masked loads
899     // and stores in IntrinsicInst.h.
900     if (IDE == Intrinsic::masked_load && IDL == Intrinsic::masked_load) {
901       // Trying to replace later masked load with the earlier one.
902       // Check that the pointers are the same, and
903       // - masks and pass-throughs are the same, or
904       // - replacee's pass-through is "undef" and replacer's mask is a
905       //   super-set of the replacee's mask.
906       if (MaskOp(Earlier) == MaskOp(Later) && ThruOp(Earlier) == ThruOp(Later))
907         return true;
908       if (!isa<UndefValue>(ThruOp(Later)))
909         return false;
910       return IsSubmask(MaskOp(Later), MaskOp(Earlier));
911     }
912     if (IDE == Intrinsic::masked_store && IDL == Intrinsic::masked_load) {
913       // Trying to replace a load of a stored value with the store's value.
914       // Check that the pointers are the same, and
915       // - load's mask is a subset of store's mask, and
916       // - load's pass-through is "undef".
917       if (!IsSubmask(MaskOp(Later), MaskOp(Earlier)))
918         return false;
919       return isa<UndefValue>(ThruOp(Later));
920     }
921     if (IDE == Intrinsic::masked_load && IDL == Intrinsic::masked_store) {
922       // Trying to remove a store of the loaded value.
923       // Check that the pointers are the same, and
924       // - store's mask is a subset of the load's mask.
925       return IsSubmask(MaskOp(Later), MaskOp(Earlier));
926     }
927     if (IDE == Intrinsic::masked_store && IDL == Intrinsic::masked_store) {
928       // Trying to remove a dead store (earlier).
929       // Check that the pointers are the same,
930       // - the to-be-removed store's mask is a subset of the other store's
931       //   mask.
932       return IsSubmask(MaskOp(Earlier), MaskOp(Later));
933     }
934     return false;
935   }
936 
937   void removeMSSA(Instruction &Inst) {
938     if (!MSSA)
939       return;
940     if (VerifyMemorySSA)
941       MSSA->verifyMemorySSA();
942     // Removing a store here can leave MemorySSA in an unoptimized state by
943     // creating MemoryPhis that have identical arguments and by creating
944     // MemoryUses whose defining access is not an actual clobber. The phi case
945     // is handled by MemorySSA when passing OptimizePhis = true to
946     // removeMemoryAccess.  The non-optimized MemoryUse case is lazily updated
947     // by MemorySSA's getClobberingMemoryAccess.
948     MSSAUpdater->removeMemoryAccess(&Inst, true);
949   }
950 };
951 
952 } // end anonymous namespace
953 
954 /// Determine if the memory referenced by LaterInst is from the same heap
955 /// version as EarlierInst.
956 /// This is currently called in two scenarios:
957 ///
958 ///   load p
959 ///   ...
960 ///   load p
961 ///
962 /// and
963 ///
964 ///   x = load p
965 ///   ...
966 ///   store x, p
967 ///
968 /// in both cases we want to verify that there are no possible writes to the
969 /// memory referenced by p between the earlier and later instruction.
970 bool EarlyCSE::isSameMemGeneration(unsigned EarlierGeneration,
971                                    unsigned LaterGeneration,
972                                    Instruction *EarlierInst,
973                                    Instruction *LaterInst) {
974   // Check the simple memory generation tracking first.
975   if (EarlierGeneration == LaterGeneration)
976     return true;
977 
978   if (!MSSA)
979     return false;
980 
981   // If MemorySSA has determined that one of EarlierInst or LaterInst does not
982   // read/write memory, then we can safely return true here.
983   // FIXME: We could be more aggressive when checking doesNotAccessMemory(),
984   // onlyReadsMemory(), mayReadFromMemory(), and mayWriteToMemory() in this pass
985   // by also checking the MemorySSA MemoryAccess on the instruction.  Initial
986   // experiments suggest this isn't worthwhile, at least for C/C++ code compiled
987   // with the default optimization pipeline.
988   auto *EarlierMA = MSSA->getMemoryAccess(EarlierInst);
989   if (!EarlierMA)
990     return true;
991   auto *LaterMA = MSSA->getMemoryAccess(LaterInst);
992   if (!LaterMA)
993     return true;
994 
995   // Since we know LaterDef dominates LaterInst and EarlierInst dominates
996   // LaterInst, if LaterDef dominates EarlierInst then it can't occur between
997   // EarlierInst and LaterInst and neither can any other write that potentially
998   // clobbers LaterInst.
999   MemoryAccess *LaterDef;
1000   if (ClobberCounter < EarlyCSEMssaOptCap) {
1001     LaterDef = MSSA->getWalker()->getClobberingMemoryAccess(LaterInst);
1002     ClobberCounter++;
1003   } else
1004     LaterDef = LaterMA->getDefiningAccess();
1005 
1006   return MSSA->dominates(LaterDef, EarlierMA);
1007 }
1008 
1009 bool EarlyCSE::isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt) {
1010   // A location loaded from with an invariant_load is assumed to *never* change
1011   // within the visible scope of the compilation.
1012   if (auto *LI = dyn_cast<LoadInst>(I))
1013     if (LI->hasMetadata(LLVMContext::MD_invariant_load))
1014       return true;
1015 
1016   auto MemLocOpt = MemoryLocation::getOrNone(I);
1017   if (!MemLocOpt)
1018     // "target" intrinsic forms of loads aren't currently known to
1019     // MemoryLocation::get.  TODO
1020     return false;
1021   MemoryLocation MemLoc = *MemLocOpt;
1022   if (!AvailableInvariants.count(MemLoc))
1023     return false;
1024 
1025   // Is the generation at which this became invariant older than the
1026   // current one?
1027   return AvailableInvariants.lookup(MemLoc) <= GenAt;
1028 }
1029 
1030 bool EarlyCSE::handleBranchCondition(Instruction *CondInst,
1031                                      const BranchInst *BI, const BasicBlock *BB,
1032                                      const BasicBlock *Pred) {
1033   assert(BI->isConditional() && "Should be a conditional branch!");
1034   assert(BI->getCondition() == CondInst && "Wrong condition?");
1035   assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
1036   auto *TorF = (BI->getSuccessor(0) == BB)
1037                    ? ConstantInt::getTrue(BB->getContext())
1038                    : ConstantInt::getFalse(BB->getContext());
1039   auto MatchBinOp = [](Instruction *I, unsigned Opcode, Value *&LHS,
1040                        Value *&RHS) {
1041     if (Opcode == Instruction::And &&
1042         match(I, m_LogicalAnd(m_Value(LHS), m_Value(RHS))))
1043       return true;
1044     else if (Opcode == Instruction::Or &&
1045              match(I, m_LogicalOr(m_Value(LHS), m_Value(RHS))))
1046       return true;
1047     return false;
1048   };
1049   // If the condition is AND operation, we can propagate its operands into the
1050   // true branch. If it is OR operation, we can propagate them into the false
1051   // branch.
1052   unsigned PropagateOpcode =
1053       (BI->getSuccessor(0) == BB) ? Instruction::And : Instruction::Or;
1054 
1055   bool MadeChanges = false;
1056   SmallVector<Instruction *, 4> WorkList;
1057   SmallPtrSet<Instruction *, 4> Visited;
1058   WorkList.push_back(CondInst);
1059   while (!WorkList.empty()) {
1060     Instruction *Curr = WorkList.pop_back_val();
1061 
1062     AvailableValues.insert(Curr, TorF);
1063     LLVM_DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
1064                       << Curr->getName() << "' as " << *TorF << " in "
1065                       << BB->getName() << "\n");
1066     if (!DebugCounter::shouldExecute(CSECounter)) {
1067       LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1068     } else {
1069       // Replace all dominated uses with the known value.
1070       if (unsigned Count = replaceDominatedUsesWith(Curr, TorF, DT,
1071                                                     BasicBlockEdge(Pred, BB))) {
1072         NumCSECVP += Count;
1073         MadeChanges = true;
1074       }
1075     }
1076 
1077     Value *LHS, *RHS;
1078     if (MatchBinOp(Curr, PropagateOpcode, LHS, RHS))
1079       for (auto &Op : { LHS, RHS })
1080         if (Instruction *OPI = dyn_cast<Instruction>(Op))
1081           if (SimpleValue::canHandle(OPI) && Visited.insert(OPI).second)
1082             WorkList.push_back(OPI);
1083   }
1084 
1085   return MadeChanges;
1086 }
1087 
1088 Value *EarlyCSE::getMatchingValue(LoadValue &InVal, ParseMemoryInst &MemInst,
1089                                   unsigned CurrentGeneration) {
1090   if (InVal.DefInst == nullptr)
1091     return nullptr;
1092   if (InVal.MatchingId != MemInst.getMatchingId())
1093     return nullptr;
1094   // We don't yet handle removing loads with ordering of any kind.
1095   if (MemInst.isVolatile() || !MemInst.isUnordered())
1096     return nullptr;
1097   // We can't replace an atomic load with one which isn't also atomic.
1098   if (MemInst.isLoad() && !InVal.IsAtomic && MemInst.isAtomic())
1099     return nullptr;
1100   // The value V returned from this function is used differently depending
1101   // on whether MemInst is a load or a store. If it's a load, we will replace
1102   // MemInst with V, if it's a store, we will check if V is the same as the
1103   // available value.
1104   bool MemInstMatching = !MemInst.isLoad();
1105   Instruction *Matching = MemInstMatching ? MemInst.get() : InVal.DefInst;
1106   Instruction *Other = MemInstMatching ? InVal.DefInst : MemInst.get();
1107 
1108   // For stores check the result values before checking memory generation
1109   // (otherwise isSameMemGeneration may crash).
1110   Value *Result = MemInst.isStore()
1111                       ? getOrCreateResult(Matching, Other->getType())
1112                       : nullptr;
1113   if (MemInst.isStore() && InVal.DefInst != Result)
1114     return nullptr;
1115 
1116   // Deal with non-target memory intrinsics.
1117   bool MatchingNTI = isHandledNonTargetIntrinsic(Matching);
1118   bool OtherNTI = isHandledNonTargetIntrinsic(Other);
1119   if (OtherNTI != MatchingNTI)
1120     return nullptr;
1121   if (OtherNTI && MatchingNTI) {
1122     if (!isNonTargetIntrinsicMatch(cast<IntrinsicInst>(InVal.DefInst),
1123                                    cast<IntrinsicInst>(MemInst.get())))
1124       return nullptr;
1125   }
1126 
1127   if (!isOperatingOnInvariantMemAt(MemInst.get(), InVal.Generation) &&
1128       !isSameMemGeneration(InVal.Generation, CurrentGeneration, InVal.DefInst,
1129                            MemInst.get()))
1130     return nullptr;
1131 
1132   if (!Result)
1133     Result = getOrCreateResult(Matching, Other->getType());
1134   return Result;
1135 }
1136 
1137 bool EarlyCSE::overridingStores(const ParseMemoryInst &Earlier,
1138                                 const ParseMemoryInst &Later) {
1139   // Can we remove Earlier store because of Later store?
1140 
1141   assert(Earlier.isUnordered() && !Earlier.isVolatile() &&
1142          "Violated invariant");
1143   if (Earlier.getPointerOperand() != Later.getPointerOperand())
1144     return false;
1145   if (Earlier.getMatchingId() != Later.getMatchingId())
1146     return false;
1147   // At the moment, we don't remove ordered stores, but do remove
1148   // unordered atomic stores.  There's no special requirement (for
1149   // unordered atomics) about removing atomic stores only in favor of
1150   // other atomic stores since we were going to execute the non-atomic
1151   // one anyway and the atomic one might never have become visible.
1152   if (!Earlier.isUnordered() || !Later.isUnordered())
1153     return false;
1154 
1155   // Deal with non-target memory intrinsics.
1156   bool ENTI = isHandledNonTargetIntrinsic(Earlier.get());
1157   bool LNTI = isHandledNonTargetIntrinsic(Later.get());
1158   if (ENTI && LNTI)
1159     return isNonTargetIntrinsicMatch(cast<IntrinsicInst>(Earlier.get()),
1160                                      cast<IntrinsicInst>(Later.get()));
1161 
1162   // Because of the check above, at least one of them is false.
1163   // For now disallow matching intrinsics with non-intrinsics,
1164   // so assume that the stores match if neither is an intrinsic.
1165   return ENTI == LNTI;
1166 }
1167 
1168 bool EarlyCSE::processNode(DomTreeNode *Node) {
1169   bool Changed = false;
1170   BasicBlock *BB = Node->getBlock();
1171 
1172   // If this block has a single predecessor, then the predecessor is the parent
1173   // of the domtree node and all of the live out memory values are still current
1174   // in this block.  If this block has multiple predecessors, then they could
1175   // have invalidated the live-out memory values of our parent value.  For now,
1176   // just be conservative and invalidate memory if this block has multiple
1177   // predecessors.
1178   if (!BB->getSinglePredecessor())
1179     ++CurrentGeneration;
1180 
1181   // If this node has a single predecessor which ends in a conditional branch,
1182   // we can infer the value of the branch condition given that we took this
1183   // path.  We need the single predecessor to ensure there's not another path
1184   // which reaches this block where the condition might hold a different
1185   // value.  Since we're adding this to the scoped hash table (like any other
1186   // def), it will have been popped if we encounter a future merge block.
1187   if (BasicBlock *Pred = BB->getSinglePredecessor()) {
1188     auto *BI = dyn_cast<BranchInst>(Pred->getTerminator());
1189     if (BI && BI->isConditional()) {
1190       auto *CondInst = dyn_cast<Instruction>(BI->getCondition());
1191       if (CondInst && SimpleValue::canHandle(CondInst))
1192         Changed |= handleBranchCondition(CondInst, BI, BB, Pred);
1193     }
1194   }
1195 
1196   /// LastStore - Keep track of the last non-volatile store that we saw... for
1197   /// as long as there in no instruction that reads memory.  If we see a store
1198   /// to the same location, we delete the dead store.  This zaps trivial dead
1199   /// stores which can occur in bitfield code among other things.
1200   Instruction *LastStore = nullptr;
1201 
1202   // See if any instructions in the block can be eliminated.  If so, do it.  If
1203   // not, add them to AvailableValues.
1204   for (Instruction &Inst : make_early_inc_range(BB->getInstList())) {
1205     // Dead instructions should just be removed.
1206     if (isInstructionTriviallyDead(&Inst, &TLI)) {
1207       LLVM_DEBUG(dbgs() << "EarlyCSE DCE: " << Inst << '\n');
1208       if (!DebugCounter::shouldExecute(CSECounter)) {
1209         LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1210         continue;
1211       }
1212 
1213       salvageKnowledge(&Inst, &AC);
1214       salvageDebugInfo(Inst);
1215       removeMSSA(Inst);
1216       Inst.eraseFromParent();
1217       Changed = true;
1218       ++NumSimplify;
1219       continue;
1220     }
1221 
1222     // Skip assume intrinsics, they don't really have side effects (although
1223     // they're marked as such to ensure preservation of control dependencies),
1224     // and this pass will not bother with its removal. However, we should mark
1225     // its condition as true for all dominated blocks.
1226     if (match(&Inst, m_Intrinsic<Intrinsic::assume>())) {
1227       auto *CondI =
1228           dyn_cast<Instruction>(cast<CallInst>(Inst).getArgOperand(0));
1229       if (CondI && SimpleValue::canHandle(CondI)) {
1230         LLVM_DEBUG(dbgs() << "EarlyCSE considering assumption: " << Inst
1231                           << '\n');
1232         AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
1233       } else
1234         LLVM_DEBUG(dbgs() << "EarlyCSE skipping assumption: " << Inst << '\n');
1235       continue;
1236     }
1237 
1238     // Likewise, noalias intrinsics don't actually write.
1239     if (match(&Inst,
1240               m_Intrinsic<Intrinsic::experimental_noalias_scope_decl>())) {
1241       LLVM_DEBUG(dbgs() << "EarlyCSE skipping noalias intrinsic: " << Inst
1242                         << '\n');
1243       continue;
1244     }
1245 
1246     // Skip sideeffect intrinsics, for the same reason as assume intrinsics.
1247     if (match(&Inst, m_Intrinsic<Intrinsic::sideeffect>())) {
1248       LLVM_DEBUG(dbgs() << "EarlyCSE skipping sideeffect: " << Inst << '\n');
1249       continue;
1250     }
1251 
1252     // We can skip all invariant.start intrinsics since they only read memory,
1253     // and we can forward values across it. For invariant starts without
1254     // invariant ends, we can use the fact that the invariantness never ends to
1255     // start a scope in the current generaton which is true for all future
1256     // generations.  Also, we dont need to consume the last store since the
1257     // semantics of invariant.start allow us to perform   DSE of the last
1258     // store, if there was a store following invariant.start. Consider:
1259     //
1260     // store 30, i8* p
1261     // invariant.start(p)
1262     // store 40, i8* p
1263     // We can DSE the store to 30, since the store 40 to invariant location p
1264     // causes undefined behaviour.
1265     if (match(&Inst, m_Intrinsic<Intrinsic::invariant_start>())) {
1266       // If there are any uses, the scope might end.
1267       if (!Inst.use_empty())
1268         continue;
1269       MemoryLocation MemLoc =
1270           MemoryLocation::getForArgument(&cast<CallInst>(Inst), 1, TLI);
1271       // Don't start a scope if we already have a better one pushed
1272       if (!AvailableInvariants.count(MemLoc))
1273         AvailableInvariants.insert(MemLoc, CurrentGeneration);
1274       continue;
1275     }
1276 
1277     if (isGuard(&Inst)) {
1278       if (auto *CondI =
1279               dyn_cast<Instruction>(cast<CallInst>(Inst).getArgOperand(0))) {
1280         if (SimpleValue::canHandle(CondI)) {
1281           // Do we already know the actual value of this condition?
1282           if (auto *KnownCond = AvailableValues.lookup(CondI)) {
1283             // Is the condition known to be true?
1284             if (isa<ConstantInt>(KnownCond) &&
1285                 cast<ConstantInt>(KnownCond)->isOne()) {
1286               LLVM_DEBUG(dbgs()
1287                          << "EarlyCSE removing guard: " << Inst << '\n');
1288               salvageKnowledge(&Inst, &AC);
1289               removeMSSA(Inst);
1290               Inst.eraseFromParent();
1291               Changed = true;
1292               continue;
1293             } else
1294               // Use the known value if it wasn't true.
1295               cast<CallInst>(Inst).setArgOperand(0, KnownCond);
1296           }
1297           // The condition we're on guarding here is true for all dominated
1298           // locations.
1299           AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
1300         }
1301       }
1302 
1303       // Guard intrinsics read all memory, but don't write any memory.
1304       // Accordingly, don't update the generation but consume the last store (to
1305       // avoid an incorrect DSE).
1306       LastStore = nullptr;
1307       continue;
1308     }
1309 
1310     // If the instruction can be simplified (e.g. X+0 = X) then replace it with
1311     // its simpler value.
1312     if (Value *V = SimplifyInstruction(&Inst, SQ)) {
1313       LLVM_DEBUG(dbgs() << "EarlyCSE Simplify: " << Inst << "  to: " << *V
1314                         << '\n');
1315       if (!DebugCounter::shouldExecute(CSECounter)) {
1316         LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1317       } else {
1318         bool Killed = false;
1319         if (!Inst.use_empty()) {
1320           Inst.replaceAllUsesWith(V);
1321           Changed = true;
1322         }
1323         if (isInstructionTriviallyDead(&Inst, &TLI)) {
1324           salvageKnowledge(&Inst, &AC);
1325           removeMSSA(Inst);
1326           Inst.eraseFromParent();
1327           Changed = true;
1328           Killed = true;
1329         }
1330         if (Changed)
1331           ++NumSimplify;
1332         if (Killed)
1333           continue;
1334       }
1335     }
1336 
1337     // If this is a simple instruction that we can value number, process it.
1338     if (SimpleValue::canHandle(&Inst)) {
1339       // See if the instruction has an available value.  If so, use it.
1340       if (Value *V = AvailableValues.lookup(&Inst)) {
1341         LLVM_DEBUG(dbgs() << "EarlyCSE CSE: " << Inst << "  to: " << *V
1342                           << '\n');
1343         if (!DebugCounter::shouldExecute(CSECounter)) {
1344           LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1345           continue;
1346         }
1347         if (auto *I = dyn_cast<Instruction>(V))
1348           I->andIRFlags(&Inst);
1349         Inst.replaceAllUsesWith(V);
1350         salvageKnowledge(&Inst, &AC);
1351         removeMSSA(Inst);
1352         Inst.eraseFromParent();
1353         Changed = true;
1354         ++NumCSE;
1355         continue;
1356       }
1357 
1358       // Otherwise, just remember that this value is available.
1359       AvailableValues.insert(&Inst, &Inst);
1360       continue;
1361     }
1362 
1363     ParseMemoryInst MemInst(&Inst, TTI);
1364     // If this is a non-volatile load, process it.
1365     if (MemInst.isValid() && MemInst.isLoad()) {
1366       // (conservatively) we can't peak past the ordering implied by this
1367       // operation, but we can add this load to our set of available values
1368       if (MemInst.isVolatile() || !MemInst.isUnordered()) {
1369         LastStore = nullptr;
1370         ++CurrentGeneration;
1371       }
1372 
1373       if (MemInst.isInvariantLoad()) {
1374         // If we pass an invariant load, we know that memory location is
1375         // indefinitely constant from the moment of first dereferenceability.
1376         // We conservatively treat the invariant_load as that moment.  If we
1377         // pass a invariant load after already establishing a scope, don't
1378         // restart it since we want to preserve the earliest point seen.
1379         auto MemLoc = MemoryLocation::get(&Inst);
1380         if (!AvailableInvariants.count(MemLoc))
1381           AvailableInvariants.insert(MemLoc, CurrentGeneration);
1382       }
1383 
1384       // If we have an available version of this load, and if it is the right
1385       // generation or the load is known to be from an invariant location,
1386       // replace this instruction.
1387       //
1388       // If either the dominating load or the current load are invariant, then
1389       // we can assume the current load loads the same value as the dominating
1390       // load.
1391       LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
1392       if (Value *Op = getMatchingValue(InVal, MemInst, CurrentGeneration)) {
1393         LLVM_DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << Inst
1394                           << "  to: " << *InVal.DefInst << '\n');
1395         if (!DebugCounter::shouldExecute(CSECounter)) {
1396           LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1397           continue;
1398         }
1399         if (!Inst.use_empty())
1400           Inst.replaceAllUsesWith(Op);
1401         salvageKnowledge(&Inst, &AC);
1402         removeMSSA(Inst);
1403         Inst.eraseFromParent();
1404         Changed = true;
1405         ++NumCSELoad;
1406         continue;
1407       }
1408 
1409       // Otherwise, remember that we have this instruction.
1410       AvailableLoads.insert(MemInst.getPointerOperand(),
1411                             LoadValue(&Inst, CurrentGeneration,
1412                                       MemInst.getMatchingId(),
1413                                       MemInst.isAtomic()));
1414       LastStore = nullptr;
1415       continue;
1416     }
1417 
1418     // If this instruction may read from memory or throw (and potentially read
1419     // from memory in the exception handler), forget LastStore.  Load/store
1420     // intrinsics will indicate both a read and a write to memory.  The target
1421     // may override this (e.g. so that a store intrinsic does not read from
1422     // memory, and thus will be treated the same as a regular store for
1423     // commoning purposes).
1424     if ((Inst.mayReadFromMemory() || Inst.mayThrow()) &&
1425         !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
1426       LastStore = nullptr;
1427 
1428     // If this is a read-only call, process it.
1429     if (CallValue::canHandle(&Inst)) {
1430       // If we have an available version of this call, and if it is the right
1431       // generation, replace this instruction.
1432       std::pair<Instruction *, unsigned> InVal = AvailableCalls.lookup(&Inst);
1433       if (InVal.first != nullptr &&
1434           isSameMemGeneration(InVal.second, CurrentGeneration, InVal.first,
1435                               &Inst)) {
1436         LLVM_DEBUG(dbgs() << "EarlyCSE CSE CALL: " << Inst
1437                           << "  to: " << *InVal.first << '\n');
1438         if (!DebugCounter::shouldExecute(CSECounter)) {
1439           LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1440           continue;
1441         }
1442         if (!Inst.use_empty())
1443           Inst.replaceAllUsesWith(InVal.first);
1444         salvageKnowledge(&Inst, &AC);
1445         removeMSSA(Inst);
1446         Inst.eraseFromParent();
1447         Changed = true;
1448         ++NumCSECall;
1449         continue;
1450       }
1451 
1452       // Otherwise, remember that we have this instruction.
1453       AvailableCalls.insert(&Inst, std::make_pair(&Inst, CurrentGeneration));
1454       continue;
1455     }
1456 
1457     // A release fence requires that all stores complete before it, but does
1458     // not prevent the reordering of following loads 'before' the fence.  As a
1459     // result, we don't need to consider it as writing to memory and don't need
1460     // to advance the generation.  We do need to prevent DSE across the fence,
1461     // but that's handled above.
1462     if (auto *FI = dyn_cast<FenceInst>(&Inst))
1463       if (FI->getOrdering() == AtomicOrdering::Release) {
1464         assert(Inst.mayReadFromMemory() && "relied on to prevent DSE above");
1465         continue;
1466       }
1467 
1468     // write back DSE - If we write back the same value we just loaded from
1469     // the same location and haven't passed any intervening writes or ordering
1470     // operations, we can remove the write.  The primary benefit is in allowing
1471     // the available load table to remain valid and value forward past where
1472     // the store originally was.
1473     if (MemInst.isValid() && MemInst.isStore()) {
1474       LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
1475       if (InVal.DefInst &&
1476           InVal.DefInst == getMatchingValue(InVal, MemInst, CurrentGeneration)) {
1477         // It is okay to have a LastStore to a different pointer here if MemorySSA
1478         // tells us that the load and store are from the same memory generation.
1479         // In that case, LastStore should keep its present value since we're
1480         // removing the current store.
1481         assert((!LastStore ||
1482                 ParseMemoryInst(LastStore, TTI).getPointerOperand() ==
1483                     MemInst.getPointerOperand() ||
1484                 MSSA) &&
1485                "can't have an intervening store if not using MemorySSA!");
1486         LLVM_DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << Inst << '\n');
1487         if (!DebugCounter::shouldExecute(CSECounter)) {
1488           LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1489           continue;
1490         }
1491         salvageKnowledge(&Inst, &AC);
1492         removeMSSA(Inst);
1493         Inst.eraseFromParent();
1494         Changed = true;
1495         ++NumDSE;
1496         // We can avoid incrementing the generation count since we were able
1497         // to eliminate this store.
1498         continue;
1499       }
1500     }
1501 
1502     // Okay, this isn't something we can CSE at all.  Check to see if it is
1503     // something that could modify memory.  If so, our available memory values
1504     // cannot be used so bump the generation count.
1505     if (Inst.mayWriteToMemory()) {
1506       ++CurrentGeneration;
1507 
1508       if (MemInst.isValid() && MemInst.isStore()) {
1509         // We do a trivial form of DSE if there are two stores to the same
1510         // location with no intervening loads.  Delete the earlier store.
1511         if (LastStore) {
1512           if (overridingStores(ParseMemoryInst(LastStore, TTI), MemInst)) {
1513             LLVM_DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
1514                               << "  due to: " << Inst << '\n');
1515             if (!DebugCounter::shouldExecute(CSECounter)) {
1516               LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1517             } else {
1518               salvageKnowledge(&Inst, &AC);
1519               removeMSSA(*LastStore);
1520               LastStore->eraseFromParent();
1521               Changed = true;
1522               ++NumDSE;
1523               LastStore = nullptr;
1524             }
1525           }
1526           // fallthrough - we can exploit information about this store
1527         }
1528 
1529         // Okay, we just invalidated anything we knew about loaded values.  Try
1530         // to salvage *something* by remembering that the stored value is a live
1531         // version of the pointer.  It is safe to forward from volatile stores
1532         // to non-volatile loads, so we don't have to check for volatility of
1533         // the store.
1534         AvailableLoads.insert(MemInst.getPointerOperand(),
1535                               LoadValue(&Inst, CurrentGeneration,
1536                                         MemInst.getMatchingId(),
1537                                         MemInst.isAtomic()));
1538 
1539         // Remember that this was the last unordered store we saw for DSE. We
1540         // don't yet handle DSE on ordered or volatile stores since we don't
1541         // have a good way to model the ordering requirement for following
1542         // passes  once the store is removed.  We could insert a fence, but
1543         // since fences are slightly stronger than stores in their ordering,
1544         // it's not clear this is a profitable transform. Another option would
1545         // be to merge the ordering with that of the post dominating store.
1546         if (MemInst.isUnordered() && !MemInst.isVolatile())
1547           LastStore = &Inst;
1548         else
1549           LastStore = nullptr;
1550       }
1551     }
1552   }
1553 
1554   return Changed;
1555 }
1556 
1557 bool EarlyCSE::run() {
1558   // Note, deque is being used here because there is significant performance
1559   // gains over vector when the container becomes very large due to the
1560   // specific access patterns. For more information see the mailing list
1561   // discussion on this:
1562   // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
1563   std::deque<StackNode *> nodesToProcess;
1564 
1565   bool Changed = false;
1566 
1567   // Process the root node.
1568   nodesToProcess.push_back(new StackNode(
1569       AvailableValues, AvailableLoads, AvailableInvariants, AvailableCalls,
1570       CurrentGeneration, DT.getRootNode(),
1571       DT.getRootNode()->begin(), DT.getRootNode()->end()));
1572 
1573   assert(!CurrentGeneration && "Create a new EarlyCSE instance to rerun it.");
1574 
1575   // Process the stack.
1576   while (!nodesToProcess.empty()) {
1577     // Grab the first item off the stack. Set the current generation, remove
1578     // the node from the stack, and process it.
1579     StackNode *NodeToProcess = nodesToProcess.back();
1580 
1581     // Initialize class members.
1582     CurrentGeneration = NodeToProcess->currentGeneration();
1583 
1584     // Check if the node needs to be processed.
1585     if (!NodeToProcess->isProcessed()) {
1586       // Process the node.
1587       Changed |= processNode(NodeToProcess->node());
1588       NodeToProcess->childGeneration(CurrentGeneration);
1589       NodeToProcess->process();
1590     } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
1591       // Push the next child onto the stack.
1592       DomTreeNode *child = NodeToProcess->nextChild();
1593       nodesToProcess.push_back(
1594           new StackNode(AvailableValues, AvailableLoads, AvailableInvariants,
1595                         AvailableCalls, NodeToProcess->childGeneration(),
1596                         child, child->begin(), child->end()));
1597     } else {
1598       // It has been processed, and there are no more children to process,
1599       // so delete it and pop it off the stack.
1600       delete NodeToProcess;
1601       nodesToProcess.pop_back();
1602     }
1603   } // while (!nodes...)
1604 
1605   return Changed;
1606 }
1607 
1608 PreservedAnalyses EarlyCSEPass::run(Function &F,
1609                                     FunctionAnalysisManager &AM) {
1610   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1611   auto &TTI = AM.getResult<TargetIRAnalysis>(F);
1612   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1613   auto &AC = AM.getResult<AssumptionAnalysis>(F);
1614   auto *MSSA =
1615       UseMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA() : nullptr;
1616 
1617   EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
1618 
1619   if (!CSE.run())
1620     return PreservedAnalyses::all();
1621 
1622   PreservedAnalyses PA;
1623   PA.preserveSet<CFGAnalyses>();
1624   PA.preserve<GlobalsAA>();
1625   if (UseMemorySSA)
1626     PA.preserve<MemorySSAAnalysis>();
1627   return PA;
1628 }
1629 
1630 namespace {
1631 
1632 /// A simple and fast domtree-based CSE pass.
1633 ///
1634 /// This pass does a simple depth-first walk over the dominator tree,
1635 /// eliminating trivially redundant instructions and using instsimplify to
1636 /// canonicalize things as it goes. It is intended to be fast and catch obvious
1637 /// cases so that instcombine and other passes are more effective. It is
1638 /// expected that a later pass of GVN will catch the interesting/hard cases.
1639 template<bool UseMemorySSA>
1640 class EarlyCSELegacyCommonPass : public FunctionPass {
1641 public:
1642   static char ID;
1643 
1644   EarlyCSELegacyCommonPass() : FunctionPass(ID) {
1645     if (UseMemorySSA)
1646       initializeEarlyCSEMemSSALegacyPassPass(*PassRegistry::getPassRegistry());
1647     else
1648       initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry());
1649   }
1650 
1651   bool runOnFunction(Function &F) override {
1652     if (skipFunction(F))
1653       return false;
1654 
1655     auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1656     auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1657     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1658     auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1659     auto *MSSA =
1660         UseMemorySSA ? &getAnalysis<MemorySSAWrapperPass>().getMSSA() : nullptr;
1661 
1662     EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
1663 
1664     return CSE.run();
1665   }
1666 
1667   void getAnalysisUsage(AnalysisUsage &AU) const override {
1668     AU.addRequired<AssumptionCacheTracker>();
1669     AU.addRequired<DominatorTreeWrapperPass>();
1670     AU.addRequired<TargetLibraryInfoWrapperPass>();
1671     AU.addRequired<TargetTransformInfoWrapperPass>();
1672     if (UseMemorySSA) {
1673       AU.addRequired<AAResultsWrapperPass>();
1674       AU.addRequired<MemorySSAWrapperPass>();
1675       AU.addPreserved<MemorySSAWrapperPass>();
1676     }
1677     AU.addPreserved<GlobalsAAWrapperPass>();
1678     AU.addPreserved<AAResultsWrapperPass>();
1679     AU.setPreservesCFG();
1680   }
1681 };
1682 
1683 } // end anonymous namespace
1684 
1685 using EarlyCSELegacyPass = EarlyCSELegacyCommonPass</*UseMemorySSA=*/false>;
1686 
1687 template<>
1688 char EarlyCSELegacyPass::ID = 0;
1689 
1690 INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
1691                       false)
1692 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1693 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1694 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1695 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1696 INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)
1697 
1698 using EarlyCSEMemSSALegacyPass =
1699     EarlyCSELegacyCommonPass</*UseMemorySSA=*/true>;
1700 
1701 template<>
1702 char EarlyCSEMemSSALegacyPass::ID = 0;
1703 
1704 FunctionPass *llvm::createEarlyCSEPass(bool UseMemorySSA) {
1705   if (UseMemorySSA)
1706     return new EarlyCSEMemSSALegacyPass();
1707   else
1708     return new EarlyCSELegacyPass();
1709 }
1710 
1711 INITIALIZE_PASS_BEGIN(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1712                       "Early CSE w/ MemorySSA", false, false)
1713 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1714 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1715 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
1716 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1717 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1718 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
1719 INITIALIZE_PASS_END(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1720                     "Early CSE w/ MemorySSA", false, false)
1721