blob: 892a12315cec50132fe2f82348cfc88430d82e89 [file] [log] [blame]
Chris Lattner704541b2011-01-02 21:47:05 +00001//===- EarlyCSE.cpp - Simple and fast CSE pass ----------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner704541b2011-01-02 21:47:05 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass performs a simple dominator tree walk that eliminates trivially
10// redundant instructions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruthe8c686a2015-02-01 10:51:23 +000014#include "llvm/Transforms/Scalar/EarlyCSE.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000015#include "llvm/ADT/DenseMapInfo.h"
Michael Ilseman336cb792012-10-09 16:57:38 +000016#include "llvm/ADT/Hashing.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000017#include "llvm/ADT/STLExtras.h"
Chris Lattner18ae5432011-01-02 23:04:14 +000018#include "llvm/ADT/ScopedHashTable.h"
Davide Italiano0dc47782017-06-14 19:29:53 +000019#include "llvm/ADT/SetVector.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000020#include "llvm/ADT/SmallVector.h"
Chris Lattner8fac5db2011-01-02 23:19:45 +000021#include "llvm/ADT/Statistic.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000022#include "llvm/Analysis/AssumptionCache.h"
Geoff Berry354fac22016-04-28 14:59:27 +000023#include "llvm/Analysis/GlobalsModRef.h"
Max Kazantsev3c284bd2018-08-30 03:39:16 +000024#include "llvm/Analysis/GuardUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/Analysis/InstructionSimplify.h"
Daniel Berlin554dcd82017-04-11 20:06:36 +000026#include "llvm/Analysis/MemorySSA.h"
27#include "llvm/Analysis/MemorySSAUpdater.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000028#include "llvm/Analysis/TargetLibraryInfo.h"
Chad Rosierf9327d62015-01-26 22:51:15 +000029#include "llvm/Analysis/TargetTransformInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000030#include "llvm/Transforms/Utils/Local.h"
Sanjay Patel3c7a35d2017-12-13 21:58:15 +000031#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000032#include "llvm/IR/BasicBlock.h"
33#include "llvm/IR/Constants.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000035#include "llvm/IR/Dominators.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000036#include "llvm/IR/Function.h"
37#include "llvm/IR/InstrTypes.h"
38#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Instructions.h"
Hal Finkel1e16fa32014-11-03 20:21:32 +000040#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000041#include "llvm/IR/Intrinsics.h"
42#include "llvm/IR/LLVMContext.h"
43#include "llvm/IR/PassManager.h"
Hal Finkel1e16fa32014-11-03 20:21:32 +000044#include "llvm/IR/PatternMatch.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000045#include "llvm/IR/Type.h"
46#include "llvm/IR/Use.h"
47#include "llvm/IR/Value.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000048#include "llvm/Pass.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000049#include "llvm/Support/Allocator.h"
50#include "llvm/Support/AtomicOrdering.h"
51#include "llvm/Support/Casting.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000052#include "llvm/Support/Debug.h"
Geoff Berry5bf4a5e2018-04-06 18:47:33 +000053#include "llvm/Support/DebugCounter.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000054#include "llvm/Support/RecyclingAllocator.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000055#include "llvm/Support/raw_ostream.h"
Chandler Carruthe8c686a2015-02-01 10:51:23 +000056#include "llvm/Transforms/Scalar.h"
Max Kazantsev3c284bd2018-08-30 03:39:16 +000057#include "llvm/Transforms/Utils/GuardUtils.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000058#include <cassert>
Lenny Maiorani9eefc812014-09-20 13:29:20 +000059#include <deque>
Eugene Zelenko3b879392017-10-13 21:17:07 +000060#include <memory>
61#include <utility>
62
Chris Lattner704541b2011-01-02 21:47:05 +000063using namespace llvm;
Hal Finkel1e16fa32014-11-03 20:21:32 +000064using namespace llvm::PatternMatch;
Chris Lattner704541b2011-01-02 21:47:05 +000065
Chandler Carruth964daaa2014-04-22 02:55:47 +000066#define DEBUG_TYPE "early-cse"
67
Chris Lattner4cb36542011-01-03 03:28:23 +000068STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
69STATISTIC(NumCSE, "Number of instructions CSE'd");
Chad Rosier1a4bc112016-04-22 18:47:21 +000070STATISTIC(NumCSECVP, "Number of compare instructions CVP'd");
Chris Lattner92bb0f92011-01-03 03:41:27 +000071STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
72STATISTIC(NumCSECall, "Number of call instructions CSE'd");
Chris Lattner9e5e9ed2011-01-03 04:17:24 +000073STATISTIC(NumDSE, "Number of trivial dead stores removed");
Chris Lattnerb9a8efc2011-01-03 03:18:43 +000074
Geoff Berry5bf4a5e2018-04-06 18:47:33 +000075DEBUG_COUNTER(CSECounter, "early-cse",
76 "Controls which instructions are removed");
77
Alina Sbirlea383ccfb2019-02-15 22:47:54 +000078static cl::opt<unsigned> EarlyCSEMssaOptCap(
79 "earlycse-mssa-optimization-cap", cl::init(500), cl::Hidden,
80 cl::desc("Enable imprecision in EarlyCSE in pathological cases, in exchange "
81 "for faster compile. Caps the MemorySSA clobbering calls."));
82
Chris Lattner79d83062011-01-03 02:20:48 +000083//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +000084// SimpleValue
Chris Lattner79d83062011-01-03 02:20:48 +000085//===----------------------------------------------------------------------===//
86
Chris Lattner704541b2011-01-02 21:47:05 +000087namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +000088
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000089/// Struct representing the available values in the scoped hash table.
Chandler Carruth7253bba2015-01-24 11:33:55 +000090struct SimpleValue {
91 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +000092
Chandler Carruth7253bba2015-01-24 11:33:55 +000093 SimpleValue(Instruction *I) : Inst(I) {
94 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
95 }
Nadav Rotem465834c2012-07-24 10:51:42 +000096
Chandler Carruth7253bba2015-01-24 11:33:55 +000097 bool isSentinel() const {
98 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
99 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
100 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000101
Chandler Carruth7253bba2015-01-24 11:33:55 +0000102 static bool canHandle(Instruction *Inst) {
103 // This can only handle non-void readnone functions.
104 if (CallInst *CI = dyn_cast<CallInst>(Inst))
105 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
106 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
107 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
108 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
109 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
110 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
111 }
112};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000113
114} // end anonymous namespace
Chris Lattner18ae5432011-01-02 23:04:14 +0000115
116namespace llvm {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000117
Chandler Carruth7253bba2015-01-24 11:33:55 +0000118template <> struct DenseMapInfo<SimpleValue> {
Chris Lattner79d83062011-01-03 02:20:48 +0000119 static inline SimpleValue getEmptyKey() {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000120 return DenseMapInfo<Instruction *>::getEmptyKey();
Chris Lattner18ae5432011-01-02 23:04:14 +0000121 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000122
Chris Lattner79d83062011-01-03 02:20:48 +0000123 static inline SimpleValue getTombstoneKey() {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000124 return DenseMapInfo<Instruction *>::getTombstoneKey();
Chris Lattner18ae5432011-01-02 23:04:14 +0000125 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000126
Chris Lattner79d83062011-01-03 02:20:48 +0000127 static unsigned getHashValue(SimpleValue Val);
128 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
Chris Lattner18ae5432011-01-02 23:04:14 +0000129};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000130
131} // end namespace llvm
Chris Lattner18ae5432011-01-02 23:04:14 +0000132
Sanjay Patele08783e2019-04-16 20:41:20 +0000133/// Match a 'select' including an optional 'not' of the condition.
134static bool matchSelectWithOptionalNotCond(Value *V, Value *&Cond,
135 Value *&T, Value *&F) {
136 if (match(V, m_Select(m_Value(Cond), m_Value(T), m_Value(F)))) {
137 // Look through a 'not' of the condition operand by swapping true/false.
138 Value *CondNot;
139 if (match(Cond, m_Not(m_Value(CondNot)))) {
140 Cond = CondNot;
141 std::swap(T, F);
142 }
143 return true;
144 }
145 return false;
146}
147
Chris Lattner79d83062011-01-03 02:20:48 +0000148unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000149 Instruction *Inst = Val.Inst;
Chris Lattner02a97762011-01-03 01:10:08 +0000150 // Hash in all of the operands as pointers.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000151 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
Michael Ilseman336cb792012-10-09 16:57:38 +0000152 Value *LHS = BinOp->getOperand(0);
153 Value *RHS = BinOp->getOperand(1);
154 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
155 std::swap(LHS, RHS);
Chris Lattner02a97762011-01-03 01:10:08 +0000156
Michael Ilseman336cb792012-10-09 16:57:38 +0000157 return hash_combine(BinOp->getOpcode(), LHS, RHS);
Chris Lattner02a97762011-01-03 01:10:08 +0000158 }
159
Michael Ilseman336cb792012-10-09 16:57:38 +0000160 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
161 Value *LHS = CI->getOperand(0);
162 Value *RHS = CI->getOperand(1);
163 CmpInst::Predicate Pred = CI->getPredicate();
164 if (Inst->getOperand(0) > Inst->getOperand(1)) {
165 std::swap(LHS, RHS);
166 Pred = CI->getSwappedPredicate();
167 }
168 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
169 }
170
Sanjay Patel558a4652017-12-13 22:57:35 +0000171 // Hash min/max/abs (cmp + select) to allow for commuted operands.
172 // Min/max may also have non-canonical compare predicate (eg, the compare for
173 // smin may use 'sgt' rather than 'slt'), and non-canonical operands in the
174 // compare.
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000175 Value *A, *B;
176 SelectPatternFlavor SPF = matchSelectPattern(Inst, A, B).Flavor;
Sanjay Patel558a4652017-12-13 22:57:35 +0000177 // TODO: We should also detect FP min/max.
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000178 if (SPF == SPF_SMIN || SPF == SPF_SMAX ||
Craig Topperf14e62c2018-05-21 18:42:42 +0000179 SPF == SPF_UMIN || SPF == SPF_UMAX) {
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000180 if (A > B)
181 std::swap(A, B);
182 return hash_combine(Inst->getOpcode(), SPF, A, B);
183 }
Craig Topperf14e62c2018-05-21 18:42:42 +0000184 if (SPF == SPF_ABS || SPF == SPF_NABS) {
185 // ABS/NABS always puts the input in A and its negation in B.
186 return hash_combine(Inst->getOpcode(), SPF, A, B);
187 }
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000188
Sanjay Patele08783e2019-04-16 20:41:20 +0000189 // Hash general selects to allow matching commuted true/false operands.
190 Value *Cond, *TVal, *FVal;
191 if (matchSelectWithOptionalNotCond(Inst, Cond, TVal, FVal)) {
192 // If we do not have a compare as the condition, just hash in the condition.
193 CmpInst::Predicate Pred;
194 Value *X, *Y;
195 if (!match(Cond, m_Cmp(Pred, m_Value(X), m_Value(Y))))
196 return hash_combine(Inst->getOpcode(), Cond, TVal, FVal);
197
198 // Similar to cmp normalization (above) - canonicalize the predicate value:
199 // select (icmp Pred, X, Y), T, F --> select (icmp InvPred, X, Y), F, T
200 if (CmpInst::getInversePredicate(Pred) < Pred) {
201 Pred = CmpInst::getInversePredicate(Pred);
202 std::swap(TVal, FVal);
203 }
204 return hash_combine(Inst->getOpcode(), Pred, X, Y, TVal, FVal);
205 }
206
Michael Ilseman336cb792012-10-09 16:57:38 +0000207 if (CastInst *CI = dyn_cast<CastInst>(Inst))
208 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
209
210 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
211 return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
212 hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
213
214 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
215 return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
216 IVI->getOperand(1),
217 hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
218
Sanjay Patele08783e2019-04-16 20:41:20 +0000219 assert((isa<CallInst>(Inst) || isa<GetElementPtrInst>(Inst) ||
Michael Ilseman336cb792012-10-09 16:57:38 +0000220 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
Chandler Carruth7253bba2015-01-24 11:33:55 +0000221 isa<ShuffleVectorInst>(Inst)) &&
222 "Invalid/unknown instruction");
Michael Ilseman336cb792012-10-09 16:57:38 +0000223
Chris Lattner02a97762011-01-03 01:10:08 +0000224 // Mix in the opcode.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000225 return hash_combine(
226 Inst->getOpcode(),
227 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
Chris Lattner18ae5432011-01-02 23:04:14 +0000228}
229
Chris Lattner79d83062011-01-03 02:20:48 +0000230bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000231 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
232
233 if (LHS.isSentinel() || RHS.isSentinel())
234 return LHSI == RHSI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000235
Chandler Carruth7253bba2015-01-24 11:33:55 +0000236 if (LHSI->getOpcode() != RHSI->getOpcode())
237 return false;
David Majnemer9554c132016-04-22 06:37:45 +0000238 if (LHSI->isIdenticalToWhenDefined(RHSI))
Chandler Carruth7253bba2015-01-24 11:33:55 +0000239 return true;
Michael Ilseman336cb792012-10-09 16:57:38 +0000240
241 // If we're not strictly identical, we still might be a commutable instruction
242 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
243 if (!LHSBinOp->isCommutative())
244 return false;
245
Chandler Carruth7253bba2015-01-24 11:33:55 +0000246 assert(isa<BinaryOperator>(RHSI) &&
247 "same opcode, but different instruction type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000248 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
249
Michael Ilseman336cb792012-10-09 16:57:38 +0000250 // Commuted equality
251 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000252 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
Michael Ilseman336cb792012-10-09 16:57:38 +0000253 }
254 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000255 assert(isa<CmpInst>(RHSI) &&
256 "same opcode, but different instruction type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000257 CmpInst *RHSCmp = cast<CmpInst>(RHSI);
258 // Commuted equality
259 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000260 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
261 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
Michael Ilseman336cb792012-10-09 16:57:38 +0000262 }
263
Sanjay Patel558a4652017-12-13 22:57:35 +0000264 // Min/max/abs can occur with commuted operands, non-canonical predicates,
265 // and/or non-canonical operands.
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000266 Value *LHSA, *LHSB;
267 SelectPatternFlavor LSPF = matchSelectPattern(LHSI, LHSA, LHSB).Flavor;
Sanjay Patel558a4652017-12-13 22:57:35 +0000268 // TODO: We should also detect FP min/max.
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000269 if (LSPF == SPF_SMIN || LSPF == SPF_SMAX ||
Sanjay Patel558a4652017-12-13 22:57:35 +0000270 LSPF == SPF_UMIN || LSPF == SPF_UMAX ||
271 LSPF == SPF_ABS || LSPF == SPF_NABS) {
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000272 Value *RHSA, *RHSB;
273 SelectPatternFlavor RSPF = matchSelectPattern(RHSI, RHSA, RHSB).Flavor;
Craig Topperf14e62c2018-05-21 18:42:42 +0000274 if (LSPF == RSPF) {
275 // Abs results are placed in a defined order by matchSelectPattern.
276 if (LSPF == SPF_ABS || LSPF == SPF_NABS)
277 return LHSA == RHSA && LHSB == RHSB;
278 return ((LHSA == RHSA && LHSB == RHSB) ||
279 (LHSA == RHSB && LHSB == RHSA));
280 }
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000281 }
282
Sanjay Patele08783e2019-04-16 20:41:20 +0000283 // Selects can be non-trivially equivalent via inverted conditions and swaps.
284 Value *CondL, *CondR, *TrueL, *TrueR, *FalseL, *FalseR;
285 if (matchSelectWithOptionalNotCond(LHSI, CondL, TrueL, FalseL) &&
286 matchSelectWithOptionalNotCond(RHSI, CondR, TrueR, FalseR)) {
287 // select Cond, T, F <--> select not(Cond), F, T
288 if (CondL == CondR && TrueL == TrueR && FalseL == FalseR)
289 return true;
290
291 // If the true/false operands are swapped and the conditions are compares
292 // with inverted predicates, the selects are equal:
293 // select (icmp Pred, X, Y), T, F <--> select (icmp InvPred, X, Y), F, T
294 //
295 // This also handles patterns with a double-negation because we looked
296 // through a 'not' in the matching function and swapped T/F:
297 // select (cmp Pred, X, Y), T, F <--> select (not (cmp InvPred, X, Y)), T, F
298 if (TrueL == FalseR && FalseL == TrueR) {
299 CmpInst::Predicate PredL, PredR;
300 Value *X, *Y;
301 if (match(CondL, m_Cmp(PredL, m_Value(X), m_Value(Y))) &&
302 match(CondR, m_Cmp(PredR, m_Specific(X), m_Specific(Y))) &&
303 CmpInst::getInversePredicate(PredL) == PredR)
304 return true;
305 }
306 }
307
Michael Ilseman336cb792012-10-09 16:57:38 +0000308 return false;
Chris Lattner18ae5432011-01-02 23:04:14 +0000309}
310
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000311//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +0000312// CallValue
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000313//===----------------------------------------------------------------------===//
314
315namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000316
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000317/// Struct representing the available call values in the scoped hash
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000318/// table.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000319struct CallValue {
320 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +0000321
Chandler Carruth7253bba2015-01-24 11:33:55 +0000322 CallValue(Instruction *I) : Inst(I) {
323 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
324 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000325
Chandler Carruth7253bba2015-01-24 11:33:55 +0000326 bool isSentinel() const {
327 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
328 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
329 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000330
Chandler Carruth7253bba2015-01-24 11:33:55 +0000331 static bool canHandle(Instruction *Inst) {
332 // Don't value number anything that returns void.
333 if (Inst->getType()->isVoidTy())
334 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000335
Chandler Carruth7253bba2015-01-24 11:33:55 +0000336 CallInst *CI = dyn_cast<CallInst>(Inst);
337 if (!CI || !CI->onlyReadsMemory())
338 return false;
339 return true;
340 }
341};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000342
343} // end anonymous namespace
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000344
345namespace llvm {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000346
Chandler Carruth7253bba2015-01-24 11:33:55 +0000347template <> struct DenseMapInfo<CallValue> {
348 static inline CallValue getEmptyKey() {
349 return DenseMapInfo<Instruction *>::getEmptyKey();
350 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000351
Chandler Carruth7253bba2015-01-24 11:33:55 +0000352 static inline CallValue getTombstoneKey() {
353 return DenseMapInfo<Instruction *>::getTombstoneKey();
354 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000355
Chandler Carruth7253bba2015-01-24 11:33:55 +0000356 static unsigned getHashValue(CallValue Val);
357 static bool isEqual(CallValue LHS, CallValue RHS);
358};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000359
360} // end namespace llvm
Chandler Carruth7253bba2015-01-24 11:33:55 +0000361
Chris Lattner92bb0f92011-01-03 03:41:27 +0000362unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000363 Instruction *Inst = Val.Inst;
Benjamin Kramer6ab86b12015-02-01 12:30:59 +0000364 // Hash all of the operands as pointers and mix in the opcode.
365 return hash_combine(
366 Inst->getOpcode(),
367 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000368}
369
Chris Lattner92bb0f92011-01-03 03:41:27 +0000370bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000371 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000372 if (LHS.isSentinel() || RHS.isSentinel())
373 return LHSI == RHSI;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000374 return LHSI->isIdenticalTo(RHSI);
375}
376
Chris Lattner79d83062011-01-03 02:20:48 +0000377//===----------------------------------------------------------------------===//
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000378// EarlyCSE implementation
Chris Lattner79d83062011-01-03 02:20:48 +0000379//===----------------------------------------------------------------------===//
380
Chris Lattner18ae5432011-01-02 23:04:14 +0000381namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000382
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000383/// A simple and fast domtree-based CSE pass.
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000384///
385/// This pass does a simple depth-first walk over the dominator tree,
386/// eliminating trivially redundant instructions and using instsimplify to
387/// canonicalize things as it goes. It is intended to be fast and catch obvious
388/// cases so that instcombine and other passes are more effective. It is
389/// expected that a later pass of GVN will catch the interesting/hard cases.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000390class EarlyCSE {
Chris Lattner704541b2011-01-02 21:47:05 +0000391public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000392 const TargetLibraryInfo &TLI;
393 const TargetTransformInfo &TTI;
394 DominatorTree &DT;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000395 AssumptionCache &AC;
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000396 const SimplifyQuery SQ;
Geoff Berry8d846052016-08-31 19:24:10 +0000397 MemorySSA *MSSA;
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000398 std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
Eugene Zelenko3b879392017-10-13 21:17:07 +0000399
400 using AllocatorTy =
401 RecyclingAllocator<BumpPtrAllocator,
402 ScopedHashTableVal<SimpleValue, Value *>>;
403 using ScopedHTType =
404 ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
405 AllocatorTy>;
Nadav Rotem465834c2012-07-24 10:51:42 +0000406
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000407 /// A scoped hash table of the current values of all of our simple
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000408 /// scalar expressions.
409 ///
410 /// As we walk down the domtree, we look to see if instructions are in this:
411 /// if so, we replace them with what we find, otherwise we insert them so
412 /// that dominated values can succeed in their lookup.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000413 ScopedHTType AvailableValues;
Nadav Rotem465834c2012-07-24 10:51:42 +0000414
Hiroshi Inouef2096492018-06-14 05:41:49 +0000415 /// A scoped hash table of the current values of previously encountered
416 /// memory locations.
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000417 ///
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000418 /// This allows us to get efficient access to dominating loads or stores when
419 /// we have a fully redundant load. In addition to the most recent load, we
420 /// keep track of a generation count of the read, which is compared against
421 /// the current generation count. The current generation count is incremented
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000422 /// after every possibly writing memory operation, which ensures that we only
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000423 /// CSE loads with other loads that have no intervening store. Ordering
424 /// events (such as fences or atomic instructions) increment the generation
425 /// count as well; essentially, we model these as writes to all possible
426 /// locations. Note that atomic and/or volatile loads and stores can be
427 /// present the table; it is the responsibility of the consumer to inspect
428 /// the atomicity/volatility if needed.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000429 struct LoadValue {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000430 Instruction *DefInst = nullptr;
431 unsigned Generation = 0;
432 int MatchingId = -1;
433 bool IsAtomic = false;
Philip Reames0adbb192018-03-14 21:35:06 +0000434
Eugene Zelenko3b879392017-10-13 21:17:07 +0000435 LoadValue() = default;
Geoff Berry5ae272c2016-04-28 15:22:37 +0000436 LoadValue(Instruction *Inst, unsigned Generation, unsigned MatchingId,
Philip Reamesca587fe2018-03-15 17:29:32 +0000437 bool IsAtomic)
Sanjoy Das07c65212016-06-16 20:47:57 +0000438 : DefInst(Inst), Generation(Generation), MatchingId(MatchingId),
Philip Reamesca587fe2018-03-15 17:29:32 +0000439 IsAtomic(IsAtomic) {}
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000440 };
Eugene Zelenko3b879392017-10-13 21:17:07 +0000441
442 using LoadMapAllocator =
443 RecyclingAllocator<BumpPtrAllocator,
444 ScopedHashTableVal<Value *, LoadValue>>;
445 using LoadHTType =
446 ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>,
447 LoadMapAllocator>;
448
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000449 LoadHTType AvailableLoads;
Fangrui Songf78650a2018-07-30 19:41:25 +0000450
Philip Reames0adbb192018-03-14 21:35:06 +0000451 // A scoped hash table mapping memory locations (represented as typed
452 // addresses) to generation numbers at which that memory location became
453 // (henceforth indefinitely) invariant.
454 using InvariantMapAllocator =
455 RecyclingAllocator<BumpPtrAllocator,
456 ScopedHashTableVal<MemoryLocation, unsigned>>;
457 using InvariantHTType =
458 ScopedHashTable<MemoryLocation, unsigned, DenseMapInfo<MemoryLocation>,
459 InvariantMapAllocator>;
460 InvariantHTType AvailableInvariants;
Nadav Rotem465834c2012-07-24 10:51:42 +0000461
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000462 /// A scoped hash table of the current values of read-only call
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000463 /// values.
464 ///
465 /// It uses the same generation count as loads.
Eugene Zelenko3b879392017-10-13 21:17:07 +0000466 using CallHTType =
467 ScopedHashTable<CallValue, std::pair<Instruction *, unsigned>>;
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000468 CallHTType AvailableCalls;
Nadav Rotem465834c2012-07-24 10:51:42 +0000469
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000470 /// This is the current generation of the memory value.
Eugene Zelenko3b879392017-10-13 21:17:07 +0000471 unsigned CurrentGeneration = 0;
Nadav Rotem465834c2012-07-24 10:51:42 +0000472
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000473 /// Set up the EarlyCSE runner for a particular function.
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000474 EarlyCSE(const DataLayout &DL, const TargetLibraryInfo &TLI,
475 const TargetTransformInfo &TTI, DominatorTree &DT,
476 AssumptionCache &AC, MemorySSA *MSSA)
477 : TLI(TLI), TTI(TTI), DT(DT), AC(AC), SQ(DL, &TLI, &DT, &AC), MSSA(MSSA),
Eugene Zelenko3b879392017-10-13 21:17:07 +0000478 MSSAUpdater(llvm::make_unique<MemorySSAUpdater>(MSSA)) {}
Chris Lattner704541b2011-01-02 21:47:05 +0000479
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000480 bool run();
Chris Lattner704541b2011-01-02 21:47:05 +0000481
482private:
Alina Sbirlea383ccfb2019-02-15 22:47:54 +0000483 unsigned ClobberCounter = 0;
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000484 // Almost a POD, but needs to call the constructors for the scoped hash
485 // tables so that a new scope gets pushed on. These are RAII so that the
486 // scope gets popped when the NodeScope is destroyed.
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000487 class NodeScope {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000488 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000489 NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
Philip Reames0adbb192018-03-14 21:35:06 +0000490 InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls)
491 : Scope(AvailableValues), LoadScope(AvailableLoads),
492 InvariantScope(AvailableInvariants), CallScope(AvailableCalls) {}
Eugene Zelenko3b879392017-10-13 21:17:07 +0000493 NodeScope(const NodeScope &) = delete;
494 NodeScope &operator=(const NodeScope &) = delete;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000495
Chandler Carruth7253bba2015-01-24 11:33:55 +0000496 private:
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000497 ScopedHTType::ScopeTy Scope;
498 LoadHTType::ScopeTy LoadScope;
Philip Reames0adbb192018-03-14 21:35:06 +0000499 InvariantHTType::ScopeTy InvariantScope;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000500 CallHTType::ScopeTy CallScope;
501 };
502
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000503 // Contains all the needed information to create a stack for doing a depth
Nick Lewyckyedd0a702016-09-07 01:49:41 +0000504 // first traversal of the tree. This includes scopes for values, loads, and
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000505 // calls as well as the generation. There is a child iterator so that the
Sanjoy Das5253a082016-04-27 01:44:31 +0000506 // children do not need to be store separately.
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000507 class StackNode {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000508 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000509 StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
Philip Reames0adbb192018-03-14 21:35:06 +0000510 InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls,
511 unsigned cg, DomTreeNode *n, DomTreeNode::iterator child,
512 DomTreeNode::iterator end)
Chandler Carruth7253bba2015-01-24 11:33:55 +0000513 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
Philip Reames0adbb192018-03-14 21:35:06 +0000514 EndIter(end),
515 Scopes(AvailableValues, AvailableLoads, AvailableInvariants,
516 AvailableCalls)
Eugene Zelenko3b879392017-10-13 21:17:07 +0000517 {}
518 StackNode(const StackNode &) = delete;
519 StackNode &operator=(const StackNode &) = delete;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000520
521 // Accessors.
522 unsigned currentGeneration() { return CurrentGeneration; }
523 unsigned childGeneration() { return ChildGeneration; }
524 void childGeneration(unsigned generation) { ChildGeneration = generation; }
525 DomTreeNode *node() { return Node; }
526 DomTreeNode::iterator childIter() { return ChildIter; }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000527
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000528 DomTreeNode *nextChild() {
529 DomTreeNode *child = *ChildIter;
530 ++ChildIter;
531 return child;
532 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000533
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000534 DomTreeNode::iterator end() { return EndIter; }
535 bool isProcessed() { return Processed; }
536 void process() { Processed = true; }
537
Chandler Carruth7253bba2015-01-24 11:33:55 +0000538 private:
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000539 unsigned CurrentGeneration;
540 unsigned ChildGeneration;
541 DomTreeNode *Node;
542 DomTreeNode::iterator ChildIter;
543 DomTreeNode::iterator EndIter;
544 NodeScope Scopes;
Eugene Zelenko3b879392017-10-13 21:17:07 +0000545 bool Processed = false;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000546 };
547
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000548 /// Wrapper class to handle memory instructions, including loads,
Chad Rosierf9327d62015-01-26 22:51:15 +0000549 /// stores and intrinsic loads and stores defined by the target.
550 class ParseMemoryInst {
551 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000552 ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
Eugene Zelenko3b879392017-10-13 21:17:07 +0000553 : Inst(Inst) {
Philip Reames9e5e2d62015-12-07 22:41:23 +0000554 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000555 if (TTI.getTgtMemIntrinsic(II, Info))
Philip Reames9e5e2d62015-12-07 22:41:23 +0000556 IsTargetMemInst = true;
557 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000558
Philip Reames9e5e2d62015-12-07 22:41:23 +0000559 bool isLoad() const {
560 if (IsTargetMemInst) return Info.ReadMem;
561 return isa<LoadInst>(Inst);
562 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000563
Philip Reames9e5e2d62015-12-07 22:41:23 +0000564 bool isStore() const {
565 if (IsTargetMemInst) return Info.WriteMem;
566 return isa<StoreInst>(Inst);
567 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000568
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000569 bool isAtomic() const {
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000570 if (IsTargetMemInst)
571 return Info.Ordering != AtomicOrdering::NotAtomic;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000572 return Inst->isAtomic();
573 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000574
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000575 bool isUnordered() const {
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000576 if (IsTargetMemInst)
577 return Info.isUnordered();
578
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000579 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
580 return LI->isUnordered();
581 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
582 return SI->isUnordered();
583 }
584 // Conservative answer
585 return !Inst->isAtomic();
586 }
587
588 bool isVolatile() const {
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000589 if (IsTargetMemInst)
590 return Info.IsVolatile;
591
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000592 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
593 return LI->isVolatile();
594 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
595 return SI->isVolatile();
596 }
597 // Conservative answer
598 return true;
599 }
600
Sanjoy Das07c65212016-06-16 20:47:57 +0000601 bool isInvariantLoad() const {
602 if (auto *LI = dyn_cast<LoadInst>(Inst))
Sanjoy Das1ab2fad2016-06-16 21:00:57 +0000603 return LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr;
Sanjoy Das07c65212016-06-16 20:47:57 +0000604 return false;
605 }
Junmo Park80440eb2016-02-18 10:09:20 +0000606
Arnaud A. de Grandmaison6fd488b2015-10-06 13:35:30 +0000607 bool isMatchingMemLoc(const ParseMemoryInst &Inst) const {
Philip Reames9e5e2d62015-12-07 22:41:23 +0000608 return (getPointerOperand() == Inst.getPointerOperand() &&
609 getMatchingId() == Inst.getMatchingId());
Chad Rosierf9327d62015-01-26 22:51:15 +0000610 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000611
Philip Reames9e5e2d62015-12-07 22:41:23 +0000612 bool isValid() const { return getPointerOperand() != nullptr; }
Chad Rosierf9327d62015-01-26 22:51:15 +0000613
Chad Rosierf9327d62015-01-26 22:51:15 +0000614 // For regular (non-intrinsic) loads/stores, this is set to -1. For
615 // intrinsic loads/stores, the id is retrieved from the corresponding
616 // field in the MemIntrinsicInfo structure. That field contains
617 // non-negative values only.
Philip Reames9e5e2d62015-12-07 22:41:23 +0000618 int getMatchingId() const {
619 if (IsTargetMemInst) return Info.MatchingId;
620 return -1;
621 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000622
Philip Reames9e5e2d62015-12-07 22:41:23 +0000623 Value *getPointerOperand() const {
624 if (IsTargetMemInst) return Info.PtrVal;
Renato Golin038ede22018-03-09 21:05:58 +0000625 return getLoadStorePointerOperand(Inst);
Philip Reames9e5e2d62015-12-07 22:41:23 +0000626 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000627
Philip Reames9e5e2d62015-12-07 22:41:23 +0000628 bool mayReadFromMemory() const {
629 if (IsTargetMemInst) return Info.ReadMem;
630 return Inst->mayReadFromMemory();
631 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000632
Philip Reames9e5e2d62015-12-07 22:41:23 +0000633 bool mayWriteToMemory() const {
634 if (IsTargetMemInst) return Info.WriteMem;
635 return Inst->mayWriteToMemory();
636 }
637
638 private:
Eugene Zelenko3b879392017-10-13 21:17:07 +0000639 bool IsTargetMemInst = false;
Philip Reames9e5e2d62015-12-07 22:41:23 +0000640 MemIntrinsicInfo Info;
641 Instruction *Inst;
Chad Rosierf9327d62015-01-26 22:51:15 +0000642 };
643
Chris Lattner18ae5432011-01-02 23:04:14 +0000644 bool processNode(DomTreeNode *Node);
Nadav Rotem465834c2012-07-24 10:51:42 +0000645
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000646 bool handleBranchCondition(Instruction *CondInst, const BranchInst *BI,
647 const BasicBlock *BB, const BasicBlock *Pred);
648
Chad Rosierf9327d62015-01-26 22:51:15 +0000649 Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const {
Sanjay Patel1c9867d2017-01-03 00:16:24 +0000650 if (auto *LI = dyn_cast<LoadInst>(Inst))
Chad Rosierf9327d62015-01-26 22:51:15 +0000651 return LI;
Sanjay Patel1c9867d2017-01-03 00:16:24 +0000652 if (auto *SI = dyn_cast<StoreInst>(Inst))
Chad Rosierf9327d62015-01-26 22:51:15 +0000653 return SI->getValueOperand();
654 assert(isa<IntrinsicInst>(Inst) && "Instruction not supported");
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000655 return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst),
656 ExpectedType);
Chad Rosierf9327d62015-01-26 22:51:15 +0000657 }
Geoff Berry8d846052016-08-31 19:24:10 +0000658
Philip Reames0adbb192018-03-14 21:35:06 +0000659 /// Return true if the instruction is known to only operate on memory
660 /// provably invariant in the given "generation".
661 bool isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt);
662
Geoff Berry8d846052016-08-31 19:24:10 +0000663 bool isSameMemGeneration(unsigned EarlierGeneration, unsigned LaterGeneration,
664 Instruction *EarlierInst, Instruction *LaterInst);
665
666 void removeMSSA(Instruction *Inst) {
667 if (!MSSA)
668 return;
Alina Sbirleaa782a702018-09-17 22:35:21 +0000669 if (VerifyMemorySSA)
670 MSSA->verifyMemorySSA();
Geoff Berry91e9a5c2016-10-25 16:18:47 +0000671 // Removing a store here can leave MemorySSA in an unoptimized state by
672 // creating MemoryPhis that have identical arguments and by creating
Alina Sbirleae2718892019-01-31 21:12:41 +0000673 // MemoryUses whose defining access is not an actual clobber. The phi case
674 // is handled by MemorySSA when passing OptimizePhis = true to
675 // removeMemoryAccess. The non-optimized MemoryUse case is lazily updated
676 // by MemorySSA's getClobberingMemoryAccess.
677 MSSAUpdater->removeMemoryAccess(Inst, true);
Geoff Berry8d846052016-08-31 19:24:10 +0000678 }
Chris Lattner704541b2011-01-02 21:47:05 +0000679};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000680
681} // end anonymous namespace
Chris Lattner704541b2011-01-02 21:47:05 +0000682
Geoff Berry68154682016-10-24 15:54:00 +0000683/// Determine if the memory referenced by LaterInst is from the same heap
684/// version as EarlierInst.
Geoff Berry8d846052016-08-31 19:24:10 +0000685/// This is currently called in two scenarios:
686///
687/// load p
688/// ...
689/// load p
690///
691/// and
692///
693/// x = load p
694/// ...
695/// store x, p
696///
697/// in both cases we want to verify that there are no possible writes to the
698/// memory referenced by p between the earlier and later instruction.
699bool EarlyCSE::isSameMemGeneration(unsigned EarlierGeneration,
700 unsigned LaterGeneration,
701 Instruction *EarlierInst,
702 Instruction *LaterInst) {
703 // Check the simple memory generation tracking first.
704 if (EarlierGeneration == LaterGeneration)
705 return true;
706
707 if (!MSSA)
708 return false;
709
Geoff Berryf7d5daa2017-07-14 20:13:21 +0000710 // If MemorySSA has determined that one of EarlierInst or LaterInst does not
711 // read/write memory, then we can safely return true here.
712 // FIXME: We could be more aggressive when checking doesNotAccessMemory(),
713 // onlyReadsMemory(), mayReadFromMemory(), and mayWriteToMemory() in this pass
714 // by also checking the MemorySSA MemoryAccess on the instruction. Initial
715 // experiments suggest this isn't worthwhile, at least for C/C++ code compiled
716 // with the default optimization pipeline.
717 auto *EarlierMA = MSSA->getMemoryAccess(EarlierInst);
718 if (!EarlierMA)
719 return true;
720 auto *LaterMA = MSSA->getMemoryAccess(LaterInst);
721 if (!LaterMA)
722 return true;
723
Geoff Berry8d846052016-08-31 19:24:10 +0000724 // Since we know LaterDef dominates LaterInst and EarlierInst dominates
725 // LaterInst, if LaterDef dominates EarlierInst then it can't occur between
726 // EarlierInst and LaterInst and neither can any other write that potentially
727 // clobbers LaterInst.
Alina Sbirlea383ccfb2019-02-15 22:47:54 +0000728 MemoryAccess *LaterDef;
729 if (ClobberCounter < EarlyCSEMssaOptCap) {
730 LaterDef = MSSA->getWalker()->getClobberingMemoryAccess(LaterInst);
731 ClobberCounter++;
732 } else
733 LaterDef = LaterMA->getDefiningAccess();
734
Geoff Berryf7d5daa2017-07-14 20:13:21 +0000735 return MSSA->dominates(LaterDef, EarlierMA);
Geoff Berry8d846052016-08-31 19:24:10 +0000736}
737
Philip Reames0adbb192018-03-14 21:35:06 +0000738bool EarlyCSE::isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt) {
739 // A location loaded from with an invariant_load is assumed to *never* change
740 // within the visible scope of the compilation.
741 if (auto *LI = dyn_cast<LoadInst>(I))
742 if (LI->getMetadata(LLVMContext::MD_invariant_load))
743 return true;
744
745 auto MemLocOpt = MemoryLocation::getOrNone(I);
746 if (!MemLocOpt)
747 // "target" intrinsic forms of loads aren't currently known to
748 // MemoryLocation::get. TODO
749 return false;
750 MemoryLocation MemLoc = *MemLocOpt;
751 if (!AvailableInvariants.count(MemLoc))
752 return false;
753
754 // Is the generation at which this became invariant older than the
755 // current one?
756 return AvailableInvariants.lookup(MemLoc) <= GenAt;
757}
758
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000759bool EarlyCSE::handleBranchCondition(Instruction *CondInst,
760 const BranchInst *BI, const BasicBlock *BB,
761 const BasicBlock *Pred) {
762 assert(BI->isConditional() && "Should be a conditional branch!");
763 assert(BI->getCondition() == CondInst && "Wrong condition?");
764 assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
765 auto *TorF = (BI->getSuccessor(0) == BB)
766 ? ConstantInt::getTrue(BB->getContext())
767 : ConstantInt::getFalse(BB->getContext());
Simon Pilgrimdee9c672018-06-14 14:22:03 +0000768 auto MatchBinOp = [](Instruction *I, unsigned Opcode) {
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000769 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(I))
Simon Pilgrimdee9c672018-06-14 14:22:03 +0000770 return BOp->getOpcode() == Opcode;
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000771 return false;
772 };
773 // If the condition is AND operation, we can propagate its operands into the
774 // true branch. If it is OR operation, we can propagate them into the false
775 // branch.
Simon Pilgrimdee9c672018-06-14 14:22:03 +0000776 unsigned PropagateOpcode =
777 (BI->getSuccessor(0) == BB) ? Instruction::And : Instruction::Or;
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000778
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000779 bool MadeChanges = false;
780 SmallVector<Instruction *, 4> WorkList;
781 SmallPtrSet<Instruction *, 4> Visited;
782 WorkList.push_back(CondInst);
783 while (!WorkList.empty()) {
784 Instruction *Curr = WorkList.pop_back_val();
785
786 AvailableValues.insert(Curr, TorF);
787 LLVM_DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
788 << Curr->getName() << "' as " << *TorF << " in "
789 << BB->getName() << "\n");
790 if (!DebugCounter::shouldExecute(CSECounter)) {
791 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
792 } else {
793 // Replace all dominated uses with the known value.
794 if (unsigned Count = replaceDominatedUsesWith(Curr, TorF, DT,
795 BasicBlockEdge(Pred, BB))) {
796 NumCSECVP += Count;
797 MadeChanges = true;
798 }
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000799 }
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000800
Simon Pilgrimdee9c672018-06-14 14:22:03 +0000801 if (MatchBinOp(Curr, PropagateOpcode))
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000802 for (auto &Op : cast<BinaryOperator>(Curr)->operands())
803 if (Instruction *OPI = dyn_cast<Instruction>(Op))
804 if (SimpleValue::canHandle(OPI) && Visited.insert(OPI).second)
805 WorkList.push_back(OPI);
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000806 }
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000807
808 return MadeChanges;
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000809}
810
Chris Lattner18ae5432011-01-02 23:04:14 +0000811bool EarlyCSE::processNode(DomTreeNode *Node) {
Chad Rosier1a4bc112016-04-22 18:47:21 +0000812 bool Changed = false;
Chris Lattner18ae5432011-01-02 23:04:14 +0000813 BasicBlock *BB = Node->getBlock();
Nadav Rotem465834c2012-07-24 10:51:42 +0000814
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000815 // If this block has a single predecessor, then the predecessor is the parent
816 // of the domtree node and all of the live out memory values are still current
817 // in this block. If this block has multiple predecessors, then they could
818 // have invalidated the live-out memory values of our parent value. For now,
819 // just be conservative and invalidate memory if this block has multiple
820 // predecessors.
Craig Topperf40110f2014-04-25 05:29:35 +0000821 if (!BB->getSinglePredecessor())
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000822 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000823
Philip Reames7c78ef72015-05-22 23:53:24 +0000824 // If this node has a single predecessor which ends in a conditional branch,
825 // we can infer the value of the branch condition given that we took this
Chad Rosierb346dcb2016-04-20 19:16:23 +0000826 // path. We need the single predecessor to ensure there's not another path
Philip Reames7c78ef72015-05-22 23:53:24 +0000827 // which reaches this block where the condition might hold a different
828 // value. Since we're adding this to the scoped hash table (like any other
829 // def), it will have been popped if we encounter a future merge block.
Sanjay Patelf1e1fba2017-03-15 20:25:05 +0000830 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
831 auto *BI = dyn_cast<BranchInst>(Pred->getTerminator());
832 if (BI && BI->isConditional()) {
833 auto *CondInst = dyn_cast<Instruction>(BI->getCondition());
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000834 if (CondInst && SimpleValue::canHandle(CondInst))
835 Changed |= handleBranchCondition(CondInst, BI, BB, Pred);
Sanjay Patelf1e1fba2017-03-15 20:25:05 +0000836 }
837 }
Philip Reames7c78ef72015-05-22 23:53:24 +0000838
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000839 /// LastStore - Keep track of the last non-volatile store that we saw... for
840 /// as long as there in no instruction that reads memory. If we see a store
841 /// to the same location, we delete the dead store. This zaps trivial dead
842 /// stores which can occur in bitfield code among other things.
Chad Rosierf9327d62015-01-26 22:51:15 +0000843 Instruction *LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000844
Chris Lattner18ae5432011-01-02 23:04:14 +0000845 // See if any instructions in the block can be eliminated. If so, do it. If
846 // not, add them to AvailableValues.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000847 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +0000848 Instruction *Inst = &*I++;
Nadav Rotem465834c2012-07-24 10:51:42 +0000849
Chris Lattner18ae5432011-01-02 23:04:14 +0000850 // Dead instructions should just be removed.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000851 if (isInstructionTriviallyDead(Inst, &TLI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000852 LLVM_DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000853 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000854 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000855 continue;
856 }
Davide Italianoe41e1d02018-12-17 01:42:39 +0000857 if (!salvageDebugInfo(*Inst))
858 replaceDbgUsesWithUndef(Inst);
Geoff Berry8d846052016-08-31 19:24:10 +0000859 removeMSSA(Inst);
Chris Lattner18ae5432011-01-02 23:04:14 +0000860 Inst->eraseFromParent();
861 Changed = true;
Chris Lattner8fac5db2011-01-02 23:19:45 +0000862 ++NumSimplify;
Chris Lattner18ae5432011-01-02 23:04:14 +0000863 continue;
864 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000865
Hal Finkel1e16fa32014-11-03 20:21:32 +0000866 // Skip assume intrinsics, they don't really have side effects (although
867 // they're marked as such to ensure preservation of control dependencies),
Max Kazantsev531db9a2017-04-28 06:25:39 +0000868 // and this pass will not bother with its removal. However, we should mark
869 // its condition as true for all dominated blocks.
Hal Finkel1e16fa32014-11-03 20:21:32 +0000870 if (match(Inst, m_Intrinsic<Intrinsic::assume>())) {
Max Kazantsev531db9a2017-04-28 06:25:39 +0000871 auto *CondI =
872 dyn_cast<Instruction>(cast<CallInst>(Inst)->getArgOperand(0));
873 if (CondI && SimpleValue::canHandle(CondI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000874 LLVM_DEBUG(dbgs() << "EarlyCSE considering assumption: " << *Inst
875 << '\n');
Max Kazantsev531db9a2017-04-28 06:25:39 +0000876 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
877 } else
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000878 LLVM_DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n');
Hal Finkel1e16fa32014-11-03 20:21:32 +0000879 continue;
880 }
881
Dan Gohman2c74fe92017-11-08 21:59:51 +0000882 // Skip sideeffect intrinsics, for the same reason as assume intrinsics.
883 if (match(Inst, m_Intrinsic<Intrinsic::sideeffect>())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000884 LLVM_DEBUG(dbgs() << "EarlyCSE skipping sideeffect: " << *Inst << '\n');
Dan Gohman2c74fe92017-11-08 21:59:51 +0000885 continue;
886 }
887
Philip Reames0adbb192018-03-14 21:35:06 +0000888 // We can skip all invariant.start intrinsics since they only read memory,
889 // and we can forward values across it. For invariant starts without
890 // invariant ends, we can use the fact that the invariantness never ends to
891 // start a scope in the current generaton which is true for all future
892 // generations. Also, we dont need to consume the last store since the
893 // semantics of invariant.start allow us to perform DSE of the last
Fangrui Songf78650a2018-07-30 19:41:25 +0000894 // store, if there was a store following invariant.start. Consider:
Anna Thomasb2d12b82016-08-09 20:00:47 +0000895 //
896 // store 30, i8* p
897 // invariant.start(p)
898 // store 40, i8* p
899 // We can DSE the store to 30, since the store 40 to invariant location p
900 // causes undefined behaviour.
Philip Reames0adbb192018-03-14 21:35:06 +0000901 if (match(Inst, m_Intrinsic<Intrinsic::invariant_start>())) {
Fangrui Songf78650a2018-07-30 19:41:25 +0000902 // If there are any uses, the scope might end.
Philip Reames0adbb192018-03-14 21:35:06 +0000903 if (!Inst->use_empty())
904 continue;
905 auto *CI = cast<CallInst>(Inst);
906 MemoryLocation MemLoc = MemoryLocation::getForArgument(CI, 1, TLI);
Philip Reames422024a2018-03-15 18:12:27 +0000907 // Don't start a scope if we already have a better one pushed
908 if (!AvailableInvariants.count(MemLoc))
909 AvailableInvariants.insert(MemLoc, CurrentGeneration);
Anna Thomasb2d12b82016-08-09 20:00:47 +0000910 continue;
Philip Reames0adbb192018-03-14 21:35:06 +0000911 }
Anna Thomasb2d12b82016-08-09 20:00:47 +0000912
Max Kazantsev3c284bd2018-08-30 03:39:16 +0000913 if (isGuard(Inst)) {
Sanjoy Das107aefc2016-04-29 22:23:16 +0000914 if (auto *CondI =
915 dyn_cast<Instruction>(cast<CallInst>(Inst)->getArgOperand(0))) {
Max Kazantsev0589d9f2017-04-28 06:05:48 +0000916 if (SimpleValue::canHandle(CondI)) {
917 // Do we already know the actual value of this condition?
918 if (auto *KnownCond = AvailableValues.lookup(CondI)) {
919 // Is the condition known to be true?
920 if (isa<ConstantInt>(KnownCond) &&
Craig Topper79ab6432017-07-06 18:39:47 +0000921 cast<ConstantInt>(KnownCond)->isOne()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000922 LLVM_DEBUG(dbgs()
923 << "EarlyCSE removing guard: " << *Inst << '\n');
Max Kazantsev0589d9f2017-04-28 06:05:48 +0000924 removeMSSA(Inst);
925 Inst->eraseFromParent();
926 Changed = true;
927 continue;
928 } else
929 // Use the known value if it wasn't true.
930 cast<CallInst>(Inst)->setArgOperand(0, KnownCond);
931 }
932 // The condition we're on guarding here is true for all dominated
933 // locations.
Sanjoy Dasee81b232016-04-29 21:52:58 +0000934 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
Max Kazantsev0589d9f2017-04-28 06:05:48 +0000935 }
Sanjoy Dasee81b232016-04-29 21:52:58 +0000936 }
937
938 // Guard intrinsics read all memory, but don't write any memory.
939 // Accordingly, don't update the generation but consume the last store (to
940 // avoid an incorrect DSE).
941 LastStore = nullptr;
942 continue;
943 }
944
Chris Lattner18ae5432011-01-02 23:04:14 +0000945 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
946 // its simpler value.
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000947 if (Value *V = SimplifyInstruction(Inst, SQ)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000948 LLVM_DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V
949 << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000950 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000951 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000952 } else {
953 bool Killed = false;
954 if (!Inst->use_empty()) {
955 Inst->replaceAllUsesWith(V);
956 Changed = true;
957 }
958 if (isInstructionTriviallyDead(Inst, &TLI)) {
959 removeMSSA(Inst);
960 Inst->eraseFromParent();
961 Changed = true;
962 Killed = true;
963 }
964 if (Changed)
965 ++NumSimplify;
966 if (Killed)
967 continue;
David Majnemerb8da3a22016-06-25 00:04:10 +0000968 }
Chris Lattner18ae5432011-01-02 23:04:14 +0000969 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000970
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000971 // If this is a simple instruction that we can value number, process it.
972 if (SimpleValue::canHandle(Inst)) {
973 // See if the instruction has an available value. If so, use it.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000974 if (Value *V = AvailableValues.lookup(Inst)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000975 LLVM_DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V
976 << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000977 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000978 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000979 continue;
980 }
David Majnemer9554c132016-04-22 06:37:45 +0000981 if (auto *I = dyn_cast<Instruction>(V))
982 I->andIRFlags(Inst);
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000983 Inst->replaceAllUsesWith(V);
Geoff Berry8d846052016-08-31 19:24:10 +0000984 removeMSSA(Inst);
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000985 Inst->eraseFromParent();
986 Changed = true;
987 ++NumCSE;
988 continue;
989 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000990
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000991 // Otherwise, just remember that this value is available.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000992 AvailableValues.insert(Inst, Inst);
Chris Lattner18ae5432011-01-02 23:04:14 +0000993 continue;
994 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000995
Chad Rosierf9327d62015-01-26 22:51:15 +0000996 ParseMemoryInst MemInst(Inst, TTI);
Chris Lattner92bb0f92011-01-03 03:41:27 +0000997 // If this is a non-volatile load, process it.
Chad Rosierf9327d62015-01-26 22:51:15 +0000998 if (MemInst.isValid() && MemInst.isLoad()) {
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000999 // (conservatively) we can't peak past the ordering implied by this
1000 // operation, but we can add this load to our set of available values
1001 if (MemInst.isVolatile() || !MemInst.isUnordered()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001002 LastStore = nullptr;
Philip Reames8fc2cbf2015-12-08 21:45:41 +00001003 ++CurrentGeneration;
Chris Lattner9e5e9ed2011-01-03 04:17:24 +00001004 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001005
Philip Reamesca587fe2018-03-15 17:29:32 +00001006 if (MemInst.isInvariantLoad()) {
1007 // If we pass an invariant load, we know that memory location is
1008 // indefinitely constant from the moment of first dereferenceability.
Philip Reames422024a2018-03-15 18:12:27 +00001009 // We conservatively treat the invariant_load as that moment. If we
1010 // pass a invariant load after already establishing a scope, don't
1011 // restart it since we want to preserve the earliest point seen.
Philip Reamesca587fe2018-03-15 17:29:32 +00001012 auto MemLoc = MemoryLocation::get(Inst);
Philip Reames422024a2018-03-15 18:12:27 +00001013 if (!AvailableInvariants.count(MemLoc))
1014 AvailableInvariants.insert(MemLoc, CurrentGeneration);
Philip Reamesca587fe2018-03-15 17:29:32 +00001015 }
1016
Chris Lattner92bb0f92011-01-03 03:41:27 +00001017 // If we have an available version of this load, and if it is the right
Sanjoy Das07c65212016-06-16 20:47:57 +00001018 // generation or the load is known to be from an invariant location,
1019 // replace this instruction.
1020 //
Geoff Berry64f5ed12016-08-31 17:45:31 +00001021 // If either the dominating load or the current load are invariant, then
1022 // we can assume the current load loads the same value as the dominating
1023 // load.
Philip Reames9e5e2d62015-12-07 22:41:23 +00001024 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
Sanjoy Das07c65212016-06-16 20:47:57 +00001025 if (InVal.DefInst != nullptr &&
Philip Reames8fc2cbf2015-12-08 21:45:41 +00001026 InVal.MatchingId == MemInst.getMatchingId() &&
1027 // We don't yet handle removing loads with ordering of any kind.
1028 !MemInst.isVolatile() && MemInst.isUnordered() &&
1029 // We can't replace an atomic load with one which isn't also atomic.
Geoff Berry8d846052016-08-31 19:24:10 +00001030 InVal.IsAtomic >= MemInst.isAtomic() &&
Philip Reamesca587fe2018-03-15 17:29:32 +00001031 (isOperatingOnInvariantMemAt(Inst, InVal.Generation) ||
Geoff Berry8d846052016-08-31 19:24:10 +00001032 isSameMemGeneration(InVal.Generation, CurrentGeneration,
1033 InVal.DefInst, Inst))) {
Philip Reames32b55182016-05-06 01:13:58 +00001034 Value *Op = getOrCreateResult(InVal.DefInst, Inst->getType());
Chad Rosierf9327d62015-01-26 22:51:15 +00001035 if (Op != nullptr) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001036 LLVM_DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst
1037 << " to: " << *InVal.DefInst << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001038 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001039 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001040 continue;
1041 }
Chad Rosierf9327d62015-01-26 22:51:15 +00001042 if (!Inst->use_empty())
1043 Inst->replaceAllUsesWith(Op);
Geoff Berry8d846052016-08-31 19:24:10 +00001044 removeMSSA(Inst);
Chad Rosierf9327d62015-01-26 22:51:15 +00001045 Inst->eraseFromParent();
1046 Changed = true;
1047 ++NumCSELoad;
1048 continue;
1049 }
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001050 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001051
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001052 // Otherwise, remember that we have this instruction.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +00001053 AvailableLoads.insert(
Philip Reames9e5e2d62015-12-07 22:41:23 +00001054 MemInst.getPointerOperand(),
Philip Reames8fc2cbf2015-12-08 21:45:41 +00001055 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
Philip Reamesca587fe2018-03-15 17:29:32 +00001056 MemInst.isAtomic()));
Craig Topperf40110f2014-04-25 05:29:35 +00001057 LastStore = nullptr;
Chris Lattner92bb0f92011-01-03 03:41:27 +00001058 continue;
1059 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001060
Sanjoy Das6de072a2017-01-17 20:15:47 +00001061 // If this instruction may read from memory or throw (and potentially read
1062 // from memory in the exception handler), forget LastStore. Load/store
1063 // intrinsics will indicate both a read and a write to memory. The target
1064 // may override this (e.g. so that a store intrinsic does not read from
1065 // memory, and thus will be treated the same as a regular store for
1066 // commoning purposes).
1067 if ((Inst->mayReadFromMemory() || Inst->mayThrow()) &&
Chad Rosierf9327d62015-01-26 22:51:15 +00001068 !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
Craig Topperf40110f2014-04-25 05:29:35 +00001069 LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +00001070
Chris Lattner92bb0f92011-01-03 03:41:27 +00001071 // If this is a read-only call, process it.
1072 if (CallValue::canHandle(Inst)) {
1073 // If we have an available version of this call, and if it is the right
1074 // generation, replace this instruction.
Geoff Berry2f64c202016-05-13 17:54:58 +00001075 std::pair<Instruction *, unsigned> InVal = AvailableCalls.lookup(Inst);
Geoff Berry8d846052016-08-31 19:24:10 +00001076 if (InVal.first != nullptr &&
1077 isSameMemGeneration(InVal.second, CurrentGeneration, InVal.first,
1078 Inst)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001079 LLVM_DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst
1080 << " to: " << *InVal.first << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001081 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001082 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001083 continue;
1084 }
Chandler Carruth7253bba2015-01-24 11:33:55 +00001085 if (!Inst->use_empty())
1086 Inst->replaceAllUsesWith(InVal.first);
Geoff Berry8d846052016-08-31 19:24:10 +00001087 removeMSSA(Inst);
Chris Lattner92bb0f92011-01-03 03:41:27 +00001088 Inst->eraseFromParent();
1089 Changed = true;
1090 ++NumCSECall;
1091 continue;
1092 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001093
Chris Lattner92bb0f92011-01-03 03:41:27 +00001094 // Otherwise, remember that we have this instruction.
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001095 AvailableCalls.insert(
Geoff Berry2f64c202016-05-13 17:54:58 +00001096 Inst, std::pair<Instruction *, unsigned>(Inst, CurrentGeneration));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001097 continue;
1098 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001099
Philip Reamesdfd890d2015-08-27 01:32:33 +00001100 // A release fence requires that all stores complete before it, but does
1101 // not prevent the reordering of following loads 'before' the fence. As a
1102 // result, we don't need to consider it as writing to memory and don't need
1103 // to advance the generation. We do need to prevent DSE across the fence,
1104 // but that's handled above.
1105 if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
JF Bastien800f87a2016-04-06 21:19:33 +00001106 if (FI->getOrdering() == AtomicOrdering::Release) {
Philip Reamesdfd890d2015-08-27 01:32:33 +00001107 assert(Inst->mayReadFromMemory() && "relied on to prevent DSE above");
1108 continue;
1109 }
1110
Philip Reamesae1f265b2015-12-16 01:01:30 +00001111 // write back DSE - If we write back the same value we just loaded from
1112 // the same location and haven't passed any intervening writes or ordering
1113 // operations, we can remove the write. The primary benefit is in allowing
1114 // the available load table to remain valid and value forward past where
1115 // the store originally was.
1116 if (MemInst.isValid() && MemInst.isStore()) {
1117 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
Philip Reames32b55182016-05-06 01:13:58 +00001118 if (InVal.DefInst &&
1119 InVal.DefInst == getOrCreateResult(Inst, InVal.DefInst->getType()) &&
Philip Reamesae1f265b2015-12-16 01:01:30 +00001120 InVal.MatchingId == MemInst.getMatchingId() &&
1121 // We don't yet handle removing stores with ordering of any kind.
Geoff Berry8d846052016-08-31 19:24:10 +00001122 !MemInst.isVolatile() && MemInst.isUnordered() &&
Philip Reames0adbb192018-03-14 21:35:06 +00001123 (isOperatingOnInvariantMemAt(Inst, InVal.Generation) ||
1124 isSameMemGeneration(InVal.Generation, CurrentGeneration,
1125 InVal.DefInst, Inst))) {
Geoff Berry8d846052016-08-31 19:24:10 +00001126 // It is okay to have a LastStore to a different pointer here if MemorySSA
1127 // tells us that the load and store are from the same memory generation.
1128 // In that case, LastStore should keep its present value since we're
1129 // removing the current store.
Philip Reamesae1f265b2015-12-16 01:01:30 +00001130 assert((!LastStore ||
1131 ParseMemoryInst(LastStore, TTI).getPointerOperand() ==
Geoff Berry8d846052016-08-31 19:24:10 +00001132 MemInst.getPointerOperand() ||
1133 MSSA) &&
1134 "can't have an intervening store if not using MemorySSA!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001135 LLVM_DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << *Inst << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001136 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001137 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001138 continue;
1139 }
Geoff Berry8d846052016-08-31 19:24:10 +00001140 removeMSSA(Inst);
Philip Reamesae1f265b2015-12-16 01:01:30 +00001141 Inst->eraseFromParent();
1142 Changed = true;
1143 ++NumDSE;
1144 // We can avoid incrementing the generation count since we were able
1145 // to eliminate this store.
1146 continue;
1147 }
1148 }
1149
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001150 // Okay, this isn't something we can CSE at all. Check to see if it is
1151 // something that could modify memory. If so, our available memory values
1152 // cannot be used so bump the generation count.
Chris Lattnere0e32a92011-01-03 03:46:34 +00001153 if (Inst->mayWriteToMemory()) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001154 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +00001155
Chad Rosierf9327d62015-01-26 22:51:15 +00001156 if (MemInst.isValid() && MemInst.isStore()) {
Chris Lattner9e5e9ed2011-01-03 04:17:24 +00001157 // We do a trivial form of DSE if there are two stores to the same
Philip Reames15145fb2015-12-17 18:50:50 +00001158 // location with no intervening loads. Delete the earlier store.
1159 // At the moment, we don't remove ordered stores, but do remove
1160 // unordered atomic stores. There's no special requirement (for
1161 // unordered atomics) about removing atomic stores only in favor of
Kristina Brooks5b1e1c02019-03-12 07:08:19 +00001162 // other atomic stores since we were going to execute the non-atomic
Philip Reames15145fb2015-12-17 18:50:50 +00001163 // one anyway and the atomic one might never have become visible.
Chad Rosierf9327d62015-01-26 22:51:15 +00001164 if (LastStore) {
1165 ParseMemoryInst LastStoreMemInst(LastStore, TTI);
Philip Reames15145fb2015-12-17 18:50:50 +00001166 assert(LastStoreMemInst.isUnordered() &&
1167 !LastStoreMemInst.isVolatile() &&
1168 "Violated invariant");
Chad Rosierf9327d62015-01-26 22:51:15 +00001169 if (LastStoreMemInst.isMatchingMemLoc(MemInst)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001170 LLVM_DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
1171 << " due to: " << *Inst << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001172 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001173 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001174 } else {
1175 removeMSSA(LastStore);
1176 LastStore->eraseFromParent();
1177 Changed = true;
1178 ++NumDSE;
1179 LastStore = nullptr;
1180 }
Chad Rosierf9327d62015-01-26 22:51:15 +00001181 }
Philip Reames018dbf12014-11-18 17:46:32 +00001182 // fallthrough - we can exploit information about this store
Chris Lattner9e5e9ed2011-01-03 04:17:24 +00001183 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001184
Chris Lattner9e5e9ed2011-01-03 04:17:24 +00001185 // Okay, we just invalidated anything we knew about loaded values. Try
1186 // to salvage *something* by remembering that the stored value is a live
1187 // version of the pointer. It is safe to forward from volatile stores
1188 // to non-volatile loads, so we don't have to check for volatility of
1189 // the store.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +00001190 AvailableLoads.insert(
Philip Reames9e5e2d62015-12-07 22:41:23 +00001191 MemInst.getPointerOperand(),
Philip Reames8fc2cbf2015-12-08 21:45:41 +00001192 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
Philip Reamesca587fe2018-03-15 17:29:32 +00001193 MemInst.isAtomic()));
Nadav Rotem465834c2012-07-24 10:51:42 +00001194
Philip Reames15145fb2015-12-17 18:50:50 +00001195 // Remember that this was the last unordered store we saw for DSE. We
1196 // don't yet handle DSE on ordered or volatile stores since we don't
1197 // have a good way to model the ordering requirement for following
1198 // passes once the store is removed. We could insert a fence, but
1199 // since fences are slightly stronger than stores in their ordering,
1200 // it's not clear this is a profitable transform. Another option would
1201 // be to merge the ordering with that of the post dominating store.
1202 if (MemInst.isUnordered() && !MemInst.isVolatile())
Chad Rosierf9327d62015-01-26 22:51:15 +00001203 LastStore = Inst;
Philip Reames8fc2cbf2015-12-08 21:45:41 +00001204 else
1205 LastStore = nullptr;
Chris Lattnere0e32a92011-01-03 03:46:34 +00001206 }
1207 }
Chris Lattner18ae5432011-01-02 23:04:14 +00001208 }
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001209
Chris Lattner18ae5432011-01-02 23:04:14 +00001210 return Changed;
Chris Lattner704541b2011-01-02 21:47:05 +00001211}
Chris Lattner18ae5432011-01-02 23:04:14 +00001212
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001213bool EarlyCSE::run() {
Chandler Carruth7253bba2015-01-24 11:33:55 +00001214 // Note, deque is being used here because there is significant performance
1215 // gains over vector when the container becomes very large due to the
1216 // specific access patterns. For more information see the mailing list
1217 // discussion on this:
Tanya Lattner0d28f802015-08-05 03:51:17 +00001218 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
Lenny Maiorani9eefc812014-09-20 13:29:20 +00001219 std::deque<StackNode *> nodesToProcess;
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001220
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001221 bool Changed = false;
1222
1223 // Process the root node.
Chandler Carruth7253bba2015-01-24 11:33:55 +00001224 nodesToProcess.push_back(new StackNode(
Philip Reames0adbb192018-03-14 21:35:06 +00001225 AvailableValues, AvailableLoads, AvailableInvariants, AvailableCalls,
1226 CurrentGeneration, DT.getRootNode(),
1227 DT.getRootNode()->begin(), DT.getRootNode()->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001228
Alina Sbirlea73446cd2019-02-21 19:49:57 +00001229 assert(!CurrentGeneration && "Create a new EarlyCSE instance to rerun it.");
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001230
1231 // Process the stack.
1232 while (!nodesToProcess.empty()) {
1233 // Grab the first item off the stack. Set the current generation, remove
1234 // the node from the stack, and process it.
Michael Gottesman2bf01732013-12-05 18:42:12 +00001235 StackNode *NodeToProcess = nodesToProcess.back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001236
1237 // Initialize class members.
1238 CurrentGeneration = NodeToProcess->currentGeneration();
1239
1240 // Check if the node needs to be processed.
1241 if (!NodeToProcess->isProcessed()) {
1242 // Process the node.
1243 Changed |= processNode(NodeToProcess->node());
1244 NodeToProcess->childGeneration(CurrentGeneration);
1245 NodeToProcess->process();
1246 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
1247 // Push the next child onto the stack.
1248 DomTreeNode *child = NodeToProcess->nextChild();
Michael Gottesman2bf01732013-12-05 18:42:12 +00001249 nodesToProcess.push_back(
Philip Reames0adbb192018-03-14 21:35:06 +00001250 new StackNode(AvailableValues, AvailableLoads, AvailableInvariants,
1251 AvailableCalls, NodeToProcess->childGeneration(),
1252 child, child->begin(), child->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001253 } else {
1254 // It has been processed, and there are no more children to process,
1255 // so delete it and pop it off the stack.
1256 delete NodeToProcess;
Michael Gottesman2bf01732013-12-05 18:42:12 +00001257 nodesToProcess.pop_back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001258 }
1259 } // while (!nodes...)
1260
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001261 return Changed;
Chris Lattner18ae5432011-01-02 23:04:14 +00001262}
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001263
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001264PreservedAnalyses EarlyCSEPass::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +00001265 FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +00001266 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1267 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
1268 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001269 auto &AC = AM.getResult<AssumptionAnalysis>(F);
Geoff Berry8d846052016-08-31 19:24:10 +00001270 auto *MSSA =
1271 UseMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA() : nullptr;
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001272
Daniel Berlin4d0fe642017-04-28 19:55:38 +00001273 EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001274
1275 if (!CSE.run())
1276 return PreservedAnalyses::all();
1277
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001278 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +00001279 PA.preserveSet<CFGAnalyses>();
Davide Italiano02861d82016-06-08 21:31:55 +00001280 PA.preserve<GlobalsAA>();
Geoff Berry8d846052016-08-31 19:24:10 +00001281 if (UseMemorySSA)
1282 PA.preserve<MemorySSAAnalysis>();
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001283 return PA;
1284}
1285
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001286namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +00001287
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001288/// A simple and fast domtree-based CSE pass.
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001289///
1290/// This pass does a simple depth-first walk over the dominator tree,
1291/// eliminating trivially redundant instructions and using instsimplify to
1292/// canonicalize things as it goes. It is intended to be fast and catch obvious
1293/// cases so that instcombine and other passes are more effective. It is
1294/// expected that a later pass of GVN will catch the interesting/hard cases.
Geoff Berry8d846052016-08-31 19:24:10 +00001295template<bool UseMemorySSA>
1296class EarlyCSELegacyCommonPass : public FunctionPass {
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001297public:
1298 static char ID;
1299
Geoff Berry8d846052016-08-31 19:24:10 +00001300 EarlyCSELegacyCommonPass() : FunctionPass(ID) {
1301 if (UseMemorySSA)
1302 initializeEarlyCSEMemSSALegacyPassPass(*PassRegistry::getPassRegistry());
1303 else
1304 initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry());
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001305 }
1306
1307 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001308 if (skipFunction(F))
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001309 return false;
1310
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001311 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +00001312 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001313 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001314 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Geoff Berry8d846052016-08-31 19:24:10 +00001315 auto *MSSA =
1316 UseMemorySSA ? &getAnalysis<MemorySSAWrapperPass>().getMSSA() : nullptr;
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001317
Daniel Berlin4d0fe642017-04-28 19:55:38 +00001318 EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001319
1320 return CSE.run();
1321 }
1322
1323 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001324 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001325 AU.addRequired<DominatorTreeWrapperPass>();
1326 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +00001327 AU.addRequired<TargetTransformInfoWrapperPass>();
Geoff Berry8d846052016-08-31 19:24:10 +00001328 if (UseMemorySSA) {
1329 AU.addRequired<MemorySSAWrapperPass>();
1330 AU.addPreserved<MemorySSAWrapperPass>();
1331 }
James Molloyefbba722015-09-10 10:22:12 +00001332 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001333 AU.setPreservesCFG();
1334 }
1335};
Eugene Zelenko3b879392017-10-13 21:17:07 +00001336
1337} // end anonymous namespace
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001338
Geoff Berry8d846052016-08-31 19:24:10 +00001339using EarlyCSELegacyPass = EarlyCSELegacyCommonPass</*UseMemorySSA=*/false>;
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001340
Geoff Berry8d846052016-08-31 19:24:10 +00001341template<>
1342char EarlyCSELegacyPass::ID = 0;
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001343
1344INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
1345 false)
Chandler Carruth705b1852015-01-31 03:43:40 +00001346INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001347INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001348INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1349INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1350INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)
Geoff Berry8d846052016-08-31 19:24:10 +00001351
1352using EarlyCSEMemSSALegacyPass =
1353 EarlyCSELegacyCommonPass</*UseMemorySSA=*/true>;
1354
1355template<>
1356char EarlyCSEMemSSALegacyPass::ID = 0;
1357
1358FunctionPass *llvm::createEarlyCSEPass(bool UseMemorySSA) {
1359 if (UseMemorySSA)
1360 return new EarlyCSEMemSSALegacyPass();
1361 else
1362 return new EarlyCSELegacyPass();
1363}
1364
1365INITIALIZE_PASS_BEGIN(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1366 "Early CSE w/ MemorySSA", false, false)
1367INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001368INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Geoff Berry8d846052016-08-31 19:24:10 +00001369INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1370INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1371INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
1372INITIALIZE_PASS_END(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1373 "Early CSE w/ MemorySSA", false, false)