blob: 7f320d5f95a3c053834f468cec3fbc08a215457e [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"
Eugene Zelenko3b879392017-10-13 21:17:07 +000016#include "llvm/ADT/DenseMapInfo.h"
Michael Ilseman336cb792012-10-09 16:57:38 +000017#include "llvm/ADT/Hashing.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000018#include "llvm/ADT/STLExtras.h"
Chris Lattner18ae5432011-01-02 23:04:14 +000019#include "llvm/ADT/ScopedHashTable.h"
Davide Italiano0dc47782017-06-14 19:29:53 +000020#include "llvm/ADT/SetVector.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000021#include "llvm/ADT/SmallVector.h"
Chris Lattner8fac5db2011-01-02 23:19:45 +000022#include "llvm/ADT/Statistic.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000023#include "llvm/Analysis/AssumptionCache.h"
Geoff Berry354fac22016-04-28 14:59:27 +000024#include "llvm/Analysis/GlobalsModRef.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 Blaikie2be39222018-03-21 22:34:23 +000030#include "llvm/Analysis/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"
Eugene Zelenko3b879392017-10-13 21:17:07 +000057#include <cassert>
Lenny Maiorani9eefc812014-09-20 13:29:20 +000058#include <deque>
Eugene Zelenko3b879392017-10-13 21:17:07 +000059#include <memory>
60#include <utility>
61
Chris Lattner704541b2011-01-02 21:47:05 +000062using namespace llvm;
Hal Finkel1e16fa32014-11-03 20:21:32 +000063using namespace llvm::PatternMatch;
Chris Lattner704541b2011-01-02 21:47:05 +000064
Chandler Carruth964daaa2014-04-22 02:55:47 +000065#define DEBUG_TYPE "early-cse"
66
Chris Lattner4cb36542011-01-03 03:28:23 +000067STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
68STATISTIC(NumCSE, "Number of instructions CSE'd");
Chad Rosier1a4bc112016-04-22 18:47:21 +000069STATISTIC(NumCSECVP, "Number of compare instructions CVP'd");
Chris Lattner92bb0f92011-01-03 03:41:27 +000070STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
71STATISTIC(NumCSECall, "Number of call instructions CSE'd");
Chris Lattner9e5e9ed2011-01-03 04:17:24 +000072STATISTIC(NumDSE, "Number of trivial dead stores removed");
Chris Lattnerb9a8efc2011-01-03 03:18:43 +000073
Geoff Berry5bf4a5e2018-04-06 18:47:33 +000074DEBUG_COUNTER(CSECounter, "early-cse",
75 "Controls which instructions are removed");
76
Chris Lattner79d83062011-01-03 02:20:48 +000077//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +000078// SimpleValue
Chris Lattner79d83062011-01-03 02:20:48 +000079//===----------------------------------------------------------------------===//
80
Chris Lattner704541b2011-01-02 21:47:05 +000081namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +000082
Chandler Carruth9dea5cd2015-01-24 11:44:32 +000083/// \brief Struct representing the available values in the scoped hash table.
Chandler Carruth7253bba2015-01-24 11:33:55 +000084struct SimpleValue {
85 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +000086
Chandler Carruth7253bba2015-01-24 11:33:55 +000087 SimpleValue(Instruction *I) : Inst(I) {
88 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
89 }
Nadav Rotem465834c2012-07-24 10:51:42 +000090
Chandler Carruth7253bba2015-01-24 11:33:55 +000091 bool isSentinel() const {
92 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
93 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
94 }
Nadav Rotem465834c2012-07-24 10:51:42 +000095
Chandler Carruth7253bba2015-01-24 11:33:55 +000096 static bool canHandle(Instruction *Inst) {
97 // This can only handle non-void readnone functions.
98 if (CallInst *CI = dyn_cast<CallInst>(Inst))
99 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
100 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
101 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
102 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
103 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
104 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
105 }
106};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000107
108} // end anonymous namespace
Chris Lattner18ae5432011-01-02 23:04:14 +0000109
110namespace llvm {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000111
Chandler Carruth7253bba2015-01-24 11:33:55 +0000112template <> struct DenseMapInfo<SimpleValue> {
Chris Lattner79d83062011-01-03 02:20:48 +0000113 static inline SimpleValue getEmptyKey() {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000114 return DenseMapInfo<Instruction *>::getEmptyKey();
Chris Lattner18ae5432011-01-02 23:04:14 +0000115 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000116
Chris Lattner79d83062011-01-03 02:20:48 +0000117 static inline SimpleValue getTombstoneKey() {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000118 return DenseMapInfo<Instruction *>::getTombstoneKey();
Chris Lattner18ae5432011-01-02 23:04:14 +0000119 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000120
Chris Lattner79d83062011-01-03 02:20:48 +0000121 static unsigned getHashValue(SimpleValue Val);
122 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
Chris Lattner18ae5432011-01-02 23:04:14 +0000123};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000124
125} // end namespace llvm
Chris Lattner18ae5432011-01-02 23:04:14 +0000126
Chris Lattner79d83062011-01-03 02:20:48 +0000127unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000128 Instruction *Inst = Val.Inst;
Chris Lattner02a97762011-01-03 01:10:08 +0000129 // Hash in all of the operands as pointers.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000130 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
Michael Ilseman336cb792012-10-09 16:57:38 +0000131 Value *LHS = BinOp->getOperand(0);
132 Value *RHS = BinOp->getOperand(1);
133 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
134 std::swap(LHS, RHS);
Chris Lattner02a97762011-01-03 01:10:08 +0000135
Michael Ilseman336cb792012-10-09 16:57:38 +0000136 return hash_combine(BinOp->getOpcode(), LHS, RHS);
Chris Lattner02a97762011-01-03 01:10:08 +0000137 }
138
Michael Ilseman336cb792012-10-09 16:57:38 +0000139 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
140 Value *LHS = CI->getOperand(0);
141 Value *RHS = CI->getOperand(1);
142 CmpInst::Predicate Pred = CI->getPredicate();
143 if (Inst->getOperand(0) > Inst->getOperand(1)) {
144 std::swap(LHS, RHS);
145 Pred = CI->getSwappedPredicate();
146 }
147 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
148 }
149
Sanjay Patel558a4652017-12-13 22:57:35 +0000150 // Hash min/max/abs (cmp + select) to allow for commuted operands.
151 // Min/max may also have non-canonical compare predicate (eg, the compare for
152 // smin may use 'sgt' rather than 'slt'), and non-canonical operands in the
153 // compare.
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000154 Value *A, *B;
155 SelectPatternFlavor SPF = matchSelectPattern(Inst, A, B).Flavor;
Sanjay Patel558a4652017-12-13 22:57:35 +0000156 // TODO: We should also detect FP min/max.
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000157 if (SPF == SPF_SMIN || SPF == SPF_SMAX ||
Sanjay Patel558a4652017-12-13 22:57:35 +0000158 SPF == SPF_UMIN || SPF == SPF_UMAX ||
159 SPF == SPF_ABS || SPF == SPF_NABS) {
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000160 if (A > B)
161 std::swap(A, B);
162 return hash_combine(Inst->getOpcode(), SPF, A, B);
163 }
164
Michael Ilseman336cb792012-10-09 16:57:38 +0000165 if (CastInst *CI = dyn_cast<CastInst>(Inst))
166 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
167
168 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
169 return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
170 hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
171
172 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
173 return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
174 IVI->getOperand(1),
175 hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
176
177 assert((isa<CallInst>(Inst) || isa<BinaryOperator>(Inst) ||
178 isa<GetElementPtrInst>(Inst) || isa<SelectInst>(Inst) ||
179 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
Chandler Carruth7253bba2015-01-24 11:33:55 +0000180 isa<ShuffleVectorInst>(Inst)) &&
181 "Invalid/unknown instruction");
Michael Ilseman336cb792012-10-09 16:57:38 +0000182
Chris Lattner02a97762011-01-03 01:10:08 +0000183 // Mix in the opcode.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000184 return hash_combine(
185 Inst->getOpcode(),
186 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
Chris Lattner18ae5432011-01-02 23:04:14 +0000187}
188
Chris Lattner79d83062011-01-03 02:20:48 +0000189bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000190 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
191
192 if (LHS.isSentinel() || RHS.isSentinel())
193 return LHSI == RHSI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000194
Chandler Carruth7253bba2015-01-24 11:33:55 +0000195 if (LHSI->getOpcode() != RHSI->getOpcode())
196 return false;
David Majnemer9554c132016-04-22 06:37:45 +0000197 if (LHSI->isIdenticalToWhenDefined(RHSI))
Chandler Carruth7253bba2015-01-24 11:33:55 +0000198 return true;
Michael Ilseman336cb792012-10-09 16:57:38 +0000199
200 // If we're not strictly identical, we still might be a commutable instruction
201 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
202 if (!LHSBinOp->isCommutative())
203 return false;
204
Chandler Carruth7253bba2015-01-24 11:33:55 +0000205 assert(isa<BinaryOperator>(RHSI) &&
206 "same opcode, but different instruction type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000207 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
208
Michael Ilseman336cb792012-10-09 16:57:38 +0000209 // Commuted equality
210 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000211 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
Michael Ilseman336cb792012-10-09 16:57:38 +0000212 }
213 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000214 assert(isa<CmpInst>(RHSI) &&
215 "same opcode, but different instruction type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000216 CmpInst *RHSCmp = cast<CmpInst>(RHSI);
217 // Commuted equality
218 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000219 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
220 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
Michael Ilseman336cb792012-10-09 16:57:38 +0000221 }
222
Sanjay Patel558a4652017-12-13 22:57:35 +0000223 // Min/max/abs can occur with commuted operands, non-canonical predicates,
224 // and/or non-canonical operands.
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000225 Value *LHSA, *LHSB;
226 SelectPatternFlavor LSPF = matchSelectPattern(LHSI, LHSA, LHSB).Flavor;
Sanjay Patel558a4652017-12-13 22:57:35 +0000227 // TODO: We should also detect FP min/max.
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000228 if (LSPF == SPF_SMIN || LSPF == SPF_SMAX ||
Sanjay Patel558a4652017-12-13 22:57:35 +0000229 LSPF == SPF_UMIN || LSPF == SPF_UMAX ||
230 LSPF == SPF_ABS || LSPF == SPF_NABS) {
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000231 Value *RHSA, *RHSB;
232 SelectPatternFlavor RSPF = matchSelectPattern(RHSI, RHSA, RHSB).Flavor;
233 return (LSPF == RSPF && ((LHSA == RHSA && LHSB == RHSB) ||
234 (LHSA == RHSB && LHSB == RHSA)));
235 }
236
Michael Ilseman336cb792012-10-09 16:57:38 +0000237 return false;
Chris Lattner18ae5432011-01-02 23:04:14 +0000238}
239
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000240//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +0000241// CallValue
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000242//===----------------------------------------------------------------------===//
243
244namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000245
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000246/// \brief Struct representing the available call values in the scoped hash
247/// table.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000248struct CallValue {
249 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +0000250
Chandler Carruth7253bba2015-01-24 11:33:55 +0000251 CallValue(Instruction *I) : Inst(I) {
252 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
253 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000254
Chandler Carruth7253bba2015-01-24 11:33:55 +0000255 bool isSentinel() const {
256 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
257 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
258 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000259
Chandler Carruth7253bba2015-01-24 11:33:55 +0000260 static bool canHandle(Instruction *Inst) {
261 // Don't value number anything that returns void.
262 if (Inst->getType()->isVoidTy())
263 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000264
Chandler Carruth7253bba2015-01-24 11:33:55 +0000265 CallInst *CI = dyn_cast<CallInst>(Inst);
266 if (!CI || !CI->onlyReadsMemory())
267 return false;
268 return true;
269 }
270};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000271
272} // end anonymous namespace
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000273
274namespace llvm {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000275
Chandler Carruth7253bba2015-01-24 11:33:55 +0000276template <> struct DenseMapInfo<CallValue> {
277 static inline CallValue getEmptyKey() {
278 return DenseMapInfo<Instruction *>::getEmptyKey();
279 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000280
Chandler Carruth7253bba2015-01-24 11:33:55 +0000281 static inline CallValue getTombstoneKey() {
282 return DenseMapInfo<Instruction *>::getTombstoneKey();
283 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000284
Chandler Carruth7253bba2015-01-24 11:33:55 +0000285 static unsigned getHashValue(CallValue Val);
286 static bool isEqual(CallValue LHS, CallValue RHS);
287};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000288
289} // end namespace llvm
Chandler Carruth7253bba2015-01-24 11:33:55 +0000290
Chris Lattner92bb0f92011-01-03 03:41:27 +0000291unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000292 Instruction *Inst = Val.Inst;
Benjamin Kramer6ab86b12015-02-01 12:30:59 +0000293 // Hash all of the operands as pointers and mix in the opcode.
294 return hash_combine(
295 Inst->getOpcode(),
296 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000297}
298
Chris Lattner92bb0f92011-01-03 03:41:27 +0000299bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000300 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000301 if (LHS.isSentinel() || RHS.isSentinel())
302 return LHSI == RHSI;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000303 return LHSI->isIdenticalTo(RHSI);
304}
305
Chris Lattner79d83062011-01-03 02:20:48 +0000306//===----------------------------------------------------------------------===//
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000307// EarlyCSE implementation
Chris Lattner79d83062011-01-03 02:20:48 +0000308//===----------------------------------------------------------------------===//
309
Chris Lattner18ae5432011-01-02 23:04:14 +0000310namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000311
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000312/// \brief A simple and fast domtree-based CSE pass.
313///
314/// This pass does a simple depth-first walk over the dominator tree,
315/// eliminating trivially redundant instructions and using instsimplify to
316/// canonicalize things as it goes. It is intended to be fast and catch obvious
317/// cases so that instcombine and other passes are more effective. It is
318/// expected that a later pass of GVN will catch the interesting/hard cases.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000319class EarlyCSE {
Chris Lattner704541b2011-01-02 21:47:05 +0000320public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000321 const TargetLibraryInfo &TLI;
322 const TargetTransformInfo &TTI;
323 DominatorTree &DT;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000324 AssumptionCache &AC;
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000325 const SimplifyQuery SQ;
Geoff Berry8d846052016-08-31 19:24:10 +0000326 MemorySSA *MSSA;
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000327 std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
Eugene Zelenko3b879392017-10-13 21:17:07 +0000328
329 using AllocatorTy =
330 RecyclingAllocator<BumpPtrAllocator,
331 ScopedHashTableVal<SimpleValue, Value *>>;
332 using ScopedHTType =
333 ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
334 AllocatorTy>;
Nadav Rotem465834c2012-07-24 10:51:42 +0000335
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000336 /// \brief A scoped hash table of the current values of all of our simple
337 /// scalar expressions.
338 ///
339 /// As we walk down the domtree, we look to see if instructions are in this:
340 /// if so, we replace them with what we find, otherwise we insert them so
341 /// that dominated values can succeed in their lookup.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000342 ScopedHTType AvailableValues;
Nadav Rotem465834c2012-07-24 10:51:42 +0000343
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000344 /// A scoped hash table of the current values of previously encounted memory
345 /// locations.
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000346 ///
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000347 /// This allows us to get efficient access to dominating loads or stores when
348 /// we have a fully redundant load. In addition to the most recent load, we
349 /// keep track of a generation count of the read, which is compared against
350 /// the current generation count. The current generation count is incremented
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000351 /// after every possibly writing memory operation, which ensures that we only
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000352 /// CSE loads with other loads that have no intervening store. Ordering
353 /// events (such as fences or atomic instructions) increment the generation
354 /// count as well; essentially, we model these as writes to all possible
355 /// locations. Note that atomic and/or volatile loads and stores can be
356 /// present the table; it is the responsibility of the consumer to inspect
357 /// the atomicity/volatility if needed.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000358 struct LoadValue {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000359 Instruction *DefInst = nullptr;
360 unsigned Generation = 0;
361 int MatchingId = -1;
362 bool IsAtomic = false;
Philip Reames0adbb192018-03-14 21:35:06 +0000363
Eugene Zelenko3b879392017-10-13 21:17:07 +0000364 LoadValue() = default;
Geoff Berry5ae272c2016-04-28 15:22:37 +0000365 LoadValue(Instruction *Inst, unsigned Generation, unsigned MatchingId,
Philip Reamesca587fe2018-03-15 17:29:32 +0000366 bool IsAtomic)
Sanjoy Das07c65212016-06-16 20:47:57 +0000367 : DefInst(Inst), Generation(Generation), MatchingId(MatchingId),
Philip Reamesca587fe2018-03-15 17:29:32 +0000368 IsAtomic(IsAtomic) {}
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000369 };
Eugene Zelenko3b879392017-10-13 21:17:07 +0000370
371 using LoadMapAllocator =
372 RecyclingAllocator<BumpPtrAllocator,
373 ScopedHashTableVal<Value *, LoadValue>>;
374 using LoadHTType =
375 ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>,
376 LoadMapAllocator>;
377
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000378 LoadHTType AvailableLoads;
Philip Reames0adbb192018-03-14 21:35:06 +0000379
380 // A scoped hash table mapping memory locations (represented as typed
381 // addresses) to generation numbers at which that memory location became
382 // (henceforth indefinitely) invariant.
383 using InvariantMapAllocator =
384 RecyclingAllocator<BumpPtrAllocator,
385 ScopedHashTableVal<MemoryLocation, unsigned>>;
386 using InvariantHTType =
387 ScopedHashTable<MemoryLocation, unsigned, DenseMapInfo<MemoryLocation>,
388 InvariantMapAllocator>;
389 InvariantHTType AvailableInvariants;
Nadav Rotem465834c2012-07-24 10:51:42 +0000390
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000391 /// \brief A scoped hash table of the current values of read-only call
392 /// values.
393 ///
394 /// It uses the same generation count as loads.
Eugene Zelenko3b879392017-10-13 21:17:07 +0000395 using CallHTType =
396 ScopedHashTable<CallValue, std::pair<Instruction *, unsigned>>;
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000397 CallHTType AvailableCalls;
Nadav Rotem465834c2012-07-24 10:51:42 +0000398
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000399 /// \brief This is the current generation of the memory value.
Eugene Zelenko3b879392017-10-13 21:17:07 +0000400 unsigned CurrentGeneration = 0;
Nadav Rotem465834c2012-07-24 10:51:42 +0000401
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000402 /// \brief Set up the EarlyCSE runner for a particular function.
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000403 EarlyCSE(const DataLayout &DL, const TargetLibraryInfo &TLI,
404 const TargetTransformInfo &TTI, DominatorTree &DT,
405 AssumptionCache &AC, MemorySSA *MSSA)
406 : TLI(TLI), TTI(TTI), DT(DT), AC(AC), SQ(DL, &TLI, &DT, &AC), MSSA(MSSA),
Eugene Zelenko3b879392017-10-13 21:17:07 +0000407 MSSAUpdater(llvm::make_unique<MemorySSAUpdater>(MSSA)) {}
Chris Lattner704541b2011-01-02 21:47:05 +0000408
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000409 bool run();
Chris Lattner704541b2011-01-02 21:47:05 +0000410
411private:
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000412 // Almost a POD, but needs to call the constructors for the scoped hash
413 // tables so that a new scope gets pushed on. These are RAII so that the
414 // scope gets popped when the NodeScope is destroyed.
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000415 class NodeScope {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000416 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000417 NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
Philip Reames0adbb192018-03-14 21:35:06 +0000418 InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls)
419 : Scope(AvailableValues), LoadScope(AvailableLoads),
420 InvariantScope(AvailableInvariants), CallScope(AvailableCalls) {}
Eugene Zelenko3b879392017-10-13 21:17:07 +0000421 NodeScope(const NodeScope &) = delete;
422 NodeScope &operator=(const NodeScope &) = delete;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000423
Chandler Carruth7253bba2015-01-24 11:33:55 +0000424 private:
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000425 ScopedHTType::ScopeTy Scope;
426 LoadHTType::ScopeTy LoadScope;
Philip Reames0adbb192018-03-14 21:35:06 +0000427 InvariantHTType::ScopeTy InvariantScope;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000428 CallHTType::ScopeTy CallScope;
429 };
430
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000431 // Contains all the needed information to create a stack for doing a depth
Nick Lewyckyedd0a702016-09-07 01:49:41 +0000432 // first traversal of the tree. This includes scopes for values, loads, and
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000433 // calls as well as the generation. There is a child iterator so that the
Sanjoy Das5253a082016-04-27 01:44:31 +0000434 // children do not need to be store separately.
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000435 class StackNode {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000436 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000437 StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
Philip Reames0adbb192018-03-14 21:35:06 +0000438 InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls,
439 unsigned cg, DomTreeNode *n, DomTreeNode::iterator child,
440 DomTreeNode::iterator end)
Chandler Carruth7253bba2015-01-24 11:33:55 +0000441 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
Philip Reames0adbb192018-03-14 21:35:06 +0000442 EndIter(end),
443 Scopes(AvailableValues, AvailableLoads, AvailableInvariants,
444 AvailableCalls)
Eugene Zelenko3b879392017-10-13 21:17:07 +0000445 {}
446 StackNode(const StackNode &) = delete;
447 StackNode &operator=(const StackNode &) = delete;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000448
449 // Accessors.
450 unsigned currentGeneration() { return CurrentGeneration; }
451 unsigned childGeneration() { return ChildGeneration; }
452 void childGeneration(unsigned generation) { ChildGeneration = generation; }
453 DomTreeNode *node() { return Node; }
454 DomTreeNode::iterator childIter() { return ChildIter; }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000455
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000456 DomTreeNode *nextChild() {
457 DomTreeNode *child = *ChildIter;
458 ++ChildIter;
459 return child;
460 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000461
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000462 DomTreeNode::iterator end() { return EndIter; }
463 bool isProcessed() { return Processed; }
464 void process() { Processed = true; }
465
Chandler Carruth7253bba2015-01-24 11:33:55 +0000466 private:
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000467 unsigned CurrentGeneration;
468 unsigned ChildGeneration;
469 DomTreeNode *Node;
470 DomTreeNode::iterator ChildIter;
471 DomTreeNode::iterator EndIter;
472 NodeScope Scopes;
Eugene Zelenko3b879392017-10-13 21:17:07 +0000473 bool Processed = false;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000474 };
475
Chad Rosierf9327d62015-01-26 22:51:15 +0000476 /// \brief Wrapper class to handle memory instructions, including loads,
477 /// stores and intrinsic loads and stores defined by the target.
478 class ParseMemoryInst {
479 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000480 ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
Eugene Zelenko3b879392017-10-13 21:17:07 +0000481 : Inst(Inst) {
Philip Reames9e5e2d62015-12-07 22:41:23 +0000482 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000483 if (TTI.getTgtMemIntrinsic(II, Info))
Philip Reames9e5e2d62015-12-07 22:41:23 +0000484 IsTargetMemInst = true;
485 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000486
Philip Reames9e5e2d62015-12-07 22:41:23 +0000487 bool isLoad() const {
488 if (IsTargetMemInst) return Info.ReadMem;
489 return isa<LoadInst>(Inst);
490 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000491
Philip Reames9e5e2d62015-12-07 22:41:23 +0000492 bool isStore() const {
493 if (IsTargetMemInst) return Info.WriteMem;
494 return isa<StoreInst>(Inst);
495 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000496
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000497 bool isAtomic() const {
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000498 if (IsTargetMemInst)
499 return Info.Ordering != AtomicOrdering::NotAtomic;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000500 return Inst->isAtomic();
501 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000502
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000503 bool isUnordered() const {
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000504 if (IsTargetMemInst)
505 return Info.isUnordered();
506
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000507 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
508 return LI->isUnordered();
509 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
510 return SI->isUnordered();
511 }
512 // Conservative answer
513 return !Inst->isAtomic();
514 }
515
516 bool isVolatile() const {
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000517 if (IsTargetMemInst)
518 return Info.IsVolatile;
519
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000520 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
521 return LI->isVolatile();
522 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
523 return SI->isVolatile();
524 }
525 // Conservative answer
526 return true;
527 }
528
Sanjoy Das07c65212016-06-16 20:47:57 +0000529 bool isInvariantLoad() const {
530 if (auto *LI = dyn_cast<LoadInst>(Inst))
Sanjoy Das1ab2fad2016-06-16 21:00:57 +0000531 return LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr;
Sanjoy Das07c65212016-06-16 20:47:57 +0000532 return false;
533 }
Junmo Park80440eb2016-02-18 10:09:20 +0000534
Arnaud A. de Grandmaison6fd488b2015-10-06 13:35:30 +0000535 bool isMatchingMemLoc(const ParseMemoryInst &Inst) const {
Philip Reames9e5e2d62015-12-07 22:41:23 +0000536 return (getPointerOperand() == Inst.getPointerOperand() &&
537 getMatchingId() == Inst.getMatchingId());
Chad Rosierf9327d62015-01-26 22:51:15 +0000538 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000539
Philip Reames9e5e2d62015-12-07 22:41:23 +0000540 bool isValid() const { return getPointerOperand() != nullptr; }
Chad Rosierf9327d62015-01-26 22:51:15 +0000541
Chad Rosierf9327d62015-01-26 22:51:15 +0000542 // For regular (non-intrinsic) loads/stores, this is set to -1. For
543 // intrinsic loads/stores, the id is retrieved from the corresponding
544 // field in the MemIntrinsicInfo structure. That field contains
545 // non-negative values only.
Philip Reames9e5e2d62015-12-07 22:41:23 +0000546 int getMatchingId() const {
547 if (IsTargetMemInst) return Info.MatchingId;
548 return -1;
549 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000550
Philip Reames9e5e2d62015-12-07 22:41:23 +0000551 Value *getPointerOperand() const {
552 if (IsTargetMemInst) return Info.PtrVal;
Renato Golin038ede22018-03-09 21:05:58 +0000553 return getLoadStorePointerOperand(Inst);
Philip Reames9e5e2d62015-12-07 22:41:23 +0000554 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000555
Philip Reames9e5e2d62015-12-07 22:41:23 +0000556 bool mayReadFromMemory() const {
557 if (IsTargetMemInst) return Info.ReadMem;
558 return Inst->mayReadFromMemory();
559 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000560
Philip Reames9e5e2d62015-12-07 22:41:23 +0000561 bool mayWriteToMemory() const {
562 if (IsTargetMemInst) return Info.WriteMem;
563 return Inst->mayWriteToMemory();
564 }
565
566 private:
Eugene Zelenko3b879392017-10-13 21:17:07 +0000567 bool IsTargetMemInst = false;
Philip Reames9e5e2d62015-12-07 22:41:23 +0000568 MemIntrinsicInfo Info;
569 Instruction *Inst;
Chad Rosierf9327d62015-01-26 22:51:15 +0000570 };
571
Chris Lattner18ae5432011-01-02 23:04:14 +0000572 bool processNode(DomTreeNode *Node);
Nadav Rotem465834c2012-07-24 10:51:42 +0000573
Chad Rosierf9327d62015-01-26 22:51:15 +0000574 Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const {
Sanjay Patel1c9867d2017-01-03 00:16:24 +0000575 if (auto *LI = dyn_cast<LoadInst>(Inst))
Chad Rosierf9327d62015-01-26 22:51:15 +0000576 return LI;
Sanjay Patel1c9867d2017-01-03 00:16:24 +0000577 if (auto *SI = dyn_cast<StoreInst>(Inst))
Chad Rosierf9327d62015-01-26 22:51:15 +0000578 return SI->getValueOperand();
579 assert(isa<IntrinsicInst>(Inst) && "Instruction not supported");
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000580 return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst),
581 ExpectedType);
Chad Rosierf9327d62015-01-26 22:51:15 +0000582 }
Geoff Berry8d846052016-08-31 19:24:10 +0000583
Philip Reames0adbb192018-03-14 21:35:06 +0000584 /// Return true if the instruction is known to only operate on memory
585 /// provably invariant in the given "generation".
586 bool isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt);
587
Geoff Berry8d846052016-08-31 19:24:10 +0000588 bool isSameMemGeneration(unsigned EarlierGeneration, unsigned LaterGeneration,
589 Instruction *EarlierInst, Instruction *LaterInst);
590
591 void removeMSSA(Instruction *Inst) {
592 if (!MSSA)
593 return;
Geoff Berry91e9a5c2016-10-25 16:18:47 +0000594 // Removing a store here can leave MemorySSA in an unoptimized state by
595 // creating MemoryPhis that have identical arguments and by creating
Geoff Berry68154682016-10-24 15:54:00 +0000596 // MemoryUses whose defining access is not an actual clobber. We handle the
Geoff Berry91e9a5c2016-10-25 16:18:47 +0000597 // phi case eagerly here. The non-optimized MemoryUse case is lazily
598 // updated by MemorySSA getClobberingMemoryAccess.
Geoff Berry68154682016-10-24 15:54:00 +0000599 if (MemoryAccess *MA = MSSA->getMemoryAccess(Inst)) {
600 // Optimize MemoryPhi nodes that may become redundant by having all the
601 // same input values once MA is removed.
Davide Italiano0dc47782017-06-14 19:29:53 +0000602 SmallSetVector<MemoryPhi *, 4> PhisToCheck;
Geoff Berry68154682016-10-24 15:54:00 +0000603 SmallVector<MemoryAccess *, 8> WorkQueue;
604 WorkQueue.push_back(MA);
605 // Process MemoryPhi nodes in FIFO order using a ever-growing vector since
606 // we shouldn't be processing that many phis and this will avoid an
607 // allocation in almost all cases.
608 for (unsigned I = 0; I < WorkQueue.size(); ++I) {
609 MemoryAccess *WI = WorkQueue[I];
610
611 for (auto *U : WI->users())
612 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(U))
Davide Italiano0dc47782017-06-14 19:29:53 +0000613 PhisToCheck.insert(MP);
Geoff Berry68154682016-10-24 15:54:00 +0000614
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000615 MSSAUpdater->removeMemoryAccess(WI);
Geoff Berry68154682016-10-24 15:54:00 +0000616
617 for (MemoryPhi *MP : PhisToCheck) {
618 MemoryAccess *FirstIn = MP->getIncomingValue(0);
Eugene Zelenko3b879392017-10-13 21:17:07 +0000619 if (llvm::all_of(MP->incoming_values(),
620 [=](Use &In) { return In == FirstIn; }))
Geoff Berry68154682016-10-24 15:54:00 +0000621 WorkQueue.push_back(MP);
622 }
623 PhisToCheck.clear();
624 }
625 }
Geoff Berry8d846052016-08-31 19:24:10 +0000626 }
Chris Lattner704541b2011-01-02 21:47:05 +0000627};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000628
629} // end anonymous namespace
Chris Lattner704541b2011-01-02 21:47:05 +0000630
Geoff Berry68154682016-10-24 15:54:00 +0000631/// Determine if the memory referenced by LaterInst is from the same heap
632/// version as EarlierInst.
Geoff Berry8d846052016-08-31 19:24:10 +0000633/// This is currently called in two scenarios:
634///
635/// load p
636/// ...
637/// load p
638///
639/// and
640///
641/// x = load p
642/// ...
643/// store x, p
644///
645/// in both cases we want to verify that there are no possible writes to the
646/// memory referenced by p between the earlier and later instruction.
647bool EarlyCSE::isSameMemGeneration(unsigned EarlierGeneration,
648 unsigned LaterGeneration,
649 Instruction *EarlierInst,
650 Instruction *LaterInst) {
651 // Check the simple memory generation tracking first.
652 if (EarlierGeneration == LaterGeneration)
653 return true;
654
655 if (!MSSA)
656 return false;
657
Geoff Berryf7d5daa2017-07-14 20:13:21 +0000658 // If MemorySSA has determined that one of EarlierInst or LaterInst does not
659 // read/write memory, then we can safely return true here.
660 // FIXME: We could be more aggressive when checking doesNotAccessMemory(),
661 // onlyReadsMemory(), mayReadFromMemory(), and mayWriteToMemory() in this pass
662 // by also checking the MemorySSA MemoryAccess on the instruction. Initial
663 // experiments suggest this isn't worthwhile, at least for C/C++ code compiled
664 // with the default optimization pipeline.
665 auto *EarlierMA = MSSA->getMemoryAccess(EarlierInst);
666 if (!EarlierMA)
667 return true;
668 auto *LaterMA = MSSA->getMemoryAccess(LaterInst);
669 if (!LaterMA)
670 return true;
671
Geoff Berry8d846052016-08-31 19:24:10 +0000672 // Since we know LaterDef dominates LaterInst and EarlierInst dominates
673 // LaterInst, if LaterDef dominates EarlierInst then it can't occur between
674 // EarlierInst and LaterInst and neither can any other write that potentially
675 // clobbers LaterInst.
Geoff Berry91e9a5c2016-10-25 16:18:47 +0000676 MemoryAccess *LaterDef =
677 MSSA->getWalker()->getClobberingMemoryAccess(LaterInst);
Geoff Berryf7d5daa2017-07-14 20:13:21 +0000678 return MSSA->dominates(LaterDef, EarlierMA);
Geoff Berry8d846052016-08-31 19:24:10 +0000679}
680
Philip Reames0adbb192018-03-14 21:35:06 +0000681bool EarlyCSE::isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt) {
682 // A location loaded from with an invariant_load is assumed to *never* change
683 // within the visible scope of the compilation.
684 if (auto *LI = dyn_cast<LoadInst>(I))
685 if (LI->getMetadata(LLVMContext::MD_invariant_load))
686 return true;
687
688 auto MemLocOpt = MemoryLocation::getOrNone(I);
689 if (!MemLocOpt)
690 // "target" intrinsic forms of loads aren't currently known to
691 // MemoryLocation::get. TODO
692 return false;
693 MemoryLocation MemLoc = *MemLocOpt;
694 if (!AvailableInvariants.count(MemLoc))
695 return false;
696
697 // Is the generation at which this became invariant older than the
698 // current one?
699 return AvailableInvariants.lookup(MemLoc) <= GenAt;
700}
701
Chris Lattner18ae5432011-01-02 23:04:14 +0000702bool EarlyCSE::processNode(DomTreeNode *Node) {
Chad Rosier1a4bc112016-04-22 18:47:21 +0000703 bool Changed = false;
Chris Lattner18ae5432011-01-02 23:04:14 +0000704 BasicBlock *BB = Node->getBlock();
Nadav Rotem465834c2012-07-24 10:51:42 +0000705
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000706 // If this block has a single predecessor, then the predecessor is the parent
707 // of the domtree node and all of the live out memory values are still current
708 // in this block. If this block has multiple predecessors, then they could
709 // have invalidated the live-out memory values of our parent value. For now,
710 // just be conservative and invalidate memory if this block has multiple
711 // predecessors.
Craig Topperf40110f2014-04-25 05:29:35 +0000712 if (!BB->getSinglePredecessor())
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000713 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000714
Philip Reames7c78ef72015-05-22 23:53:24 +0000715 // If this node has a single predecessor which ends in a conditional branch,
716 // we can infer the value of the branch condition given that we took this
Chad Rosierb346dcb2016-04-20 19:16:23 +0000717 // path. We need the single predecessor to ensure there's not another path
Philip Reames7c78ef72015-05-22 23:53:24 +0000718 // which reaches this block where the condition might hold a different
719 // value. Since we're adding this to the scoped hash table (like any other
720 // def), it will have been popped if we encounter a future merge block.
Sanjay Patelf1e1fba2017-03-15 20:25:05 +0000721 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
722 auto *BI = dyn_cast<BranchInst>(Pred->getTerminator());
723 if (BI && BI->isConditional()) {
724 auto *CondInst = dyn_cast<Instruction>(BI->getCondition());
725 if (CondInst && SimpleValue::canHandle(CondInst)) {
726 assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
727 auto *TorF = (BI->getSuccessor(0) == BB)
728 ? ConstantInt::getTrue(BB->getContext())
729 : ConstantInt::getFalse(BB->getContext());
730 AvailableValues.insert(CondInst, TorF);
731 DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
732 << CondInst->getName() << "' as " << *TorF << " in "
733 << BB->getName() << "\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000734 if (!DebugCounter::shouldExecute(CSECounter)) {
735 DEBUG(dbgs() << "Skipping due to debug counter\n");
736 } else {
737 // Replace all dominated uses with the known value.
738 if (unsigned Count = replaceDominatedUsesWith(
739 CondInst, TorF, DT, BasicBlockEdge(Pred, BB))) {
740 Changed = true;
741 NumCSECVP += Count;
742 }
Sanjay Patelf1e1fba2017-03-15 20:25:05 +0000743 }
744 }
745 }
746 }
Philip Reames7c78ef72015-05-22 23:53:24 +0000747
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000748 /// LastStore - Keep track of the last non-volatile store that we saw... for
749 /// as long as there in no instruction that reads memory. If we see a store
750 /// to the same location, we delete the dead store. This zaps trivial dead
751 /// stores which can occur in bitfield code among other things.
Chad Rosierf9327d62015-01-26 22:51:15 +0000752 Instruction *LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000753
Chris Lattner18ae5432011-01-02 23:04:14 +0000754 // See if any instructions in the block can be eliminated. If so, do it. If
755 // not, add them to AvailableValues.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000756 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +0000757 Instruction *Inst = &*I++;
Nadav Rotem465834c2012-07-24 10:51:42 +0000758
Chris Lattner18ae5432011-01-02 23:04:14 +0000759 // Dead instructions should just be removed.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000760 if (isInstructionTriviallyDead(Inst, &TLI)) {
Chris Lattner8fac5db2011-01-02 23:19:45 +0000761 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000762 if (!DebugCounter::shouldExecute(CSECounter)) {
763 DEBUG(dbgs() << "Skipping due to debug counter\n");
764 continue;
765 }
Petar Jovanovic1d26c7e2018-01-09 15:08:37 +0000766 salvageDebugInfo(*Inst);
Geoff Berry8d846052016-08-31 19:24:10 +0000767 removeMSSA(Inst);
Chris Lattner18ae5432011-01-02 23:04:14 +0000768 Inst->eraseFromParent();
769 Changed = true;
Chris Lattner8fac5db2011-01-02 23:19:45 +0000770 ++NumSimplify;
Chris Lattner18ae5432011-01-02 23:04:14 +0000771 continue;
772 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000773
Hal Finkel1e16fa32014-11-03 20:21:32 +0000774 // Skip assume intrinsics, they don't really have side effects (although
775 // they're marked as such to ensure preservation of control dependencies),
Max Kazantsev531db9a2017-04-28 06:25:39 +0000776 // and this pass will not bother with its removal. However, we should mark
777 // its condition as true for all dominated blocks.
Hal Finkel1e16fa32014-11-03 20:21:32 +0000778 if (match(Inst, m_Intrinsic<Intrinsic::assume>())) {
Max Kazantsev531db9a2017-04-28 06:25:39 +0000779 auto *CondI =
780 dyn_cast<Instruction>(cast<CallInst>(Inst)->getArgOperand(0));
781 if (CondI && SimpleValue::canHandle(CondI)) {
782 DEBUG(dbgs() << "EarlyCSE considering assumption: " << *Inst << '\n');
783 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
784 } else
785 DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n');
Hal Finkel1e16fa32014-11-03 20:21:32 +0000786 continue;
787 }
788
Dan Gohman2c74fe92017-11-08 21:59:51 +0000789 // Skip sideeffect intrinsics, for the same reason as assume intrinsics.
790 if (match(Inst, m_Intrinsic<Intrinsic::sideeffect>())) {
791 DEBUG(dbgs() << "EarlyCSE skipping sideeffect: " << *Inst << '\n');
792 continue;
793 }
794
Philip Reames0adbb192018-03-14 21:35:06 +0000795 // We can skip all invariant.start intrinsics since they only read memory,
796 // and we can forward values across it. For invariant starts without
797 // invariant ends, we can use the fact that the invariantness never ends to
798 // start a scope in the current generaton which is true for all future
799 // generations. Also, we dont need to consume the last store since the
800 // semantics of invariant.start allow us to perform DSE of the last
801 // store, if there was a store following invariant.start. Consider:
Anna Thomasb2d12b82016-08-09 20:00:47 +0000802 //
803 // store 30, i8* p
804 // invariant.start(p)
805 // store 40, i8* p
806 // We can DSE the store to 30, since the store 40 to invariant location p
807 // causes undefined behaviour.
Philip Reames0adbb192018-03-14 21:35:06 +0000808 if (match(Inst, m_Intrinsic<Intrinsic::invariant_start>())) {
809 // If there are any uses, the scope might end.
810 if (!Inst->use_empty())
811 continue;
812 auto *CI = cast<CallInst>(Inst);
813 MemoryLocation MemLoc = MemoryLocation::getForArgument(CI, 1, TLI);
Philip Reames422024a2018-03-15 18:12:27 +0000814 // Don't start a scope if we already have a better one pushed
815 if (!AvailableInvariants.count(MemLoc))
816 AvailableInvariants.insert(MemLoc, CurrentGeneration);
Anna Thomasb2d12b82016-08-09 20:00:47 +0000817 continue;
Philip Reames0adbb192018-03-14 21:35:06 +0000818 }
Anna Thomasb2d12b82016-08-09 20:00:47 +0000819
Sanjoy Dasee81b232016-04-29 21:52:58 +0000820 if (match(Inst, m_Intrinsic<Intrinsic::experimental_guard>())) {
Sanjoy Das107aefc2016-04-29 22:23:16 +0000821 if (auto *CondI =
822 dyn_cast<Instruction>(cast<CallInst>(Inst)->getArgOperand(0))) {
Max Kazantsev0589d9f2017-04-28 06:05:48 +0000823 if (SimpleValue::canHandle(CondI)) {
824 // Do we already know the actual value of this condition?
825 if (auto *KnownCond = AvailableValues.lookup(CondI)) {
826 // Is the condition known to be true?
827 if (isa<ConstantInt>(KnownCond) &&
Craig Topper79ab6432017-07-06 18:39:47 +0000828 cast<ConstantInt>(KnownCond)->isOne()) {
Max Kazantsev0589d9f2017-04-28 06:05:48 +0000829 DEBUG(dbgs() << "EarlyCSE removing guard: " << *Inst << '\n');
830 removeMSSA(Inst);
831 Inst->eraseFromParent();
832 Changed = true;
833 continue;
834 } else
835 // Use the known value if it wasn't true.
836 cast<CallInst>(Inst)->setArgOperand(0, KnownCond);
837 }
838 // The condition we're on guarding here is true for all dominated
839 // locations.
Sanjoy Dasee81b232016-04-29 21:52:58 +0000840 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
Max Kazantsev0589d9f2017-04-28 06:05:48 +0000841 }
Sanjoy Dasee81b232016-04-29 21:52:58 +0000842 }
843
844 // Guard intrinsics read all memory, but don't write any memory.
845 // Accordingly, don't update the generation but consume the last store (to
846 // avoid an incorrect DSE).
847 LastStore = nullptr;
848 continue;
849 }
850
Chris Lattner18ae5432011-01-02 23:04:14 +0000851 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
852 // its simpler value.
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000853 if (Value *V = SimplifyInstruction(Inst, SQ)) {
Chris Lattner8fac5db2011-01-02 23:19:45 +0000854 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000855 if (!DebugCounter::shouldExecute(CSECounter)) {
856 DEBUG(dbgs() << "Skipping due to debug counter\n");
857 } else {
858 bool Killed = false;
859 if (!Inst->use_empty()) {
860 Inst->replaceAllUsesWith(V);
861 Changed = true;
862 }
863 if (isInstructionTriviallyDead(Inst, &TLI)) {
864 removeMSSA(Inst);
865 Inst->eraseFromParent();
866 Changed = true;
867 Killed = true;
868 }
869 if (Changed)
870 ++NumSimplify;
871 if (Killed)
872 continue;
David Majnemerb8da3a22016-06-25 00:04:10 +0000873 }
Chris Lattner18ae5432011-01-02 23:04:14 +0000874 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000875
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000876 // If this is a simple instruction that we can value number, process it.
877 if (SimpleValue::canHandle(Inst)) {
878 // See if the instruction has an available value. If so, use it.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000879 if (Value *V = AvailableValues.lookup(Inst)) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000880 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000881 if (!DebugCounter::shouldExecute(CSECounter)) {
882 DEBUG(dbgs() << "Skipping due to debug counter\n");
883 continue;
884 }
David Majnemer9554c132016-04-22 06:37:45 +0000885 if (auto *I = dyn_cast<Instruction>(V))
886 I->andIRFlags(Inst);
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000887 Inst->replaceAllUsesWith(V);
Geoff Berry8d846052016-08-31 19:24:10 +0000888 removeMSSA(Inst);
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000889 Inst->eraseFromParent();
890 Changed = true;
891 ++NumCSE;
892 continue;
893 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000894
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000895 // Otherwise, just remember that this value is available.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000896 AvailableValues.insert(Inst, Inst);
Chris Lattner18ae5432011-01-02 23:04:14 +0000897 continue;
898 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000899
Chad Rosierf9327d62015-01-26 22:51:15 +0000900 ParseMemoryInst MemInst(Inst, TTI);
Chris Lattner92bb0f92011-01-03 03:41:27 +0000901 // If this is a non-volatile load, process it.
Chad Rosierf9327d62015-01-26 22:51:15 +0000902 if (MemInst.isValid() && MemInst.isLoad()) {
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000903 // (conservatively) we can't peak past the ordering implied by this
904 // operation, but we can add this load to our set of available values
905 if (MemInst.isVolatile() || !MemInst.isUnordered()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000906 LastStore = nullptr;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000907 ++CurrentGeneration;
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000908 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000909
Philip Reamesca587fe2018-03-15 17:29:32 +0000910 if (MemInst.isInvariantLoad()) {
911 // If we pass an invariant load, we know that memory location is
912 // indefinitely constant from the moment of first dereferenceability.
Philip Reames422024a2018-03-15 18:12:27 +0000913 // We conservatively treat the invariant_load as that moment. If we
914 // pass a invariant load after already establishing a scope, don't
915 // restart it since we want to preserve the earliest point seen.
Philip Reamesca587fe2018-03-15 17:29:32 +0000916 auto MemLoc = MemoryLocation::get(Inst);
Philip Reames422024a2018-03-15 18:12:27 +0000917 if (!AvailableInvariants.count(MemLoc))
918 AvailableInvariants.insert(MemLoc, CurrentGeneration);
Philip Reamesca587fe2018-03-15 17:29:32 +0000919 }
920
Chris Lattner92bb0f92011-01-03 03:41:27 +0000921 // If we have an available version of this load, and if it is the right
Sanjoy Das07c65212016-06-16 20:47:57 +0000922 // generation or the load is known to be from an invariant location,
923 // replace this instruction.
924 //
Geoff Berry64f5ed12016-08-31 17:45:31 +0000925 // If either the dominating load or the current load are invariant, then
926 // we can assume the current load loads the same value as the dominating
927 // load.
Philip Reames9e5e2d62015-12-07 22:41:23 +0000928 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
Sanjoy Das07c65212016-06-16 20:47:57 +0000929 if (InVal.DefInst != nullptr &&
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000930 InVal.MatchingId == MemInst.getMatchingId() &&
931 // We don't yet handle removing loads with ordering of any kind.
932 !MemInst.isVolatile() && MemInst.isUnordered() &&
933 // We can't replace an atomic load with one which isn't also atomic.
Geoff Berry8d846052016-08-31 19:24:10 +0000934 InVal.IsAtomic >= MemInst.isAtomic() &&
Philip Reamesca587fe2018-03-15 17:29:32 +0000935 (isOperatingOnInvariantMemAt(Inst, InVal.Generation) ||
Geoff Berry8d846052016-08-31 19:24:10 +0000936 isSameMemGeneration(InVal.Generation, CurrentGeneration,
937 InVal.DefInst, Inst))) {
Philip Reames32b55182016-05-06 01:13:58 +0000938 Value *Op = getOrCreateResult(InVal.DefInst, Inst->getType());
Chad Rosierf9327d62015-01-26 22:51:15 +0000939 if (Op != nullptr) {
940 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst
Philip Reames32b55182016-05-06 01:13:58 +0000941 << " to: " << *InVal.DefInst << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000942 if (!DebugCounter::shouldExecute(CSECounter)) {
943 DEBUG(dbgs() << "Skipping due to debug counter\n");
944 continue;
945 }
Chad Rosierf9327d62015-01-26 22:51:15 +0000946 if (!Inst->use_empty())
947 Inst->replaceAllUsesWith(Op);
Geoff Berry8d846052016-08-31 19:24:10 +0000948 removeMSSA(Inst);
Chad Rosierf9327d62015-01-26 22:51:15 +0000949 Inst->eraseFromParent();
950 Changed = true;
951 ++NumCSELoad;
952 continue;
953 }
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000954 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000955
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000956 // Otherwise, remember that we have this instruction.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000957 AvailableLoads.insert(
Philip Reames9e5e2d62015-12-07 22:41:23 +0000958 MemInst.getPointerOperand(),
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000959 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
Philip Reamesca587fe2018-03-15 17:29:32 +0000960 MemInst.isAtomic()));
Craig Topperf40110f2014-04-25 05:29:35 +0000961 LastStore = nullptr;
Chris Lattner92bb0f92011-01-03 03:41:27 +0000962 continue;
963 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000964
Sanjoy Das6de072a2017-01-17 20:15:47 +0000965 // If this instruction may read from memory or throw (and potentially read
966 // from memory in the exception handler), forget LastStore. Load/store
967 // intrinsics will indicate both a read and a write to memory. The target
968 // may override this (e.g. so that a store intrinsic does not read from
969 // memory, and thus will be treated the same as a regular store for
970 // commoning purposes).
971 if ((Inst->mayReadFromMemory() || Inst->mayThrow()) &&
Chad Rosierf9327d62015-01-26 22:51:15 +0000972 !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
Craig Topperf40110f2014-04-25 05:29:35 +0000973 LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000974
Chris Lattner92bb0f92011-01-03 03:41:27 +0000975 // If this is a read-only call, process it.
976 if (CallValue::canHandle(Inst)) {
977 // If we have an available version of this call, and if it is the right
978 // generation, replace this instruction.
Geoff Berry2f64c202016-05-13 17:54:58 +0000979 std::pair<Instruction *, unsigned> InVal = AvailableCalls.lookup(Inst);
Geoff Berry8d846052016-08-31 19:24:10 +0000980 if (InVal.first != nullptr &&
981 isSameMemGeneration(InVal.second, CurrentGeneration, InVal.first,
982 Inst)) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000983 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst
984 << " to: " << *InVal.first << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000985 if (!DebugCounter::shouldExecute(CSECounter)) {
986 DEBUG(dbgs() << "Skipping due to debug counter\n");
987 continue;
988 }
Chandler Carruth7253bba2015-01-24 11:33:55 +0000989 if (!Inst->use_empty())
990 Inst->replaceAllUsesWith(InVal.first);
Geoff Berry8d846052016-08-31 19:24:10 +0000991 removeMSSA(Inst);
Chris Lattner92bb0f92011-01-03 03:41:27 +0000992 Inst->eraseFromParent();
993 Changed = true;
994 ++NumCSECall;
995 continue;
996 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000997
Chris Lattner92bb0f92011-01-03 03:41:27 +0000998 // Otherwise, remember that we have this instruction.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000999 AvailableCalls.insert(
Geoff Berry2f64c202016-05-13 17:54:58 +00001000 Inst, std::pair<Instruction *, unsigned>(Inst, CurrentGeneration));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001001 continue;
1002 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001003
Philip Reamesdfd890d2015-08-27 01:32:33 +00001004 // A release fence requires that all stores complete before it, but does
1005 // not prevent the reordering of following loads 'before' the fence. As a
1006 // result, we don't need to consider it as writing to memory and don't need
1007 // to advance the generation. We do need to prevent DSE across the fence,
1008 // but that's handled above.
1009 if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
JF Bastien800f87a2016-04-06 21:19:33 +00001010 if (FI->getOrdering() == AtomicOrdering::Release) {
Philip Reamesdfd890d2015-08-27 01:32:33 +00001011 assert(Inst->mayReadFromMemory() && "relied on to prevent DSE above");
1012 continue;
1013 }
1014
Philip Reamesae1f265b2015-12-16 01:01:30 +00001015 // write back DSE - If we write back the same value we just loaded from
1016 // the same location and haven't passed any intervening writes or ordering
1017 // operations, we can remove the write. The primary benefit is in allowing
1018 // the available load table to remain valid and value forward past where
1019 // the store originally was.
1020 if (MemInst.isValid() && MemInst.isStore()) {
1021 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
Philip Reames32b55182016-05-06 01:13:58 +00001022 if (InVal.DefInst &&
1023 InVal.DefInst == getOrCreateResult(Inst, InVal.DefInst->getType()) &&
Philip Reamesae1f265b2015-12-16 01:01:30 +00001024 InVal.MatchingId == MemInst.getMatchingId() &&
1025 // We don't yet handle removing stores with ordering of any kind.
Geoff Berry8d846052016-08-31 19:24:10 +00001026 !MemInst.isVolatile() && MemInst.isUnordered() &&
Philip Reames0adbb192018-03-14 21:35:06 +00001027 (isOperatingOnInvariantMemAt(Inst, InVal.Generation) ||
1028 isSameMemGeneration(InVal.Generation, CurrentGeneration,
1029 InVal.DefInst, Inst))) {
Geoff Berry8d846052016-08-31 19:24:10 +00001030 // It is okay to have a LastStore to a different pointer here if MemorySSA
1031 // tells us that the load and store are from the same memory generation.
1032 // In that case, LastStore should keep its present value since we're
1033 // removing the current store.
Philip Reamesae1f265b2015-12-16 01:01:30 +00001034 assert((!LastStore ||
1035 ParseMemoryInst(LastStore, TTI).getPointerOperand() ==
Geoff Berry8d846052016-08-31 19:24:10 +00001036 MemInst.getPointerOperand() ||
1037 MSSA) &&
1038 "can't have an intervening store if not using MemorySSA!");
Philip Reamesae1f265b2015-12-16 01:01:30 +00001039 DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << *Inst << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001040 if (!DebugCounter::shouldExecute(CSECounter)) {
1041 DEBUG(dbgs() << "Skipping due to debug counter\n");
1042 continue;
1043 }
Geoff Berry8d846052016-08-31 19:24:10 +00001044 removeMSSA(Inst);
Philip Reamesae1f265b2015-12-16 01:01:30 +00001045 Inst->eraseFromParent();
1046 Changed = true;
1047 ++NumDSE;
1048 // We can avoid incrementing the generation count since we were able
1049 // to eliminate this store.
1050 continue;
1051 }
1052 }
1053
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001054 // Okay, this isn't something we can CSE at all. Check to see if it is
1055 // something that could modify memory. If so, our available memory values
1056 // cannot be used so bump the generation count.
Chris Lattnere0e32a92011-01-03 03:46:34 +00001057 if (Inst->mayWriteToMemory()) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001058 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +00001059
Chad Rosierf9327d62015-01-26 22:51:15 +00001060 if (MemInst.isValid() && MemInst.isStore()) {
Chris Lattner9e5e9ed2011-01-03 04:17:24 +00001061 // We do a trivial form of DSE if there are two stores to the same
Philip Reames15145fb2015-12-17 18:50:50 +00001062 // location with no intervening loads. Delete the earlier store.
1063 // At the moment, we don't remove ordered stores, but do remove
1064 // unordered atomic stores. There's no special requirement (for
1065 // unordered atomics) about removing atomic stores only in favor of
1066 // other atomic stores since we we're going to execute the non-atomic
1067 // one anyway and the atomic one might never have become visible.
Chad Rosierf9327d62015-01-26 22:51:15 +00001068 if (LastStore) {
1069 ParseMemoryInst LastStoreMemInst(LastStore, TTI);
Philip Reames15145fb2015-12-17 18:50:50 +00001070 assert(LastStoreMemInst.isUnordered() &&
1071 !LastStoreMemInst.isVolatile() &&
1072 "Violated invariant");
Chad Rosierf9327d62015-01-26 22:51:15 +00001073 if (LastStoreMemInst.isMatchingMemLoc(MemInst)) {
1074 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
1075 << " due to: " << *Inst << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001076 if (!DebugCounter::shouldExecute(CSECounter)) {
1077 DEBUG(dbgs() << "Skipping due to debug counter\n");
1078 } else {
1079 removeMSSA(LastStore);
1080 LastStore->eraseFromParent();
1081 Changed = true;
1082 ++NumDSE;
1083 LastStore = nullptr;
1084 }
Chad Rosierf9327d62015-01-26 22:51:15 +00001085 }
Philip Reames018dbf12014-11-18 17:46:32 +00001086 // fallthrough - we can exploit information about this store
Chris Lattner9e5e9ed2011-01-03 04:17:24 +00001087 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001088
Chris Lattner9e5e9ed2011-01-03 04:17:24 +00001089 // Okay, we just invalidated anything we knew about loaded values. Try
1090 // to salvage *something* by remembering that the stored value is a live
1091 // version of the pointer. It is safe to forward from volatile stores
1092 // to non-volatile loads, so we don't have to check for volatility of
1093 // the store.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +00001094 AvailableLoads.insert(
Philip Reames9e5e2d62015-12-07 22:41:23 +00001095 MemInst.getPointerOperand(),
Philip Reames8fc2cbf2015-12-08 21:45:41 +00001096 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
Philip Reamesca587fe2018-03-15 17:29:32 +00001097 MemInst.isAtomic()));
Nadav Rotem465834c2012-07-24 10:51:42 +00001098
Philip Reames15145fb2015-12-17 18:50:50 +00001099 // Remember that this was the last unordered store we saw for DSE. We
1100 // don't yet handle DSE on ordered or volatile stores since we don't
1101 // have a good way to model the ordering requirement for following
1102 // passes once the store is removed. We could insert a fence, but
1103 // since fences are slightly stronger than stores in their ordering,
1104 // it's not clear this is a profitable transform. Another option would
1105 // be to merge the ordering with that of the post dominating store.
1106 if (MemInst.isUnordered() && !MemInst.isVolatile())
Chad Rosierf9327d62015-01-26 22:51:15 +00001107 LastStore = Inst;
Philip Reames8fc2cbf2015-12-08 21:45:41 +00001108 else
1109 LastStore = nullptr;
Chris Lattnere0e32a92011-01-03 03:46:34 +00001110 }
1111 }
Chris Lattner18ae5432011-01-02 23:04:14 +00001112 }
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001113
Chris Lattner18ae5432011-01-02 23:04:14 +00001114 return Changed;
Chris Lattner704541b2011-01-02 21:47:05 +00001115}
Chris Lattner18ae5432011-01-02 23:04:14 +00001116
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001117bool EarlyCSE::run() {
Chandler Carruth7253bba2015-01-24 11:33:55 +00001118 // Note, deque is being used here because there is significant performance
1119 // gains over vector when the container becomes very large due to the
1120 // specific access patterns. For more information see the mailing list
1121 // discussion on this:
Tanya Lattner0d28f802015-08-05 03:51:17 +00001122 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
Lenny Maiorani9eefc812014-09-20 13:29:20 +00001123 std::deque<StackNode *> nodesToProcess;
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001124
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001125 bool Changed = false;
1126
1127 // Process the root node.
Chandler Carruth7253bba2015-01-24 11:33:55 +00001128 nodesToProcess.push_back(new StackNode(
Philip Reames0adbb192018-03-14 21:35:06 +00001129 AvailableValues, AvailableLoads, AvailableInvariants, AvailableCalls,
1130 CurrentGeneration, DT.getRootNode(),
1131 DT.getRootNode()->begin(), DT.getRootNode()->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001132
1133 // Save the current generation.
1134 unsigned LiveOutGeneration = CurrentGeneration;
1135
1136 // Process the stack.
1137 while (!nodesToProcess.empty()) {
1138 // Grab the first item off the stack. Set the current generation, remove
1139 // the node from the stack, and process it.
Michael Gottesman2bf01732013-12-05 18:42:12 +00001140 StackNode *NodeToProcess = nodesToProcess.back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001141
1142 // Initialize class members.
1143 CurrentGeneration = NodeToProcess->currentGeneration();
1144
1145 // Check if the node needs to be processed.
1146 if (!NodeToProcess->isProcessed()) {
1147 // Process the node.
1148 Changed |= processNode(NodeToProcess->node());
1149 NodeToProcess->childGeneration(CurrentGeneration);
1150 NodeToProcess->process();
1151 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
1152 // Push the next child onto the stack.
1153 DomTreeNode *child = NodeToProcess->nextChild();
Michael Gottesman2bf01732013-12-05 18:42:12 +00001154 nodesToProcess.push_back(
Philip Reames0adbb192018-03-14 21:35:06 +00001155 new StackNode(AvailableValues, AvailableLoads, AvailableInvariants,
1156 AvailableCalls, NodeToProcess->childGeneration(),
1157 child, child->begin(), child->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001158 } else {
1159 // It has been processed, and there are no more children to process,
1160 // so delete it and pop it off the stack.
1161 delete NodeToProcess;
Michael Gottesman2bf01732013-12-05 18:42:12 +00001162 nodesToProcess.pop_back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001163 }
1164 } // while (!nodes...)
1165
1166 // Reset the current generation.
1167 CurrentGeneration = LiveOutGeneration;
1168
1169 return Changed;
Chris Lattner18ae5432011-01-02 23:04:14 +00001170}
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001171
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001172PreservedAnalyses EarlyCSEPass::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +00001173 FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +00001174 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1175 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
1176 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001177 auto &AC = AM.getResult<AssumptionAnalysis>(F);
Geoff Berry8d846052016-08-31 19:24:10 +00001178 auto *MSSA =
1179 UseMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA() : nullptr;
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001180
Daniel Berlin4d0fe642017-04-28 19:55:38 +00001181 EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001182
1183 if (!CSE.run())
1184 return PreservedAnalyses::all();
1185
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001186 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +00001187 PA.preserveSet<CFGAnalyses>();
Davide Italiano02861d82016-06-08 21:31:55 +00001188 PA.preserve<GlobalsAA>();
Geoff Berry8d846052016-08-31 19:24:10 +00001189 if (UseMemorySSA)
1190 PA.preserve<MemorySSAAnalysis>();
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001191 return PA;
1192}
1193
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001194namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +00001195
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001196/// \brief A simple and fast domtree-based CSE pass.
1197///
1198/// This pass does a simple depth-first walk over the dominator tree,
1199/// eliminating trivially redundant instructions and using instsimplify to
1200/// canonicalize things as it goes. It is intended to be fast and catch obvious
1201/// cases so that instcombine and other passes are more effective. It is
1202/// expected that a later pass of GVN will catch the interesting/hard cases.
Geoff Berry8d846052016-08-31 19:24:10 +00001203template<bool UseMemorySSA>
1204class EarlyCSELegacyCommonPass : public FunctionPass {
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001205public:
1206 static char ID;
1207
Geoff Berry8d846052016-08-31 19:24:10 +00001208 EarlyCSELegacyCommonPass() : FunctionPass(ID) {
1209 if (UseMemorySSA)
1210 initializeEarlyCSEMemSSALegacyPassPass(*PassRegistry::getPassRegistry());
1211 else
1212 initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry());
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001213 }
1214
1215 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001216 if (skipFunction(F))
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001217 return false;
1218
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001219 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +00001220 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001221 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001222 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Geoff Berry8d846052016-08-31 19:24:10 +00001223 auto *MSSA =
1224 UseMemorySSA ? &getAnalysis<MemorySSAWrapperPass>().getMSSA() : nullptr;
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001225
Daniel Berlin4d0fe642017-04-28 19:55:38 +00001226 EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001227
1228 return CSE.run();
1229 }
1230
1231 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001232 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001233 AU.addRequired<DominatorTreeWrapperPass>();
1234 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +00001235 AU.addRequired<TargetTransformInfoWrapperPass>();
Geoff Berry8d846052016-08-31 19:24:10 +00001236 if (UseMemorySSA) {
1237 AU.addRequired<MemorySSAWrapperPass>();
1238 AU.addPreserved<MemorySSAWrapperPass>();
1239 }
James Molloyefbba722015-09-10 10:22:12 +00001240 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001241 AU.setPreservesCFG();
1242 }
1243};
Eugene Zelenko3b879392017-10-13 21:17:07 +00001244
1245} // end anonymous namespace
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001246
Geoff Berry8d846052016-08-31 19:24:10 +00001247using EarlyCSELegacyPass = EarlyCSELegacyCommonPass</*UseMemorySSA=*/false>;
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001248
Geoff Berry8d846052016-08-31 19:24:10 +00001249template<>
1250char EarlyCSELegacyPass::ID = 0;
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001251
1252INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
1253 false)
Chandler Carruth705b1852015-01-31 03:43:40 +00001254INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001255INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001256INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1257INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1258INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)
Geoff Berry8d846052016-08-31 19:24:10 +00001259
1260using EarlyCSEMemSSALegacyPass =
1261 EarlyCSELegacyCommonPass</*UseMemorySSA=*/true>;
1262
1263template<>
1264char EarlyCSEMemSSALegacyPass::ID = 0;
1265
1266FunctionPass *llvm::createEarlyCSEPass(bool UseMemorySSA) {
1267 if (UseMemorySSA)
1268 return new EarlyCSEMemSSALegacyPass();
1269 else
1270 return new EarlyCSELegacyPass();
1271}
1272
1273INITIALIZE_PASS_BEGIN(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1274 "Early CSE w/ MemorySSA", false, false)
1275INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001276INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Geoff Berry8d846052016-08-31 19:24:10 +00001277INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1278INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1279INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
1280INITIALIZE_PASS_END(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1281 "Early CSE w/ MemorySSA", false, false)