blob: 949300b94a787eb9ad0d1b2c529d533d1061ce82 [file] [log] [blame]
Chris Lattner704541b2011-01-02 21:47:05 +00001//===- EarlyCSE.cpp - Simple and fast CSE pass ----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs a simple dominator tree walk that eliminates trivially
11// redundant instructions.
12//
13//===----------------------------------------------------------------------===//
14
Chandler Carruthe8c686a2015-02-01 10:51:23 +000015#include "llvm/Transforms/Scalar/EarlyCSE.h"
Michael Ilseman336cb792012-10-09 16:57:38 +000016#include "llvm/ADT/Hashing.h"
Chris Lattner18ae5432011-01-02 23:04:14 +000017#include "llvm/ADT/ScopedHashTable.h"
Chris Lattner8fac5db2011-01-02 23:19:45 +000018#include "llvm/ADT/Statistic.h"
James Molloyefbba722015-09-10 10:22:12 +000019#include "llvm/Analysis/GlobalsModRef.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000020#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/Analysis/InstructionSimplify.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000022#include "llvm/Analysis/TargetLibraryInfo.h"
Chad Rosierf9327d62015-01-26 22:51:15 +000023#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000025#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Instructions.h"
Hal Finkel1e16fa32014-11-03 20:21:32 +000027#include "llvm/IR/IntrinsicInst.h"
28#include "llvm/IR/PatternMatch.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/Pass.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/RecyclingAllocator.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000032#include "llvm/Support/raw_ostream.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +000033#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Transforms/Utils/Local.h"
Lenny Maiorani9eefc812014-09-20 13:29:20 +000035#include <deque>
Chris Lattner704541b2011-01-02 21:47:05 +000036using namespace llvm;
Hal Finkel1e16fa32014-11-03 20:21:32 +000037using namespace llvm::PatternMatch;
Chris Lattner704541b2011-01-02 21:47:05 +000038
Chandler Carruth964daaa2014-04-22 02:55:47 +000039#define DEBUG_TYPE "early-cse"
40
Chris Lattner4cb36542011-01-03 03:28:23 +000041STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
42STATISTIC(NumCSE, "Number of instructions CSE'd");
Chris Lattner92bb0f92011-01-03 03:41:27 +000043STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
44STATISTIC(NumCSECall, "Number of call instructions CSE'd");
Chris Lattner9e5e9ed2011-01-03 04:17:24 +000045STATISTIC(NumDSE, "Number of trivial dead stores removed");
Chris Lattnerb9a8efc2011-01-03 03:18:43 +000046
Chris Lattner79d83062011-01-03 02:20:48 +000047//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +000048// SimpleValue
Chris Lattner79d83062011-01-03 02:20:48 +000049//===----------------------------------------------------------------------===//
50
Chris Lattner704541b2011-01-02 21:47:05 +000051namespace {
Chandler Carruth9dea5cd2015-01-24 11:44:32 +000052/// \brief Struct representing the available values in the scoped hash table.
Chandler Carruth7253bba2015-01-24 11:33:55 +000053struct SimpleValue {
54 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +000055
Chandler Carruth7253bba2015-01-24 11:33:55 +000056 SimpleValue(Instruction *I) : Inst(I) {
57 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
58 }
Nadav Rotem465834c2012-07-24 10:51:42 +000059
Chandler Carruth7253bba2015-01-24 11:33:55 +000060 bool isSentinel() const {
61 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
62 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
63 }
Nadav Rotem465834c2012-07-24 10:51:42 +000064
Chandler Carruth7253bba2015-01-24 11:33:55 +000065 static bool canHandle(Instruction *Inst) {
66 // This can only handle non-void readnone functions.
67 if (CallInst *CI = dyn_cast<CallInst>(Inst))
68 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
69 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
70 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
71 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
72 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
73 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
74 }
75};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000076}
Chris Lattner18ae5432011-01-02 23:04:14 +000077
78namespace llvm {
Chandler Carruth7253bba2015-01-24 11:33:55 +000079template <> struct DenseMapInfo<SimpleValue> {
Chris Lattner79d83062011-01-03 02:20:48 +000080 static inline SimpleValue getEmptyKey() {
Chandler Carruth7253bba2015-01-24 11:33:55 +000081 return DenseMapInfo<Instruction *>::getEmptyKey();
Chris Lattner18ae5432011-01-02 23:04:14 +000082 }
Chris Lattner79d83062011-01-03 02:20:48 +000083 static inline SimpleValue getTombstoneKey() {
Chandler Carruth7253bba2015-01-24 11:33:55 +000084 return DenseMapInfo<Instruction *>::getTombstoneKey();
Chris Lattner18ae5432011-01-02 23:04:14 +000085 }
Chris Lattner79d83062011-01-03 02:20:48 +000086 static unsigned getHashValue(SimpleValue Val);
87 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
Chris Lattner18ae5432011-01-02 23:04:14 +000088};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000089}
Chris Lattner18ae5432011-01-02 23:04:14 +000090
Chris Lattner79d83062011-01-03 02:20:48 +000091unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
Chris Lattner18ae5432011-01-02 23:04:14 +000092 Instruction *Inst = Val.Inst;
Chris Lattner02a97762011-01-03 01:10:08 +000093 // Hash in all of the operands as pointers.
Chandler Carruth7253bba2015-01-24 11:33:55 +000094 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
Michael Ilseman336cb792012-10-09 16:57:38 +000095 Value *LHS = BinOp->getOperand(0);
96 Value *RHS = BinOp->getOperand(1);
97 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
98 std::swap(LHS, RHS);
Chris Lattner02a97762011-01-03 01:10:08 +000099
Michael Ilseman336cb792012-10-09 16:57:38 +0000100 return hash_combine(BinOp->getOpcode(), LHS, RHS);
Chris Lattner02a97762011-01-03 01:10:08 +0000101 }
102
Michael Ilseman336cb792012-10-09 16:57:38 +0000103 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
104 Value *LHS = CI->getOperand(0);
105 Value *RHS = CI->getOperand(1);
106 CmpInst::Predicate Pred = CI->getPredicate();
107 if (Inst->getOperand(0) > Inst->getOperand(1)) {
108 std::swap(LHS, RHS);
109 Pred = CI->getSwappedPredicate();
110 }
111 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
112 }
113
114 if (CastInst *CI = dyn_cast<CastInst>(Inst))
115 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
116
117 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
118 return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
119 hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
120
121 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
122 return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
123 IVI->getOperand(1),
124 hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
125
126 assert((isa<CallInst>(Inst) || isa<BinaryOperator>(Inst) ||
127 isa<GetElementPtrInst>(Inst) || isa<SelectInst>(Inst) ||
128 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
Chandler Carruth7253bba2015-01-24 11:33:55 +0000129 isa<ShuffleVectorInst>(Inst)) &&
130 "Invalid/unknown instruction");
Michael Ilseman336cb792012-10-09 16:57:38 +0000131
Chris Lattner02a97762011-01-03 01:10:08 +0000132 // Mix in the opcode.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000133 return hash_combine(
134 Inst->getOpcode(),
135 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
Chris Lattner18ae5432011-01-02 23:04:14 +0000136}
137
Chris Lattner79d83062011-01-03 02:20:48 +0000138bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000139 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
140
141 if (LHS.isSentinel() || RHS.isSentinel())
142 return LHSI == RHSI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000143
Chandler Carruth7253bba2015-01-24 11:33:55 +0000144 if (LHSI->getOpcode() != RHSI->getOpcode())
145 return false;
David Majnemer9554c132016-04-22 06:37:45 +0000146 if (LHSI->isIdenticalToWhenDefined(RHSI))
Chandler Carruth7253bba2015-01-24 11:33:55 +0000147 return true;
Michael Ilseman336cb792012-10-09 16:57:38 +0000148
149 // If we're not strictly identical, we still might be a commutable instruction
150 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
151 if (!LHSBinOp->isCommutative())
152 return false;
153
Chandler Carruth7253bba2015-01-24 11:33:55 +0000154 assert(isa<BinaryOperator>(RHSI) &&
155 "same opcode, but different instruction type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000156 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
157
Michael Ilseman336cb792012-10-09 16:57:38 +0000158 // Commuted equality
159 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000160 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
Michael Ilseman336cb792012-10-09 16:57:38 +0000161 }
162 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000163 assert(isa<CmpInst>(RHSI) &&
164 "same opcode, but different instruction type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000165 CmpInst *RHSCmp = cast<CmpInst>(RHSI);
166 // Commuted equality
167 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000168 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
169 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
Michael Ilseman336cb792012-10-09 16:57:38 +0000170 }
171
172 return false;
Chris Lattner18ae5432011-01-02 23:04:14 +0000173}
174
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000175//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +0000176// CallValue
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000177//===----------------------------------------------------------------------===//
178
179namespace {
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000180/// \brief Struct representing the available call values in the scoped hash
181/// table.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000182struct CallValue {
183 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +0000184
Chandler Carruth7253bba2015-01-24 11:33:55 +0000185 CallValue(Instruction *I) : Inst(I) {
186 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
187 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000188
Chandler Carruth7253bba2015-01-24 11:33:55 +0000189 bool isSentinel() const {
190 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
191 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
192 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000193
Chandler Carruth7253bba2015-01-24 11:33:55 +0000194 static bool canHandle(Instruction *Inst) {
195 // Don't value number anything that returns void.
196 if (Inst->getType()->isVoidTy())
197 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000198
Chandler Carruth7253bba2015-01-24 11:33:55 +0000199 CallInst *CI = dyn_cast<CallInst>(Inst);
200 if (!CI || !CI->onlyReadsMemory())
201 return false;
202 return true;
203 }
204};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000205}
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000206
207namespace llvm {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000208template <> struct DenseMapInfo<CallValue> {
209 static inline CallValue getEmptyKey() {
210 return DenseMapInfo<Instruction *>::getEmptyKey();
211 }
212 static inline CallValue getTombstoneKey() {
213 return DenseMapInfo<Instruction *>::getTombstoneKey();
214 }
215 static unsigned getHashValue(CallValue Val);
216 static bool isEqual(CallValue LHS, CallValue RHS);
217};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000218}
Chandler Carruth7253bba2015-01-24 11:33:55 +0000219
Chris Lattner92bb0f92011-01-03 03:41:27 +0000220unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000221 Instruction *Inst = Val.Inst;
Benjamin Kramer6ab86b12015-02-01 12:30:59 +0000222 // Hash all of the operands as pointers and mix in the opcode.
223 return hash_combine(
224 Inst->getOpcode(),
225 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000226}
227
Chris Lattner92bb0f92011-01-03 03:41:27 +0000228bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000229 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000230 if (LHS.isSentinel() || RHS.isSentinel())
231 return LHSI == RHSI;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000232 return LHSI->isIdenticalTo(RHSI);
233}
234
Chris Lattner79d83062011-01-03 02:20:48 +0000235//===----------------------------------------------------------------------===//
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000236// EarlyCSE implementation
Chris Lattner79d83062011-01-03 02:20:48 +0000237//===----------------------------------------------------------------------===//
238
Chris Lattner18ae5432011-01-02 23:04:14 +0000239namespace {
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000240/// \brief A simple and fast domtree-based CSE pass.
241///
242/// This pass does a simple depth-first walk over the dominator tree,
243/// eliminating trivially redundant instructions and using instsimplify to
244/// canonicalize things as it goes. It is intended to be fast and catch obvious
245/// cases so that instcombine and other passes are more effective. It is
246/// expected that a later pass of GVN will catch the interesting/hard cases.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000247class EarlyCSE {
Chris Lattner704541b2011-01-02 21:47:05 +0000248public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000249 const TargetLibraryInfo &TLI;
250 const TargetTransformInfo &TTI;
251 DominatorTree &DT;
252 AssumptionCache &AC;
Chandler Carruth7253bba2015-01-24 11:33:55 +0000253 typedef RecyclingAllocator<
254 BumpPtrAllocator, ScopedHashTableVal<SimpleValue, Value *>> AllocatorTy;
255 typedef ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
Chris Lattnerd815f692011-01-03 01:42:46 +0000256 AllocatorTy> ScopedHTType;
Nadav Rotem465834c2012-07-24 10:51:42 +0000257
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000258 /// \brief A scoped hash table of the current values of all of our simple
259 /// scalar expressions.
260 ///
261 /// As we walk down the domtree, we look to see if instructions are in this:
262 /// if so, we replace them with what we find, otherwise we insert them so
263 /// that dominated values can succeed in their lookup.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000264 ScopedHTType AvailableValues;
Nadav Rotem465834c2012-07-24 10:51:42 +0000265
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000266 /// A scoped hash table of the current values of previously encounted memory
267 /// locations.
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000268 ///
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000269 /// This allows us to get efficient access to dominating loads or stores when
270 /// we have a fully redundant load. In addition to the most recent load, we
271 /// keep track of a generation count of the read, which is compared against
272 /// the current generation count. The current generation count is incremented
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000273 /// after every possibly writing memory operation, which ensures that we only
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000274 /// CSE loads with other loads that have no intervening store. Ordering
275 /// events (such as fences or atomic instructions) increment the generation
276 /// count as well; essentially, we model these as writes to all possible
277 /// locations. Note that atomic and/or volatile loads and stores can be
278 /// present the table; it is the responsibility of the consumer to inspect
279 /// the atomicity/volatility if needed.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000280 struct LoadValue {
Arnaud A. de Grandmaison859b2ac2015-10-09 09:23:01 +0000281 Value *Data;
282 unsigned Generation;
283 int MatchingId;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000284 bool IsAtomic;
285 LoadValue()
286 : Data(nullptr), Generation(0), MatchingId(-1), IsAtomic(false) {}
287 LoadValue(Value *Data, unsigned Generation, unsigned MatchingId,
288 bool IsAtomic)
289 : Data(Data), Generation(Generation), MatchingId(MatchingId),
290 IsAtomic(IsAtomic) {}
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000291 };
292 typedef RecyclingAllocator<BumpPtrAllocator,
293 ScopedHashTableVal<Value *, LoadValue>>
Chandler Carruth7253bba2015-01-24 11:33:55 +0000294 LoadMapAllocator;
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000295 typedef ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>,
296 LoadMapAllocator> LoadHTType;
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000297 LoadHTType AvailableLoads;
Nadav Rotem465834c2012-07-24 10:51:42 +0000298
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000299 /// \brief A scoped hash table of the current values of read-only call
300 /// values.
301 ///
302 /// It uses the same generation count as loads.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000303 typedef ScopedHashTable<CallValue, std::pair<Value *, unsigned>> CallHTType;
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000304 CallHTType AvailableCalls;
Nadav Rotem465834c2012-07-24 10:51:42 +0000305
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000306 /// \brief This is the current generation of the memory value.
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000307 unsigned CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000308
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000309 /// \brief Set up the EarlyCSE runner for a particular function.
Benjamin Kramer6db33382015-10-15 15:08:58 +0000310 EarlyCSE(const TargetLibraryInfo &TLI, const TargetTransformInfo &TTI,
311 DominatorTree &DT, AssumptionCache &AC)
312 : TLI(TLI), TTI(TTI), DT(DT), AC(AC), CurrentGeneration(0) {}
Chris Lattner704541b2011-01-02 21:47:05 +0000313
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000314 bool run();
Chris Lattner704541b2011-01-02 21:47:05 +0000315
316private:
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000317 // Almost a POD, but needs to call the constructors for the scoped hash
318 // tables so that a new scope gets pushed on. These are RAII so that the
319 // scope gets popped when the NodeScope is destroyed.
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000320 class NodeScope {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000321 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000322 NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
323 CallHTType &AvailableCalls)
324 : Scope(AvailableValues), LoadScope(AvailableLoads),
325 CallScope(AvailableCalls) {}
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000326
Chandler Carruth7253bba2015-01-24 11:33:55 +0000327 private:
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000328 NodeScope(const NodeScope &) = delete;
329 void operator=(const NodeScope &) = delete;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000330
331 ScopedHTType::ScopeTy Scope;
332 LoadHTType::ScopeTy LoadScope;
333 CallHTType::ScopeTy CallScope;
334 };
335
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000336 // Contains all the needed information to create a stack for doing a depth
337 // first tranversal of the tree. This includes scopes for values, loads, and
338 // calls as well as the generation. There is a child iterator so that the
339 // children do not need to be store spearately.
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000340 class StackNode {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000341 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000342 StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
343 CallHTType &AvailableCalls, unsigned cg, DomTreeNode *n,
Chandler Carruth7253bba2015-01-24 11:33:55 +0000344 DomTreeNode::iterator child, DomTreeNode::iterator end)
345 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000346 EndIter(end), Scopes(AvailableValues, AvailableLoads, AvailableCalls),
Chandler Carruth7253bba2015-01-24 11:33:55 +0000347 Processed(false) {}
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000348
349 // Accessors.
350 unsigned currentGeneration() { return CurrentGeneration; }
351 unsigned childGeneration() { return ChildGeneration; }
352 void childGeneration(unsigned generation) { ChildGeneration = generation; }
353 DomTreeNode *node() { return Node; }
354 DomTreeNode::iterator childIter() { return ChildIter; }
355 DomTreeNode *nextChild() {
356 DomTreeNode *child = *ChildIter;
357 ++ChildIter;
358 return child;
359 }
360 DomTreeNode::iterator end() { return EndIter; }
361 bool isProcessed() { return Processed; }
362 void process() { Processed = true; }
363
Chandler Carruth7253bba2015-01-24 11:33:55 +0000364 private:
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000365 StackNode(const StackNode &) = delete;
366 void operator=(const StackNode &) = delete;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000367
368 // Members.
369 unsigned CurrentGeneration;
370 unsigned ChildGeneration;
371 DomTreeNode *Node;
372 DomTreeNode::iterator ChildIter;
373 DomTreeNode::iterator EndIter;
374 NodeScope Scopes;
375 bool Processed;
376 };
377
Chad Rosierf9327d62015-01-26 22:51:15 +0000378 /// \brief Wrapper class to handle memory instructions, including loads,
379 /// stores and intrinsic loads and stores defined by the target.
380 class ParseMemoryInst {
381 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000382 ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
Philip Reames9e5e2d62015-12-07 22:41:23 +0000383 : IsTargetMemInst(false), Inst(Inst) {
384 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
385 if (TTI.getTgtMemIntrinsic(II, Info) && Info.NumMemRefs == 1)
386 IsTargetMemInst = true;
387 }
388 bool isLoad() const {
389 if (IsTargetMemInst) return Info.ReadMem;
390 return isa<LoadInst>(Inst);
391 }
392 bool isStore() const {
393 if (IsTargetMemInst) return Info.WriteMem;
394 return isa<StoreInst>(Inst);
395 }
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000396 bool isAtomic() const {
397 if (IsTargetMemInst) {
398 assert(Info.IsSimple && "need to refine IsSimple in TTI");
399 return false;
400 }
401 return Inst->isAtomic();
402 }
403 bool isUnordered() const {
404 if (IsTargetMemInst) {
405 assert(Info.IsSimple && "need to refine IsSimple in TTI");
406 return true;
407 }
408 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
409 return LI->isUnordered();
410 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
411 return SI->isUnordered();
412 }
413 // Conservative answer
414 return !Inst->isAtomic();
415 }
416
417 bool isVolatile() const {
418 if (IsTargetMemInst) {
419 assert(Info.IsSimple && "need to refine IsSimple in TTI");
420 return false;
421 }
422 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
423 return LI->isVolatile();
424 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
425 return SI->isVolatile();
426 }
427 // Conservative answer
428 return true;
429 }
430
Junmo Park80440eb2016-02-18 10:09:20 +0000431
Arnaud A. de Grandmaison6fd488b2015-10-06 13:35:30 +0000432 bool isMatchingMemLoc(const ParseMemoryInst &Inst) const {
Philip Reames9e5e2d62015-12-07 22:41:23 +0000433 return (getPointerOperand() == Inst.getPointerOperand() &&
434 getMatchingId() == Inst.getMatchingId());
Chad Rosierf9327d62015-01-26 22:51:15 +0000435 }
Philip Reames9e5e2d62015-12-07 22:41:23 +0000436 bool isValid() const { return getPointerOperand() != nullptr; }
Chad Rosierf9327d62015-01-26 22:51:15 +0000437
Chad Rosierf9327d62015-01-26 22:51:15 +0000438 // For regular (non-intrinsic) loads/stores, this is set to -1. For
439 // intrinsic loads/stores, the id is retrieved from the corresponding
440 // field in the MemIntrinsicInfo structure. That field contains
441 // non-negative values only.
Philip Reames9e5e2d62015-12-07 22:41:23 +0000442 int getMatchingId() const {
443 if (IsTargetMemInst) return Info.MatchingId;
444 return -1;
445 }
446 Value *getPointerOperand() const {
447 if (IsTargetMemInst) return Info.PtrVal;
448 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
449 return LI->getPointerOperand();
450 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
451 return SI->getPointerOperand();
452 }
453 return nullptr;
454 }
455 bool mayReadFromMemory() const {
456 if (IsTargetMemInst) return Info.ReadMem;
457 return Inst->mayReadFromMemory();
458 }
459 bool mayWriteToMemory() const {
460 if (IsTargetMemInst) return Info.WriteMem;
461 return Inst->mayWriteToMemory();
462 }
463
464 private:
465 bool IsTargetMemInst;
466 MemIntrinsicInfo Info;
467 Instruction *Inst;
Chad Rosierf9327d62015-01-26 22:51:15 +0000468 };
469
Chris Lattner18ae5432011-01-02 23:04:14 +0000470 bool processNode(DomTreeNode *Node);
Nadav Rotem465834c2012-07-24 10:51:42 +0000471
Chad Rosierf9327d62015-01-26 22:51:15 +0000472 Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const {
473 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
474 return LI;
475 else if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
476 return SI->getValueOperand();
477 assert(isa<IntrinsicInst>(Inst) && "Instruction not supported");
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000478 return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst),
479 ExpectedType);
Chad Rosierf9327d62015-01-26 22:51:15 +0000480 }
Chris Lattner704541b2011-01-02 21:47:05 +0000481};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000482}
Chris Lattner704541b2011-01-02 21:47:05 +0000483
Chris Lattner18ae5432011-01-02 23:04:14 +0000484bool EarlyCSE::processNode(DomTreeNode *Node) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000485 BasicBlock *BB = Node->getBlock();
Nadav Rotem465834c2012-07-24 10:51:42 +0000486
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000487 // If this block has a single predecessor, then the predecessor is the parent
488 // of the domtree node and all of the live out memory values are still current
489 // in this block. If this block has multiple predecessors, then they could
490 // have invalidated the live-out memory values of our parent value. For now,
491 // just be conservative and invalidate memory if this block has multiple
492 // predecessors.
Craig Topperf40110f2014-04-25 05:29:35 +0000493 if (!BB->getSinglePredecessor())
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000494 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000495
Philip Reames7c78ef72015-05-22 23:53:24 +0000496 // If this node has a single predecessor which ends in a conditional branch,
497 // we can infer the value of the branch condition given that we took this
Chad Rosierb346dcb2016-04-20 19:16:23 +0000498 // path. We need the single predecessor to ensure there's not another path
Philip Reames7c78ef72015-05-22 23:53:24 +0000499 // which reaches this block where the condition might hold a different
500 // value. Since we're adding this to the scoped hash table (like any other
501 // def), it will have been popped if we encounter a future merge block.
502 if (BasicBlock *Pred = BB->getSinglePredecessor())
503 if (auto *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
504 if (BI->isConditional())
505 if (auto *CondInst = dyn_cast<Instruction>(BI->getCondition()))
506 if (SimpleValue::canHandle(CondInst)) {
507 assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
508 auto *ConditionalConstant = (BI->getSuccessor(0) == BB) ?
509 ConstantInt::getTrue(BB->getContext()) :
510 ConstantInt::getFalse(BB->getContext());
511 AvailableValues.insert(CondInst, ConditionalConstant);
512 DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
513 << CondInst->getName() << "' as " << *ConditionalConstant
514 << " in " << BB->getName() << "\n");
515 // Replace all dominated uses with the known value
516 replaceDominatedUsesWith(CondInst, ConditionalConstant, DT,
517 BasicBlockEdge(Pred, BB));
518 }
519
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000520 /// LastStore - Keep track of the last non-volatile store that we saw... for
521 /// as long as there in no instruction that reads memory. If we see a store
522 /// to the same location, we delete the dead store. This zaps trivial dead
523 /// stores which can occur in bitfield code among other things.
Chad Rosierf9327d62015-01-26 22:51:15 +0000524 Instruction *LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000525
Chris Lattner18ae5432011-01-02 23:04:14 +0000526 bool Changed = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000527 const DataLayout &DL = BB->getModule()->getDataLayout();
Chris Lattner18ae5432011-01-02 23:04:14 +0000528
529 // See if any instructions in the block can be eliminated. If so, do it. If
530 // not, add them to AvailableValues.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000531 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +0000532 Instruction *Inst = &*I++;
Nadav Rotem465834c2012-07-24 10:51:42 +0000533
Chris Lattner18ae5432011-01-02 23:04:14 +0000534 // Dead instructions should just be removed.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000535 if (isInstructionTriviallyDead(Inst, &TLI)) {
Chris Lattner8fac5db2011-01-02 23:19:45 +0000536 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
Chris Lattner18ae5432011-01-02 23:04:14 +0000537 Inst->eraseFromParent();
538 Changed = true;
Chris Lattner8fac5db2011-01-02 23:19:45 +0000539 ++NumSimplify;
Chris Lattner18ae5432011-01-02 23:04:14 +0000540 continue;
541 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000542
Hal Finkel1e16fa32014-11-03 20:21:32 +0000543 // Skip assume intrinsics, they don't really have side effects (although
544 // they're marked as such to ensure preservation of control dependencies),
545 // and this pass will not disturb any of the assumption's control
546 // dependencies.
547 if (match(Inst, m_Intrinsic<Intrinsic::assume>())) {
548 DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n');
549 continue;
550 }
551
Chris Lattner18ae5432011-01-02 23:04:14 +0000552 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
553 // its simpler value.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000554 if (Value *V = SimplifyInstruction(Inst, DL, &TLI, &DT, &AC)) {
Chris Lattner8fac5db2011-01-02 23:19:45 +0000555 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
Chris Lattner18ae5432011-01-02 23:04:14 +0000556 Inst->replaceAllUsesWith(V);
557 Inst->eraseFromParent();
558 Changed = true;
Chris Lattner8fac5db2011-01-02 23:19:45 +0000559 ++NumSimplify;
Chris Lattner18ae5432011-01-02 23:04:14 +0000560 continue;
561 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000562
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000563 // If this is a simple instruction that we can value number, process it.
564 if (SimpleValue::canHandle(Inst)) {
565 // See if the instruction has an available value. If so, use it.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000566 if (Value *V = AvailableValues.lookup(Inst)) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000567 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
David Majnemer9554c132016-04-22 06:37:45 +0000568 if (auto *I = dyn_cast<Instruction>(V))
569 I->andIRFlags(Inst);
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000570 Inst->replaceAllUsesWith(V);
571 Inst->eraseFromParent();
572 Changed = true;
573 ++NumCSE;
574 continue;
575 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000576
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000577 // Otherwise, just remember that this value is available.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000578 AvailableValues.insert(Inst, Inst);
Chris Lattner18ae5432011-01-02 23:04:14 +0000579 continue;
580 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000581
Chad Rosierf9327d62015-01-26 22:51:15 +0000582 ParseMemoryInst MemInst(Inst, TTI);
Chris Lattner92bb0f92011-01-03 03:41:27 +0000583 // If this is a non-volatile load, process it.
Chad Rosierf9327d62015-01-26 22:51:15 +0000584 if (MemInst.isValid() && MemInst.isLoad()) {
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000585 // (conservatively) we can't peak past the ordering implied by this
586 // operation, but we can add this load to our set of available values
587 if (MemInst.isVolatile() || !MemInst.isUnordered()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000588 LastStore = nullptr;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000589 ++CurrentGeneration;
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000590 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000591
Chris Lattner92bb0f92011-01-03 03:41:27 +0000592 // If we have an available version of this load, and if it is the right
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000593 // generation, replace this instruction.
Philip Reames9e5e2d62015-12-07 22:41:23 +0000594 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
Arnaud A. de Grandmaison859b2ac2015-10-09 09:23:01 +0000595 if (InVal.Data != nullptr && InVal.Generation == CurrentGeneration &&
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000596 InVal.MatchingId == MemInst.getMatchingId() &&
597 // We don't yet handle removing loads with ordering of any kind.
598 !MemInst.isVolatile() && MemInst.isUnordered() &&
599 // We can't replace an atomic load with one which isn't also atomic.
600 InVal.IsAtomic >= MemInst.isAtomic()) {
Arnaud A. de Grandmaison859b2ac2015-10-09 09:23:01 +0000601 Value *Op = getOrCreateResult(InVal.Data, Inst->getType());
Chad Rosierf9327d62015-01-26 22:51:15 +0000602 if (Op != nullptr) {
603 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst
Arnaud A. de Grandmaison859b2ac2015-10-09 09:23:01 +0000604 << " to: " << *InVal.Data << '\n');
Chad Rosierf9327d62015-01-26 22:51:15 +0000605 if (!Inst->use_empty())
606 Inst->replaceAllUsesWith(Op);
607 Inst->eraseFromParent();
608 Changed = true;
609 ++NumCSELoad;
610 continue;
611 }
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000612 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000613
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000614 // Otherwise, remember that we have this instruction.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000615 AvailableLoads.insert(
Philip Reames9e5e2d62015-12-07 22:41:23 +0000616 MemInst.getPointerOperand(),
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000617 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
618 MemInst.isAtomic()));
Craig Topperf40110f2014-04-25 05:29:35 +0000619 LastStore = nullptr;
Chris Lattner92bb0f92011-01-03 03:41:27 +0000620 continue;
621 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000622
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000623 // If this instruction may read from memory, forget LastStore.
Chad Rosierf9327d62015-01-26 22:51:15 +0000624 // Load/store intrinsics will indicate both a read and a write to
625 // memory. The target may override this (e.g. so that a store intrinsic
626 // does not read from memory, and thus will be treated the same as a
627 // regular store for commoning purposes).
628 if (Inst->mayReadFromMemory() &&
629 !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
Craig Topperf40110f2014-04-25 05:29:35 +0000630 LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000631
Chris Lattner92bb0f92011-01-03 03:41:27 +0000632 // If this is a read-only call, process it.
633 if (CallValue::canHandle(Inst)) {
634 // If we have an available version of this call, and if it is the right
635 // generation, replace this instruction.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000636 std::pair<Value *, unsigned> InVal = AvailableCalls.lookup(Inst);
Craig Topperf40110f2014-04-25 05:29:35 +0000637 if (InVal.first != nullptr && InVal.second == CurrentGeneration) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000638 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst
639 << " to: " << *InVal.first << '\n');
640 if (!Inst->use_empty())
641 Inst->replaceAllUsesWith(InVal.first);
Chris Lattner92bb0f92011-01-03 03:41:27 +0000642 Inst->eraseFromParent();
643 Changed = true;
644 ++NumCSECall;
645 continue;
646 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000647
Chris Lattner92bb0f92011-01-03 03:41:27 +0000648 // Otherwise, remember that we have this instruction.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000649 AvailableCalls.insert(
Chandler Carruth7253bba2015-01-24 11:33:55 +0000650 Inst, std::pair<Value *, unsigned>(Inst, CurrentGeneration));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000651 continue;
652 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000653
Philip Reamesdfd890d2015-08-27 01:32:33 +0000654 // A release fence requires that all stores complete before it, but does
655 // not prevent the reordering of following loads 'before' the fence. As a
656 // result, we don't need to consider it as writing to memory and don't need
657 // to advance the generation. We do need to prevent DSE across the fence,
658 // but that's handled above.
659 if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
JF Bastien800f87a2016-04-06 21:19:33 +0000660 if (FI->getOrdering() == AtomicOrdering::Release) {
Philip Reamesdfd890d2015-08-27 01:32:33 +0000661 assert(Inst->mayReadFromMemory() && "relied on to prevent DSE above");
662 continue;
663 }
664
Philip Reamesae1f265b2015-12-16 01:01:30 +0000665 // write back DSE - If we write back the same value we just loaded from
666 // the same location and haven't passed any intervening writes or ordering
667 // operations, we can remove the write. The primary benefit is in allowing
668 // the available load table to remain valid and value forward past where
669 // the store originally was.
670 if (MemInst.isValid() && MemInst.isStore()) {
671 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
672 if (InVal.Data &&
673 InVal.Data == getOrCreateResult(Inst, InVal.Data->getType()) &&
674 InVal.Generation == CurrentGeneration &&
675 InVal.MatchingId == MemInst.getMatchingId() &&
676 // We don't yet handle removing stores with ordering of any kind.
677 !MemInst.isVolatile() && MemInst.isUnordered()) {
678 assert((!LastStore ||
679 ParseMemoryInst(LastStore, TTI).getPointerOperand() ==
680 MemInst.getPointerOperand()) &&
681 "can't have an intervening store!");
682 DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << *Inst << '\n');
683 Inst->eraseFromParent();
684 Changed = true;
685 ++NumDSE;
686 // We can avoid incrementing the generation count since we were able
687 // to eliminate this store.
688 continue;
689 }
690 }
691
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000692 // Okay, this isn't something we can CSE at all. Check to see if it is
693 // something that could modify memory. If so, our available memory values
694 // cannot be used so bump the generation count.
Chris Lattnere0e32a92011-01-03 03:46:34 +0000695 if (Inst->mayWriteToMemory()) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000696 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000697
Chad Rosierf9327d62015-01-26 22:51:15 +0000698 if (MemInst.isValid() && MemInst.isStore()) {
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000699 // We do a trivial form of DSE if there are two stores to the same
Philip Reames15145fb2015-12-17 18:50:50 +0000700 // location with no intervening loads. Delete the earlier store.
701 // At the moment, we don't remove ordered stores, but do remove
702 // unordered atomic stores. There's no special requirement (for
703 // unordered atomics) about removing atomic stores only in favor of
704 // other atomic stores since we we're going to execute the non-atomic
705 // one anyway and the atomic one might never have become visible.
Chad Rosierf9327d62015-01-26 22:51:15 +0000706 if (LastStore) {
707 ParseMemoryInst LastStoreMemInst(LastStore, TTI);
Philip Reames15145fb2015-12-17 18:50:50 +0000708 assert(LastStoreMemInst.isUnordered() &&
709 !LastStoreMemInst.isVolatile() &&
710 "Violated invariant");
Chad Rosierf9327d62015-01-26 22:51:15 +0000711 if (LastStoreMemInst.isMatchingMemLoc(MemInst)) {
712 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
713 << " due to: " << *Inst << '\n');
714 LastStore->eraseFromParent();
715 Changed = true;
716 ++NumDSE;
717 LastStore = nullptr;
718 }
Philip Reames018dbf12014-11-18 17:46:32 +0000719 // fallthrough - we can exploit information about this store
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000720 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000721
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000722 // Okay, we just invalidated anything we knew about loaded values. Try
723 // to salvage *something* by remembering that the stored value is a live
724 // version of the pointer. It is safe to forward from volatile stores
725 // to non-volatile loads, so we don't have to check for volatility of
726 // the store.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000727 AvailableLoads.insert(
Philip Reames9e5e2d62015-12-07 22:41:23 +0000728 MemInst.getPointerOperand(),
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000729 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
730 MemInst.isAtomic()));
Nadav Rotem465834c2012-07-24 10:51:42 +0000731
Philip Reames15145fb2015-12-17 18:50:50 +0000732 // Remember that this was the last unordered store we saw for DSE. We
733 // don't yet handle DSE on ordered or volatile stores since we don't
734 // have a good way to model the ordering requirement for following
735 // passes once the store is removed. We could insert a fence, but
736 // since fences are slightly stronger than stores in their ordering,
737 // it's not clear this is a profitable transform. Another option would
738 // be to merge the ordering with that of the post dominating store.
739 if (MemInst.isUnordered() && !MemInst.isVolatile())
Chad Rosierf9327d62015-01-26 22:51:15 +0000740 LastStore = Inst;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000741 else
742 LastStore = nullptr;
Chris Lattnere0e32a92011-01-03 03:46:34 +0000743 }
744 }
Chris Lattner18ae5432011-01-02 23:04:14 +0000745 }
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000746
Chris Lattner18ae5432011-01-02 23:04:14 +0000747 return Changed;
Chris Lattner704541b2011-01-02 21:47:05 +0000748}
Chris Lattner18ae5432011-01-02 23:04:14 +0000749
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000750bool EarlyCSE::run() {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000751 // Note, deque is being used here because there is significant performance
752 // gains over vector when the container becomes very large due to the
753 // specific access patterns. For more information see the mailing list
754 // discussion on this:
Tanya Lattner0d28f802015-08-05 03:51:17 +0000755 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
Lenny Maiorani9eefc812014-09-20 13:29:20 +0000756 std::deque<StackNode *> nodesToProcess;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000757
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000758 bool Changed = false;
759
760 // Process the root node.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000761 nodesToProcess.push_back(new StackNode(
762 AvailableValues, AvailableLoads, AvailableCalls, CurrentGeneration,
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000763 DT.getRootNode(), DT.getRootNode()->begin(), DT.getRootNode()->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000764
765 // Save the current generation.
766 unsigned LiveOutGeneration = CurrentGeneration;
767
768 // Process the stack.
769 while (!nodesToProcess.empty()) {
770 // Grab the first item off the stack. Set the current generation, remove
771 // the node from the stack, and process it.
Michael Gottesman2bf01732013-12-05 18:42:12 +0000772 StackNode *NodeToProcess = nodesToProcess.back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000773
774 // Initialize class members.
775 CurrentGeneration = NodeToProcess->currentGeneration();
776
777 // Check if the node needs to be processed.
778 if (!NodeToProcess->isProcessed()) {
779 // Process the node.
780 Changed |= processNode(NodeToProcess->node());
781 NodeToProcess->childGeneration(CurrentGeneration);
782 NodeToProcess->process();
783 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
784 // Push the next child onto the stack.
785 DomTreeNode *child = NodeToProcess->nextChild();
Michael Gottesman2bf01732013-12-05 18:42:12 +0000786 nodesToProcess.push_back(
Chandler Carruth7253bba2015-01-24 11:33:55 +0000787 new StackNode(AvailableValues, AvailableLoads, AvailableCalls,
788 NodeToProcess->childGeneration(), child, child->begin(),
789 child->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000790 } else {
791 // It has been processed, and there are no more children to process,
792 // so delete it and pop it off the stack.
793 delete NodeToProcess;
Michael Gottesman2bf01732013-12-05 18:42:12 +0000794 nodesToProcess.pop_back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000795 }
796 } // while (!nodes...)
797
798 // Reset the current generation.
799 CurrentGeneration = LiveOutGeneration;
800
801 return Changed;
Chris Lattner18ae5432011-01-02 23:04:14 +0000802}
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000803
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000804PreservedAnalyses EarlyCSEPass::run(Function &F,
Chandler Carruthb47f8012016-03-11 11:05:24 +0000805 AnalysisManager<Function> &AM) {
806 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
807 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
808 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
809 auto &AC = AM.getResult<AssumptionAnalysis>(F);
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000810
Benjamin Kramer6db33382015-10-15 15:08:58 +0000811 EarlyCSE CSE(TLI, TTI, DT, AC);
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000812
813 if (!CSE.run())
814 return PreservedAnalyses::all();
815
816 // CSE preserves the dominator tree because it doesn't mutate the CFG.
817 // FIXME: Bundle this with other CFG-preservation.
818 PreservedAnalyses PA;
819 PA.preserve<DominatorTreeAnalysis>();
820 return PA;
821}
822
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000823namespace {
824/// \brief A simple and fast domtree-based CSE pass.
825///
826/// This pass does a simple depth-first walk over the dominator tree,
827/// eliminating trivially redundant instructions and using instsimplify to
828/// canonicalize things as it goes. It is intended to be fast and catch obvious
829/// cases so that instcombine and other passes are more effective. It is
830/// expected that a later pass of GVN will catch the interesting/hard cases.
831class EarlyCSELegacyPass : public FunctionPass {
832public:
833 static char ID;
834
835 EarlyCSELegacyPass() : FunctionPass(ID) {
836 initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry());
837 }
838
839 bool runOnFunction(Function &F) override {
Vedant Kumar6013f452016-04-22 06:51:37 +0000840 if (skipOptnoneFunction(F))
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000841 return false;
842
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000843 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000844 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000845 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
846 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
847
Benjamin Kramer6db33382015-10-15 15:08:58 +0000848 EarlyCSE CSE(TLI, TTI, DT, AC);
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000849
850 return CSE.run();
851 }
852
853 void getAnalysisUsage(AnalysisUsage &AU) const override {
854 AU.addRequired<AssumptionCacheTracker>();
855 AU.addRequired<DominatorTreeWrapperPass>();
856 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000857 AU.addRequired<TargetTransformInfoWrapperPass>();
James Molloyefbba722015-09-10 10:22:12 +0000858 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000859 AU.setPreservesCFG();
860 }
861};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000862}
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000863
864char EarlyCSELegacyPass::ID = 0;
865
866FunctionPass *llvm::createEarlyCSEPass() { return new EarlyCSELegacyPass(); }
867
868INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
869 false)
Chandler Carruth705b1852015-01-31 03:43:40 +0000870INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000871INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
872INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
873INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
874INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)