blob: cb02b2cbc7ebb62b6d6b9095f4c0b8cd6002b205 [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"
Chandler Carruth66b31302015-01-04 12:03:27 +000019#include "llvm/Analysis/AssumptionCache.h"
Geoff Berry354fac22016-04-28 14:59:27 +000020#include "llvm/Analysis/GlobalsModRef.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"
Geoff Berry8d846052016-08-31 19:24:10 +000035#include "llvm/Transforms/Utils/MemorySSA.h"
Lenny Maiorani9eefc812014-09-20 13:29:20 +000036#include <deque>
Chris Lattner704541b2011-01-02 21:47:05 +000037using namespace llvm;
Hal Finkel1e16fa32014-11-03 20:21:32 +000038using namespace llvm::PatternMatch;
Chris Lattner704541b2011-01-02 21:47:05 +000039
Chandler Carruth964daaa2014-04-22 02:55:47 +000040#define DEBUG_TYPE "early-cse"
41
Chris Lattner4cb36542011-01-03 03:28:23 +000042STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
43STATISTIC(NumCSE, "Number of instructions CSE'd");
Chad Rosier1a4bc112016-04-22 18:47:21 +000044STATISTIC(NumCSECVP, "Number of compare instructions CVP'd");
Chris Lattner92bb0f92011-01-03 03:41:27 +000045STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
46STATISTIC(NumCSECall, "Number of call instructions CSE'd");
Chris Lattner9e5e9ed2011-01-03 04:17:24 +000047STATISTIC(NumDSE, "Number of trivial dead stores removed");
Chris Lattnerb9a8efc2011-01-03 03:18:43 +000048
Chris Lattner79d83062011-01-03 02:20:48 +000049//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +000050// SimpleValue
Chris Lattner79d83062011-01-03 02:20:48 +000051//===----------------------------------------------------------------------===//
52
Chris Lattner704541b2011-01-02 21:47:05 +000053namespace {
Chandler Carruth9dea5cd2015-01-24 11:44:32 +000054/// \brief Struct representing the available values in the scoped hash table.
Chandler Carruth7253bba2015-01-24 11:33:55 +000055struct SimpleValue {
56 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +000057
Chandler Carruth7253bba2015-01-24 11:33:55 +000058 SimpleValue(Instruction *I) : Inst(I) {
59 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
60 }
Nadav Rotem465834c2012-07-24 10:51:42 +000061
Chandler Carruth7253bba2015-01-24 11:33:55 +000062 bool isSentinel() const {
63 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
64 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
65 }
Nadav Rotem465834c2012-07-24 10:51:42 +000066
Chandler Carruth7253bba2015-01-24 11:33:55 +000067 static bool canHandle(Instruction *Inst) {
68 // This can only handle non-void readnone functions.
69 if (CallInst *CI = dyn_cast<CallInst>(Inst))
70 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
71 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
72 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
73 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
74 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
75 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
76 }
77};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000078}
Chris Lattner18ae5432011-01-02 23:04:14 +000079
80namespace llvm {
Chandler Carruth7253bba2015-01-24 11:33:55 +000081template <> struct DenseMapInfo<SimpleValue> {
Chris Lattner79d83062011-01-03 02:20:48 +000082 static inline SimpleValue getEmptyKey() {
Chandler Carruth7253bba2015-01-24 11:33:55 +000083 return DenseMapInfo<Instruction *>::getEmptyKey();
Chris Lattner18ae5432011-01-02 23:04:14 +000084 }
Chris Lattner79d83062011-01-03 02:20:48 +000085 static inline SimpleValue getTombstoneKey() {
Chandler Carruth7253bba2015-01-24 11:33:55 +000086 return DenseMapInfo<Instruction *>::getTombstoneKey();
Chris Lattner18ae5432011-01-02 23:04:14 +000087 }
Chris Lattner79d83062011-01-03 02:20:48 +000088 static unsigned getHashValue(SimpleValue Val);
89 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
Chris Lattner18ae5432011-01-02 23:04:14 +000090};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000091}
Chris Lattner18ae5432011-01-02 23:04:14 +000092
Chris Lattner79d83062011-01-03 02:20:48 +000093unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
Chris Lattner18ae5432011-01-02 23:04:14 +000094 Instruction *Inst = Val.Inst;
Chris Lattner02a97762011-01-03 01:10:08 +000095 // Hash in all of the operands as pointers.
Chandler Carruth7253bba2015-01-24 11:33:55 +000096 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
Michael Ilseman336cb792012-10-09 16:57:38 +000097 Value *LHS = BinOp->getOperand(0);
98 Value *RHS = BinOp->getOperand(1);
99 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
100 std::swap(LHS, RHS);
Chris Lattner02a97762011-01-03 01:10:08 +0000101
Michael Ilseman336cb792012-10-09 16:57:38 +0000102 return hash_combine(BinOp->getOpcode(), LHS, RHS);
Chris Lattner02a97762011-01-03 01:10:08 +0000103 }
104
Michael Ilseman336cb792012-10-09 16:57:38 +0000105 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
106 Value *LHS = CI->getOperand(0);
107 Value *RHS = CI->getOperand(1);
108 CmpInst::Predicate Pred = CI->getPredicate();
109 if (Inst->getOperand(0) > Inst->getOperand(1)) {
110 std::swap(LHS, RHS);
111 Pred = CI->getSwappedPredicate();
112 }
113 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
114 }
115
116 if (CastInst *CI = dyn_cast<CastInst>(Inst))
117 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
118
119 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
120 return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
121 hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
122
123 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
124 return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
125 IVI->getOperand(1),
126 hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
127
128 assert((isa<CallInst>(Inst) || isa<BinaryOperator>(Inst) ||
129 isa<GetElementPtrInst>(Inst) || isa<SelectInst>(Inst) ||
130 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
Chandler Carruth7253bba2015-01-24 11:33:55 +0000131 isa<ShuffleVectorInst>(Inst)) &&
132 "Invalid/unknown instruction");
Michael Ilseman336cb792012-10-09 16:57:38 +0000133
Chris Lattner02a97762011-01-03 01:10:08 +0000134 // Mix in the opcode.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000135 return hash_combine(
136 Inst->getOpcode(),
137 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
Chris Lattner18ae5432011-01-02 23:04:14 +0000138}
139
Chris Lattner79d83062011-01-03 02:20:48 +0000140bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000141 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
142
143 if (LHS.isSentinel() || RHS.isSentinel())
144 return LHSI == RHSI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000145
Chandler Carruth7253bba2015-01-24 11:33:55 +0000146 if (LHSI->getOpcode() != RHSI->getOpcode())
147 return false;
David Majnemer9554c132016-04-22 06:37:45 +0000148 if (LHSI->isIdenticalToWhenDefined(RHSI))
Chandler Carruth7253bba2015-01-24 11:33:55 +0000149 return true;
Michael Ilseman336cb792012-10-09 16:57:38 +0000150
151 // If we're not strictly identical, we still might be a commutable instruction
152 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
153 if (!LHSBinOp->isCommutative())
154 return false;
155
Chandler Carruth7253bba2015-01-24 11:33:55 +0000156 assert(isa<BinaryOperator>(RHSI) &&
157 "same opcode, but different instruction type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000158 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
159
Michael Ilseman336cb792012-10-09 16:57:38 +0000160 // Commuted equality
161 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000162 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
Michael Ilseman336cb792012-10-09 16:57:38 +0000163 }
164 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000165 assert(isa<CmpInst>(RHSI) &&
166 "same opcode, but different instruction type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000167 CmpInst *RHSCmp = cast<CmpInst>(RHSI);
168 // Commuted equality
169 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000170 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
171 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
Michael Ilseman336cb792012-10-09 16:57:38 +0000172 }
173
174 return false;
Chris Lattner18ae5432011-01-02 23:04:14 +0000175}
176
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000177//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +0000178// CallValue
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000179//===----------------------------------------------------------------------===//
180
181namespace {
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000182/// \brief Struct representing the available call values in the scoped hash
183/// table.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000184struct CallValue {
185 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +0000186
Chandler Carruth7253bba2015-01-24 11:33:55 +0000187 CallValue(Instruction *I) : Inst(I) {
188 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
189 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000190
Chandler Carruth7253bba2015-01-24 11:33:55 +0000191 bool isSentinel() const {
192 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
193 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
194 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000195
Chandler Carruth7253bba2015-01-24 11:33:55 +0000196 static bool canHandle(Instruction *Inst) {
197 // Don't value number anything that returns void.
198 if (Inst->getType()->isVoidTy())
199 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000200
Chandler Carruth7253bba2015-01-24 11:33:55 +0000201 CallInst *CI = dyn_cast<CallInst>(Inst);
202 if (!CI || !CI->onlyReadsMemory())
203 return false;
204 return true;
205 }
206};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000207}
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000208
209namespace llvm {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000210template <> struct DenseMapInfo<CallValue> {
211 static inline CallValue getEmptyKey() {
212 return DenseMapInfo<Instruction *>::getEmptyKey();
213 }
214 static inline CallValue getTombstoneKey() {
215 return DenseMapInfo<Instruction *>::getTombstoneKey();
216 }
217 static unsigned getHashValue(CallValue Val);
218 static bool isEqual(CallValue LHS, CallValue RHS);
219};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000220}
Chandler Carruth7253bba2015-01-24 11:33:55 +0000221
Chris Lattner92bb0f92011-01-03 03:41:27 +0000222unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000223 Instruction *Inst = Val.Inst;
Benjamin Kramer6ab86b12015-02-01 12:30:59 +0000224 // Hash all of the operands as pointers and mix in the opcode.
225 return hash_combine(
226 Inst->getOpcode(),
227 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000228}
229
Chris Lattner92bb0f92011-01-03 03:41:27 +0000230bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000231 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000232 if (LHS.isSentinel() || RHS.isSentinel())
233 return LHSI == RHSI;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000234 return LHSI->isIdenticalTo(RHSI);
235}
236
Chris Lattner79d83062011-01-03 02:20:48 +0000237//===----------------------------------------------------------------------===//
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000238// EarlyCSE implementation
Chris Lattner79d83062011-01-03 02:20:48 +0000239//===----------------------------------------------------------------------===//
240
Chris Lattner18ae5432011-01-02 23:04:14 +0000241namespace {
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000242/// \brief A simple and fast domtree-based CSE pass.
243///
244/// This pass does a simple depth-first walk over the dominator tree,
245/// eliminating trivially redundant instructions and using instsimplify to
246/// canonicalize things as it goes. It is intended to be fast and catch obvious
247/// cases so that instcombine and other passes are more effective. It is
248/// expected that a later pass of GVN will catch the interesting/hard cases.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000249class EarlyCSE {
Chris Lattner704541b2011-01-02 21:47:05 +0000250public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000251 const TargetLibraryInfo &TLI;
252 const TargetTransformInfo &TTI;
253 DominatorTree &DT;
254 AssumptionCache &AC;
Geoff Berry8d846052016-08-31 19:24:10 +0000255 MemorySSA *MSSA;
Chandler Carruth7253bba2015-01-24 11:33:55 +0000256 typedef RecyclingAllocator<
257 BumpPtrAllocator, ScopedHashTableVal<SimpleValue, Value *>> AllocatorTy;
258 typedef ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
Chris Lattnerd815f692011-01-03 01:42:46 +0000259 AllocatorTy> ScopedHTType;
Nadav Rotem465834c2012-07-24 10:51:42 +0000260
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000261 /// \brief A scoped hash table of the current values of all of our simple
262 /// scalar expressions.
263 ///
264 /// As we walk down the domtree, we look to see if instructions are in this:
265 /// if so, we replace them with what we find, otherwise we insert them so
266 /// that dominated values can succeed in their lookup.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000267 ScopedHTType AvailableValues;
Nadav Rotem465834c2012-07-24 10:51:42 +0000268
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000269 /// A scoped hash table of the current values of previously encounted memory
270 /// locations.
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000271 ///
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000272 /// This allows us to get efficient access to dominating loads or stores when
273 /// we have a fully redundant load. In addition to the most recent load, we
274 /// keep track of a generation count of the read, which is compared against
275 /// the current generation count. The current generation count is incremented
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000276 /// after every possibly writing memory operation, which ensures that we only
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000277 /// CSE loads with other loads that have no intervening store. Ordering
278 /// events (such as fences or atomic instructions) increment the generation
279 /// count as well; essentially, we model these as writes to all possible
280 /// locations. Note that atomic and/or volatile loads and stores can be
281 /// present the table; it is the responsibility of the consumer to inspect
282 /// the atomicity/volatility if needed.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000283 struct LoadValue {
Philip Reames32b55182016-05-06 01:13:58 +0000284 Instruction *DefInst;
Arnaud A. de Grandmaison859b2ac2015-10-09 09:23:01 +0000285 unsigned Generation;
286 int MatchingId;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000287 bool IsAtomic;
Sanjoy Das07c65212016-06-16 20:47:57 +0000288 bool IsInvariant;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000289 LoadValue()
Sanjoy Das07c65212016-06-16 20:47:57 +0000290 : DefInst(nullptr), Generation(0), MatchingId(-1), IsAtomic(false),
291 IsInvariant(false) {}
Geoff Berry5ae272c2016-04-28 15:22:37 +0000292 LoadValue(Instruction *Inst, unsigned Generation, unsigned MatchingId,
Sanjoy Das07c65212016-06-16 20:47:57 +0000293 bool IsAtomic, bool IsInvariant)
294 : DefInst(Inst), Generation(Generation), MatchingId(MatchingId),
295 IsAtomic(IsAtomic), IsInvariant(IsInvariant) {}
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000296 };
297 typedef RecyclingAllocator<BumpPtrAllocator,
298 ScopedHashTableVal<Value *, LoadValue>>
Chandler Carruth7253bba2015-01-24 11:33:55 +0000299 LoadMapAllocator;
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000300 typedef ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>,
301 LoadMapAllocator> LoadHTType;
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000302 LoadHTType AvailableLoads;
Nadav Rotem465834c2012-07-24 10:51:42 +0000303
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000304 /// \brief A scoped hash table of the current values of read-only call
305 /// values.
306 ///
307 /// It uses the same generation count as loads.
Geoff Berry2f64c202016-05-13 17:54:58 +0000308 typedef ScopedHashTable<CallValue, std::pair<Instruction *, unsigned>>
309 CallHTType;
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000310 CallHTType AvailableCalls;
Nadav Rotem465834c2012-07-24 10:51:42 +0000311
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000312 /// \brief This is the current generation of the memory value.
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000313 unsigned CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000314
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000315 /// \brief Set up the EarlyCSE runner for a particular function.
Benjamin Kramer6db33382015-10-15 15:08:58 +0000316 EarlyCSE(const TargetLibraryInfo &TLI, const TargetTransformInfo &TTI,
Geoff Berry8d846052016-08-31 19:24:10 +0000317 DominatorTree &DT, AssumptionCache &AC, MemorySSA *MSSA)
318 : TLI(TLI), TTI(TTI), DT(DT), AC(AC), MSSA(MSSA), CurrentGeneration(0) {}
Chris Lattner704541b2011-01-02 21:47:05 +0000319
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000320 bool run();
Chris Lattner704541b2011-01-02 21:47:05 +0000321
322private:
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000323 // Almost a POD, but needs to call the constructors for the scoped hash
324 // tables so that a new scope gets pushed on. These are RAII so that the
325 // scope gets popped when the NodeScope is destroyed.
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000326 class NodeScope {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000327 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000328 NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
329 CallHTType &AvailableCalls)
330 : Scope(AvailableValues), LoadScope(AvailableLoads),
331 CallScope(AvailableCalls) {}
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000332
Chandler Carruth7253bba2015-01-24 11:33:55 +0000333 private:
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000334 NodeScope(const NodeScope &) = delete;
335 void operator=(const NodeScope &) = delete;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000336
337 ScopedHTType::ScopeTy Scope;
338 LoadHTType::ScopeTy LoadScope;
339 CallHTType::ScopeTy CallScope;
340 };
341
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000342 // Contains all the needed information to create a stack for doing a depth
Nick Lewyckyedd0a702016-09-07 01:49:41 +0000343 // first traversal of the tree. This includes scopes for values, loads, and
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000344 // calls as well as the generation. There is a child iterator so that the
Sanjoy Das5253a082016-04-27 01:44:31 +0000345 // children do not need to be store separately.
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000346 class StackNode {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000347 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000348 StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
349 CallHTType &AvailableCalls, unsigned cg, DomTreeNode *n,
Chandler Carruth7253bba2015-01-24 11:33:55 +0000350 DomTreeNode::iterator child, DomTreeNode::iterator end)
351 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000352 EndIter(end), Scopes(AvailableValues, AvailableLoads, AvailableCalls),
Chandler Carruth7253bba2015-01-24 11:33:55 +0000353 Processed(false) {}
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000354
355 // Accessors.
356 unsigned currentGeneration() { return CurrentGeneration; }
357 unsigned childGeneration() { return ChildGeneration; }
358 void childGeneration(unsigned generation) { ChildGeneration = generation; }
359 DomTreeNode *node() { return Node; }
360 DomTreeNode::iterator childIter() { return ChildIter; }
361 DomTreeNode *nextChild() {
362 DomTreeNode *child = *ChildIter;
363 ++ChildIter;
364 return child;
365 }
366 DomTreeNode::iterator end() { return EndIter; }
367 bool isProcessed() { return Processed; }
368 void process() { Processed = true; }
369
Chandler Carruth7253bba2015-01-24 11:33:55 +0000370 private:
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000371 StackNode(const StackNode &) = delete;
372 void operator=(const StackNode &) = delete;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000373
374 // Members.
375 unsigned CurrentGeneration;
376 unsigned ChildGeneration;
377 DomTreeNode *Node;
378 DomTreeNode::iterator ChildIter;
379 DomTreeNode::iterator EndIter;
380 NodeScope Scopes;
381 bool Processed;
382 };
383
Chad Rosierf9327d62015-01-26 22:51:15 +0000384 /// \brief Wrapper class to handle memory instructions, including loads,
385 /// stores and intrinsic loads and stores defined by the target.
386 class ParseMemoryInst {
387 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000388 ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
Philip Reames9e5e2d62015-12-07 22:41:23 +0000389 : IsTargetMemInst(false), Inst(Inst) {
390 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
391 if (TTI.getTgtMemIntrinsic(II, Info) && Info.NumMemRefs == 1)
392 IsTargetMemInst = true;
393 }
394 bool isLoad() const {
395 if (IsTargetMemInst) return Info.ReadMem;
396 return isa<LoadInst>(Inst);
397 }
398 bool isStore() const {
399 if (IsTargetMemInst) return Info.WriteMem;
400 return isa<StoreInst>(Inst);
401 }
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000402 bool isAtomic() const {
403 if (IsTargetMemInst) {
404 assert(Info.IsSimple && "need to refine IsSimple in TTI");
405 return false;
406 }
407 return Inst->isAtomic();
408 }
409 bool isUnordered() const {
410 if (IsTargetMemInst) {
411 assert(Info.IsSimple && "need to refine IsSimple in TTI");
412 return true;
413 }
414 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
415 return LI->isUnordered();
416 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
417 return SI->isUnordered();
418 }
419 // Conservative answer
420 return !Inst->isAtomic();
421 }
422
423 bool isVolatile() const {
424 if (IsTargetMemInst) {
425 assert(Info.IsSimple && "need to refine IsSimple in TTI");
426 return false;
427 }
428 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
429 return LI->isVolatile();
430 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
431 return SI->isVolatile();
432 }
433 // Conservative answer
434 return true;
435 }
436
Sanjoy Das07c65212016-06-16 20:47:57 +0000437 bool isInvariantLoad() const {
438 if (auto *LI = dyn_cast<LoadInst>(Inst))
Sanjoy Das1ab2fad2016-06-16 21:00:57 +0000439 return LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr;
Sanjoy Das07c65212016-06-16 20:47:57 +0000440 return false;
441 }
Junmo Park80440eb2016-02-18 10:09:20 +0000442
Arnaud A. de Grandmaison6fd488b2015-10-06 13:35:30 +0000443 bool isMatchingMemLoc(const ParseMemoryInst &Inst) const {
Philip Reames9e5e2d62015-12-07 22:41:23 +0000444 return (getPointerOperand() == Inst.getPointerOperand() &&
445 getMatchingId() == Inst.getMatchingId());
Chad Rosierf9327d62015-01-26 22:51:15 +0000446 }
Philip Reames9e5e2d62015-12-07 22:41:23 +0000447 bool isValid() const { return getPointerOperand() != nullptr; }
Chad Rosierf9327d62015-01-26 22:51:15 +0000448
Chad Rosierf9327d62015-01-26 22:51:15 +0000449 // For regular (non-intrinsic) loads/stores, this is set to -1. For
450 // intrinsic loads/stores, the id is retrieved from the corresponding
451 // field in the MemIntrinsicInfo structure. That field contains
452 // non-negative values only.
Philip Reames9e5e2d62015-12-07 22:41:23 +0000453 int getMatchingId() const {
454 if (IsTargetMemInst) return Info.MatchingId;
455 return -1;
456 }
457 Value *getPointerOperand() const {
458 if (IsTargetMemInst) return Info.PtrVal;
459 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
460 return LI->getPointerOperand();
461 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
462 return SI->getPointerOperand();
463 }
464 return nullptr;
465 }
466 bool mayReadFromMemory() const {
467 if (IsTargetMemInst) return Info.ReadMem;
468 return Inst->mayReadFromMemory();
469 }
470 bool mayWriteToMemory() const {
471 if (IsTargetMemInst) return Info.WriteMem;
472 return Inst->mayWriteToMemory();
473 }
474
475 private:
476 bool IsTargetMemInst;
477 MemIntrinsicInfo Info;
478 Instruction *Inst;
Chad Rosierf9327d62015-01-26 22:51:15 +0000479 };
480
Chris Lattner18ae5432011-01-02 23:04:14 +0000481 bool processNode(DomTreeNode *Node);
Nadav Rotem465834c2012-07-24 10:51:42 +0000482
Chad Rosierf9327d62015-01-26 22:51:15 +0000483 Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const {
484 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
485 return LI;
486 else if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
487 return SI->getValueOperand();
488 assert(isa<IntrinsicInst>(Inst) && "Instruction not supported");
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000489 return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst),
490 ExpectedType);
Chad Rosierf9327d62015-01-26 22:51:15 +0000491 }
Geoff Berry8d846052016-08-31 19:24:10 +0000492
493 bool isSameMemGeneration(unsigned EarlierGeneration, unsigned LaterGeneration,
494 Instruction *EarlierInst, Instruction *LaterInst);
495
496 void removeMSSA(Instruction *Inst) {
497 if (!MSSA)
498 return;
499 // FIXME: Removing a store here can leave MemorySSA in an unoptimized state
500 // by creating MemoryPhis that have identical arguments and by creating
501 // MemoryUses whose defining access is not an actual clobber.
502 if (MemoryAccess *MA = MSSA->getMemoryAccess(Inst))
503 MSSA->removeMemoryAccess(MA);
504 }
Chris Lattner704541b2011-01-02 21:47:05 +0000505};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000506}
Chris Lattner704541b2011-01-02 21:47:05 +0000507
Geoff Berry8d846052016-08-31 19:24:10 +0000508/// Determine if the memory referenced by LaterInst is from the same heap version
509/// as EarlierInst.
510/// This is currently called in two scenarios:
511///
512/// load p
513/// ...
514/// load p
515///
516/// and
517///
518/// x = load p
519/// ...
520/// store x, p
521///
522/// in both cases we want to verify that there are no possible writes to the
523/// memory referenced by p between the earlier and later instruction.
524bool EarlyCSE::isSameMemGeneration(unsigned EarlierGeneration,
525 unsigned LaterGeneration,
526 Instruction *EarlierInst,
527 Instruction *LaterInst) {
528 // Check the simple memory generation tracking first.
529 if (EarlierGeneration == LaterGeneration)
530 return true;
531
532 if (!MSSA)
533 return false;
534
535 // Since we know LaterDef dominates LaterInst and EarlierInst dominates
536 // LaterInst, if LaterDef dominates EarlierInst then it can't occur between
537 // EarlierInst and LaterInst and neither can any other write that potentially
538 // clobbers LaterInst.
539 // FIXME: This is currently fairly expensive since it does an AA check even
540 // for MemoryUses that were already optimized by MemorySSA construction.
541 // Re-visit once MemorySSA optimized use tracking change has been committed.
542 MemoryAccess *LaterDef =
543 MSSA->getWalker()->getClobberingMemoryAccess(LaterInst);
544 return MSSA->dominates(LaterDef, MSSA->getMemoryAccess(EarlierInst));
545}
546
Chris Lattner18ae5432011-01-02 23:04:14 +0000547bool EarlyCSE::processNode(DomTreeNode *Node) {
Chad Rosier1a4bc112016-04-22 18:47:21 +0000548 bool Changed = false;
Chris Lattner18ae5432011-01-02 23:04:14 +0000549 BasicBlock *BB = Node->getBlock();
Nadav Rotem465834c2012-07-24 10:51:42 +0000550
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000551 // If this block has a single predecessor, then the predecessor is the parent
552 // of the domtree node and all of the live out memory values are still current
553 // in this block. If this block has multiple predecessors, then they could
554 // have invalidated the live-out memory values of our parent value. For now,
555 // just be conservative and invalidate memory if this block has multiple
556 // predecessors.
Craig Topperf40110f2014-04-25 05:29:35 +0000557 if (!BB->getSinglePredecessor())
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000558 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000559
Philip Reames7c78ef72015-05-22 23:53:24 +0000560 // If this node has a single predecessor which ends in a conditional branch,
561 // we can infer the value of the branch condition given that we took this
Chad Rosierb346dcb2016-04-20 19:16:23 +0000562 // path. We need the single predecessor to ensure there's not another path
Philip Reames7c78ef72015-05-22 23:53:24 +0000563 // which reaches this block where the condition might hold a different
564 // value. Since we're adding this to the scoped hash table (like any other
565 // def), it will have been popped if we encounter a future merge block.
566 if (BasicBlock *Pred = BB->getSinglePredecessor())
567 if (auto *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
568 if (BI->isConditional())
569 if (auto *CondInst = dyn_cast<Instruction>(BI->getCondition()))
570 if (SimpleValue::canHandle(CondInst)) {
571 assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
572 auto *ConditionalConstant = (BI->getSuccessor(0) == BB) ?
573 ConstantInt::getTrue(BB->getContext()) :
574 ConstantInt::getFalse(BB->getContext());
575 AvailableValues.insert(CondInst, ConditionalConstant);
576 DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
577 << CondInst->getName() << "' as " << *ConditionalConstant
578 << " in " << BB->getName() << "\n");
Chad Rosier1a4bc112016-04-22 18:47:21 +0000579 // Replace all dominated uses with the known value.
580 if (unsigned Count =
581 replaceDominatedUsesWith(CondInst, ConditionalConstant, DT,
582 BasicBlockEdge(Pred, BB))) {
583 Changed = true;
584 NumCSECVP = NumCSECVP + Count;
585 }
Philip Reames7c78ef72015-05-22 23:53:24 +0000586 }
587
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000588 /// LastStore - Keep track of the last non-volatile store that we saw... for
589 /// as long as there in no instruction that reads memory. If we see a store
590 /// to the same location, we delete the dead store. This zaps trivial dead
591 /// stores which can occur in bitfield code among other things.
Chad Rosierf9327d62015-01-26 22:51:15 +0000592 Instruction *LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000593
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000594 const DataLayout &DL = BB->getModule()->getDataLayout();
Chris Lattner18ae5432011-01-02 23:04:14 +0000595
596 // See if any instructions in the block can be eliminated. If so, do it. If
597 // not, add them to AvailableValues.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000598 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +0000599 Instruction *Inst = &*I++;
Nadav Rotem465834c2012-07-24 10:51:42 +0000600
Chris Lattner18ae5432011-01-02 23:04:14 +0000601 // Dead instructions should just be removed.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000602 if (isInstructionTriviallyDead(Inst, &TLI)) {
Chris Lattner8fac5db2011-01-02 23:19:45 +0000603 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
Geoff Berry8d846052016-08-31 19:24:10 +0000604 removeMSSA(Inst);
Chris Lattner18ae5432011-01-02 23:04:14 +0000605 Inst->eraseFromParent();
606 Changed = true;
Chris Lattner8fac5db2011-01-02 23:19:45 +0000607 ++NumSimplify;
Chris Lattner18ae5432011-01-02 23:04:14 +0000608 continue;
609 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000610
Hal Finkel1e16fa32014-11-03 20:21:32 +0000611 // Skip assume intrinsics, they don't really have side effects (although
612 // they're marked as such to ensure preservation of control dependencies),
613 // and this pass will not disturb any of the assumption's control
614 // dependencies.
615 if (match(Inst, m_Intrinsic<Intrinsic::assume>())) {
616 DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n');
617 continue;
618 }
619
Anna Thomasb2d12b82016-08-09 20:00:47 +0000620 // Skip invariant.start intrinsics since they only read memory, and we can
621 // forward values across it. Also, we dont need to consume the last store
622 // since the semantics of invariant.start allow us to perform DSE of the
623 // last store, if there was a store following invariant.start. Consider:
624 //
625 // store 30, i8* p
626 // invariant.start(p)
627 // store 40, i8* p
628 // We can DSE the store to 30, since the store 40 to invariant location p
629 // causes undefined behaviour.
630 if (match(Inst, m_Intrinsic<Intrinsic::invariant_start>()))
631 continue;
632
Sanjoy Dasee81b232016-04-29 21:52:58 +0000633 if (match(Inst, m_Intrinsic<Intrinsic::experimental_guard>())) {
Sanjoy Das107aefc2016-04-29 22:23:16 +0000634 if (auto *CondI =
635 dyn_cast<Instruction>(cast<CallInst>(Inst)->getArgOperand(0))) {
Sanjoy Dasee81b232016-04-29 21:52:58 +0000636 // The condition we're on guarding here is true for all dominated
637 // locations.
638 if (SimpleValue::canHandle(CondI))
639 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
640 }
641
642 // Guard intrinsics read all memory, but don't write any memory.
643 // Accordingly, don't update the generation but consume the last store (to
644 // avoid an incorrect DSE).
645 LastStore = nullptr;
646 continue;
647 }
648
Chris Lattner18ae5432011-01-02 23:04:14 +0000649 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
650 // its simpler value.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000651 if (Value *V = SimplifyInstruction(Inst, DL, &TLI, &DT, &AC)) {
Chris Lattner8fac5db2011-01-02 23:19:45 +0000652 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
David Majnemer130b9f92016-07-29 05:39:21 +0000653 bool Killed = false;
David Majnemerb8da3a22016-06-25 00:04:10 +0000654 if (!Inst->use_empty()) {
655 Inst->replaceAllUsesWith(V);
656 Changed = true;
657 }
658 if (isInstructionTriviallyDead(Inst, &TLI)) {
Geoff Berry8d846052016-08-31 19:24:10 +0000659 removeMSSA(Inst);
David Majnemerb8da3a22016-06-25 00:04:10 +0000660 Inst->eraseFromParent();
661 Changed = true;
David Majnemer130b9f92016-07-29 05:39:21 +0000662 Killed = true;
David Majnemerb8da3a22016-06-25 00:04:10 +0000663 }
David Majnemer130b9f92016-07-29 05:39:21 +0000664 if (Changed)
David Majnemerb8da3a22016-06-25 00:04:10 +0000665 ++NumSimplify;
David Majnemer130b9f92016-07-29 05:39:21 +0000666 if (Killed)
David Majnemerb8da3a22016-06-25 00:04:10 +0000667 continue;
Chris Lattner18ae5432011-01-02 23:04:14 +0000668 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000669
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000670 // If this is a simple instruction that we can value number, process it.
671 if (SimpleValue::canHandle(Inst)) {
672 // See if the instruction has an available value. If so, use it.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000673 if (Value *V = AvailableValues.lookup(Inst)) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000674 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
David Majnemer9554c132016-04-22 06:37:45 +0000675 if (auto *I = dyn_cast<Instruction>(V))
676 I->andIRFlags(Inst);
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000677 Inst->replaceAllUsesWith(V);
Geoff Berry8d846052016-08-31 19:24:10 +0000678 removeMSSA(Inst);
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000679 Inst->eraseFromParent();
680 Changed = true;
681 ++NumCSE;
682 continue;
683 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000684
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000685 // Otherwise, just remember that this value is available.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000686 AvailableValues.insert(Inst, Inst);
Chris Lattner18ae5432011-01-02 23:04:14 +0000687 continue;
688 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000689
Chad Rosierf9327d62015-01-26 22:51:15 +0000690 ParseMemoryInst MemInst(Inst, TTI);
Chris Lattner92bb0f92011-01-03 03:41:27 +0000691 // If this is a non-volatile load, process it.
Chad Rosierf9327d62015-01-26 22:51:15 +0000692 if (MemInst.isValid() && MemInst.isLoad()) {
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000693 // (conservatively) we can't peak past the ordering implied by this
694 // operation, but we can add this load to our set of available values
695 if (MemInst.isVolatile() || !MemInst.isUnordered()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000696 LastStore = nullptr;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000697 ++CurrentGeneration;
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000698 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000699
Chris Lattner92bb0f92011-01-03 03:41:27 +0000700 // If we have an available version of this load, and if it is the right
Sanjoy Das07c65212016-06-16 20:47:57 +0000701 // generation or the load is known to be from an invariant location,
702 // replace this instruction.
703 //
Geoff Berry64f5ed12016-08-31 17:45:31 +0000704 // If either the dominating load or the current load are invariant, then
705 // we can assume the current load loads the same value as the dominating
706 // load.
Philip Reames9e5e2d62015-12-07 22:41:23 +0000707 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
Sanjoy Das07c65212016-06-16 20:47:57 +0000708 if (InVal.DefInst != nullptr &&
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000709 InVal.MatchingId == MemInst.getMatchingId() &&
710 // We don't yet handle removing loads with ordering of any kind.
711 !MemInst.isVolatile() && MemInst.isUnordered() &&
712 // We can't replace an atomic load with one which isn't also atomic.
Geoff Berry8d846052016-08-31 19:24:10 +0000713 InVal.IsAtomic >= MemInst.isAtomic() &&
714 (InVal.IsInvariant || MemInst.isInvariantLoad() ||
715 isSameMemGeneration(InVal.Generation, CurrentGeneration,
716 InVal.DefInst, Inst))) {
Philip Reames32b55182016-05-06 01:13:58 +0000717 Value *Op = getOrCreateResult(InVal.DefInst, Inst->getType());
Chad Rosierf9327d62015-01-26 22:51:15 +0000718 if (Op != nullptr) {
719 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst
Philip Reames32b55182016-05-06 01:13:58 +0000720 << " to: " << *InVal.DefInst << '\n');
Chad Rosierf9327d62015-01-26 22:51:15 +0000721 if (!Inst->use_empty())
722 Inst->replaceAllUsesWith(Op);
Geoff Berry8d846052016-08-31 19:24:10 +0000723 removeMSSA(Inst);
Chad Rosierf9327d62015-01-26 22:51:15 +0000724 Inst->eraseFromParent();
725 Changed = true;
726 ++NumCSELoad;
727 continue;
728 }
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000729 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000730
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000731 // Otherwise, remember that we have this instruction.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000732 AvailableLoads.insert(
Philip Reames9e5e2d62015-12-07 22:41:23 +0000733 MemInst.getPointerOperand(),
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000734 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
Sanjoy Das07c65212016-06-16 20:47:57 +0000735 MemInst.isAtomic(), MemInst.isInvariantLoad()));
Craig Topperf40110f2014-04-25 05:29:35 +0000736 LastStore = nullptr;
Chris Lattner92bb0f92011-01-03 03:41:27 +0000737 continue;
738 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000739
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000740 // If this instruction may read from memory, forget LastStore.
Chad Rosierf9327d62015-01-26 22:51:15 +0000741 // Load/store intrinsics will indicate both a read and a write to
742 // memory. The target may override this (e.g. so that a store intrinsic
743 // does not read from memory, and thus will be treated the same as a
744 // regular store for commoning purposes).
745 if (Inst->mayReadFromMemory() &&
746 !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
Craig Topperf40110f2014-04-25 05:29:35 +0000747 LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000748
Chris Lattner92bb0f92011-01-03 03:41:27 +0000749 // If this is a read-only call, process it.
750 if (CallValue::canHandle(Inst)) {
751 // If we have an available version of this call, and if it is the right
752 // generation, replace this instruction.
Geoff Berry2f64c202016-05-13 17:54:58 +0000753 std::pair<Instruction *, unsigned> InVal = AvailableCalls.lookup(Inst);
Geoff Berry8d846052016-08-31 19:24:10 +0000754 if (InVal.first != nullptr &&
755 isSameMemGeneration(InVal.second, CurrentGeneration, InVal.first,
756 Inst)) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000757 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst
758 << " to: " << *InVal.first << '\n');
759 if (!Inst->use_empty())
760 Inst->replaceAllUsesWith(InVal.first);
Geoff Berry8d846052016-08-31 19:24:10 +0000761 removeMSSA(Inst);
Chris Lattner92bb0f92011-01-03 03:41:27 +0000762 Inst->eraseFromParent();
763 Changed = true;
764 ++NumCSECall;
765 continue;
766 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000767
Chris Lattner92bb0f92011-01-03 03:41:27 +0000768 // Otherwise, remember that we have this instruction.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000769 AvailableCalls.insert(
Geoff Berry2f64c202016-05-13 17:54:58 +0000770 Inst, std::pair<Instruction *, unsigned>(Inst, CurrentGeneration));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000771 continue;
772 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000773
Philip Reamesdfd890d2015-08-27 01:32:33 +0000774 // A release fence requires that all stores complete before it, but does
775 // not prevent the reordering of following loads 'before' the fence. As a
776 // result, we don't need to consider it as writing to memory and don't need
777 // to advance the generation. We do need to prevent DSE across the fence,
778 // but that's handled above.
779 if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
JF Bastien800f87a2016-04-06 21:19:33 +0000780 if (FI->getOrdering() == AtomicOrdering::Release) {
Philip Reamesdfd890d2015-08-27 01:32:33 +0000781 assert(Inst->mayReadFromMemory() && "relied on to prevent DSE above");
782 continue;
783 }
784
Philip Reamesae1f265b2015-12-16 01:01:30 +0000785 // write back DSE - If we write back the same value we just loaded from
786 // the same location and haven't passed any intervening writes or ordering
787 // operations, we can remove the write. The primary benefit is in allowing
788 // the available load table to remain valid and value forward past where
789 // the store originally was.
790 if (MemInst.isValid() && MemInst.isStore()) {
791 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
Philip Reames32b55182016-05-06 01:13:58 +0000792 if (InVal.DefInst &&
793 InVal.DefInst == getOrCreateResult(Inst, InVal.DefInst->getType()) &&
Philip Reamesae1f265b2015-12-16 01:01:30 +0000794 InVal.MatchingId == MemInst.getMatchingId() &&
795 // We don't yet handle removing stores with ordering of any kind.
Geoff Berry8d846052016-08-31 19:24:10 +0000796 !MemInst.isVolatile() && MemInst.isUnordered() &&
797 isSameMemGeneration(InVal.Generation, CurrentGeneration,
798 InVal.DefInst, Inst)) {
799 // It is okay to have a LastStore to a different pointer here if MemorySSA
800 // tells us that the load and store are from the same memory generation.
801 // In that case, LastStore should keep its present value since we're
802 // removing the current store.
Philip Reamesae1f265b2015-12-16 01:01:30 +0000803 assert((!LastStore ||
804 ParseMemoryInst(LastStore, TTI).getPointerOperand() ==
Geoff Berry8d846052016-08-31 19:24:10 +0000805 MemInst.getPointerOperand() ||
806 MSSA) &&
807 "can't have an intervening store if not using MemorySSA!");
Philip Reamesae1f265b2015-12-16 01:01:30 +0000808 DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << *Inst << '\n');
Geoff Berry8d846052016-08-31 19:24:10 +0000809 removeMSSA(Inst);
Philip Reamesae1f265b2015-12-16 01:01:30 +0000810 Inst->eraseFromParent();
811 Changed = true;
812 ++NumDSE;
813 // We can avoid incrementing the generation count since we were able
814 // to eliminate this store.
815 continue;
816 }
817 }
818
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000819 // Okay, this isn't something we can CSE at all. Check to see if it is
820 // something that could modify memory. If so, our available memory values
821 // cannot be used so bump the generation count.
Chris Lattnere0e32a92011-01-03 03:46:34 +0000822 if (Inst->mayWriteToMemory()) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000823 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000824
Chad Rosierf9327d62015-01-26 22:51:15 +0000825 if (MemInst.isValid() && MemInst.isStore()) {
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000826 // We do a trivial form of DSE if there are two stores to the same
Philip Reames15145fb2015-12-17 18:50:50 +0000827 // location with no intervening loads. Delete the earlier store.
828 // At the moment, we don't remove ordered stores, but do remove
829 // unordered atomic stores. There's no special requirement (for
830 // unordered atomics) about removing atomic stores only in favor of
831 // other atomic stores since we we're going to execute the non-atomic
832 // one anyway and the atomic one might never have become visible.
Chad Rosierf9327d62015-01-26 22:51:15 +0000833 if (LastStore) {
834 ParseMemoryInst LastStoreMemInst(LastStore, TTI);
Philip Reames15145fb2015-12-17 18:50:50 +0000835 assert(LastStoreMemInst.isUnordered() &&
836 !LastStoreMemInst.isVolatile() &&
837 "Violated invariant");
Chad Rosierf9327d62015-01-26 22:51:15 +0000838 if (LastStoreMemInst.isMatchingMemLoc(MemInst)) {
839 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
840 << " due to: " << *Inst << '\n');
Geoff Berry8d846052016-08-31 19:24:10 +0000841 removeMSSA(LastStore);
Chad Rosierf9327d62015-01-26 22:51:15 +0000842 LastStore->eraseFromParent();
843 Changed = true;
844 ++NumDSE;
845 LastStore = nullptr;
846 }
Philip Reames018dbf12014-11-18 17:46:32 +0000847 // fallthrough - we can exploit information about this store
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000848 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000849
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000850 // Okay, we just invalidated anything we knew about loaded values. Try
851 // to salvage *something* by remembering that the stored value is a live
852 // version of the pointer. It is safe to forward from volatile stores
853 // to non-volatile loads, so we don't have to check for volatility of
854 // the store.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000855 AvailableLoads.insert(
Philip Reames9e5e2d62015-12-07 22:41:23 +0000856 MemInst.getPointerOperand(),
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000857 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
Sanjoy Das1ab2fad2016-06-16 21:00:57 +0000858 MemInst.isAtomic(), /*IsInvariant=*/false));
Nadav Rotem465834c2012-07-24 10:51:42 +0000859
Philip Reames15145fb2015-12-17 18:50:50 +0000860 // Remember that this was the last unordered store we saw for DSE. We
861 // don't yet handle DSE on ordered or volatile stores since we don't
862 // have a good way to model the ordering requirement for following
863 // passes once the store is removed. We could insert a fence, but
864 // since fences are slightly stronger than stores in their ordering,
865 // it's not clear this is a profitable transform. Another option would
866 // be to merge the ordering with that of the post dominating store.
867 if (MemInst.isUnordered() && !MemInst.isVolatile())
Chad Rosierf9327d62015-01-26 22:51:15 +0000868 LastStore = Inst;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000869 else
870 LastStore = nullptr;
Chris Lattnere0e32a92011-01-03 03:46:34 +0000871 }
872 }
Chris Lattner18ae5432011-01-02 23:04:14 +0000873 }
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000874
Chris Lattner18ae5432011-01-02 23:04:14 +0000875 return Changed;
Chris Lattner704541b2011-01-02 21:47:05 +0000876}
Chris Lattner18ae5432011-01-02 23:04:14 +0000877
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000878bool EarlyCSE::run() {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000879 // Note, deque is being used here because there is significant performance
880 // gains over vector when the container becomes very large due to the
881 // specific access patterns. For more information see the mailing list
882 // discussion on this:
Tanya Lattner0d28f802015-08-05 03:51:17 +0000883 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
Lenny Maiorani9eefc812014-09-20 13:29:20 +0000884 std::deque<StackNode *> nodesToProcess;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000885
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000886 bool Changed = false;
887
888 // Process the root node.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000889 nodesToProcess.push_back(new StackNode(
890 AvailableValues, AvailableLoads, AvailableCalls, CurrentGeneration,
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000891 DT.getRootNode(), DT.getRootNode()->begin(), DT.getRootNode()->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000892
893 // Save the current generation.
894 unsigned LiveOutGeneration = CurrentGeneration;
895
896 // Process the stack.
897 while (!nodesToProcess.empty()) {
898 // Grab the first item off the stack. Set the current generation, remove
899 // the node from the stack, and process it.
Michael Gottesman2bf01732013-12-05 18:42:12 +0000900 StackNode *NodeToProcess = nodesToProcess.back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000901
902 // Initialize class members.
903 CurrentGeneration = NodeToProcess->currentGeneration();
904
905 // Check if the node needs to be processed.
906 if (!NodeToProcess->isProcessed()) {
907 // Process the node.
908 Changed |= processNode(NodeToProcess->node());
909 NodeToProcess->childGeneration(CurrentGeneration);
910 NodeToProcess->process();
911 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
912 // Push the next child onto the stack.
913 DomTreeNode *child = NodeToProcess->nextChild();
Michael Gottesman2bf01732013-12-05 18:42:12 +0000914 nodesToProcess.push_back(
Chandler Carruth7253bba2015-01-24 11:33:55 +0000915 new StackNode(AvailableValues, AvailableLoads, AvailableCalls,
916 NodeToProcess->childGeneration(), child, child->begin(),
917 child->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000918 } else {
919 // It has been processed, and there are no more children to process,
920 // so delete it and pop it off the stack.
921 delete NodeToProcess;
Michael Gottesman2bf01732013-12-05 18:42:12 +0000922 nodesToProcess.pop_back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000923 }
924 } // while (!nodes...)
925
926 // Reset the current generation.
927 CurrentGeneration = LiveOutGeneration;
928
929 return Changed;
Chris Lattner18ae5432011-01-02 23:04:14 +0000930}
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000931
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000932PreservedAnalyses EarlyCSEPass::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +0000933 FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +0000934 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
935 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
936 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
937 auto &AC = AM.getResult<AssumptionAnalysis>(F);
Geoff Berry8d846052016-08-31 19:24:10 +0000938 auto *MSSA =
939 UseMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA() : nullptr;
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000940
Geoff Berry8d846052016-08-31 19:24:10 +0000941 EarlyCSE CSE(TLI, TTI, DT, AC, MSSA);
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000942
943 if (!CSE.run())
944 return PreservedAnalyses::all();
945
946 // CSE preserves the dominator tree because it doesn't mutate the CFG.
947 // FIXME: Bundle this with other CFG-preservation.
948 PreservedAnalyses PA;
949 PA.preserve<DominatorTreeAnalysis>();
Davide Italiano02861d82016-06-08 21:31:55 +0000950 PA.preserve<GlobalsAA>();
Geoff Berry8d846052016-08-31 19:24:10 +0000951 if (UseMemorySSA)
952 PA.preserve<MemorySSAAnalysis>();
Chandler Carruthe8c686a2015-02-01 10:51:23 +0000953 return PA;
954}
955
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000956namespace {
957/// \brief A simple and fast domtree-based CSE pass.
958///
959/// This pass does a simple depth-first walk over the dominator tree,
960/// eliminating trivially redundant instructions and using instsimplify to
961/// canonicalize things as it goes. It is intended to be fast and catch obvious
962/// cases so that instcombine and other passes are more effective. It is
963/// expected that a later pass of GVN will catch the interesting/hard cases.
Geoff Berry8d846052016-08-31 19:24:10 +0000964template<bool UseMemorySSA>
965class EarlyCSELegacyCommonPass : public FunctionPass {
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000966public:
967 static char ID;
968
Geoff Berry8d846052016-08-31 19:24:10 +0000969 EarlyCSELegacyCommonPass() : FunctionPass(ID) {
970 if (UseMemorySSA)
971 initializeEarlyCSEMemSSALegacyPassPass(*PassRegistry::getPassRegistry());
972 else
973 initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry());
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000974 }
975
976 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000977 if (skipFunction(F))
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000978 return false;
979
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000980 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000981 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000982 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
983 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Geoff Berry8d846052016-08-31 19:24:10 +0000984 auto *MSSA =
985 UseMemorySSA ? &getAnalysis<MemorySSAWrapperPass>().getMSSA() : nullptr;
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000986
Geoff Berry8d846052016-08-31 19:24:10 +0000987 EarlyCSE CSE(TLI, TTI, DT, AC, MSSA);
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000988
989 return CSE.run();
990 }
991
992 void getAnalysisUsage(AnalysisUsage &AU) const override {
993 AU.addRequired<AssumptionCacheTracker>();
994 AU.addRequired<DominatorTreeWrapperPass>();
995 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000996 AU.addRequired<TargetTransformInfoWrapperPass>();
Geoff Berry8d846052016-08-31 19:24:10 +0000997 if (UseMemorySSA) {
998 AU.addRequired<MemorySSAWrapperPass>();
999 AU.addPreserved<MemorySSAWrapperPass>();
1000 }
James Molloyefbba722015-09-10 10:22:12 +00001001 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001002 AU.setPreservesCFG();
1003 }
1004};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001005}
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001006
Geoff Berry8d846052016-08-31 19:24:10 +00001007using EarlyCSELegacyPass = EarlyCSELegacyCommonPass</*UseMemorySSA=*/false>;
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001008
Geoff Berry8d846052016-08-31 19:24:10 +00001009template<>
1010char EarlyCSELegacyPass::ID = 0;
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001011
1012INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
1013 false)
Chandler Carruth705b1852015-01-31 03:43:40 +00001014INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001015INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1016INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1017INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1018INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)
Geoff Berry8d846052016-08-31 19:24:10 +00001019
1020using EarlyCSEMemSSALegacyPass =
1021 EarlyCSELegacyCommonPass</*UseMemorySSA=*/true>;
1022
1023template<>
1024char EarlyCSEMemSSALegacyPass::ID = 0;
1025
1026FunctionPass *llvm::createEarlyCSEPass(bool UseMemorySSA) {
1027 if (UseMemorySSA)
1028 return new EarlyCSEMemSSALegacyPass();
1029 else
1030 return new EarlyCSELegacyPass();
1031}
1032
1033INITIALIZE_PASS_BEGIN(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1034 "Early CSE w/ MemorySSA", false, false)
1035INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1036INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1037INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1038INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1039INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
1040INITIALIZE_PASS_END(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1041 "Early CSE w/ MemorySSA", false, false)