xref: /aosp_15_r20/external/llvm/lib/Transforms/Scalar/EarlyCSE.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===- EarlyCSE.cpp - Simple and fast CSE pass ----------------------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker //                     The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This pass performs a simple dominator tree walk that eliminates trivially
11*9880d681SAndroid Build Coastguard Worker // redundant instructions.
12*9880d681SAndroid Build Coastguard Worker //
13*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
14*9880d681SAndroid Build Coastguard Worker 
15*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar/EarlyCSE.h"
16*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Hashing.h"
17*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/ScopedHashTable.h"
18*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
19*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/AssumptionCache.h"
20*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/GlobalsModRef.h"
21*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/InstructionSimplify.h"
22*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetLibraryInfo.h"
23*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetTransformInfo.h"
24*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DataLayout.h"
25*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Dominators.h"
26*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Instructions.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/PatternMatch.h"
29*9880d681SAndroid Build Coastguard Worker #include "llvm/Pass.h"
30*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
31*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/RecyclingAllocator.h"
32*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
33*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar.h"
34*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/Local.h"
35*9880d681SAndroid Build Coastguard Worker #include <deque>
36*9880d681SAndroid Build Coastguard Worker using namespace llvm;
37*9880d681SAndroid Build Coastguard Worker using namespace llvm::PatternMatch;
38*9880d681SAndroid Build Coastguard Worker 
39*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "early-cse"
40*9880d681SAndroid Build Coastguard Worker 
41*9880d681SAndroid Build Coastguard Worker STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
42*9880d681SAndroid Build Coastguard Worker STATISTIC(NumCSE,      "Number of instructions CSE'd");
43*9880d681SAndroid Build Coastguard Worker STATISTIC(NumCSECVP,   "Number of compare instructions CVP'd");
44*9880d681SAndroid Build Coastguard Worker STATISTIC(NumCSELoad,  "Number of load instructions CSE'd");
45*9880d681SAndroid Build Coastguard Worker STATISTIC(NumCSECall,  "Number of call instructions CSE'd");
46*9880d681SAndroid Build Coastguard Worker STATISTIC(NumDSE,      "Number of trivial dead stores removed");
47*9880d681SAndroid Build Coastguard Worker 
48*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
49*9880d681SAndroid Build Coastguard Worker // SimpleValue
50*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
51*9880d681SAndroid Build Coastguard Worker 
52*9880d681SAndroid Build Coastguard Worker namespace {
53*9880d681SAndroid Build Coastguard Worker /// \brief Struct representing the available values in the scoped hash table.
54*9880d681SAndroid Build Coastguard Worker struct SimpleValue {
55*9880d681SAndroid Build Coastguard Worker   Instruction *Inst;
56*9880d681SAndroid Build Coastguard Worker 
SimpleValue__anon3c76a8a30111::SimpleValue57*9880d681SAndroid Build Coastguard Worker   SimpleValue(Instruction *I) : Inst(I) {
58*9880d681SAndroid Build Coastguard Worker     assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
59*9880d681SAndroid Build Coastguard Worker   }
60*9880d681SAndroid Build Coastguard Worker 
isSentinel__anon3c76a8a30111::SimpleValue61*9880d681SAndroid Build Coastguard Worker   bool isSentinel() const {
62*9880d681SAndroid Build Coastguard Worker     return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
63*9880d681SAndroid Build Coastguard Worker            Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
64*9880d681SAndroid Build Coastguard Worker   }
65*9880d681SAndroid Build Coastguard Worker 
canHandle__anon3c76a8a30111::SimpleValue66*9880d681SAndroid Build Coastguard Worker   static bool canHandle(Instruction *Inst) {
67*9880d681SAndroid Build Coastguard Worker     // This can only handle non-void readnone functions.
68*9880d681SAndroid Build Coastguard Worker     if (CallInst *CI = dyn_cast<CallInst>(Inst))
69*9880d681SAndroid Build Coastguard Worker       return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
70*9880d681SAndroid Build Coastguard Worker     return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
71*9880d681SAndroid Build Coastguard Worker            isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
72*9880d681SAndroid Build Coastguard Worker            isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
73*9880d681SAndroid Build Coastguard Worker            isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
74*9880d681SAndroid Build Coastguard Worker            isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
75*9880d681SAndroid Build Coastguard Worker   }
76*9880d681SAndroid Build Coastguard Worker };
77*9880d681SAndroid Build Coastguard Worker }
78*9880d681SAndroid Build Coastguard Worker 
79*9880d681SAndroid Build Coastguard Worker namespace llvm {
80*9880d681SAndroid Build Coastguard Worker template <> struct DenseMapInfo<SimpleValue> {
getEmptyKeyllvm::DenseMapInfo81*9880d681SAndroid Build Coastguard Worker   static inline SimpleValue getEmptyKey() {
82*9880d681SAndroid Build Coastguard Worker     return DenseMapInfo<Instruction *>::getEmptyKey();
83*9880d681SAndroid Build Coastguard Worker   }
getTombstoneKeyllvm::DenseMapInfo84*9880d681SAndroid Build Coastguard Worker   static inline SimpleValue getTombstoneKey() {
85*9880d681SAndroid Build Coastguard Worker     return DenseMapInfo<Instruction *>::getTombstoneKey();
86*9880d681SAndroid Build Coastguard Worker   }
87*9880d681SAndroid Build Coastguard Worker   static unsigned getHashValue(SimpleValue Val);
88*9880d681SAndroid Build Coastguard Worker   static bool isEqual(SimpleValue LHS, SimpleValue RHS);
89*9880d681SAndroid Build Coastguard Worker };
90*9880d681SAndroid Build Coastguard Worker }
91*9880d681SAndroid Build Coastguard Worker 
getHashValue(SimpleValue Val)92*9880d681SAndroid Build Coastguard Worker unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
93*9880d681SAndroid Build Coastguard Worker   Instruction *Inst = Val.Inst;
94*9880d681SAndroid Build Coastguard Worker   // Hash in all of the operands as pointers.
95*9880d681SAndroid Build Coastguard Worker   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
96*9880d681SAndroid Build Coastguard Worker     Value *LHS = BinOp->getOperand(0);
97*9880d681SAndroid Build Coastguard Worker     Value *RHS = BinOp->getOperand(1);
98*9880d681SAndroid Build Coastguard Worker     if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
99*9880d681SAndroid Build Coastguard Worker       std::swap(LHS, RHS);
100*9880d681SAndroid Build Coastguard Worker 
101*9880d681SAndroid Build Coastguard Worker     return hash_combine(BinOp->getOpcode(), LHS, RHS);
102*9880d681SAndroid Build Coastguard Worker   }
103*9880d681SAndroid Build Coastguard Worker 
104*9880d681SAndroid Build Coastguard Worker   if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
105*9880d681SAndroid Build Coastguard Worker     Value *LHS = CI->getOperand(0);
106*9880d681SAndroid Build Coastguard Worker     Value *RHS = CI->getOperand(1);
107*9880d681SAndroid Build Coastguard Worker     CmpInst::Predicate Pred = CI->getPredicate();
108*9880d681SAndroid Build Coastguard Worker     if (Inst->getOperand(0) > Inst->getOperand(1)) {
109*9880d681SAndroid Build Coastguard Worker       std::swap(LHS, RHS);
110*9880d681SAndroid Build Coastguard Worker       Pred = CI->getSwappedPredicate();
111*9880d681SAndroid Build Coastguard Worker     }
112*9880d681SAndroid Build Coastguard Worker     return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
113*9880d681SAndroid Build Coastguard Worker   }
114*9880d681SAndroid Build Coastguard Worker 
115*9880d681SAndroid Build Coastguard Worker   if (CastInst *CI = dyn_cast<CastInst>(Inst))
116*9880d681SAndroid Build Coastguard Worker     return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
117*9880d681SAndroid Build Coastguard Worker 
118*9880d681SAndroid Build Coastguard Worker   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
119*9880d681SAndroid Build Coastguard Worker     return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
120*9880d681SAndroid Build Coastguard Worker                         hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
121*9880d681SAndroid Build Coastguard Worker 
122*9880d681SAndroid Build Coastguard Worker   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
123*9880d681SAndroid Build Coastguard Worker     return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
124*9880d681SAndroid Build Coastguard Worker                         IVI->getOperand(1),
125*9880d681SAndroid Build Coastguard Worker                         hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
126*9880d681SAndroid Build Coastguard Worker 
127*9880d681SAndroid Build Coastguard Worker   assert((isa<CallInst>(Inst) || isa<BinaryOperator>(Inst) ||
128*9880d681SAndroid Build Coastguard Worker           isa<GetElementPtrInst>(Inst) || isa<SelectInst>(Inst) ||
129*9880d681SAndroid Build Coastguard Worker           isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
130*9880d681SAndroid Build Coastguard Worker           isa<ShuffleVectorInst>(Inst)) &&
131*9880d681SAndroid Build Coastguard Worker          "Invalid/unknown instruction");
132*9880d681SAndroid Build Coastguard Worker 
133*9880d681SAndroid Build Coastguard Worker   // Mix in the opcode.
134*9880d681SAndroid Build Coastguard Worker   return hash_combine(
135*9880d681SAndroid Build Coastguard Worker       Inst->getOpcode(),
136*9880d681SAndroid Build Coastguard Worker       hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
137*9880d681SAndroid Build Coastguard Worker }
138*9880d681SAndroid Build Coastguard Worker 
isEqual(SimpleValue LHS,SimpleValue RHS)139*9880d681SAndroid Build Coastguard Worker bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
140*9880d681SAndroid Build Coastguard Worker   Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
141*9880d681SAndroid Build Coastguard Worker 
142*9880d681SAndroid Build Coastguard Worker   if (LHS.isSentinel() || RHS.isSentinel())
143*9880d681SAndroid Build Coastguard Worker     return LHSI == RHSI;
144*9880d681SAndroid Build Coastguard Worker 
145*9880d681SAndroid Build Coastguard Worker   if (LHSI->getOpcode() != RHSI->getOpcode())
146*9880d681SAndroid Build Coastguard Worker     return false;
147*9880d681SAndroid Build Coastguard Worker   if (LHSI->isIdenticalToWhenDefined(RHSI))
148*9880d681SAndroid Build Coastguard Worker     return true;
149*9880d681SAndroid Build Coastguard Worker 
150*9880d681SAndroid Build Coastguard Worker   // If we're not strictly identical, we still might be a commutable instruction
151*9880d681SAndroid Build Coastguard Worker   if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
152*9880d681SAndroid Build Coastguard Worker     if (!LHSBinOp->isCommutative())
153*9880d681SAndroid Build Coastguard Worker       return false;
154*9880d681SAndroid Build Coastguard Worker 
155*9880d681SAndroid Build Coastguard Worker     assert(isa<BinaryOperator>(RHSI) &&
156*9880d681SAndroid Build Coastguard Worker            "same opcode, but different instruction type?");
157*9880d681SAndroid Build Coastguard Worker     BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
158*9880d681SAndroid Build Coastguard Worker 
159*9880d681SAndroid Build Coastguard Worker     // Commuted equality
160*9880d681SAndroid Build Coastguard Worker     return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
161*9880d681SAndroid Build Coastguard Worker            LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
162*9880d681SAndroid Build Coastguard Worker   }
163*9880d681SAndroid Build Coastguard Worker   if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
164*9880d681SAndroid Build Coastguard Worker     assert(isa<CmpInst>(RHSI) &&
165*9880d681SAndroid Build Coastguard Worker            "same opcode, but different instruction type?");
166*9880d681SAndroid Build Coastguard Worker     CmpInst *RHSCmp = cast<CmpInst>(RHSI);
167*9880d681SAndroid Build Coastguard Worker     // Commuted equality
168*9880d681SAndroid Build Coastguard Worker     return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
169*9880d681SAndroid Build Coastguard Worker            LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
170*9880d681SAndroid Build Coastguard Worker            LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
171*9880d681SAndroid Build Coastguard Worker   }
172*9880d681SAndroid Build Coastguard Worker 
173*9880d681SAndroid Build Coastguard Worker   return false;
174*9880d681SAndroid Build Coastguard Worker }
175*9880d681SAndroid Build Coastguard Worker 
176*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
177*9880d681SAndroid Build Coastguard Worker // CallValue
178*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
179*9880d681SAndroid Build Coastguard Worker 
180*9880d681SAndroid Build Coastguard Worker namespace {
181*9880d681SAndroid Build Coastguard Worker /// \brief Struct representing the available call values in the scoped hash
182*9880d681SAndroid Build Coastguard Worker /// table.
183*9880d681SAndroid Build Coastguard Worker struct CallValue {
184*9880d681SAndroid Build Coastguard Worker   Instruction *Inst;
185*9880d681SAndroid Build Coastguard Worker 
CallValue__anon3c76a8a30211::CallValue186*9880d681SAndroid Build Coastguard Worker   CallValue(Instruction *I) : Inst(I) {
187*9880d681SAndroid Build Coastguard Worker     assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
188*9880d681SAndroid Build Coastguard Worker   }
189*9880d681SAndroid Build Coastguard Worker 
isSentinel__anon3c76a8a30211::CallValue190*9880d681SAndroid Build Coastguard Worker   bool isSentinel() const {
191*9880d681SAndroid Build Coastguard Worker     return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
192*9880d681SAndroid Build Coastguard Worker            Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
193*9880d681SAndroid Build Coastguard Worker   }
194*9880d681SAndroid Build Coastguard Worker 
canHandle__anon3c76a8a30211::CallValue195*9880d681SAndroid Build Coastguard Worker   static bool canHandle(Instruction *Inst) {
196*9880d681SAndroid Build Coastguard Worker     // Don't value number anything that returns void.
197*9880d681SAndroid Build Coastguard Worker     if (Inst->getType()->isVoidTy())
198*9880d681SAndroid Build Coastguard Worker       return false;
199*9880d681SAndroid Build Coastguard Worker 
200*9880d681SAndroid Build Coastguard Worker     CallInst *CI = dyn_cast<CallInst>(Inst);
201*9880d681SAndroid Build Coastguard Worker     if (!CI || !CI->onlyReadsMemory())
202*9880d681SAndroid Build Coastguard Worker       return false;
203*9880d681SAndroid Build Coastguard Worker     return true;
204*9880d681SAndroid Build Coastguard Worker   }
205*9880d681SAndroid Build Coastguard Worker };
206*9880d681SAndroid Build Coastguard Worker }
207*9880d681SAndroid Build Coastguard Worker 
208*9880d681SAndroid Build Coastguard Worker namespace llvm {
209*9880d681SAndroid Build Coastguard Worker template <> struct DenseMapInfo<CallValue> {
getEmptyKeyllvm::DenseMapInfo210*9880d681SAndroid Build Coastguard Worker   static inline CallValue getEmptyKey() {
211*9880d681SAndroid Build Coastguard Worker     return DenseMapInfo<Instruction *>::getEmptyKey();
212*9880d681SAndroid Build Coastguard Worker   }
getTombstoneKeyllvm::DenseMapInfo213*9880d681SAndroid Build Coastguard Worker   static inline CallValue getTombstoneKey() {
214*9880d681SAndroid Build Coastguard Worker     return DenseMapInfo<Instruction *>::getTombstoneKey();
215*9880d681SAndroid Build Coastguard Worker   }
216*9880d681SAndroid Build Coastguard Worker   static unsigned getHashValue(CallValue Val);
217*9880d681SAndroid Build Coastguard Worker   static bool isEqual(CallValue LHS, CallValue RHS);
218*9880d681SAndroid Build Coastguard Worker };
219*9880d681SAndroid Build Coastguard Worker }
220*9880d681SAndroid Build Coastguard Worker 
getHashValue(CallValue Val)221*9880d681SAndroid Build Coastguard Worker unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
222*9880d681SAndroid Build Coastguard Worker   Instruction *Inst = Val.Inst;
223*9880d681SAndroid Build Coastguard Worker   // Hash all of the operands as pointers and mix in the opcode.
224*9880d681SAndroid Build Coastguard Worker   return hash_combine(
225*9880d681SAndroid Build Coastguard Worker       Inst->getOpcode(),
226*9880d681SAndroid Build Coastguard Worker       hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
227*9880d681SAndroid Build Coastguard Worker }
228*9880d681SAndroid Build Coastguard Worker 
isEqual(CallValue LHS,CallValue RHS)229*9880d681SAndroid Build Coastguard Worker bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
230*9880d681SAndroid Build Coastguard Worker   Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
231*9880d681SAndroid Build Coastguard Worker   if (LHS.isSentinel() || RHS.isSentinel())
232*9880d681SAndroid Build Coastguard Worker     return LHSI == RHSI;
233*9880d681SAndroid Build Coastguard Worker   return LHSI->isIdenticalTo(RHSI);
234*9880d681SAndroid Build Coastguard Worker }
235*9880d681SAndroid Build Coastguard Worker 
236*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
237*9880d681SAndroid Build Coastguard Worker // EarlyCSE implementation
238*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
239*9880d681SAndroid Build Coastguard Worker 
240*9880d681SAndroid Build Coastguard Worker namespace {
241*9880d681SAndroid Build Coastguard Worker /// \brief A simple and fast domtree-based CSE pass.
242*9880d681SAndroid Build Coastguard Worker ///
243*9880d681SAndroid Build Coastguard Worker /// This pass does a simple depth-first walk over the dominator tree,
244*9880d681SAndroid Build Coastguard Worker /// eliminating trivially redundant instructions and using instsimplify to
245*9880d681SAndroid Build Coastguard Worker /// canonicalize things as it goes. It is intended to be fast and catch obvious
246*9880d681SAndroid Build Coastguard Worker /// cases so that instcombine and other passes are more effective. It is
247*9880d681SAndroid Build Coastguard Worker /// expected that a later pass of GVN will catch the interesting/hard cases.
248*9880d681SAndroid Build Coastguard Worker class EarlyCSE {
249*9880d681SAndroid Build Coastguard Worker public:
250*9880d681SAndroid Build Coastguard Worker   const TargetLibraryInfo &TLI;
251*9880d681SAndroid Build Coastguard Worker   const TargetTransformInfo &TTI;
252*9880d681SAndroid Build Coastguard Worker   DominatorTree &DT;
253*9880d681SAndroid Build Coastguard Worker   AssumptionCache &AC;
254*9880d681SAndroid Build Coastguard Worker   typedef RecyclingAllocator<
255*9880d681SAndroid Build Coastguard Worker       BumpPtrAllocator, ScopedHashTableVal<SimpleValue, Value *>> AllocatorTy;
256*9880d681SAndroid Build Coastguard Worker   typedef ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
257*9880d681SAndroid Build Coastguard Worker                           AllocatorTy> ScopedHTType;
258*9880d681SAndroid Build Coastguard Worker 
259*9880d681SAndroid Build Coastguard Worker   /// \brief A scoped hash table of the current values of all of our simple
260*9880d681SAndroid Build Coastguard Worker   /// scalar expressions.
261*9880d681SAndroid Build Coastguard Worker   ///
262*9880d681SAndroid Build Coastguard Worker   /// As we walk down the domtree, we look to see if instructions are in this:
263*9880d681SAndroid Build Coastguard Worker   /// if so, we replace them with what we find, otherwise we insert them so
264*9880d681SAndroid Build Coastguard Worker   /// that dominated values can succeed in their lookup.
265*9880d681SAndroid Build Coastguard Worker   ScopedHTType AvailableValues;
266*9880d681SAndroid Build Coastguard Worker 
267*9880d681SAndroid Build Coastguard Worker   /// A scoped hash table of the current values of previously encounted memory
268*9880d681SAndroid Build Coastguard Worker   /// locations.
269*9880d681SAndroid Build Coastguard Worker   ///
270*9880d681SAndroid Build Coastguard Worker   /// This allows us to get efficient access to dominating loads or stores when
271*9880d681SAndroid Build Coastguard Worker   /// we have a fully redundant load.  In addition to the most recent load, we
272*9880d681SAndroid Build Coastguard Worker   /// keep track of a generation count of the read, which is compared against
273*9880d681SAndroid Build Coastguard Worker   /// the current generation count.  The current generation count is incremented
274*9880d681SAndroid Build Coastguard Worker   /// after every possibly writing memory operation, which ensures that we only
275*9880d681SAndroid Build Coastguard Worker   /// CSE loads with other loads that have no intervening store.  Ordering
276*9880d681SAndroid Build Coastguard Worker   /// events (such as fences or atomic instructions) increment the generation
277*9880d681SAndroid Build Coastguard Worker   /// count as well; essentially, we model these as writes to all possible
278*9880d681SAndroid Build Coastguard Worker   /// locations.  Note that atomic and/or volatile loads and stores can be
279*9880d681SAndroid Build Coastguard Worker   /// present the table; it is the responsibility of the consumer to inspect
280*9880d681SAndroid Build Coastguard Worker   /// the atomicity/volatility if needed.
281*9880d681SAndroid Build Coastguard Worker   struct LoadValue {
282*9880d681SAndroid Build Coastguard Worker     Instruction *DefInst;
283*9880d681SAndroid Build Coastguard Worker     unsigned Generation;
284*9880d681SAndroid Build Coastguard Worker     int MatchingId;
285*9880d681SAndroid Build Coastguard Worker     bool IsAtomic;
286*9880d681SAndroid Build Coastguard Worker     bool IsInvariant;
LoadValue__anon3c76a8a30311::EarlyCSE::LoadValue287*9880d681SAndroid Build Coastguard Worker     LoadValue()
288*9880d681SAndroid Build Coastguard Worker         : DefInst(nullptr), Generation(0), MatchingId(-1), IsAtomic(false),
289*9880d681SAndroid Build Coastguard Worker           IsInvariant(false) {}
LoadValue__anon3c76a8a30311::EarlyCSE::LoadValue290*9880d681SAndroid Build Coastguard Worker     LoadValue(Instruction *Inst, unsigned Generation, unsigned MatchingId,
291*9880d681SAndroid Build Coastguard Worker               bool IsAtomic, bool IsInvariant)
292*9880d681SAndroid Build Coastguard Worker         : DefInst(Inst), Generation(Generation), MatchingId(MatchingId),
293*9880d681SAndroid Build Coastguard Worker           IsAtomic(IsAtomic), IsInvariant(IsInvariant) {}
294*9880d681SAndroid Build Coastguard Worker   };
295*9880d681SAndroid Build Coastguard Worker   typedef RecyclingAllocator<BumpPtrAllocator,
296*9880d681SAndroid Build Coastguard Worker                              ScopedHashTableVal<Value *, LoadValue>>
297*9880d681SAndroid Build Coastguard Worker       LoadMapAllocator;
298*9880d681SAndroid Build Coastguard Worker   typedef ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>,
299*9880d681SAndroid Build Coastguard Worker                           LoadMapAllocator> LoadHTType;
300*9880d681SAndroid Build Coastguard Worker   LoadHTType AvailableLoads;
301*9880d681SAndroid Build Coastguard Worker 
302*9880d681SAndroid Build Coastguard Worker   /// \brief A scoped hash table of the current values of read-only call
303*9880d681SAndroid Build Coastguard Worker   /// values.
304*9880d681SAndroid Build Coastguard Worker   ///
305*9880d681SAndroid Build Coastguard Worker   /// It uses the same generation count as loads.
306*9880d681SAndroid Build Coastguard Worker   typedef ScopedHashTable<CallValue, std::pair<Instruction *, unsigned>>
307*9880d681SAndroid Build Coastguard Worker       CallHTType;
308*9880d681SAndroid Build Coastguard Worker   CallHTType AvailableCalls;
309*9880d681SAndroid Build Coastguard Worker 
310*9880d681SAndroid Build Coastguard Worker   /// \brief This is the current generation of the memory value.
311*9880d681SAndroid Build Coastguard Worker   unsigned CurrentGeneration;
312*9880d681SAndroid Build Coastguard Worker 
313*9880d681SAndroid Build Coastguard Worker   /// \brief Set up the EarlyCSE runner for a particular function.
EarlyCSE(const TargetLibraryInfo & TLI,const TargetTransformInfo & TTI,DominatorTree & DT,AssumptionCache & AC)314*9880d681SAndroid Build Coastguard Worker   EarlyCSE(const TargetLibraryInfo &TLI, const TargetTransformInfo &TTI,
315*9880d681SAndroid Build Coastguard Worker            DominatorTree &DT, AssumptionCache &AC)
316*9880d681SAndroid Build Coastguard Worker       : TLI(TLI), TTI(TTI), DT(DT), AC(AC), CurrentGeneration(0) {}
317*9880d681SAndroid Build Coastguard Worker 
318*9880d681SAndroid Build Coastguard Worker   bool run();
319*9880d681SAndroid Build Coastguard Worker 
320*9880d681SAndroid Build Coastguard Worker private:
321*9880d681SAndroid Build Coastguard Worker   // Almost a POD, but needs to call the constructors for the scoped hash
322*9880d681SAndroid Build Coastguard Worker   // tables so that a new scope gets pushed on. These are RAII so that the
323*9880d681SAndroid Build Coastguard Worker   // scope gets popped when the NodeScope is destroyed.
324*9880d681SAndroid Build Coastguard Worker   class NodeScope {
325*9880d681SAndroid Build Coastguard Worker   public:
NodeScope(ScopedHTType & AvailableValues,LoadHTType & AvailableLoads,CallHTType & AvailableCalls)326*9880d681SAndroid Build Coastguard Worker     NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
327*9880d681SAndroid Build Coastguard Worker               CallHTType &AvailableCalls)
328*9880d681SAndroid Build Coastguard Worker         : Scope(AvailableValues), LoadScope(AvailableLoads),
329*9880d681SAndroid Build Coastguard Worker           CallScope(AvailableCalls) {}
330*9880d681SAndroid Build Coastguard Worker 
331*9880d681SAndroid Build Coastguard Worker   private:
332*9880d681SAndroid Build Coastguard Worker     NodeScope(const NodeScope &) = delete;
333*9880d681SAndroid Build Coastguard Worker     void operator=(const NodeScope &) = delete;
334*9880d681SAndroid Build Coastguard Worker 
335*9880d681SAndroid Build Coastguard Worker     ScopedHTType::ScopeTy Scope;
336*9880d681SAndroid Build Coastguard Worker     LoadHTType::ScopeTy LoadScope;
337*9880d681SAndroid Build Coastguard Worker     CallHTType::ScopeTy CallScope;
338*9880d681SAndroid Build Coastguard Worker   };
339*9880d681SAndroid Build Coastguard Worker 
340*9880d681SAndroid Build Coastguard Worker   // Contains all the needed information to create a stack for doing a depth
341*9880d681SAndroid Build Coastguard Worker   // first tranversal of the tree. This includes scopes for values, loads, and
342*9880d681SAndroid Build Coastguard Worker   // calls as well as the generation. There is a child iterator so that the
343*9880d681SAndroid Build Coastguard Worker   // children do not need to be store separately.
344*9880d681SAndroid Build Coastguard Worker   class StackNode {
345*9880d681SAndroid Build Coastguard Worker   public:
StackNode(ScopedHTType & AvailableValues,LoadHTType & AvailableLoads,CallHTType & AvailableCalls,unsigned cg,DomTreeNode * n,DomTreeNode::iterator child,DomTreeNode::iterator end)346*9880d681SAndroid Build Coastguard Worker     StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
347*9880d681SAndroid Build Coastguard Worker               CallHTType &AvailableCalls, unsigned cg, DomTreeNode *n,
348*9880d681SAndroid Build Coastguard Worker               DomTreeNode::iterator child, DomTreeNode::iterator end)
349*9880d681SAndroid Build Coastguard Worker         : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
350*9880d681SAndroid Build Coastguard Worker           EndIter(end), Scopes(AvailableValues, AvailableLoads, AvailableCalls),
351*9880d681SAndroid Build Coastguard Worker           Processed(false) {}
352*9880d681SAndroid Build Coastguard Worker 
353*9880d681SAndroid Build Coastguard Worker     // Accessors.
currentGeneration()354*9880d681SAndroid Build Coastguard Worker     unsigned currentGeneration() { return CurrentGeneration; }
childGeneration()355*9880d681SAndroid Build Coastguard Worker     unsigned childGeneration() { return ChildGeneration; }
childGeneration(unsigned generation)356*9880d681SAndroid Build Coastguard Worker     void childGeneration(unsigned generation) { ChildGeneration = generation; }
node()357*9880d681SAndroid Build Coastguard Worker     DomTreeNode *node() { return Node; }
childIter()358*9880d681SAndroid Build Coastguard Worker     DomTreeNode::iterator childIter() { return ChildIter; }
nextChild()359*9880d681SAndroid Build Coastguard Worker     DomTreeNode *nextChild() {
360*9880d681SAndroid Build Coastguard Worker       DomTreeNode *child = *ChildIter;
361*9880d681SAndroid Build Coastguard Worker       ++ChildIter;
362*9880d681SAndroid Build Coastguard Worker       return child;
363*9880d681SAndroid Build Coastguard Worker     }
end()364*9880d681SAndroid Build Coastguard Worker     DomTreeNode::iterator end() { return EndIter; }
isProcessed()365*9880d681SAndroid Build Coastguard Worker     bool isProcessed() { return Processed; }
process()366*9880d681SAndroid Build Coastguard Worker     void process() { Processed = true; }
367*9880d681SAndroid Build Coastguard Worker 
368*9880d681SAndroid Build Coastguard Worker   private:
369*9880d681SAndroid Build Coastguard Worker     StackNode(const StackNode &) = delete;
370*9880d681SAndroid Build Coastguard Worker     void operator=(const StackNode &) = delete;
371*9880d681SAndroid Build Coastguard Worker 
372*9880d681SAndroid Build Coastguard Worker     // Members.
373*9880d681SAndroid Build Coastguard Worker     unsigned CurrentGeneration;
374*9880d681SAndroid Build Coastguard Worker     unsigned ChildGeneration;
375*9880d681SAndroid Build Coastguard Worker     DomTreeNode *Node;
376*9880d681SAndroid Build Coastguard Worker     DomTreeNode::iterator ChildIter;
377*9880d681SAndroid Build Coastguard Worker     DomTreeNode::iterator EndIter;
378*9880d681SAndroid Build Coastguard Worker     NodeScope Scopes;
379*9880d681SAndroid Build Coastguard Worker     bool Processed;
380*9880d681SAndroid Build Coastguard Worker   };
381*9880d681SAndroid Build Coastguard Worker 
382*9880d681SAndroid Build Coastguard Worker   /// \brief Wrapper class to handle memory instructions, including loads,
383*9880d681SAndroid Build Coastguard Worker   /// stores and intrinsic loads and stores defined by the target.
384*9880d681SAndroid Build Coastguard Worker   class ParseMemoryInst {
385*9880d681SAndroid Build Coastguard Worker   public:
ParseMemoryInst(Instruction * Inst,const TargetTransformInfo & TTI)386*9880d681SAndroid Build Coastguard Worker     ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
387*9880d681SAndroid Build Coastguard Worker       : IsTargetMemInst(false), Inst(Inst) {
388*9880d681SAndroid Build Coastguard Worker       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
389*9880d681SAndroid Build Coastguard Worker         if (TTI.getTgtMemIntrinsic(II, Info) && Info.NumMemRefs == 1)
390*9880d681SAndroid Build Coastguard Worker           IsTargetMemInst = true;
391*9880d681SAndroid Build Coastguard Worker     }
isLoad() const392*9880d681SAndroid Build Coastguard Worker     bool isLoad() const {
393*9880d681SAndroid Build Coastguard Worker       if (IsTargetMemInst) return Info.ReadMem;
394*9880d681SAndroid Build Coastguard Worker       return isa<LoadInst>(Inst);
395*9880d681SAndroid Build Coastguard Worker     }
isStore() const396*9880d681SAndroid Build Coastguard Worker     bool isStore() const {
397*9880d681SAndroid Build Coastguard Worker       if (IsTargetMemInst) return Info.WriteMem;
398*9880d681SAndroid Build Coastguard Worker       return isa<StoreInst>(Inst);
399*9880d681SAndroid Build Coastguard Worker     }
isAtomic() const400*9880d681SAndroid Build Coastguard Worker     bool isAtomic() const {
401*9880d681SAndroid Build Coastguard Worker       if (IsTargetMemInst) {
402*9880d681SAndroid Build Coastguard Worker         assert(Info.IsSimple && "need to refine IsSimple in TTI");
403*9880d681SAndroid Build Coastguard Worker         return false;
404*9880d681SAndroid Build Coastguard Worker       }
405*9880d681SAndroid Build Coastguard Worker       return Inst->isAtomic();
406*9880d681SAndroid Build Coastguard Worker     }
isUnordered() const407*9880d681SAndroid Build Coastguard Worker     bool isUnordered() const {
408*9880d681SAndroid Build Coastguard Worker       if (IsTargetMemInst) {
409*9880d681SAndroid Build Coastguard Worker         assert(Info.IsSimple && "need to refine IsSimple in TTI");
410*9880d681SAndroid Build Coastguard Worker         return true;
411*9880d681SAndroid Build Coastguard Worker       }
412*9880d681SAndroid Build Coastguard Worker       if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
413*9880d681SAndroid Build Coastguard Worker         return LI->isUnordered();
414*9880d681SAndroid Build Coastguard Worker       } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
415*9880d681SAndroid Build Coastguard Worker         return SI->isUnordered();
416*9880d681SAndroid Build Coastguard Worker       }
417*9880d681SAndroid Build Coastguard Worker       // Conservative answer
418*9880d681SAndroid Build Coastguard Worker       return !Inst->isAtomic();
419*9880d681SAndroid Build Coastguard Worker     }
420*9880d681SAndroid Build Coastguard Worker 
isVolatile() const421*9880d681SAndroid Build Coastguard Worker     bool isVolatile() const {
422*9880d681SAndroid Build Coastguard Worker       if (IsTargetMemInst) {
423*9880d681SAndroid Build Coastguard Worker         assert(Info.IsSimple && "need to refine IsSimple in TTI");
424*9880d681SAndroid Build Coastguard Worker         return false;
425*9880d681SAndroid Build Coastguard Worker       }
426*9880d681SAndroid Build Coastguard Worker       if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
427*9880d681SAndroid Build Coastguard Worker         return LI->isVolatile();
428*9880d681SAndroid Build Coastguard Worker       } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
429*9880d681SAndroid Build Coastguard Worker         return SI->isVolatile();
430*9880d681SAndroid Build Coastguard Worker       }
431*9880d681SAndroid Build Coastguard Worker       // Conservative answer
432*9880d681SAndroid Build Coastguard Worker       return true;
433*9880d681SAndroid Build Coastguard Worker     }
434*9880d681SAndroid Build Coastguard Worker 
isInvariantLoad() const435*9880d681SAndroid Build Coastguard Worker     bool isInvariantLoad() const {
436*9880d681SAndroid Build Coastguard Worker       if (auto *LI = dyn_cast<LoadInst>(Inst))
437*9880d681SAndroid Build Coastguard Worker         return LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr;
438*9880d681SAndroid Build Coastguard Worker       return false;
439*9880d681SAndroid Build Coastguard Worker     }
440*9880d681SAndroid Build Coastguard Worker 
isMatchingMemLoc(const ParseMemoryInst & Inst) const441*9880d681SAndroid Build Coastguard Worker     bool isMatchingMemLoc(const ParseMemoryInst &Inst) const {
442*9880d681SAndroid Build Coastguard Worker       return (getPointerOperand() == Inst.getPointerOperand() &&
443*9880d681SAndroid Build Coastguard Worker               getMatchingId() == Inst.getMatchingId());
444*9880d681SAndroid Build Coastguard Worker     }
isValid() const445*9880d681SAndroid Build Coastguard Worker     bool isValid() const { return getPointerOperand() != nullptr; }
446*9880d681SAndroid Build Coastguard Worker 
447*9880d681SAndroid Build Coastguard Worker     // For regular (non-intrinsic) loads/stores, this is set to -1. For
448*9880d681SAndroid Build Coastguard Worker     // intrinsic loads/stores, the id is retrieved from the corresponding
449*9880d681SAndroid Build Coastguard Worker     // field in the MemIntrinsicInfo structure.  That field contains
450*9880d681SAndroid Build Coastguard Worker     // non-negative values only.
getMatchingId() const451*9880d681SAndroid Build Coastguard Worker     int getMatchingId() const {
452*9880d681SAndroid Build Coastguard Worker       if (IsTargetMemInst) return Info.MatchingId;
453*9880d681SAndroid Build Coastguard Worker       return -1;
454*9880d681SAndroid Build Coastguard Worker     }
getPointerOperand() const455*9880d681SAndroid Build Coastguard Worker     Value *getPointerOperand() const {
456*9880d681SAndroid Build Coastguard Worker       if (IsTargetMemInst) return Info.PtrVal;
457*9880d681SAndroid Build Coastguard Worker       if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
458*9880d681SAndroid Build Coastguard Worker         return LI->getPointerOperand();
459*9880d681SAndroid Build Coastguard Worker       } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
460*9880d681SAndroid Build Coastguard Worker         return SI->getPointerOperand();
461*9880d681SAndroid Build Coastguard Worker       }
462*9880d681SAndroid Build Coastguard Worker       return nullptr;
463*9880d681SAndroid Build Coastguard Worker     }
mayReadFromMemory() const464*9880d681SAndroid Build Coastguard Worker     bool mayReadFromMemory() const {
465*9880d681SAndroid Build Coastguard Worker       if (IsTargetMemInst) return Info.ReadMem;
466*9880d681SAndroid Build Coastguard Worker       return Inst->mayReadFromMemory();
467*9880d681SAndroid Build Coastguard Worker     }
mayWriteToMemory() const468*9880d681SAndroid Build Coastguard Worker     bool mayWriteToMemory() const {
469*9880d681SAndroid Build Coastguard Worker       if (IsTargetMemInst) return Info.WriteMem;
470*9880d681SAndroid Build Coastguard Worker       return Inst->mayWriteToMemory();
471*9880d681SAndroid Build Coastguard Worker     }
472*9880d681SAndroid Build Coastguard Worker 
473*9880d681SAndroid Build Coastguard Worker   private:
474*9880d681SAndroid Build Coastguard Worker     bool IsTargetMemInst;
475*9880d681SAndroid Build Coastguard Worker     MemIntrinsicInfo Info;
476*9880d681SAndroid Build Coastguard Worker     Instruction *Inst;
477*9880d681SAndroid Build Coastguard Worker   };
478*9880d681SAndroid Build Coastguard Worker 
479*9880d681SAndroid Build Coastguard Worker   bool processNode(DomTreeNode *Node);
480*9880d681SAndroid Build Coastguard Worker 
getOrCreateResult(Value * Inst,Type * ExpectedType) const481*9880d681SAndroid Build Coastguard Worker   Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const {
482*9880d681SAndroid Build Coastguard Worker     if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
483*9880d681SAndroid Build Coastguard Worker       return LI;
484*9880d681SAndroid Build Coastguard Worker     else if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
485*9880d681SAndroid Build Coastguard Worker       return SI->getValueOperand();
486*9880d681SAndroid Build Coastguard Worker     assert(isa<IntrinsicInst>(Inst) && "Instruction not supported");
487*9880d681SAndroid Build Coastguard Worker     return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst),
488*9880d681SAndroid Build Coastguard Worker                                                  ExpectedType);
489*9880d681SAndroid Build Coastguard Worker   }
490*9880d681SAndroid Build Coastguard Worker };
491*9880d681SAndroid Build Coastguard Worker }
492*9880d681SAndroid Build Coastguard Worker 
processNode(DomTreeNode * Node)493*9880d681SAndroid Build Coastguard Worker bool EarlyCSE::processNode(DomTreeNode *Node) {
494*9880d681SAndroid Build Coastguard Worker   bool Changed = false;
495*9880d681SAndroid Build Coastguard Worker   BasicBlock *BB = Node->getBlock();
496*9880d681SAndroid Build Coastguard Worker 
497*9880d681SAndroid Build Coastguard Worker   // If this block has a single predecessor, then the predecessor is the parent
498*9880d681SAndroid Build Coastguard Worker   // of the domtree node and all of the live out memory values are still current
499*9880d681SAndroid Build Coastguard Worker   // in this block.  If this block has multiple predecessors, then they could
500*9880d681SAndroid Build Coastguard Worker   // have invalidated the live-out memory values of our parent value.  For now,
501*9880d681SAndroid Build Coastguard Worker   // just be conservative and invalidate memory if this block has multiple
502*9880d681SAndroid Build Coastguard Worker   // predecessors.
503*9880d681SAndroid Build Coastguard Worker   if (!BB->getSinglePredecessor())
504*9880d681SAndroid Build Coastguard Worker     ++CurrentGeneration;
505*9880d681SAndroid Build Coastguard Worker 
506*9880d681SAndroid Build Coastguard Worker   // If this node has a single predecessor which ends in a conditional branch,
507*9880d681SAndroid Build Coastguard Worker   // we can infer the value of the branch condition given that we took this
508*9880d681SAndroid Build Coastguard Worker   // path.  We need the single predecessor to ensure there's not another path
509*9880d681SAndroid Build Coastguard Worker   // which reaches this block where the condition might hold a different
510*9880d681SAndroid Build Coastguard Worker   // value.  Since we're adding this to the scoped hash table (like any other
511*9880d681SAndroid Build Coastguard Worker   // def), it will have been popped if we encounter a future merge block.
512*9880d681SAndroid Build Coastguard Worker   if (BasicBlock *Pred = BB->getSinglePredecessor())
513*9880d681SAndroid Build Coastguard Worker     if (auto *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
514*9880d681SAndroid Build Coastguard Worker       if (BI->isConditional())
515*9880d681SAndroid Build Coastguard Worker         if (auto *CondInst = dyn_cast<Instruction>(BI->getCondition()))
516*9880d681SAndroid Build Coastguard Worker           if (SimpleValue::canHandle(CondInst)) {
517*9880d681SAndroid Build Coastguard Worker             assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
518*9880d681SAndroid Build Coastguard Worker             auto *ConditionalConstant = (BI->getSuccessor(0) == BB) ?
519*9880d681SAndroid Build Coastguard Worker               ConstantInt::getTrue(BB->getContext()) :
520*9880d681SAndroid Build Coastguard Worker               ConstantInt::getFalse(BB->getContext());
521*9880d681SAndroid Build Coastguard Worker             AvailableValues.insert(CondInst, ConditionalConstant);
522*9880d681SAndroid Build Coastguard Worker             DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
523*9880d681SAndroid Build Coastguard Worker                   << CondInst->getName() << "' as " << *ConditionalConstant
524*9880d681SAndroid Build Coastguard Worker                   << " in " << BB->getName() << "\n");
525*9880d681SAndroid Build Coastguard Worker             // Replace all dominated uses with the known value.
526*9880d681SAndroid Build Coastguard Worker             if (unsigned Count =
527*9880d681SAndroid Build Coastguard Worker                     replaceDominatedUsesWith(CondInst, ConditionalConstant, DT,
528*9880d681SAndroid Build Coastguard Worker                                              BasicBlockEdge(Pred, BB))) {
529*9880d681SAndroid Build Coastguard Worker               Changed = true;
530*9880d681SAndroid Build Coastguard Worker               NumCSECVP = NumCSECVP + Count;
531*9880d681SAndroid Build Coastguard Worker             }
532*9880d681SAndroid Build Coastguard Worker           }
533*9880d681SAndroid Build Coastguard Worker 
534*9880d681SAndroid Build Coastguard Worker   /// LastStore - Keep track of the last non-volatile store that we saw... for
535*9880d681SAndroid Build Coastguard Worker   /// as long as there in no instruction that reads memory.  If we see a store
536*9880d681SAndroid Build Coastguard Worker   /// to the same location, we delete the dead store.  This zaps trivial dead
537*9880d681SAndroid Build Coastguard Worker   /// stores which can occur in bitfield code among other things.
538*9880d681SAndroid Build Coastguard Worker   Instruction *LastStore = nullptr;
539*9880d681SAndroid Build Coastguard Worker 
540*9880d681SAndroid Build Coastguard Worker   const DataLayout &DL = BB->getModule()->getDataLayout();
541*9880d681SAndroid Build Coastguard Worker 
542*9880d681SAndroid Build Coastguard Worker   // See if any instructions in the block can be eliminated.  If so, do it.  If
543*9880d681SAndroid Build Coastguard Worker   // not, add them to AvailableValues.
544*9880d681SAndroid Build Coastguard Worker   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
545*9880d681SAndroid Build Coastguard Worker     Instruction *Inst = &*I++;
546*9880d681SAndroid Build Coastguard Worker 
547*9880d681SAndroid Build Coastguard Worker     // Dead instructions should just be removed.
548*9880d681SAndroid Build Coastguard Worker     if (isInstructionTriviallyDead(Inst, &TLI)) {
549*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
550*9880d681SAndroid Build Coastguard Worker       Inst->eraseFromParent();
551*9880d681SAndroid Build Coastguard Worker       Changed = true;
552*9880d681SAndroid Build Coastguard Worker       ++NumSimplify;
553*9880d681SAndroid Build Coastguard Worker       continue;
554*9880d681SAndroid Build Coastguard Worker     }
555*9880d681SAndroid Build Coastguard Worker 
556*9880d681SAndroid Build Coastguard Worker     // Skip assume intrinsics, they don't really have side effects (although
557*9880d681SAndroid Build Coastguard Worker     // they're marked as such to ensure preservation of control dependencies),
558*9880d681SAndroid Build Coastguard Worker     // and this pass will not disturb any of the assumption's control
559*9880d681SAndroid Build Coastguard Worker     // dependencies.
560*9880d681SAndroid Build Coastguard Worker     if (match(Inst, m_Intrinsic<Intrinsic::assume>())) {
561*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n');
562*9880d681SAndroid Build Coastguard Worker       continue;
563*9880d681SAndroid Build Coastguard Worker     }
564*9880d681SAndroid Build Coastguard Worker 
565*9880d681SAndroid Build Coastguard Worker     if (match(Inst, m_Intrinsic<Intrinsic::experimental_guard>())) {
566*9880d681SAndroid Build Coastguard Worker       if (auto *CondI =
567*9880d681SAndroid Build Coastguard Worker               dyn_cast<Instruction>(cast<CallInst>(Inst)->getArgOperand(0))) {
568*9880d681SAndroid Build Coastguard Worker         // The condition we're on guarding here is true for all dominated
569*9880d681SAndroid Build Coastguard Worker         // locations.
570*9880d681SAndroid Build Coastguard Worker         if (SimpleValue::canHandle(CondI))
571*9880d681SAndroid Build Coastguard Worker           AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
572*9880d681SAndroid Build Coastguard Worker       }
573*9880d681SAndroid Build Coastguard Worker 
574*9880d681SAndroid Build Coastguard Worker       // Guard intrinsics read all memory, but don't write any memory.
575*9880d681SAndroid Build Coastguard Worker       // Accordingly, don't update the generation but consume the last store (to
576*9880d681SAndroid Build Coastguard Worker       // avoid an incorrect DSE).
577*9880d681SAndroid Build Coastguard Worker       LastStore = nullptr;
578*9880d681SAndroid Build Coastguard Worker       continue;
579*9880d681SAndroid Build Coastguard Worker     }
580*9880d681SAndroid Build Coastguard Worker 
581*9880d681SAndroid Build Coastguard Worker     // If the instruction can be simplified (e.g. X+0 = X) then replace it with
582*9880d681SAndroid Build Coastguard Worker     // its simpler value.
583*9880d681SAndroid Build Coastguard Worker     if (Value *V = SimplifyInstruction(Inst, DL, &TLI, &DT, &AC)) {
584*9880d681SAndroid Build Coastguard Worker       DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << "  to: " << *V << '\n');
585*9880d681SAndroid Build Coastguard Worker       if (!Inst->use_empty()) {
586*9880d681SAndroid Build Coastguard Worker         Inst->replaceAllUsesWith(V);
587*9880d681SAndroid Build Coastguard Worker         Changed = true;
588*9880d681SAndroid Build Coastguard Worker       }
589*9880d681SAndroid Build Coastguard Worker       if (isInstructionTriviallyDead(Inst, &TLI)) {
590*9880d681SAndroid Build Coastguard Worker         Inst->eraseFromParent();
591*9880d681SAndroid Build Coastguard Worker         Changed = true;
592*9880d681SAndroid Build Coastguard Worker       }
593*9880d681SAndroid Build Coastguard Worker       if (Changed) {
594*9880d681SAndroid Build Coastguard Worker         ++NumSimplify;
595*9880d681SAndroid Build Coastguard Worker         continue;
596*9880d681SAndroid Build Coastguard Worker       }
597*9880d681SAndroid Build Coastguard Worker     }
598*9880d681SAndroid Build Coastguard Worker 
599*9880d681SAndroid Build Coastguard Worker     // If this is a simple instruction that we can value number, process it.
600*9880d681SAndroid Build Coastguard Worker     if (SimpleValue::canHandle(Inst)) {
601*9880d681SAndroid Build Coastguard Worker       // See if the instruction has an available value.  If so, use it.
602*9880d681SAndroid Build Coastguard Worker       if (Value *V = AvailableValues.lookup(Inst)) {
603*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << "  to: " << *V << '\n');
604*9880d681SAndroid Build Coastguard Worker         if (auto *I = dyn_cast<Instruction>(V))
605*9880d681SAndroid Build Coastguard Worker           I->andIRFlags(Inst);
606*9880d681SAndroid Build Coastguard Worker         Inst->replaceAllUsesWith(V);
607*9880d681SAndroid Build Coastguard Worker         Inst->eraseFromParent();
608*9880d681SAndroid Build Coastguard Worker         Changed = true;
609*9880d681SAndroid Build Coastguard Worker         ++NumCSE;
610*9880d681SAndroid Build Coastguard Worker         continue;
611*9880d681SAndroid Build Coastguard Worker       }
612*9880d681SAndroid Build Coastguard Worker 
613*9880d681SAndroid Build Coastguard Worker       // Otherwise, just remember that this value is available.
614*9880d681SAndroid Build Coastguard Worker       AvailableValues.insert(Inst, Inst);
615*9880d681SAndroid Build Coastguard Worker       continue;
616*9880d681SAndroid Build Coastguard Worker     }
617*9880d681SAndroid Build Coastguard Worker 
618*9880d681SAndroid Build Coastguard Worker     ParseMemoryInst MemInst(Inst, TTI);
619*9880d681SAndroid Build Coastguard Worker     // If this is a non-volatile load, process it.
620*9880d681SAndroid Build Coastguard Worker     if (MemInst.isValid() && MemInst.isLoad()) {
621*9880d681SAndroid Build Coastguard Worker       // (conservatively) we can't peak past the ordering implied by this
622*9880d681SAndroid Build Coastguard Worker       // operation, but we can add this load to our set of available values
623*9880d681SAndroid Build Coastguard Worker       if (MemInst.isVolatile() || !MemInst.isUnordered()) {
624*9880d681SAndroid Build Coastguard Worker         LastStore = nullptr;
625*9880d681SAndroid Build Coastguard Worker         ++CurrentGeneration;
626*9880d681SAndroid Build Coastguard Worker       }
627*9880d681SAndroid Build Coastguard Worker 
628*9880d681SAndroid Build Coastguard Worker       // If we have an available version of this load, and if it is the right
629*9880d681SAndroid Build Coastguard Worker       // generation or the load is known to be from an invariant location,
630*9880d681SAndroid Build Coastguard Worker       // replace this instruction.
631*9880d681SAndroid Build Coastguard Worker       //
632*9880d681SAndroid Build Coastguard Worker       // A dominating invariant load implies that the location loaded from is
633*9880d681SAndroid Build Coastguard Worker       // unchanging beginning at the point of the invariant load, so the load
634*9880d681SAndroid Build Coastguard Worker       // we're CSE'ing _away_ does not need to be invariant, only the available
635*9880d681SAndroid Build Coastguard Worker       // load we're CSE'ing _to_ does.
636*9880d681SAndroid Build Coastguard Worker       LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
637*9880d681SAndroid Build Coastguard Worker       if (InVal.DefInst != nullptr &&
638*9880d681SAndroid Build Coastguard Worker           (InVal.Generation == CurrentGeneration || InVal.IsInvariant) &&
639*9880d681SAndroid Build Coastguard Worker           InVal.MatchingId == MemInst.getMatchingId() &&
640*9880d681SAndroid Build Coastguard Worker           // We don't yet handle removing loads with ordering of any kind.
641*9880d681SAndroid Build Coastguard Worker           !MemInst.isVolatile() && MemInst.isUnordered() &&
642*9880d681SAndroid Build Coastguard Worker           // We can't replace an atomic load with one which isn't also atomic.
643*9880d681SAndroid Build Coastguard Worker           InVal.IsAtomic >= MemInst.isAtomic()) {
644*9880d681SAndroid Build Coastguard Worker         Value *Op = getOrCreateResult(InVal.DefInst, Inst->getType());
645*9880d681SAndroid Build Coastguard Worker         if (Op != nullptr) {
646*9880d681SAndroid Build Coastguard Worker           DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst
647*9880d681SAndroid Build Coastguard Worker                        << "  to: " << *InVal.DefInst << '\n');
648*9880d681SAndroid Build Coastguard Worker           if (!Inst->use_empty())
649*9880d681SAndroid Build Coastguard Worker             Inst->replaceAllUsesWith(Op);
650*9880d681SAndroid Build Coastguard Worker           Inst->eraseFromParent();
651*9880d681SAndroid Build Coastguard Worker           Changed = true;
652*9880d681SAndroid Build Coastguard Worker           ++NumCSELoad;
653*9880d681SAndroid Build Coastguard Worker           continue;
654*9880d681SAndroid Build Coastguard Worker         }
655*9880d681SAndroid Build Coastguard Worker       }
656*9880d681SAndroid Build Coastguard Worker 
657*9880d681SAndroid Build Coastguard Worker       // Otherwise, remember that we have this instruction.
658*9880d681SAndroid Build Coastguard Worker       AvailableLoads.insert(
659*9880d681SAndroid Build Coastguard Worker           MemInst.getPointerOperand(),
660*9880d681SAndroid Build Coastguard Worker           LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
661*9880d681SAndroid Build Coastguard Worker                     MemInst.isAtomic(), MemInst.isInvariantLoad()));
662*9880d681SAndroid Build Coastguard Worker       LastStore = nullptr;
663*9880d681SAndroid Build Coastguard Worker       continue;
664*9880d681SAndroid Build Coastguard Worker     }
665*9880d681SAndroid Build Coastguard Worker 
666*9880d681SAndroid Build Coastguard Worker     // If this instruction may read from memory, forget LastStore.
667*9880d681SAndroid Build Coastguard Worker     // Load/store intrinsics will indicate both a read and a write to
668*9880d681SAndroid Build Coastguard Worker     // memory.  The target may override this (e.g. so that a store intrinsic
669*9880d681SAndroid Build Coastguard Worker     // does not read  from memory, and thus will be treated the same as a
670*9880d681SAndroid Build Coastguard Worker     // regular store for commoning purposes).
671*9880d681SAndroid Build Coastguard Worker     if (Inst->mayReadFromMemory() &&
672*9880d681SAndroid Build Coastguard Worker         !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
673*9880d681SAndroid Build Coastguard Worker       LastStore = nullptr;
674*9880d681SAndroid Build Coastguard Worker 
675*9880d681SAndroid Build Coastguard Worker     // If this is a read-only call, process it.
676*9880d681SAndroid Build Coastguard Worker     if (CallValue::canHandle(Inst)) {
677*9880d681SAndroid Build Coastguard Worker       // If we have an available version of this call, and if it is the right
678*9880d681SAndroid Build Coastguard Worker       // generation, replace this instruction.
679*9880d681SAndroid Build Coastguard Worker       std::pair<Instruction *, unsigned> InVal = AvailableCalls.lookup(Inst);
680*9880d681SAndroid Build Coastguard Worker       if (InVal.first != nullptr && InVal.second == CurrentGeneration) {
681*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst
682*9880d681SAndroid Build Coastguard Worker                      << "  to: " << *InVal.first << '\n');
683*9880d681SAndroid Build Coastguard Worker         if (!Inst->use_empty())
684*9880d681SAndroid Build Coastguard Worker           Inst->replaceAllUsesWith(InVal.first);
685*9880d681SAndroid Build Coastguard Worker         Inst->eraseFromParent();
686*9880d681SAndroid Build Coastguard Worker         Changed = true;
687*9880d681SAndroid Build Coastguard Worker         ++NumCSECall;
688*9880d681SAndroid Build Coastguard Worker         continue;
689*9880d681SAndroid Build Coastguard Worker       }
690*9880d681SAndroid Build Coastguard Worker 
691*9880d681SAndroid Build Coastguard Worker       // Otherwise, remember that we have this instruction.
692*9880d681SAndroid Build Coastguard Worker       AvailableCalls.insert(
693*9880d681SAndroid Build Coastguard Worker           Inst, std::pair<Instruction *, unsigned>(Inst, CurrentGeneration));
694*9880d681SAndroid Build Coastguard Worker       continue;
695*9880d681SAndroid Build Coastguard Worker     }
696*9880d681SAndroid Build Coastguard Worker 
697*9880d681SAndroid Build Coastguard Worker     // A release fence requires that all stores complete before it, but does
698*9880d681SAndroid Build Coastguard Worker     // not prevent the reordering of following loads 'before' the fence.  As a
699*9880d681SAndroid Build Coastguard Worker     // result, we don't need to consider it as writing to memory and don't need
700*9880d681SAndroid Build Coastguard Worker     // to advance the generation.  We do need to prevent DSE across the fence,
701*9880d681SAndroid Build Coastguard Worker     // but that's handled above.
702*9880d681SAndroid Build Coastguard Worker     if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
703*9880d681SAndroid Build Coastguard Worker       if (FI->getOrdering() == AtomicOrdering::Release) {
704*9880d681SAndroid Build Coastguard Worker         assert(Inst->mayReadFromMemory() && "relied on to prevent DSE above");
705*9880d681SAndroid Build Coastguard Worker         continue;
706*9880d681SAndroid Build Coastguard Worker       }
707*9880d681SAndroid Build Coastguard Worker 
708*9880d681SAndroid Build Coastguard Worker     // write back DSE - If we write back the same value we just loaded from
709*9880d681SAndroid Build Coastguard Worker     // the same location and haven't passed any intervening writes or ordering
710*9880d681SAndroid Build Coastguard Worker     // operations, we can remove the write.  The primary benefit is in allowing
711*9880d681SAndroid Build Coastguard Worker     // the available load table to remain valid and value forward past where
712*9880d681SAndroid Build Coastguard Worker     // the store originally was.
713*9880d681SAndroid Build Coastguard Worker     if (MemInst.isValid() && MemInst.isStore()) {
714*9880d681SAndroid Build Coastguard Worker       LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
715*9880d681SAndroid Build Coastguard Worker       if (InVal.DefInst &&
716*9880d681SAndroid Build Coastguard Worker           InVal.DefInst == getOrCreateResult(Inst, InVal.DefInst->getType()) &&
717*9880d681SAndroid Build Coastguard Worker           InVal.Generation == CurrentGeneration &&
718*9880d681SAndroid Build Coastguard Worker           InVal.MatchingId == MemInst.getMatchingId() &&
719*9880d681SAndroid Build Coastguard Worker           // We don't yet handle removing stores with ordering of any kind.
720*9880d681SAndroid Build Coastguard Worker           !MemInst.isVolatile() && MemInst.isUnordered()) {
721*9880d681SAndroid Build Coastguard Worker         assert((!LastStore ||
722*9880d681SAndroid Build Coastguard Worker                 ParseMemoryInst(LastStore, TTI).getPointerOperand() ==
723*9880d681SAndroid Build Coastguard Worker                 MemInst.getPointerOperand()) &&
724*9880d681SAndroid Build Coastguard Worker                "can't have an intervening store!");
725*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << *Inst << '\n');
726*9880d681SAndroid Build Coastguard Worker         Inst->eraseFromParent();
727*9880d681SAndroid Build Coastguard Worker         Changed = true;
728*9880d681SAndroid Build Coastguard Worker         ++NumDSE;
729*9880d681SAndroid Build Coastguard Worker         // We can avoid incrementing the generation count since we were able
730*9880d681SAndroid Build Coastguard Worker         // to eliminate this store.
731*9880d681SAndroid Build Coastguard Worker         continue;
732*9880d681SAndroid Build Coastguard Worker       }
733*9880d681SAndroid Build Coastguard Worker     }
734*9880d681SAndroid Build Coastguard Worker 
735*9880d681SAndroid Build Coastguard Worker     // Okay, this isn't something we can CSE at all.  Check to see if it is
736*9880d681SAndroid Build Coastguard Worker     // something that could modify memory.  If so, our available memory values
737*9880d681SAndroid Build Coastguard Worker     // cannot be used so bump the generation count.
738*9880d681SAndroid Build Coastguard Worker     if (Inst->mayWriteToMemory()) {
739*9880d681SAndroid Build Coastguard Worker       ++CurrentGeneration;
740*9880d681SAndroid Build Coastguard Worker 
741*9880d681SAndroid Build Coastguard Worker       if (MemInst.isValid() && MemInst.isStore()) {
742*9880d681SAndroid Build Coastguard Worker         // We do a trivial form of DSE if there are two stores to the same
743*9880d681SAndroid Build Coastguard Worker         // location with no intervening loads.  Delete the earlier store.
744*9880d681SAndroid Build Coastguard Worker         // At the moment, we don't remove ordered stores, but do remove
745*9880d681SAndroid Build Coastguard Worker         // unordered atomic stores.  There's no special requirement (for
746*9880d681SAndroid Build Coastguard Worker         // unordered atomics) about removing atomic stores only in favor of
747*9880d681SAndroid Build Coastguard Worker         // other atomic stores since we we're going to execute the non-atomic
748*9880d681SAndroid Build Coastguard Worker         // one anyway and the atomic one might never have become visible.
749*9880d681SAndroid Build Coastguard Worker         if (LastStore) {
750*9880d681SAndroid Build Coastguard Worker           ParseMemoryInst LastStoreMemInst(LastStore, TTI);
751*9880d681SAndroid Build Coastguard Worker           assert(LastStoreMemInst.isUnordered() &&
752*9880d681SAndroid Build Coastguard Worker                  !LastStoreMemInst.isVolatile() &&
753*9880d681SAndroid Build Coastguard Worker                  "Violated invariant");
754*9880d681SAndroid Build Coastguard Worker           if (LastStoreMemInst.isMatchingMemLoc(MemInst)) {
755*9880d681SAndroid Build Coastguard Worker             DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
756*9880d681SAndroid Build Coastguard Worker                          << "  due to: " << *Inst << '\n');
757*9880d681SAndroid Build Coastguard Worker             LastStore->eraseFromParent();
758*9880d681SAndroid Build Coastguard Worker             Changed = true;
759*9880d681SAndroid Build Coastguard Worker             ++NumDSE;
760*9880d681SAndroid Build Coastguard Worker             LastStore = nullptr;
761*9880d681SAndroid Build Coastguard Worker           }
762*9880d681SAndroid Build Coastguard Worker           // fallthrough - we can exploit information about this store
763*9880d681SAndroid Build Coastguard Worker         }
764*9880d681SAndroid Build Coastguard Worker 
765*9880d681SAndroid Build Coastguard Worker         // Okay, we just invalidated anything we knew about loaded values.  Try
766*9880d681SAndroid Build Coastguard Worker         // to salvage *something* by remembering that the stored value is a live
767*9880d681SAndroid Build Coastguard Worker         // version of the pointer.  It is safe to forward from volatile stores
768*9880d681SAndroid Build Coastguard Worker         // to non-volatile loads, so we don't have to check for volatility of
769*9880d681SAndroid Build Coastguard Worker         // the store.
770*9880d681SAndroid Build Coastguard Worker         AvailableLoads.insert(
771*9880d681SAndroid Build Coastguard Worker             MemInst.getPointerOperand(),
772*9880d681SAndroid Build Coastguard Worker             LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
773*9880d681SAndroid Build Coastguard Worker                       MemInst.isAtomic(), /*IsInvariant=*/false));
774*9880d681SAndroid Build Coastguard Worker 
775*9880d681SAndroid Build Coastguard Worker         // Remember that this was the last unordered store we saw for DSE. We
776*9880d681SAndroid Build Coastguard Worker         // don't yet handle DSE on ordered or volatile stores since we don't
777*9880d681SAndroid Build Coastguard Worker         // have a good way to model the ordering requirement for following
778*9880d681SAndroid Build Coastguard Worker         // passes  once the store is removed.  We could insert a fence, but
779*9880d681SAndroid Build Coastguard Worker         // since fences are slightly stronger than stores in their ordering,
780*9880d681SAndroid Build Coastguard Worker         // it's not clear this is a profitable transform. Another option would
781*9880d681SAndroid Build Coastguard Worker         // be to merge the ordering with that of the post dominating store.
782*9880d681SAndroid Build Coastguard Worker         if (MemInst.isUnordered() && !MemInst.isVolatile())
783*9880d681SAndroid Build Coastguard Worker           LastStore = Inst;
784*9880d681SAndroid Build Coastguard Worker         else
785*9880d681SAndroid Build Coastguard Worker           LastStore = nullptr;
786*9880d681SAndroid Build Coastguard Worker       }
787*9880d681SAndroid Build Coastguard Worker     }
788*9880d681SAndroid Build Coastguard Worker   }
789*9880d681SAndroid Build Coastguard Worker 
790*9880d681SAndroid Build Coastguard Worker   return Changed;
791*9880d681SAndroid Build Coastguard Worker }
792*9880d681SAndroid Build Coastguard Worker 
run()793*9880d681SAndroid Build Coastguard Worker bool EarlyCSE::run() {
794*9880d681SAndroid Build Coastguard Worker   // Note, deque is being used here because there is significant performance
795*9880d681SAndroid Build Coastguard Worker   // gains over vector when the container becomes very large due to the
796*9880d681SAndroid Build Coastguard Worker   // specific access patterns. For more information see the mailing list
797*9880d681SAndroid Build Coastguard Worker   // discussion on this:
798*9880d681SAndroid Build Coastguard Worker   // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
799*9880d681SAndroid Build Coastguard Worker   std::deque<StackNode *> nodesToProcess;
800*9880d681SAndroid Build Coastguard Worker 
801*9880d681SAndroid Build Coastguard Worker   bool Changed = false;
802*9880d681SAndroid Build Coastguard Worker 
803*9880d681SAndroid Build Coastguard Worker   // Process the root node.
804*9880d681SAndroid Build Coastguard Worker   nodesToProcess.push_back(new StackNode(
805*9880d681SAndroid Build Coastguard Worker       AvailableValues, AvailableLoads, AvailableCalls, CurrentGeneration,
806*9880d681SAndroid Build Coastguard Worker       DT.getRootNode(), DT.getRootNode()->begin(), DT.getRootNode()->end()));
807*9880d681SAndroid Build Coastguard Worker 
808*9880d681SAndroid Build Coastguard Worker   // Save the current generation.
809*9880d681SAndroid Build Coastguard Worker   unsigned LiveOutGeneration = CurrentGeneration;
810*9880d681SAndroid Build Coastguard Worker 
811*9880d681SAndroid Build Coastguard Worker   // Process the stack.
812*9880d681SAndroid Build Coastguard Worker   while (!nodesToProcess.empty()) {
813*9880d681SAndroid Build Coastguard Worker     // Grab the first item off the stack. Set the current generation, remove
814*9880d681SAndroid Build Coastguard Worker     // the node from the stack, and process it.
815*9880d681SAndroid Build Coastguard Worker     StackNode *NodeToProcess = nodesToProcess.back();
816*9880d681SAndroid Build Coastguard Worker 
817*9880d681SAndroid Build Coastguard Worker     // Initialize class members.
818*9880d681SAndroid Build Coastguard Worker     CurrentGeneration = NodeToProcess->currentGeneration();
819*9880d681SAndroid Build Coastguard Worker 
820*9880d681SAndroid Build Coastguard Worker     // Check if the node needs to be processed.
821*9880d681SAndroid Build Coastguard Worker     if (!NodeToProcess->isProcessed()) {
822*9880d681SAndroid Build Coastguard Worker       // Process the node.
823*9880d681SAndroid Build Coastguard Worker       Changed |= processNode(NodeToProcess->node());
824*9880d681SAndroid Build Coastguard Worker       NodeToProcess->childGeneration(CurrentGeneration);
825*9880d681SAndroid Build Coastguard Worker       NodeToProcess->process();
826*9880d681SAndroid Build Coastguard Worker     } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
827*9880d681SAndroid Build Coastguard Worker       // Push the next child onto the stack.
828*9880d681SAndroid Build Coastguard Worker       DomTreeNode *child = NodeToProcess->nextChild();
829*9880d681SAndroid Build Coastguard Worker       nodesToProcess.push_back(
830*9880d681SAndroid Build Coastguard Worker           new StackNode(AvailableValues, AvailableLoads, AvailableCalls,
831*9880d681SAndroid Build Coastguard Worker                         NodeToProcess->childGeneration(), child, child->begin(),
832*9880d681SAndroid Build Coastguard Worker                         child->end()));
833*9880d681SAndroid Build Coastguard Worker     } else {
834*9880d681SAndroid Build Coastguard Worker       // It has been processed, and there are no more children to process,
835*9880d681SAndroid Build Coastguard Worker       // so delete it and pop it off the stack.
836*9880d681SAndroid Build Coastguard Worker       delete NodeToProcess;
837*9880d681SAndroid Build Coastguard Worker       nodesToProcess.pop_back();
838*9880d681SAndroid Build Coastguard Worker     }
839*9880d681SAndroid Build Coastguard Worker   } // while (!nodes...)
840*9880d681SAndroid Build Coastguard Worker 
841*9880d681SAndroid Build Coastguard Worker   // Reset the current generation.
842*9880d681SAndroid Build Coastguard Worker   CurrentGeneration = LiveOutGeneration;
843*9880d681SAndroid Build Coastguard Worker 
844*9880d681SAndroid Build Coastguard Worker   return Changed;
845*9880d681SAndroid Build Coastguard Worker }
846*9880d681SAndroid Build Coastguard Worker 
run(Function & F,AnalysisManager<Function> & AM)847*9880d681SAndroid Build Coastguard Worker PreservedAnalyses EarlyCSEPass::run(Function &F,
848*9880d681SAndroid Build Coastguard Worker                                     AnalysisManager<Function> &AM) {
849*9880d681SAndroid Build Coastguard Worker   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
850*9880d681SAndroid Build Coastguard Worker   auto &TTI = AM.getResult<TargetIRAnalysis>(F);
851*9880d681SAndroid Build Coastguard Worker   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
852*9880d681SAndroid Build Coastguard Worker   auto &AC = AM.getResult<AssumptionAnalysis>(F);
853*9880d681SAndroid Build Coastguard Worker 
854*9880d681SAndroid Build Coastguard Worker   EarlyCSE CSE(TLI, TTI, DT, AC);
855*9880d681SAndroid Build Coastguard Worker 
856*9880d681SAndroid Build Coastguard Worker   if (!CSE.run())
857*9880d681SAndroid Build Coastguard Worker     return PreservedAnalyses::all();
858*9880d681SAndroid Build Coastguard Worker 
859*9880d681SAndroid Build Coastguard Worker   // CSE preserves the dominator tree because it doesn't mutate the CFG.
860*9880d681SAndroid Build Coastguard Worker   // FIXME: Bundle this with other CFG-preservation.
861*9880d681SAndroid Build Coastguard Worker   PreservedAnalyses PA;
862*9880d681SAndroid Build Coastguard Worker   PA.preserve<DominatorTreeAnalysis>();
863*9880d681SAndroid Build Coastguard Worker   PA.preserve<GlobalsAA>();
864*9880d681SAndroid Build Coastguard Worker   return PA;
865*9880d681SAndroid Build Coastguard Worker }
866*9880d681SAndroid Build Coastguard Worker 
867*9880d681SAndroid Build Coastguard Worker namespace {
868*9880d681SAndroid Build Coastguard Worker /// \brief A simple and fast domtree-based CSE pass.
869*9880d681SAndroid Build Coastguard Worker ///
870*9880d681SAndroid Build Coastguard Worker /// This pass does a simple depth-first walk over the dominator tree,
871*9880d681SAndroid Build Coastguard Worker /// eliminating trivially redundant instructions and using instsimplify to
872*9880d681SAndroid Build Coastguard Worker /// canonicalize things as it goes. It is intended to be fast and catch obvious
873*9880d681SAndroid Build Coastguard Worker /// cases so that instcombine and other passes are more effective. It is
874*9880d681SAndroid Build Coastguard Worker /// expected that a later pass of GVN will catch the interesting/hard cases.
875*9880d681SAndroid Build Coastguard Worker class EarlyCSELegacyPass : public FunctionPass {
876*9880d681SAndroid Build Coastguard Worker public:
877*9880d681SAndroid Build Coastguard Worker   static char ID;
878*9880d681SAndroid Build Coastguard Worker 
EarlyCSELegacyPass()879*9880d681SAndroid Build Coastguard Worker   EarlyCSELegacyPass() : FunctionPass(ID) {
880*9880d681SAndroid Build Coastguard Worker     initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry());
881*9880d681SAndroid Build Coastguard Worker   }
882*9880d681SAndroid Build Coastguard Worker 
runOnFunction(Function & F)883*9880d681SAndroid Build Coastguard Worker   bool runOnFunction(Function &F) override {
884*9880d681SAndroid Build Coastguard Worker     if (skipFunction(F))
885*9880d681SAndroid Build Coastguard Worker       return false;
886*9880d681SAndroid Build Coastguard Worker 
887*9880d681SAndroid Build Coastguard Worker     auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
888*9880d681SAndroid Build Coastguard Worker     auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
889*9880d681SAndroid Build Coastguard Worker     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
890*9880d681SAndroid Build Coastguard Worker     auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
891*9880d681SAndroid Build Coastguard Worker 
892*9880d681SAndroid Build Coastguard Worker     EarlyCSE CSE(TLI, TTI, DT, AC);
893*9880d681SAndroid Build Coastguard Worker 
894*9880d681SAndroid Build Coastguard Worker     return CSE.run();
895*9880d681SAndroid Build Coastguard Worker   }
896*9880d681SAndroid Build Coastguard Worker 
getAnalysisUsage(AnalysisUsage & AU) const897*9880d681SAndroid Build Coastguard Worker   void getAnalysisUsage(AnalysisUsage &AU) const override {
898*9880d681SAndroid Build Coastguard Worker     AU.addRequired<AssumptionCacheTracker>();
899*9880d681SAndroid Build Coastguard Worker     AU.addRequired<DominatorTreeWrapperPass>();
900*9880d681SAndroid Build Coastguard Worker     AU.addRequired<TargetLibraryInfoWrapperPass>();
901*9880d681SAndroid Build Coastguard Worker     AU.addRequired<TargetTransformInfoWrapperPass>();
902*9880d681SAndroid Build Coastguard Worker     AU.addPreserved<GlobalsAAWrapperPass>();
903*9880d681SAndroid Build Coastguard Worker     AU.setPreservesCFG();
904*9880d681SAndroid Build Coastguard Worker   }
905*9880d681SAndroid Build Coastguard Worker };
906*9880d681SAndroid Build Coastguard Worker }
907*9880d681SAndroid Build Coastguard Worker 
908*9880d681SAndroid Build Coastguard Worker char EarlyCSELegacyPass::ID = 0;
909*9880d681SAndroid Build Coastguard Worker 
createEarlyCSEPass()910*9880d681SAndroid Build Coastguard Worker FunctionPass *llvm::createEarlyCSEPass() { return new EarlyCSELegacyPass(); }
911*9880d681SAndroid Build Coastguard Worker 
912*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
913*9880d681SAndroid Build Coastguard Worker                       false)
914*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
915*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
916*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
917*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
918*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)
919