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