blob: ad60aac4585b9bdec191dc2f67b14f4191d2bbf4 [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
Chris Lattner79d83062011-01-03 02:20:48 +000078//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +000079// SimpleValue
Chris Lattner79d83062011-01-03 02:20:48 +000080//===----------------------------------------------------------------------===//
81
Chris Lattner704541b2011-01-02 21:47:05 +000082namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +000083
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000084/// Struct representing the available values in the scoped hash table.
Chandler Carruth7253bba2015-01-24 11:33:55 +000085struct SimpleValue {
86 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +000087
Chandler Carruth7253bba2015-01-24 11:33:55 +000088 SimpleValue(Instruction *I) : Inst(I) {
89 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
90 }
Nadav Rotem465834c2012-07-24 10:51:42 +000091
Chandler Carruth7253bba2015-01-24 11:33:55 +000092 bool isSentinel() const {
93 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
94 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
95 }
Nadav Rotem465834c2012-07-24 10:51:42 +000096
Chandler Carruth7253bba2015-01-24 11:33:55 +000097 static bool canHandle(Instruction *Inst) {
98 // This can only handle non-void readnone functions.
99 if (CallInst *CI = dyn_cast<CallInst>(Inst))
100 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
101 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
102 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
103 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
104 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
105 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
106 }
107};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000108
109} // end anonymous namespace
Chris Lattner18ae5432011-01-02 23:04:14 +0000110
111namespace llvm {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000112
Chandler Carruth7253bba2015-01-24 11:33:55 +0000113template <> struct DenseMapInfo<SimpleValue> {
Chris Lattner79d83062011-01-03 02:20:48 +0000114 static inline SimpleValue getEmptyKey() {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000115 return DenseMapInfo<Instruction *>::getEmptyKey();
Chris Lattner18ae5432011-01-02 23:04:14 +0000116 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000117
Chris Lattner79d83062011-01-03 02:20:48 +0000118 static inline SimpleValue getTombstoneKey() {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000119 return DenseMapInfo<Instruction *>::getTombstoneKey();
Chris Lattner18ae5432011-01-02 23:04:14 +0000120 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000121
Chris Lattner79d83062011-01-03 02:20:48 +0000122 static unsigned getHashValue(SimpleValue Val);
123 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
Chris Lattner18ae5432011-01-02 23:04:14 +0000124};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000125
126} // end namespace llvm
Chris Lattner18ae5432011-01-02 23:04:14 +0000127
Chris Lattner79d83062011-01-03 02:20:48 +0000128unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000129 Instruction *Inst = Val.Inst;
Chris Lattner02a97762011-01-03 01:10:08 +0000130 // Hash in all of the operands as pointers.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000131 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
Michael Ilseman336cb792012-10-09 16:57:38 +0000132 Value *LHS = BinOp->getOperand(0);
133 Value *RHS = BinOp->getOperand(1);
134 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
135 std::swap(LHS, RHS);
Chris Lattner02a97762011-01-03 01:10:08 +0000136
Michael Ilseman336cb792012-10-09 16:57:38 +0000137 return hash_combine(BinOp->getOpcode(), LHS, RHS);
Chris Lattner02a97762011-01-03 01:10:08 +0000138 }
139
Michael Ilseman336cb792012-10-09 16:57:38 +0000140 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
141 Value *LHS = CI->getOperand(0);
142 Value *RHS = CI->getOperand(1);
143 CmpInst::Predicate Pred = CI->getPredicate();
144 if (Inst->getOperand(0) > Inst->getOperand(1)) {
145 std::swap(LHS, RHS);
146 Pred = CI->getSwappedPredicate();
147 }
148 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
149 }
150
Sanjay Patel558a4652017-12-13 22:57:35 +0000151 // Hash min/max/abs (cmp + select) to allow for commuted operands.
152 // Min/max may also have non-canonical compare predicate (eg, the compare for
153 // smin may use 'sgt' rather than 'slt'), and non-canonical operands in the
154 // compare.
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000155 Value *A, *B;
156 SelectPatternFlavor SPF = matchSelectPattern(Inst, A, B).Flavor;
Sanjay Patel558a4652017-12-13 22:57:35 +0000157 // TODO: We should also detect FP min/max.
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000158 if (SPF == SPF_SMIN || SPF == SPF_SMAX ||
Craig Topperf14e62c2018-05-21 18:42:42 +0000159 SPF == SPF_UMIN || SPF == SPF_UMAX) {
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 }
Craig Topperf14e62c2018-05-21 18:42:42 +0000164 if (SPF == SPF_ABS || SPF == SPF_NABS) {
165 // ABS/NABS always puts the input in A and its negation in B.
166 return hash_combine(Inst->getOpcode(), SPF, A, B);
167 }
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000168
Michael Ilseman336cb792012-10-09 16:57:38 +0000169 if (CastInst *CI = dyn_cast<CastInst>(Inst))
170 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
171
172 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
173 return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
174 hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
175
176 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
177 return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
178 IVI->getOperand(1),
179 hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
180
181 assert((isa<CallInst>(Inst) || isa<BinaryOperator>(Inst) ||
182 isa<GetElementPtrInst>(Inst) || isa<SelectInst>(Inst) ||
183 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
Chandler Carruth7253bba2015-01-24 11:33:55 +0000184 isa<ShuffleVectorInst>(Inst)) &&
185 "Invalid/unknown instruction");
Michael Ilseman336cb792012-10-09 16:57:38 +0000186
Chris Lattner02a97762011-01-03 01:10:08 +0000187 // Mix in the opcode.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000188 return hash_combine(
189 Inst->getOpcode(),
190 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
Chris Lattner18ae5432011-01-02 23:04:14 +0000191}
192
Chris Lattner79d83062011-01-03 02:20:48 +0000193bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
Chris Lattner18ae5432011-01-02 23:04:14 +0000194 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
195
196 if (LHS.isSentinel() || RHS.isSentinel())
197 return LHSI == RHSI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000198
Chandler Carruth7253bba2015-01-24 11:33:55 +0000199 if (LHSI->getOpcode() != RHSI->getOpcode())
200 return false;
David Majnemer9554c132016-04-22 06:37:45 +0000201 if (LHSI->isIdenticalToWhenDefined(RHSI))
Chandler Carruth7253bba2015-01-24 11:33:55 +0000202 return true;
Michael Ilseman336cb792012-10-09 16:57:38 +0000203
204 // If we're not strictly identical, we still might be a commutable instruction
205 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
206 if (!LHSBinOp->isCommutative())
207 return false;
208
Chandler Carruth7253bba2015-01-24 11:33:55 +0000209 assert(isa<BinaryOperator>(RHSI) &&
210 "same opcode, but different instruction type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000211 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
212
Michael Ilseman336cb792012-10-09 16:57:38 +0000213 // Commuted equality
214 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000215 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
Michael Ilseman336cb792012-10-09 16:57:38 +0000216 }
217 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000218 assert(isa<CmpInst>(RHSI) &&
219 "same opcode, but different instruction type?");
Michael Ilseman336cb792012-10-09 16:57:38 +0000220 CmpInst *RHSCmp = cast<CmpInst>(RHSI);
221 // Commuted equality
222 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
Chandler Carruth7253bba2015-01-24 11:33:55 +0000223 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
224 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
Michael Ilseman336cb792012-10-09 16:57:38 +0000225 }
226
Sanjay Patel558a4652017-12-13 22:57:35 +0000227 // Min/max/abs can occur with commuted operands, non-canonical predicates,
228 // and/or non-canonical operands.
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000229 Value *LHSA, *LHSB;
230 SelectPatternFlavor LSPF = matchSelectPattern(LHSI, LHSA, LHSB).Flavor;
Sanjay Patel558a4652017-12-13 22:57:35 +0000231 // TODO: We should also detect FP min/max.
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000232 if (LSPF == SPF_SMIN || LSPF == SPF_SMAX ||
Sanjay Patel558a4652017-12-13 22:57:35 +0000233 LSPF == SPF_UMIN || LSPF == SPF_UMAX ||
234 LSPF == SPF_ABS || LSPF == SPF_NABS) {
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000235 Value *RHSA, *RHSB;
236 SelectPatternFlavor RSPF = matchSelectPattern(RHSI, RHSA, RHSB).Flavor;
Craig Topperf14e62c2018-05-21 18:42:42 +0000237 if (LSPF == RSPF) {
238 // Abs results are placed in a defined order by matchSelectPattern.
239 if (LSPF == SPF_ABS || LSPF == SPF_NABS)
240 return LHSA == RHSA && LHSB == RHSB;
241 return ((LHSA == RHSA && LHSB == RHSB) ||
242 (LHSA == RHSB && LHSB == RHSA));
243 }
Sanjay Patel3c7a35d2017-12-13 21:58:15 +0000244 }
245
Michael Ilseman336cb792012-10-09 16:57:38 +0000246 return false;
Chris Lattner18ae5432011-01-02 23:04:14 +0000247}
248
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000249//===----------------------------------------------------------------------===//
Nadav Rotem465834c2012-07-24 10:51:42 +0000250// CallValue
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000251//===----------------------------------------------------------------------===//
252
253namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000254
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000255/// Struct representing the available call values in the scoped hash
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000256/// table.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000257struct CallValue {
258 Instruction *Inst;
Nadav Rotem465834c2012-07-24 10:51:42 +0000259
Chandler Carruth7253bba2015-01-24 11:33:55 +0000260 CallValue(Instruction *I) : Inst(I) {
261 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
262 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000263
Chandler Carruth7253bba2015-01-24 11:33:55 +0000264 bool isSentinel() const {
265 return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
266 Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
267 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000268
Chandler Carruth7253bba2015-01-24 11:33:55 +0000269 static bool canHandle(Instruction *Inst) {
270 // Don't value number anything that returns void.
271 if (Inst->getType()->isVoidTy())
272 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000273
Chandler Carruth7253bba2015-01-24 11:33:55 +0000274 CallInst *CI = dyn_cast<CallInst>(Inst);
275 if (!CI || !CI->onlyReadsMemory())
276 return false;
277 return true;
278 }
279};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000280
281} // end anonymous namespace
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000282
283namespace llvm {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000284
Chandler Carruth7253bba2015-01-24 11:33:55 +0000285template <> struct DenseMapInfo<CallValue> {
286 static inline CallValue getEmptyKey() {
287 return DenseMapInfo<Instruction *>::getEmptyKey();
288 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000289
Chandler Carruth7253bba2015-01-24 11:33:55 +0000290 static inline CallValue getTombstoneKey() {
291 return DenseMapInfo<Instruction *>::getTombstoneKey();
292 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000293
Chandler Carruth7253bba2015-01-24 11:33:55 +0000294 static unsigned getHashValue(CallValue Val);
295 static bool isEqual(CallValue LHS, CallValue RHS);
296};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000297
298} // end namespace llvm
Chandler Carruth7253bba2015-01-24 11:33:55 +0000299
Chris Lattner92bb0f92011-01-03 03:41:27 +0000300unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000301 Instruction *Inst = Val.Inst;
Benjamin Kramer6ab86b12015-02-01 12:30:59 +0000302 // Hash all of the operands as pointers and mix in the opcode.
303 return hash_combine(
304 Inst->getOpcode(),
305 hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000306}
307
Chris Lattner92bb0f92011-01-03 03:41:27 +0000308bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000309 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000310 if (LHS.isSentinel() || RHS.isSentinel())
311 return LHSI == RHSI;
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000312 return LHSI->isIdenticalTo(RHSI);
313}
314
Chris Lattner79d83062011-01-03 02:20:48 +0000315//===----------------------------------------------------------------------===//
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000316// EarlyCSE implementation
Chris Lattner79d83062011-01-03 02:20:48 +0000317//===----------------------------------------------------------------------===//
318
Chris Lattner18ae5432011-01-02 23:04:14 +0000319namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000320
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000321/// A simple and fast domtree-based CSE pass.
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000322///
323/// This pass does a simple depth-first walk over the dominator tree,
324/// eliminating trivially redundant instructions and using instsimplify to
325/// canonicalize things as it goes. It is intended to be fast and catch obvious
326/// cases so that instcombine and other passes are more effective. It is
327/// expected that a later pass of GVN will catch the interesting/hard cases.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000328class EarlyCSE {
Chris Lattner704541b2011-01-02 21:47:05 +0000329public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000330 const TargetLibraryInfo &TLI;
331 const TargetTransformInfo &TTI;
332 DominatorTree &DT;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000333 AssumptionCache &AC;
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000334 const SimplifyQuery SQ;
Geoff Berry8d846052016-08-31 19:24:10 +0000335 MemorySSA *MSSA;
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000336 std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
Eugene Zelenko3b879392017-10-13 21:17:07 +0000337
338 using AllocatorTy =
339 RecyclingAllocator<BumpPtrAllocator,
340 ScopedHashTableVal<SimpleValue, Value *>>;
341 using ScopedHTType =
342 ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
343 AllocatorTy>;
Nadav Rotem465834c2012-07-24 10:51:42 +0000344
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000345 /// A scoped hash table of the current values of all of our simple
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000346 /// scalar expressions.
347 ///
348 /// As we walk down the domtree, we look to see if instructions are in this:
349 /// if so, we replace them with what we find, otherwise we insert them so
350 /// that dominated values can succeed in their lookup.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000351 ScopedHTType AvailableValues;
Nadav Rotem465834c2012-07-24 10:51:42 +0000352
Hiroshi Inouef2096492018-06-14 05:41:49 +0000353 /// A scoped hash table of the current values of previously encountered
354 /// memory locations.
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000355 ///
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000356 /// This allows us to get efficient access to dominating loads or stores when
357 /// we have a fully redundant load. In addition to the most recent load, we
358 /// keep track of a generation count of the read, which is compared against
359 /// the current generation count. The current generation count is incremented
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000360 /// after every possibly writing memory operation, which ensures that we only
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000361 /// CSE loads with other loads that have no intervening store. Ordering
362 /// events (such as fences or atomic instructions) increment the generation
363 /// count as well; essentially, we model these as writes to all possible
364 /// locations. Note that atomic and/or volatile loads and stores can be
365 /// present the table; it is the responsibility of the consumer to inspect
366 /// the atomicity/volatility if needed.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000367 struct LoadValue {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000368 Instruction *DefInst = nullptr;
369 unsigned Generation = 0;
370 int MatchingId = -1;
371 bool IsAtomic = false;
Philip Reames0adbb192018-03-14 21:35:06 +0000372
Eugene Zelenko3b879392017-10-13 21:17:07 +0000373 LoadValue() = default;
Geoff Berry5ae272c2016-04-28 15:22:37 +0000374 LoadValue(Instruction *Inst, unsigned Generation, unsigned MatchingId,
Philip Reamesca587fe2018-03-15 17:29:32 +0000375 bool IsAtomic)
Sanjoy Das07c65212016-06-16 20:47:57 +0000376 : DefInst(Inst), Generation(Generation), MatchingId(MatchingId),
Philip Reamesca587fe2018-03-15 17:29:32 +0000377 IsAtomic(IsAtomic) {}
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +0000378 };
Eugene Zelenko3b879392017-10-13 21:17:07 +0000379
380 using LoadMapAllocator =
381 RecyclingAllocator<BumpPtrAllocator,
382 ScopedHashTableVal<Value *, LoadValue>>;
383 using LoadHTType =
384 ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>,
385 LoadMapAllocator>;
386
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000387 LoadHTType AvailableLoads;
Fangrui Songf78650a2018-07-30 19:41:25 +0000388
Philip Reames0adbb192018-03-14 21:35:06 +0000389 // A scoped hash table mapping memory locations (represented as typed
390 // addresses) to generation numbers at which that memory location became
391 // (henceforth indefinitely) invariant.
392 using InvariantMapAllocator =
393 RecyclingAllocator<BumpPtrAllocator,
394 ScopedHashTableVal<MemoryLocation, unsigned>>;
395 using InvariantHTType =
396 ScopedHashTable<MemoryLocation, unsigned, DenseMapInfo<MemoryLocation>,
397 InvariantMapAllocator>;
398 InvariantHTType AvailableInvariants;
Nadav Rotem465834c2012-07-24 10:51:42 +0000399
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000400 /// A scoped hash table of the current values of read-only call
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000401 /// values.
402 ///
403 /// It uses the same generation count as loads.
Eugene Zelenko3b879392017-10-13 21:17:07 +0000404 using CallHTType =
405 ScopedHashTable<CallValue, std::pair<Instruction *, unsigned>>;
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000406 CallHTType AvailableCalls;
Nadav Rotem465834c2012-07-24 10:51:42 +0000407
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000408 /// This is the current generation of the memory value.
Eugene Zelenko3b879392017-10-13 21:17:07 +0000409 unsigned CurrentGeneration = 0;
Nadav Rotem465834c2012-07-24 10:51:42 +0000410
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000411 /// Set up the EarlyCSE runner for a particular function.
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000412 EarlyCSE(const DataLayout &DL, const TargetLibraryInfo &TLI,
413 const TargetTransformInfo &TTI, DominatorTree &DT,
414 AssumptionCache &AC, MemorySSA *MSSA)
415 : TLI(TLI), TTI(TTI), DT(DT), AC(AC), SQ(DL, &TLI, &DT, &AC), MSSA(MSSA),
Eugene Zelenko3b879392017-10-13 21:17:07 +0000416 MSSAUpdater(llvm::make_unique<MemorySSAUpdater>(MSSA)) {}
Chris Lattner704541b2011-01-02 21:47:05 +0000417
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000418 bool run();
Chris Lattner704541b2011-01-02 21:47:05 +0000419
420private:
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000421 // Almost a POD, but needs to call the constructors for the scoped hash
422 // tables so that a new scope gets pushed on. These are RAII so that the
423 // scope gets popped when the NodeScope is destroyed.
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000424 class NodeScope {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000425 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000426 NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
Philip Reames0adbb192018-03-14 21:35:06 +0000427 InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls)
428 : Scope(AvailableValues), LoadScope(AvailableLoads),
429 InvariantScope(AvailableInvariants), CallScope(AvailableCalls) {}
Eugene Zelenko3b879392017-10-13 21:17:07 +0000430 NodeScope(const NodeScope &) = delete;
431 NodeScope &operator=(const NodeScope &) = delete;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000432
Chandler Carruth7253bba2015-01-24 11:33:55 +0000433 private:
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000434 ScopedHTType::ScopeTy Scope;
435 LoadHTType::ScopeTy LoadScope;
Philip Reames0adbb192018-03-14 21:35:06 +0000436 InvariantHTType::ScopeTy InvariantScope;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000437 CallHTType::ScopeTy CallScope;
438 };
439
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000440 // Contains all the needed information to create a stack for doing a depth
Nick Lewyckyedd0a702016-09-07 01:49:41 +0000441 // first traversal of the tree. This includes scopes for values, loads, and
Chandler Carruth9dea5cd2015-01-24 11:44:32 +0000442 // calls as well as the generation. There is a child iterator so that the
Sanjoy Das5253a082016-04-27 01:44:31 +0000443 // children do not need to be store separately.
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000444 class StackNode {
Chandler Carruth7253bba2015-01-24 11:33:55 +0000445 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000446 StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
Philip Reames0adbb192018-03-14 21:35:06 +0000447 InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls,
448 unsigned cg, DomTreeNode *n, DomTreeNode::iterator child,
449 DomTreeNode::iterator end)
Chandler Carruth7253bba2015-01-24 11:33:55 +0000450 : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
Philip Reames0adbb192018-03-14 21:35:06 +0000451 EndIter(end),
452 Scopes(AvailableValues, AvailableLoads, AvailableInvariants,
453 AvailableCalls)
Eugene Zelenko3b879392017-10-13 21:17:07 +0000454 {}
455 StackNode(const StackNode &) = delete;
456 StackNode &operator=(const StackNode &) = delete;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000457
458 // Accessors.
459 unsigned currentGeneration() { return CurrentGeneration; }
460 unsigned childGeneration() { return ChildGeneration; }
461 void childGeneration(unsigned generation) { ChildGeneration = generation; }
462 DomTreeNode *node() { return Node; }
463 DomTreeNode::iterator childIter() { return ChildIter; }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000464
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000465 DomTreeNode *nextChild() {
466 DomTreeNode *child = *ChildIter;
467 ++ChildIter;
468 return child;
469 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000470
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000471 DomTreeNode::iterator end() { return EndIter; }
472 bool isProcessed() { return Processed; }
473 void process() { Processed = true; }
474
Chandler Carruth7253bba2015-01-24 11:33:55 +0000475 private:
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000476 unsigned CurrentGeneration;
477 unsigned ChildGeneration;
478 DomTreeNode *Node;
479 DomTreeNode::iterator ChildIter;
480 DomTreeNode::iterator EndIter;
481 NodeScope Scopes;
Eugene Zelenko3b879392017-10-13 21:17:07 +0000482 bool Processed = false;
Lenny Maiorani8d670b82012-01-31 23:14:41 +0000483 };
484
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000485 /// Wrapper class to handle memory instructions, including loads,
Chad Rosierf9327d62015-01-26 22:51:15 +0000486 /// stores and intrinsic loads and stores defined by the target.
487 class ParseMemoryInst {
488 public:
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000489 ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
Eugene Zelenko3b879392017-10-13 21:17:07 +0000490 : Inst(Inst) {
Philip Reames9e5e2d62015-12-07 22:41:23 +0000491 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000492 if (TTI.getTgtMemIntrinsic(II, Info))
Philip Reames9e5e2d62015-12-07 22:41:23 +0000493 IsTargetMemInst = true;
494 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000495
Philip Reames9e5e2d62015-12-07 22:41:23 +0000496 bool isLoad() const {
497 if (IsTargetMemInst) return Info.ReadMem;
498 return isa<LoadInst>(Inst);
499 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000500
Philip Reames9e5e2d62015-12-07 22:41:23 +0000501 bool isStore() const {
502 if (IsTargetMemInst) return Info.WriteMem;
503 return isa<StoreInst>(Inst);
504 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000505
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000506 bool isAtomic() const {
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000507 if (IsTargetMemInst)
508 return Info.Ordering != AtomicOrdering::NotAtomic;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000509 return Inst->isAtomic();
510 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000511
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000512 bool isUnordered() const {
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000513 if (IsTargetMemInst)
514 return Info.isUnordered();
515
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000516 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
517 return LI->isUnordered();
518 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
519 return SI->isUnordered();
520 }
521 // Conservative answer
522 return !Inst->isAtomic();
523 }
524
525 bool isVolatile() const {
Matt Arsenault18bb24a2017-03-24 18:56:43 +0000526 if (IsTargetMemInst)
527 return Info.IsVolatile;
528
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000529 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
530 return LI->isVolatile();
531 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
532 return SI->isVolatile();
533 }
534 // Conservative answer
535 return true;
536 }
537
Sanjoy Das07c65212016-06-16 20:47:57 +0000538 bool isInvariantLoad() const {
539 if (auto *LI = dyn_cast<LoadInst>(Inst))
Sanjoy Das1ab2fad2016-06-16 21:00:57 +0000540 return LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr;
Sanjoy Das07c65212016-06-16 20:47:57 +0000541 return false;
542 }
Junmo Park80440eb2016-02-18 10:09:20 +0000543
Arnaud A. de Grandmaison6fd488b2015-10-06 13:35:30 +0000544 bool isMatchingMemLoc(const ParseMemoryInst &Inst) const {
Philip Reames9e5e2d62015-12-07 22:41:23 +0000545 return (getPointerOperand() == Inst.getPointerOperand() &&
546 getMatchingId() == Inst.getMatchingId());
Chad Rosierf9327d62015-01-26 22:51:15 +0000547 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000548
Philip Reames9e5e2d62015-12-07 22:41:23 +0000549 bool isValid() const { return getPointerOperand() != nullptr; }
Chad Rosierf9327d62015-01-26 22:51:15 +0000550
Chad Rosierf9327d62015-01-26 22:51:15 +0000551 // For regular (non-intrinsic) loads/stores, this is set to -1. For
552 // intrinsic loads/stores, the id is retrieved from the corresponding
553 // field in the MemIntrinsicInfo structure. That field contains
554 // non-negative values only.
Philip Reames9e5e2d62015-12-07 22:41:23 +0000555 int getMatchingId() const {
556 if (IsTargetMemInst) return Info.MatchingId;
557 return -1;
558 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000559
Philip Reames9e5e2d62015-12-07 22:41:23 +0000560 Value *getPointerOperand() const {
561 if (IsTargetMemInst) return Info.PtrVal;
Renato Golin038ede22018-03-09 21:05:58 +0000562 return getLoadStorePointerOperand(Inst);
Philip Reames9e5e2d62015-12-07 22:41:23 +0000563 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000564
Philip Reames9e5e2d62015-12-07 22:41:23 +0000565 bool mayReadFromMemory() const {
566 if (IsTargetMemInst) return Info.ReadMem;
567 return Inst->mayReadFromMemory();
568 }
Eugene Zelenko3b879392017-10-13 21:17:07 +0000569
Philip Reames9e5e2d62015-12-07 22:41:23 +0000570 bool mayWriteToMemory() const {
571 if (IsTargetMemInst) return Info.WriteMem;
572 return Inst->mayWriteToMemory();
573 }
574
575 private:
Eugene Zelenko3b879392017-10-13 21:17:07 +0000576 bool IsTargetMemInst = false;
Philip Reames9e5e2d62015-12-07 22:41:23 +0000577 MemIntrinsicInfo Info;
578 Instruction *Inst;
Chad Rosierf9327d62015-01-26 22:51:15 +0000579 };
580
Chris Lattner18ae5432011-01-02 23:04:14 +0000581 bool processNode(DomTreeNode *Node);
Nadav Rotem465834c2012-07-24 10:51:42 +0000582
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000583 bool handleBranchCondition(Instruction *CondInst, const BranchInst *BI,
584 const BasicBlock *BB, const BasicBlock *Pred);
585
Chad Rosierf9327d62015-01-26 22:51:15 +0000586 Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const {
Sanjay Patel1c9867d2017-01-03 00:16:24 +0000587 if (auto *LI = dyn_cast<LoadInst>(Inst))
Chad Rosierf9327d62015-01-26 22:51:15 +0000588 return LI;
Sanjay Patel1c9867d2017-01-03 00:16:24 +0000589 if (auto *SI = dyn_cast<StoreInst>(Inst))
Chad Rosierf9327d62015-01-26 22:51:15 +0000590 return SI->getValueOperand();
591 assert(isa<IntrinsicInst>(Inst) && "Instruction not supported");
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000592 return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst),
593 ExpectedType);
Chad Rosierf9327d62015-01-26 22:51:15 +0000594 }
Geoff Berry8d846052016-08-31 19:24:10 +0000595
Philip Reames0adbb192018-03-14 21:35:06 +0000596 /// Return true if the instruction is known to only operate on memory
597 /// provably invariant in the given "generation".
598 bool isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt);
599
Geoff Berry8d846052016-08-31 19:24:10 +0000600 bool isSameMemGeneration(unsigned EarlierGeneration, unsigned LaterGeneration,
601 Instruction *EarlierInst, Instruction *LaterInst);
602
603 void removeMSSA(Instruction *Inst) {
604 if (!MSSA)
605 return;
Alina Sbirleaa782a702018-09-17 22:35:21 +0000606 if (VerifyMemorySSA)
607 MSSA->verifyMemorySSA();
Geoff Berry91e9a5c2016-10-25 16:18:47 +0000608 // Removing a store here can leave MemorySSA in an unoptimized state by
609 // creating MemoryPhis that have identical arguments and by creating
Geoff Berry68154682016-10-24 15:54:00 +0000610 // MemoryUses whose defining access is not an actual clobber. We handle the
Geoff Berry91e9a5c2016-10-25 16:18:47 +0000611 // phi case eagerly here. The non-optimized MemoryUse case is lazily
612 // updated by MemorySSA getClobberingMemoryAccess.
Geoff Berry68154682016-10-24 15:54:00 +0000613 if (MemoryAccess *MA = MSSA->getMemoryAccess(Inst)) {
614 // Optimize MemoryPhi nodes that may become redundant by having all the
615 // same input values once MA is removed.
Davide Italiano0dc47782017-06-14 19:29:53 +0000616 SmallSetVector<MemoryPhi *, 4> PhisToCheck;
Geoff Berry68154682016-10-24 15:54:00 +0000617 SmallVector<MemoryAccess *, 8> WorkQueue;
618 WorkQueue.push_back(MA);
619 // Process MemoryPhi nodes in FIFO order using a ever-growing vector since
620 // we shouldn't be processing that many phis and this will avoid an
621 // allocation in almost all cases.
622 for (unsigned I = 0; I < WorkQueue.size(); ++I) {
623 MemoryAccess *WI = WorkQueue[I];
624
625 for (auto *U : WI->users())
626 if (MemoryPhi *MP = dyn_cast<MemoryPhi>(U))
Davide Italiano0dc47782017-06-14 19:29:53 +0000627 PhisToCheck.insert(MP);
Geoff Berry68154682016-10-24 15:54:00 +0000628
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000629 MSSAUpdater->removeMemoryAccess(WI);
Geoff Berry68154682016-10-24 15:54:00 +0000630
631 for (MemoryPhi *MP : PhisToCheck) {
632 MemoryAccess *FirstIn = MP->getIncomingValue(0);
Eugene Zelenko3b879392017-10-13 21:17:07 +0000633 if (llvm::all_of(MP->incoming_values(),
634 [=](Use &In) { return In == FirstIn; }))
Geoff Berry68154682016-10-24 15:54:00 +0000635 WorkQueue.push_back(MP);
636 }
637 PhisToCheck.clear();
638 }
639 }
Geoff Berry8d846052016-08-31 19:24:10 +0000640 }
Chris Lattner704541b2011-01-02 21:47:05 +0000641};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000642
643} // end anonymous namespace
Chris Lattner704541b2011-01-02 21:47:05 +0000644
Geoff Berry68154682016-10-24 15:54:00 +0000645/// Determine if the memory referenced by LaterInst is from the same heap
646/// version as EarlierInst.
Geoff Berry8d846052016-08-31 19:24:10 +0000647/// This is currently called in two scenarios:
648///
649/// load p
650/// ...
651/// load p
652///
653/// and
654///
655/// x = load p
656/// ...
657/// store x, p
658///
659/// in both cases we want to verify that there are no possible writes to the
660/// memory referenced by p between the earlier and later instruction.
661bool EarlyCSE::isSameMemGeneration(unsigned EarlierGeneration,
662 unsigned LaterGeneration,
663 Instruction *EarlierInst,
664 Instruction *LaterInst) {
665 // Check the simple memory generation tracking first.
666 if (EarlierGeneration == LaterGeneration)
667 return true;
668
669 if (!MSSA)
670 return false;
671
Geoff Berryf7d5daa2017-07-14 20:13:21 +0000672 // If MemorySSA has determined that one of EarlierInst or LaterInst does not
673 // read/write memory, then we can safely return true here.
674 // FIXME: We could be more aggressive when checking doesNotAccessMemory(),
675 // onlyReadsMemory(), mayReadFromMemory(), and mayWriteToMemory() in this pass
676 // by also checking the MemorySSA MemoryAccess on the instruction. Initial
677 // experiments suggest this isn't worthwhile, at least for C/C++ code compiled
678 // with the default optimization pipeline.
679 auto *EarlierMA = MSSA->getMemoryAccess(EarlierInst);
680 if (!EarlierMA)
681 return true;
682 auto *LaterMA = MSSA->getMemoryAccess(LaterInst);
683 if (!LaterMA)
684 return true;
685
Geoff Berry8d846052016-08-31 19:24:10 +0000686 // Since we know LaterDef dominates LaterInst and EarlierInst dominates
687 // LaterInst, if LaterDef dominates EarlierInst then it can't occur between
688 // EarlierInst and LaterInst and neither can any other write that potentially
689 // clobbers LaterInst.
Geoff Berry91e9a5c2016-10-25 16:18:47 +0000690 MemoryAccess *LaterDef =
691 MSSA->getWalker()->getClobberingMemoryAccess(LaterInst);
Geoff Berryf7d5daa2017-07-14 20:13:21 +0000692 return MSSA->dominates(LaterDef, EarlierMA);
Geoff Berry8d846052016-08-31 19:24:10 +0000693}
694
Philip Reames0adbb192018-03-14 21:35:06 +0000695bool EarlyCSE::isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt) {
696 // A location loaded from with an invariant_load is assumed to *never* change
697 // within the visible scope of the compilation.
698 if (auto *LI = dyn_cast<LoadInst>(I))
699 if (LI->getMetadata(LLVMContext::MD_invariant_load))
700 return true;
701
702 auto MemLocOpt = MemoryLocation::getOrNone(I);
703 if (!MemLocOpt)
704 // "target" intrinsic forms of loads aren't currently known to
705 // MemoryLocation::get. TODO
706 return false;
707 MemoryLocation MemLoc = *MemLocOpt;
708 if (!AvailableInvariants.count(MemLoc))
709 return false;
710
711 // Is the generation at which this became invariant older than the
712 // current one?
713 return AvailableInvariants.lookup(MemLoc) <= GenAt;
714}
715
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000716bool EarlyCSE::handleBranchCondition(Instruction *CondInst,
717 const BranchInst *BI, const BasicBlock *BB,
718 const BasicBlock *Pred) {
719 assert(BI->isConditional() && "Should be a conditional branch!");
720 assert(BI->getCondition() == CondInst && "Wrong condition?");
721 assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
722 auto *TorF = (BI->getSuccessor(0) == BB)
723 ? ConstantInt::getTrue(BB->getContext())
724 : ConstantInt::getFalse(BB->getContext());
Simon Pilgrimdee9c672018-06-14 14:22:03 +0000725 auto MatchBinOp = [](Instruction *I, unsigned Opcode) {
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000726 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(I))
Simon Pilgrimdee9c672018-06-14 14:22:03 +0000727 return BOp->getOpcode() == Opcode;
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000728 return false;
729 };
730 // If the condition is AND operation, we can propagate its operands into the
731 // true branch. If it is OR operation, we can propagate them into the false
732 // branch.
Simon Pilgrimdee9c672018-06-14 14:22:03 +0000733 unsigned PropagateOpcode =
734 (BI->getSuccessor(0) == BB) ? Instruction::And : Instruction::Or;
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000735
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000736 bool MadeChanges = false;
737 SmallVector<Instruction *, 4> WorkList;
738 SmallPtrSet<Instruction *, 4> Visited;
739 WorkList.push_back(CondInst);
740 while (!WorkList.empty()) {
741 Instruction *Curr = WorkList.pop_back_val();
742
743 AvailableValues.insert(Curr, TorF);
744 LLVM_DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
745 << Curr->getName() << "' as " << *TorF << " in "
746 << BB->getName() << "\n");
747 if (!DebugCounter::shouldExecute(CSECounter)) {
748 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
749 } else {
750 // Replace all dominated uses with the known value.
751 if (unsigned Count = replaceDominatedUsesWith(Curr, TorF, DT,
752 BasicBlockEdge(Pred, BB))) {
753 NumCSECVP += Count;
754 MadeChanges = true;
755 }
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000756 }
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000757
Simon Pilgrimdee9c672018-06-14 14:22:03 +0000758 if (MatchBinOp(Curr, PropagateOpcode))
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000759 for (auto &Op : cast<BinaryOperator>(Curr)->operands())
760 if (Instruction *OPI = dyn_cast<Instruction>(Op))
761 if (SimpleValue::canHandle(OPI) && Visited.insert(OPI).second)
762 WorkList.push_back(OPI);
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000763 }
Max Kazantsevff6d1c92018-06-14 13:02:13 +0000764
765 return MadeChanges;
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000766}
767
Chris Lattner18ae5432011-01-02 23:04:14 +0000768bool EarlyCSE::processNode(DomTreeNode *Node) {
Chad Rosier1a4bc112016-04-22 18:47:21 +0000769 bool Changed = false;
Chris Lattner18ae5432011-01-02 23:04:14 +0000770 BasicBlock *BB = Node->getBlock();
Nadav Rotem465834c2012-07-24 10:51:42 +0000771
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000772 // If this block has a single predecessor, then the predecessor is the parent
773 // of the domtree node and all of the live out memory values are still current
774 // in this block. If this block has multiple predecessors, then they could
775 // have invalidated the live-out memory values of our parent value. For now,
776 // just be conservative and invalidate memory if this block has multiple
777 // predecessors.
Craig Topperf40110f2014-04-25 05:29:35 +0000778 if (!BB->getSinglePredecessor())
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000779 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +0000780
Philip Reames7c78ef72015-05-22 23:53:24 +0000781 // If this node has a single predecessor which ends in a conditional branch,
782 // we can infer the value of the branch condition given that we took this
Chad Rosierb346dcb2016-04-20 19:16:23 +0000783 // path. We need the single predecessor to ensure there's not another path
Philip Reames7c78ef72015-05-22 23:53:24 +0000784 // which reaches this block where the condition might hold a different
785 // value. Since we're adding this to the scoped hash table (like any other
786 // def), it will have been popped if we encounter a future merge block.
Sanjay Patelf1e1fba2017-03-15 20:25:05 +0000787 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
788 auto *BI = dyn_cast<BranchInst>(Pred->getTerminator());
789 if (BI && BI->isConditional()) {
790 auto *CondInst = dyn_cast<Instruction>(BI->getCondition());
Max Kazantsev0bad5be2018-05-31 08:08:34 +0000791 if (CondInst && SimpleValue::canHandle(CondInst))
792 Changed |= handleBranchCondition(CondInst, BI, BB, Pred);
Sanjay Patelf1e1fba2017-03-15 20:25:05 +0000793 }
794 }
Philip Reames7c78ef72015-05-22 23:53:24 +0000795
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000796 /// LastStore - Keep track of the last non-volatile store that we saw... for
797 /// as long as there in no instruction that reads memory. If we see a store
798 /// to the same location, we delete the dead store. This zaps trivial dead
799 /// stores which can occur in bitfield code among other things.
Chad Rosierf9327d62015-01-26 22:51:15 +0000800 Instruction *LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000801
Chris Lattner18ae5432011-01-02 23:04:14 +0000802 // See if any instructions in the block can be eliminated. If so, do it. If
803 // not, add them to AvailableValues.
Chandler Carruth7253bba2015-01-24 11:33:55 +0000804 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +0000805 Instruction *Inst = &*I++;
Nadav Rotem465834c2012-07-24 10:51:42 +0000806
Chris Lattner18ae5432011-01-02 23:04:14 +0000807 // Dead instructions should just be removed.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000808 if (isInstructionTriviallyDead(Inst, &TLI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000809 LLVM_DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000810 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000811 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000812 continue;
813 }
Davide Italianoe41e1d02018-12-17 01:42:39 +0000814 if (!salvageDebugInfo(*Inst))
815 replaceDbgUsesWithUndef(Inst);
Geoff Berry8d846052016-08-31 19:24:10 +0000816 removeMSSA(Inst);
Chris Lattner18ae5432011-01-02 23:04:14 +0000817 Inst->eraseFromParent();
818 Changed = true;
Chris Lattner8fac5db2011-01-02 23:19:45 +0000819 ++NumSimplify;
Chris Lattner18ae5432011-01-02 23:04:14 +0000820 continue;
821 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000822
Hal Finkel1e16fa32014-11-03 20:21:32 +0000823 // Skip assume intrinsics, they don't really have side effects (although
824 // they're marked as such to ensure preservation of control dependencies),
Max Kazantsev531db9a2017-04-28 06:25:39 +0000825 // and this pass will not bother with its removal. However, we should mark
826 // its condition as true for all dominated blocks.
Hal Finkel1e16fa32014-11-03 20:21:32 +0000827 if (match(Inst, m_Intrinsic<Intrinsic::assume>())) {
Max Kazantsev531db9a2017-04-28 06:25:39 +0000828 auto *CondI =
829 dyn_cast<Instruction>(cast<CallInst>(Inst)->getArgOperand(0));
830 if (CondI && SimpleValue::canHandle(CondI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000831 LLVM_DEBUG(dbgs() << "EarlyCSE considering assumption: " << *Inst
832 << '\n');
Max Kazantsev531db9a2017-04-28 06:25:39 +0000833 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
834 } else
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000835 LLVM_DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n');
Hal Finkel1e16fa32014-11-03 20:21:32 +0000836 continue;
837 }
838
Dan Gohman2c74fe92017-11-08 21:59:51 +0000839 // Skip sideeffect intrinsics, for the same reason as assume intrinsics.
840 if (match(Inst, m_Intrinsic<Intrinsic::sideeffect>())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000841 LLVM_DEBUG(dbgs() << "EarlyCSE skipping sideeffect: " << *Inst << '\n');
Dan Gohman2c74fe92017-11-08 21:59:51 +0000842 continue;
843 }
844
Philip Reames0adbb192018-03-14 21:35:06 +0000845 // We can skip all invariant.start intrinsics since they only read memory,
846 // and we can forward values across it. For invariant starts without
847 // invariant ends, we can use the fact that the invariantness never ends to
848 // start a scope in the current generaton which is true for all future
849 // generations. Also, we dont need to consume the last store since the
850 // semantics of invariant.start allow us to perform DSE of the last
Fangrui Songf78650a2018-07-30 19:41:25 +0000851 // store, if there was a store following invariant.start. Consider:
Anna Thomasb2d12b82016-08-09 20:00:47 +0000852 //
853 // store 30, i8* p
854 // invariant.start(p)
855 // store 40, i8* p
856 // We can DSE the store to 30, since the store 40 to invariant location p
857 // causes undefined behaviour.
Philip Reames0adbb192018-03-14 21:35:06 +0000858 if (match(Inst, m_Intrinsic<Intrinsic::invariant_start>())) {
Fangrui Songf78650a2018-07-30 19:41:25 +0000859 // If there are any uses, the scope might end.
Philip Reames0adbb192018-03-14 21:35:06 +0000860 if (!Inst->use_empty())
861 continue;
862 auto *CI = cast<CallInst>(Inst);
863 MemoryLocation MemLoc = MemoryLocation::getForArgument(CI, 1, TLI);
Philip Reames422024a2018-03-15 18:12:27 +0000864 // Don't start a scope if we already have a better one pushed
865 if (!AvailableInvariants.count(MemLoc))
866 AvailableInvariants.insert(MemLoc, CurrentGeneration);
Anna Thomasb2d12b82016-08-09 20:00:47 +0000867 continue;
Philip Reames0adbb192018-03-14 21:35:06 +0000868 }
Anna Thomasb2d12b82016-08-09 20:00:47 +0000869
Max Kazantsev3c284bd2018-08-30 03:39:16 +0000870 if (isGuard(Inst)) {
Sanjoy Das107aefc2016-04-29 22:23:16 +0000871 if (auto *CondI =
872 dyn_cast<Instruction>(cast<CallInst>(Inst)->getArgOperand(0))) {
Max Kazantsev0589d9f2017-04-28 06:05:48 +0000873 if (SimpleValue::canHandle(CondI)) {
874 // Do we already know the actual value of this condition?
875 if (auto *KnownCond = AvailableValues.lookup(CondI)) {
876 // Is the condition known to be true?
877 if (isa<ConstantInt>(KnownCond) &&
Craig Topper79ab6432017-07-06 18:39:47 +0000878 cast<ConstantInt>(KnownCond)->isOne()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000879 LLVM_DEBUG(dbgs()
880 << "EarlyCSE removing guard: " << *Inst << '\n');
Max Kazantsev0589d9f2017-04-28 06:05:48 +0000881 removeMSSA(Inst);
882 Inst->eraseFromParent();
883 Changed = true;
884 continue;
885 } else
886 // Use the known value if it wasn't true.
887 cast<CallInst>(Inst)->setArgOperand(0, KnownCond);
888 }
889 // The condition we're on guarding here is true for all dominated
890 // locations.
Sanjoy Dasee81b232016-04-29 21:52:58 +0000891 AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
Max Kazantsev0589d9f2017-04-28 06:05:48 +0000892 }
Sanjoy Dasee81b232016-04-29 21:52:58 +0000893 }
894
895 // Guard intrinsics read all memory, but don't write any memory.
896 // Accordingly, don't update the generation but consume the last store (to
897 // avoid an incorrect DSE).
898 LastStore = nullptr;
899 continue;
900 }
901
Chris Lattner18ae5432011-01-02 23:04:14 +0000902 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
903 // its simpler value.
Daniel Berlin4d0fe642017-04-28 19:55:38 +0000904 if (Value *V = SimplifyInstruction(Inst, SQ)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000905 LLVM_DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V
906 << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000907 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000908 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000909 } else {
910 bool Killed = false;
911 if (!Inst->use_empty()) {
912 Inst->replaceAllUsesWith(V);
913 Changed = true;
914 }
915 if (isInstructionTriviallyDead(Inst, &TLI)) {
916 removeMSSA(Inst);
917 Inst->eraseFromParent();
918 Changed = true;
919 Killed = true;
920 }
921 if (Changed)
922 ++NumSimplify;
923 if (Killed)
924 continue;
David Majnemerb8da3a22016-06-25 00:04:10 +0000925 }
Chris Lattner18ae5432011-01-02 23:04:14 +0000926 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000927
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000928 // If this is a simple instruction that we can value number, process it.
929 if (SimpleValue::canHandle(Inst)) {
930 // See if the instruction has an available value. If so, use it.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000931 if (Value *V = AvailableValues.lookup(Inst)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000932 LLVM_DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V
933 << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000934 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000935 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000936 continue;
937 }
David Majnemer9554c132016-04-22 06:37:45 +0000938 if (auto *I = dyn_cast<Instruction>(V))
939 I->andIRFlags(Inst);
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000940 Inst->replaceAllUsesWith(V);
Geoff Berry8d846052016-08-31 19:24:10 +0000941 removeMSSA(Inst);
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000942 Inst->eraseFromParent();
943 Changed = true;
944 ++NumCSE;
945 continue;
946 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000947
Chris Lattnerb9a8efc2011-01-03 03:18:43 +0000948 // Otherwise, just remember that this value is available.
Chandler Carruthd649c0a2015-01-27 01:34:14 +0000949 AvailableValues.insert(Inst, Inst);
Chris Lattner18ae5432011-01-02 23:04:14 +0000950 continue;
951 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000952
Chad Rosierf9327d62015-01-26 22:51:15 +0000953 ParseMemoryInst MemInst(Inst, TTI);
Chris Lattner92bb0f92011-01-03 03:41:27 +0000954 // If this is a non-volatile load, process it.
Chad Rosierf9327d62015-01-26 22:51:15 +0000955 if (MemInst.isValid() && MemInst.isLoad()) {
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000956 // (conservatively) we can't peak past the ordering implied by this
957 // operation, but we can add this load to our set of available values
958 if (MemInst.isVolatile() || !MemInst.isUnordered()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000959 LastStore = nullptr;
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000960 ++CurrentGeneration;
Chris Lattner9e5e9ed2011-01-03 04:17:24 +0000961 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000962
Philip Reamesca587fe2018-03-15 17:29:32 +0000963 if (MemInst.isInvariantLoad()) {
964 // If we pass an invariant load, we know that memory location is
965 // indefinitely constant from the moment of first dereferenceability.
Philip Reames422024a2018-03-15 18:12:27 +0000966 // We conservatively treat the invariant_load as that moment. If we
967 // pass a invariant load after already establishing a scope, don't
968 // restart it since we want to preserve the earliest point seen.
Philip Reamesca587fe2018-03-15 17:29:32 +0000969 auto MemLoc = MemoryLocation::get(Inst);
Philip Reames422024a2018-03-15 18:12:27 +0000970 if (!AvailableInvariants.count(MemLoc))
971 AvailableInvariants.insert(MemLoc, CurrentGeneration);
Philip Reamesca587fe2018-03-15 17:29:32 +0000972 }
973
Chris Lattner92bb0f92011-01-03 03:41:27 +0000974 // If we have an available version of this load, and if it is the right
Sanjoy Das07c65212016-06-16 20:47:57 +0000975 // generation or the load is known to be from an invariant location,
976 // replace this instruction.
977 //
Geoff Berry64f5ed12016-08-31 17:45:31 +0000978 // If either the dominating load or the current load are invariant, then
979 // we can assume the current load loads the same value as the dominating
980 // load.
Philip Reames9e5e2d62015-12-07 22:41:23 +0000981 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
Sanjoy Das07c65212016-06-16 20:47:57 +0000982 if (InVal.DefInst != nullptr &&
Philip Reames8fc2cbf2015-12-08 21:45:41 +0000983 InVal.MatchingId == MemInst.getMatchingId() &&
984 // We don't yet handle removing loads with ordering of any kind.
985 !MemInst.isVolatile() && MemInst.isUnordered() &&
986 // We can't replace an atomic load with one which isn't also atomic.
Geoff Berry8d846052016-08-31 19:24:10 +0000987 InVal.IsAtomic >= MemInst.isAtomic() &&
Philip Reamesca587fe2018-03-15 17:29:32 +0000988 (isOperatingOnInvariantMemAt(Inst, InVal.Generation) ||
Geoff Berry8d846052016-08-31 19:24:10 +0000989 isSameMemGeneration(InVal.Generation, CurrentGeneration,
990 InVal.DefInst, Inst))) {
Philip Reames32b55182016-05-06 01:13:58 +0000991 Value *Op = getOrCreateResult(InVal.DefInst, Inst->getType());
Chad Rosierf9327d62015-01-26 22:51:15 +0000992 if (Op != nullptr) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000993 LLVM_DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst
994 << " to: " << *InVal.DefInst << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000995 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000996 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +0000997 continue;
998 }
Chad Rosierf9327d62015-01-26 22:51:15 +0000999 if (!Inst->use_empty())
1000 Inst->replaceAllUsesWith(Op);
Geoff Berry8d846052016-08-31 19:24:10 +00001001 removeMSSA(Inst);
Chad Rosierf9327d62015-01-26 22:51:15 +00001002 Inst->eraseFromParent();
1003 Changed = true;
1004 ++NumCSELoad;
1005 continue;
1006 }
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001007 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001008
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001009 // Otherwise, remember that we have this instruction.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +00001010 AvailableLoads.insert(
Philip Reames9e5e2d62015-12-07 22:41:23 +00001011 MemInst.getPointerOperand(),
Philip Reames8fc2cbf2015-12-08 21:45:41 +00001012 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
Philip Reamesca587fe2018-03-15 17:29:32 +00001013 MemInst.isAtomic()));
Craig Topperf40110f2014-04-25 05:29:35 +00001014 LastStore = nullptr;
Chris Lattner92bb0f92011-01-03 03:41:27 +00001015 continue;
1016 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001017
Sanjoy Das6de072a2017-01-17 20:15:47 +00001018 // If this instruction may read from memory or throw (and potentially read
1019 // from memory in the exception handler), forget LastStore. Load/store
1020 // intrinsics will indicate both a read and a write to memory. The target
1021 // may override this (e.g. so that a store intrinsic does not read from
1022 // memory, and thus will be treated the same as a regular store for
1023 // commoning purposes).
1024 if ((Inst->mayReadFromMemory() || Inst->mayThrow()) &&
Chad Rosierf9327d62015-01-26 22:51:15 +00001025 !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
Craig Topperf40110f2014-04-25 05:29:35 +00001026 LastStore = nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +00001027
Chris Lattner92bb0f92011-01-03 03:41:27 +00001028 // If this is a read-only call, process it.
1029 if (CallValue::canHandle(Inst)) {
1030 // If we have an available version of this call, and if it is the right
1031 // generation, replace this instruction.
Geoff Berry2f64c202016-05-13 17:54:58 +00001032 std::pair<Instruction *, unsigned> InVal = AvailableCalls.lookup(Inst);
Geoff Berry8d846052016-08-31 19:24:10 +00001033 if (InVal.first != nullptr &&
1034 isSameMemGeneration(InVal.second, CurrentGeneration, InVal.first,
1035 Inst)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001036 LLVM_DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst
1037 << " to: " << *InVal.first << '\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 }
Chandler Carruth7253bba2015-01-24 11:33:55 +00001042 if (!Inst->use_empty())
1043 Inst->replaceAllUsesWith(InVal.first);
Geoff Berry8d846052016-08-31 19:24:10 +00001044 removeMSSA(Inst);
Chris Lattner92bb0f92011-01-03 03:41:27 +00001045 Inst->eraseFromParent();
1046 Changed = true;
1047 ++NumCSECall;
1048 continue;
1049 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001050
Chris Lattner92bb0f92011-01-03 03:41:27 +00001051 // Otherwise, remember that we have this instruction.
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001052 AvailableCalls.insert(
Geoff Berry2f64c202016-05-13 17:54:58 +00001053 Inst, std::pair<Instruction *, unsigned>(Inst, CurrentGeneration));
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001054 continue;
1055 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001056
Philip Reamesdfd890d2015-08-27 01:32:33 +00001057 // A release fence requires that all stores complete before it, but does
1058 // not prevent the reordering of following loads 'before' the fence. As a
1059 // result, we don't need to consider it as writing to memory and don't need
1060 // to advance the generation. We do need to prevent DSE across the fence,
1061 // but that's handled above.
1062 if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
JF Bastien800f87a2016-04-06 21:19:33 +00001063 if (FI->getOrdering() == AtomicOrdering::Release) {
Philip Reamesdfd890d2015-08-27 01:32:33 +00001064 assert(Inst->mayReadFromMemory() && "relied on to prevent DSE above");
1065 continue;
1066 }
1067
Philip Reamesae1f265b2015-12-16 01:01:30 +00001068 // write back DSE - If we write back the same value we just loaded from
1069 // the same location and haven't passed any intervening writes or ordering
1070 // operations, we can remove the write. The primary benefit is in allowing
1071 // the available load table to remain valid and value forward past where
1072 // the store originally was.
1073 if (MemInst.isValid() && MemInst.isStore()) {
1074 LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
Philip Reames32b55182016-05-06 01:13:58 +00001075 if (InVal.DefInst &&
1076 InVal.DefInst == getOrCreateResult(Inst, InVal.DefInst->getType()) &&
Philip Reamesae1f265b2015-12-16 01:01:30 +00001077 InVal.MatchingId == MemInst.getMatchingId() &&
1078 // We don't yet handle removing stores with ordering of any kind.
Geoff Berry8d846052016-08-31 19:24:10 +00001079 !MemInst.isVolatile() && MemInst.isUnordered() &&
Philip Reames0adbb192018-03-14 21:35:06 +00001080 (isOperatingOnInvariantMemAt(Inst, InVal.Generation) ||
1081 isSameMemGeneration(InVal.Generation, CurrentGeneration,
1082 InVal.DefInst, Inst))) {
Geoff Berry8d846052016-08-31 19:24:10 +00001083 // It is okay to have a LastStore to a different pointer here if MemorySSA
1084 // tells us that the load and store are from the same memory generation.
1085 // In that case, LastStore should keep its present value since we're
1086 // removing the current store.
Philip Reamesae1f265b2015-12-16 01:01:30 +00001087 assert((!LastStore ||
1088 ParseMemoryInst(LastStore, TTI).getPointerOperand() ==
Geoff Berry8d846052016-08-31 19:24:10 +00001089 MemInst.getPointerOperand() ||
1090 MSSA) &&
1091 "can't have an intervening store if not using MemorySSA!");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001092 LLVM_DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << *Inst << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001093 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001094 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001095 continue;
1096 }
Geoff Berry8d846052016-08-31 19:24:10 +00001097 removeMSSA(Inst);
Philip Reamesae1f265b2015-12-16 01:01:30 +00001098 Inst->eraseFromParent();
1099 Changed = true;
1100 ++NumDSE;
1101 // We can avoid incrementing the generation count since we were able
1102 // to eliminate this store.
1103 continue;
1104 }
1105 }
1106
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001107 // Okay, this isn't something we can CSE at all. Check to see if it is
1108 // something that could modify memory. If so, our available memory values
1109 // cannot be used so bump the generation count.
Chris Lattnere0e32a92011-01-03 03:46:34 +00001110 if (Inst->mayWriteToMemory()) {
Chris Lattnerb9a8efc2011-01-03 03:18:43 +00001111 ++CurrentGeneration;
Nadav Rotem465834c2012-07-24 10:51:42 +00001112
Chad Rosierf9327d62015-01-26 22:51:15 +00001113 if (MemInst.isValid() && MemInst.isStore()) {
Chris Lattner9e5e9ed2011-01-03 04:17:24 +00001114 // We do a trivial form of DSE if there are two stores to the same
Philip Reames15145fb2015-12-17 18:50:50 +00001115 // location with no intervening loads. Delete the earlier store.
1116 // At the moment, we don't remove ordered stores, but do remove
1117 // unordered atomic stores. There's no special requirement (for
1118 // unordered atomics) about removing atomic stores only in favor of
1119 // other atomic stores since we we're going to execute the non-atomic
1120 // one anyway and the atomic one might never have become visible.
Chad Rosierf9327d62015-01-26 22:51:15 +00001121 if (LastStore) {
1122 ParseMemoryInst LastStoreMemInst(LastStore, TTI);
Philip Reames15145fb2015-12-17 18:50:50 +00001123 assert(LastStoreMemInst.isUnordered() &&
1124 !LastStoreMemInst.isVolatile() &&
1125 "Violated invariant");
Chad Rosierf9327d62015-01-26 22:51:15 +00001126 if (LastStoreMemInst.isMatchingMemLoc(MemInst)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001127 LLVM_DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
1128 << " due to: " << *Inst << '\n');
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001129 if (!DebugCounter::shouldExecute(CSECounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001130 LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
Geoff Berry5bf4a5e2018-04-06 18:47:33 +00001131 } else {
1132 removeMSSA(LastStore);
1133 LastStore->eraseFromParent();
1134 Changed = true;
1135 ++NumDSE;
1136 LastStore = nullptr;
1137 }
Chad Rosierf9327d62015-01-26 22:51:15 +00001138 }
Philip Reames018dbf12014-11-18 17:46:32 +00001139 // fallthrough - we can exploit information about this store
Chris Lattner9e5e9ed2011-01-03 04:17:24 +00001140 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001141
Chris Lattner9e5e9ed2011-01-03 04:17:24 +00001142 // Okay, we just invalidated anything we knew about loaded values. Try
1143 // to salvage *something* by remembering that the stored value is a live
1144 // version of the pointer. It is safe to forward from volatile stores
1145 // to non-volatile loads, so we don't have to check for volatility of
1146 // the store.
Arnaud A. de Grandmaisona6178a12015-10-07 07:41:29 +00001147 AvailableLoads.insert(
Philip Reames9e5e2d62015-12-07 22:41:23 +00001148 MemInst.getPointerOperand(),
Philip Reames8fc2cbf2015-12-08 21:45:41 +00001149 LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId(),
Philip Reamesca587fe2018-03-15 17:29:32 +00001150 MemInst.isAtomic()));
Nadav Rotem465834c2012-07-24 10:51:42 +00001151
Philip Reames15145fb2015-12-17 18:50:50 +00001152 // Remember that this was the last unordered store we saw for DSE. We
1153 // don't yet handle DSE on ordered or volatile stores since we don't
1154 // have a good way to model the ordering requirement for following
1155 // passes once the store is removed. We could insert a fence, but
1156 // since fences are slightly stronger than stores in their ordering,
1157 // it's not clear this is a profitable transform. Another option would
1158 // be to merge the ordering with that of the post dominating store.
1159 if (MemInst.isUnordered() && !MemInst.isVolatile())
Chad Rosierf9327d62015-01-26 22:51:15 +00001160 LastStore = Inst;
Philip Reames8fc2cbf2015-12-08 21:45:41 +00001161 else
1162 LastStore = nullptr;
Chris Lattnere0e32a92011-01-03 03:46:34 +00001163 }
1164 }
Chris Lattner18ae5432011-01-02 23:04:14 +00001165 }
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001166
Chris Lattner18ae5432011-01-02 23:04:14 +00001167 return Changed;
Chris Lattner704541b2011-01-02 21:47:05 +00001168}
Chris Lattner18ae5432011-01-02 23:04:14 +00001169
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001170bool EarlyCSE::run() {
Chandler Carruth7253bba2015-01-24 11:33:55 +00001171 // Note, deque is being used here because there is significant performance
1172 // gains over vector when the container becomes very large due to the
1173 // specific access patterns. For more information see the mailing list
1174 // discussion on this:
Tanya Lattner0d28f802015-08-05 03:51:17 +00001175 // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
Lenny Maiorani9eefc812014-09-20 13:29:20 +00001176 std::deque<StackNode *> nodesToProcess;
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001177
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001178 bool Changed = false;
1179
1180 // Process the root node.
Chandler Carruth7253bba2015-01-24 11:33:55 +00001181 nodesToProcess.push_back(new StackNode(
Philip Reames0adbb192018-03-14 21:35:06 +00001182 AvailableValues, AvailableLoads, AvailableInvariants, AvailableCalls,
1183 CurrentGeneration, DT.getRootNode(),
1184 DT.getRootNode()->begin(), DT.getRootNode()->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001185
1186 // Save the current generation.
1187 unsigned LiveOutGeneration = CurrentGeneration;
1188
1189 // Process the stack.
1190 while (!nodesToProcess.empty()) {
1191 // Grab the first item off the stack. Set the current generation, remove
1192 // the node from the stack, and process it.
Michael Gottesman2bf01732013-12-05 18:42:12 +00001193 StackNode *NodeToProcess = nodesToProcess.back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001194
1195 // Initialize class members.
1196 CurrentGeneration = NodeToProcess->currentGeneration();
1197
1198 // Check if the node needs to be processed.
1199 if (!NodeToProcess->isProcessed()) {
1200 // Process the node.
1201 Changed |= processNode(NodeToProcess->node());
1202 NodeToProcess->childGeneration(CurrentGeneration);
1203 NodeToProcess->process();
1204 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
1205 // Push the next child onto the stack.
1206 DomTreeNode *child = NodeToProcess->nextChild();
Michael Gottesman2bf01732013-12-05 18:42:12 +00001207 nodesToProcess.push_back(
Philip Reames0adbb192018-03-14 21:35:06 +00001208 new StackNode(AvailableValues, AvailableLoads, AvailableInvariants,
1209 AvailableCalls, NodeToProcess->childGeneration(),
1210 child, child->begin(), child->end()));
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001211 } else {
1212 // It has been processed, and there are no more children to process,
1213 // so delete it and pop it off the stack.
1214 delete NodeToProcess;
Michael Gottesman2bf01732013-12-05 18:42:12 +00001215 nodesToProcess.pop_back();
Lenny Maiorani8d670b82012-01-31 23:14:41 +00001216 }
1217 } // while (!nodes...)
1218
1219 // Reset the current generation.
1220 CurrentGeneration = LiveOutGeneration;
1221
1222 return Changed;
Chris Lattner18ae5432011-01-02 23:04:14 +00001223}
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001224
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001225PreservedAnalyses EarlyCSEPass::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +00001226 FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +00001227 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1228 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
1229 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001230 auto &AC = AM.getResult<AssumptionAnalysis>(F);
Geoff Berry8d846052016-08-31 19:24:10 +00001231 auto *MSSA =
1232 UseMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA() : nullptr;
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001233
Daniel Berlin4d0fe642017-04-28 19:55:38 +00001234 EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001235
1236 if (!CSE.run())
1237 return PreservedAnalyses::all();
1238
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001239 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +00001240 PA.preserveSet<CFGAnalyses>();
Davide Italiano02861d82016-06-08 21:31:55 +00001241 PA.preserve<GlobalsAA>();
Geoff Berry8d846052016-08-31 19:24:10 +00001242 if (UseMemorySSA)
1243 PA.preserve<MemorySSAAnalysis>();
Chandler Carruthe8c686a2015-02-01 10:51:23 +00001244 return PA;
1245}
1246
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001247namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +00001248
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001249/// A simple and fast domtree-based CSE pass.
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001250///
1251/// This pass does a simple depth-first walk over the dominator tree,
1252/// eliminating trivially redundant instructions and using instsimplify to
1253/// canonicalize things as it goes. It is intended to be fast and catch obvious
1254/// cases so that instcombine and other passes are more effective. It is
1255/// expected that a later pass of GVN will catch the interesting/hard cases.
Geoff Berry8d846052016-08-31 19:24:10 +00001256template<bool UseMemorySSA>
1257class EarlyCSELegacyCommonPass : public FunctionPass {
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001258public:
1259 static char ID;
1260
Geoff Berry8d846052016-08-31 19:24:10 +00001261 EarlyCSELegacyCommonPass() : FunctionPass(ID) {
1262 if (UseMemorySSA)
1263 initializeEarlyCSEMemSSALegacyPassPass(*PassRegistry::getPassRegistry());
1264 else
1265 initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry());
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001266 }
1267
1268 bool runOnFunction(Function &F) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001269 if (skipFunction(F))
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001270 return false;
1271
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001272 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +00001273 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001274 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001275 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Geoff Berry8d846052016-08-31 19:24:10 +00001276 auto *MSSA =
1277 UseMemorySSA ? &getAnalysis<MemorySSAWrapperPass>().getMSSA() : nullptr;
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001278
Daniel Berlin4d0fe642017-04-28 19:55:38 +00001279 EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001280
1281 return CSE.run();
1282 }
1283
1284 void getAnalysisUsage(AnalysisUsage &AU) const override {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001285 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001286 AU.addRequired<DominatorTreeWrapperPass>();
1287 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +00001288 AU.addRequired<TargetTransformInfoWrapperPass>();
Geoff Berry8d846052016-08-31 19:24:10 +00001289 if (UseMemorySSA) {
1290 AU.addRequired<MemorySSAWrapperPass>();
1291 AU.addPreserved<MemorySSAWrapperPass>();
1292 }
James Molloyefbba722015-09-10 10:22:12 +00001293 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001294 AU.setPreservesCFG();
1295 }
1296};
Eugene Zelenko3b879392017-10-13 21:17:07 +00001297
1298} // end anonymous namespace
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001299
Geoff Berry8d846052016-08-31 19:24:10 +00001300using EarlyCSELegacyPass = EarlyCSELegacyCommonPass</*UseMemorySSA=*/false>;
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001301
Geoff Berry8d846052016-08-31 19:24:10 +00001302template<>
1303char EarlyCSELegacyPass::ID = 0;
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001304
1305INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
1306 false)
Chandler Carruth705b1852015-01-31 03:43:40 +00001307INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001308INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthd649c0a2015-01-27 01:34:14 +00001309INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1310INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1311INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)
Geoff Berry8d846052016-08-31 19:24:10 +00001312
1313using EarlyCSEMemSSALegacyPass =
1314 EarlyCSELegacyCommonPass</*UseMemorySSA=*/true>;
1315
1316template<>
1317char EarlyCSEMemSSALegacyPass::ID = 0;
1318
1319FunctionPass *llvm::createEarlyCSEPass(bool UseMemorySSA) {
1320 if (UseMemorySSA)
1321 return new EarlyCSEMemSSALegacyPass();
1322 else
1323 return new EarlyCSELegacyPass();
1324}
1325
1326INITIALIZE_PASS_BEGIN(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1327 "Early CSE w/ MemorySSA", false, false)
1328INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001329INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Geoff Berry8d846052016-08-31 19:24:10 +00001330INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1331INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1332INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
1333INITIALIZE_PASS_END(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1334 "Early CSE w/ MemorySSA", false, false)