blob: 4edb91d34c4e4a66eb8d6bd55f8f98cad0d0d577 [file] [log] [blame]
Owen Andersone3590582007-08-02 18:11:11 +00001//===- DeadStoreElimination.cpp - Fast Dead Store Elimination -------------===//
Owen Anderson5e72db32007-07-11 00:46:18 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Owen Anderson5e72db32007-07-11 00:46:18 +00007//
8//===----------------------------------------------------------------------===//
9//
Chad Rosierd7634fc2015-12-11 18:39:41 +000010// This file implements a trivial dead store elimination that only considers
11// basic-block local redundant stores.
12//
13// FIXME: This should eventually be extended to be a post-dominator tree
14// traversal. Doing so would be pretty trivial.
Owen Anderson5e72db32007-07-11 00:46:18 +000015//
16//===----------------------------------------------------------------------===//
17
Justin Bogner594e07b2016-05-17 21:38:13 +000018#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SetVector.h"
21#include "llvm/ADT/Statistic.h"
Owen Andersonaa071722007-07-11 23:19:17 +000022#include "llvm/Analysis/AliasAnalysis.h"
Nick Lewycky32f80512011-10-22 21:59:35 +000023#include "llvm/Analysis/CaptureTracking.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000024#include "llvm/Analysis/GlobalsModRef.h"
Victor Hernandezf390e042009-10-27 20:05:49 +000025#include "llvm/Analysis/MemoryBuiltins.h"
Owen Anderson5e72db32007-07-11 00:46:18 +000026#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000027#include "llvm/Analysis/TargetLibraryInfo.h"
Chris Lattnerc0f33792010-11-30 23:05:20 +000028#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Constants.h"
30#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000031#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Function.h"
33#include "llvm/IR/GlobalVariable.h"
34#include "llvm/IR/Instructions.h"
35#include "llvm/IR/IntrinsicInst.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Pass.h"
37#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000038#include "llvm/Support/raw_ostream.h"
Justin Bogner594e07b2016-05-17 21:38:13 +000039#include "llvm/Transforms/Scalar.h"
Owen Anderson5e72db32007-07-11 00:46:18 +000040#include "llvm/Transforms/Utils/Local.h"
Owen Anderson5e72db32007-07-11 00:46:18 +000041using namespace llvm;
42
Chandler Carruth964daaa2014-04-22 02:55:47 +000043#define DEBUG_TYPE "dse"
44
Erik Eckstein11fc8172015-08-13 15:36:11 +000045STATISTIC(NumRedundantStores, "Number of redundant stores deleted");
Owen Anderson5e72db32007-07-11 00:46:18 +000046STATISTIC(NumFastStores, "Number of stores deleted");
47STATISTIC(NumFastOther , "Number of other instrs removed");
48
Owen Anderson5e72db32007-07-11 00:46:18 +000049
Chris Lattner67122512010-11-30 21:58:14 +000050//===----------------------------------------------------------------------===//
51// Helper functions
52//===----------------------------------------------------------------------===//
53
Chad Rosiera8bc5122016-06-10 17:58:01 +000054/// Delete this instruction. Before we do, go through and zero out all the
Justin Bogner594e07b2016-05-17 21:38:13 +000055/// operands of this instruction. If any of them become dead, delete them and
56/// the computation tree that feeds them.
Eric Christopher0efe9f62015-08-19 02:15:13 +000057/// If ValueSet is non-null, remove any deleted instructions from it as well.
Justin Bogner594e07b2016-05-17 21:38:13 +000058static void
59deleteDeadInstruction(Instruction *I, MemoryDependenceResults &MD,
60 const TargetLibraryInfo &TLI,
61 SmallSetVector<Value *, 16> *ValueSet = nullptr) {
Eric Christopher0efe9f62015-08-19 02:15:13 +000062 SmallVector<Instruction*, 32> NowDeadInsts;
63
64 NowDeadInsts.push_back(I);
65 --NumFastOther;
66
67 // Before we touch this instruction, remove it from memdep!
68 do {
69 Instruction *DeadInst = NowDeadInsts.pop_back_val();
70 ++NumFastOther;
71
72 // This instruction is dead, zap it, in stages. Start by removing it from
73 // MemDep, which needs to know the operands and needs it to be in the
74 // function.
75 MD.removeInstruction(DeadInst);
76
77 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
78 Value *Op = DeadInst->getOperand(op);
79 DeadInst->setOperand(op, nullptr);
80
81 // If this operand just became dead, add it to the NowDeadInsts list.
82 if (!Op->use_empty()) continue;
83
84 if (Instruction *OpI = dyn_cast<Instruction>(Op))
85 if (isInstructionTriviallyDead(OpI, &TLI))
86 NowDeadInsts.push_back(OpI);
87 }
88
89 DeadInst->eraseFromParent();
90
91 if (ValueSet) ValueSet->remove(DeadInst);
92 } while (!NowDeadInsts.empty());
93}
94
Justin Bogner594e07b2016-05-17 21:38:13 +000095/// Does this instruction write some memory? This only returns true for things
96/// that we can analyze with other helpers below.
Chandler Carruthdbe40fb2015-08-12 18:01:44 +000097static bool hasMemoryWrite(Instruction *I, const TargetLibraryInfo &TLI) {
Nick Lewycky90271472009-11-10 06:46:40 +000098 if (isa<StoreInst>(I))
99 return true;
100 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
101 switch (II->getIntrinsicID()) {
Chris Lattner2764b4d2009-12-02 06:35:55 +0000102 default:
103 return false;
104 case Intrinsic::memset:
105 case Intrinsic::memmove:
106 case Intrinsic::memcpy:
107 case Intrinsic::init_trampoline:
108 case Intrinsic::lifetime_end:
109 return true;
Nick Lewycky90271472009-11-10 06:46:40 +0000110 }
111 }
Benjamin Kramer3a09ef62015-04-10 14:50:08 +0000112 if (auto CS = CallSite(I)) {
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000113 if (Function *F = CS.getCalledFunction()) {
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000114 if (TLI.has(LibFunc::strcpy) &&
115 F->getName() == TLI.getName(LibFunc::strcpy)) {
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000116 return true;
117 }
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000118 if (TLI.has(LibFunc::strncpy) &&
119 F->getName() == TLI.getName(LibFunc::strncpy)) {
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000120 return true;
121 }
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000122 if (TLI.has(LibFunc::strcat) &&
123 F->getName() == TLI.getName(LibFunc::strcat)) {
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000124 return true;
125 }
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000126 if (TLI.has(LibFunc::strncat) &&
127 F->getName() == TLI.getName(LibFunc::strncat)) {
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000128 return true;
129 }
130 }
131 }
Nick Lewycky90271472009-11-10 06:46:40 +0000132 return false;
133}
134
Justin Bogner594e07b2016-05-17 21:38:13 +0000135/// Return a Location stored to by the specified instruction. If isRemovable
136/// returns true, this function and getLocForRead completely describe the memory
137/// operations for this instruction.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000138static MemoryLocation getLocForWrite(Instruction *Inst, AliasAnalysis &AA) {
Chris Lattner58b779e2010-11-30 07:23:21 +0000139 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
Chandler Carruth70c61c12015-06-04 02:03:15 +0000140 return MemoryLocation::get(SI);
Owen Anderson58704ee2011-09-06 18:14:09 +0000141
Chris Lattner58b779e2010-11-30 07:23:21 +0000142 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(Inst)) {
143 // memcpy/memmove/memset.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000144 MemoryLocation Loc = MemoryLocation::getForDest(MI);
Chris Lattner58b779e2010-11-30 07:23:21 +0000145 return Loc;
146 }
Owen Anderson58704ee2011-09-06 18:14:09 +0000147
Chris Lattner58b779e2010-11-30 07:23:21 +0000148 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
Chandler Carruthac80dc72015-06-17 07:18:54 +0000149 if (!II)
150 return MemoryLocation();
Owen Anderson58704ee2011-09-06 18:14:09 +0000151
Chris Lattner58b779e2010-11-30 07:23:21 +0000152 switch (II->getIntrinsicID()) {
Chandler Carruthac80dc72015-06-17 07:18:54 +0000153 default:
154 return MemoryLocation(); // Unhandled intrinsic.
Chris Lattner58b779e2010-11-30 07:23:21 +0000155 case Intrinsic::init_trampoline:
Chris Lattner58b779e2010-11-30 07:23:21 +0000156 // FIXME: We don't know the size of the trampoline, so we can't really
157 // handle it here.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000158 return MemoryLocation(II->getArgOperand(0));
Chris Lattner58b779e2010-11-30 07:23:21 +0000159 case Intrinsic::lifetime_end: {
160 uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
Chandler Carruthac80dc72015-06-17 07:18:54 +0000161 return MemoryLocation(II->getArgOperand(1), Len);
Chris Lattner58b779e2010-11-30 07:23:21 +0000162 }
163 }
164}
165
Justin Bogner594e07b2016-05-17 21:38:13 +0000166/// Return the location read by the specified "hasMemoryWrite" instruction if
167/// any.
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000168static MemoryLocation getLocForRead(Instruction *Inst,
169 const TargetLibraryInfo &TLI) {
170 assert(hasMemoryWrite(Inst, TLI) && "Unknown instruction case");
Owen Anderson58704ee2011-09-06 18:14:09 +0000171
Chris Lattner94fbdf32010-12-06 01:48:06 +0000172 // The only instructions that both read and write are the mem transfer
173 // instructions (memcpy/memmove).
174 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(Inst))
Chandler Carruth70c61c12015-06-04 02:03:15 +0000175 return MemoryLocation::getForSource(MTI);
Chandler Carruthac80dc72015-06-17 07:18:54 +0000176 return MemoryLocation();
Chris Lattner94fbdf32010-12-06 01:48:06 +0000177}
178
Justin Bogner594e07b2016-05-17 21:38:13 +0000179/// If the value of this instruction and the memory it writes to is unused, may
180/// we delete this instruction?
Chris Lattner3590ef82010-11-30 05:30:45 +0000181static bool isRemovable(Instruction *I) {
Eli Friedman9a468152011-08-17 22:22:24 +0000182 // Don't remove volatile/atomic stores.
Nick Lewycky90271472009-11-10 06:46:40 +0000183 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Eli Friedman9a468152011-08-17 22:22:24 +0000184 return SI->isUnordered();
Owen Anderson58704ee2011-09-06 18:14:09 +0000185
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000186 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
187 switch (II->getIntrinsicID()) {
188 default: llvm_unreachable("doesn't pass 'hasMemoryWrite' predicate");
189 case Intrinsic::lifetime_end:
190 // Never remove dead lifetime_end's, e.g. because it is followed by a
191 // free.
192 return false;
193 case Intrinsic::init_trampoline:
194 // Always safe to remove init_trampoline.
195 return true;
Owen Anderson58704ee2011-09-06 18:14:09 +0000196
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000197 case Intrinsic::memset:
198 case Intrinsic::memmove:
199 case Intrinsic::memcpy:
200 // Don't remove volatile memory intrinsics.
201 return !cast<MemIntrinsic>(II)->isVolatile();
202 }
Chris Lattnerb63ba732010-11-30 19:12:10 +0000203 }
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000204
Benjamin Kramer3a09ef62015-04-10 14:50:08 +0000205 if (auto CS = CallSite(I))
Nick Lewycky42bca052012-09-25 01:55:59 +0000206 return CS.getInstruction()->use_empty();
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000207
208 return false;
Nick Lewycky90271472009-11-10 06:46:40 +0000209}
210
Pete Cooper856977c2011-11-09 23:07:35 +0000211
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000212/// Returns true if the end of this instruction can be safely shortened in
Pete Cooper856977c2011-11-09 23:07:35 +0000213/// length.
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000214static bool isShortenableAtTheEnd(Instruction *I) {
Pete Cooper856977c2011-11-09 23:07:35 +0000215 // Don't shorten stores for now
216 if (isa<StoreInst>(I))
217 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000218
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000219 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
220 switch (II->getIntrinsicID()) {
221 default: return false;
222 case Intrinsic::memset:
223 case Intrinsic::memcpy:
224 // Do shorten memory intrinsics.
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000225 // FIXME: Add memmove if it's also safe to transform.
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000226 return true;
227 }
Pete Cooper856977c2011-11-09 23:07:35 +0000228 }
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000229
230 // Don't shorten libcalls calls for now.
231
232 return false;
Pete Cooper856977c2011-11-09 23:07:35 +0000233}
234
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000235/// Returns true if the beginning of this instruction can be safely shortened
236/// in length.
237static bool isShortenableAtTheBeginning(Instruction *I) {
238 // FIXME: Handle only memset for now. Supporting memcpy/memmove should be
239 // easily done by offsetting the source address.
240 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
241 return II && II->getIntrinsicID() == Intrinsic::memset;
242}
243
Justin Bogner594e07b2016-05-17 21:38:13 +0000244/// Return the pointer that is being written to.
Chris Lattner67122512010-11-30 21:58:14 +0000245static Value *getStoredPointerOperand(Instruction *I) {
Nick Lewycky90271472009-11-10 06:46:40 +0000246 if (StoreInst *SI = dyn_cast<StoreInst>(I))
247 return SI->getPointerOperand();
248 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
Chris Lattner67122512010-11-30 21:58:14 +0000249 return MI->getDest();
Gabor Greif91f95892010-06-24 12:03:56 +0000250
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000251 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
252 switch (II->getIntrinsicID()) {
253 default: llvm_unreachable("Unexpected intrinsic!");
254 case Intrinsic::init_trampoline:
255 return II->getArgOperand(0);
256 }
Duncan Sands1925d3a2009-11-10 13:49:50 +0000257 }
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000258
Benjamin Kramer3a09ef62015-04-10 14:50:08 +0000259 CallSite CS(I);
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000260 // All the supported functions so far happen to have dest as their first
261 // argument.
262 return CS.getArgument(0);
Nick Lewycky90271472009-11-10 06:46:40 +0000263}
264
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000265static uint64_t getPointerSize(const Value *V, const DataLayout &DL,
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000266 const TargetLibraryInfo &TLI) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000267 uint64_t Size;
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000268 if (getObjectSize(V, Size, DL, &TLI))
Nuno Lopes55fff832012-06-21 15:45:28 +0000269 return Size;
Chandler Carruthecbd1682015-06-17 07:21:38 +0000270 return MemoryLocation::UnknownSize;
Chris Lattner903add82010-11-30 23:43:23 +0000271}
Chris Lattner51c28a92010-11-30 19:34:42 +0000272
Pete Cooper856977c2011-11-09 23:07:35 +0000273namespace {
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000274enum OverwriteResult {
275 OverwriteBegin,
276 OverwriteComplete,
277 OverwriteEnd,
278 OverwriteUnknown
279};
Pete Cooper856977c2011-11-09 23:07:35 +0000280}
281
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000282/// Return 'OverwriteComplete' if a store to the 'Later' location completely
283/// overwrites a store to the 'Earlier' location, 'OverwriteEnd' if the end of
284/// the 'Earlier' location is completely overwritten by 'Later',
285/// 'OverwriteBegin' if the beginning of the 'Earlier' location is overwritten
286/// by 'Later', or 'OverwriteUnknown' if nothing can be determined.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000287static OverwriteResult isOverwrite(const MemoryLocation &Later,
288 const MemoryLocation &Earlier,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000289 const DataLayout &DL,
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000290 const TargetLibraryInfo &TLI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000291 int64_t &EarlierOff, int64_t &LaterOff) {
Chad Rosier72a793c2016-06-15 22:17:38 +0000292 // If we don't know the sizes of either access, then we can't do a comparison.
293 if (Later.Size == MemoryLocation::UnknownSize ||
294 Earlier.Size == MemoryLocation::UnknownSize)
295 return OverwriteUnknown;
296
Chris Lattnerc0f33792010-11-30 23:05:20 +0000297 const Value *P1 = Earlier.Ptr->stripPointerCasts();
298 const Value *P2 = Later.Ptr->stripPointerCasts();
Owen Anderson58704ee2011-09-06 18:14:09 +0000299
Chris Lattnerc0f33792010-11-30 23:05:20 +0000300 // If the start pointers are the same, we just have to compare sizes to see if
301 // the later store was larger than the earlier store.
302 if (P1 == P2) {
Chris Lattnerc0f33792010-11-30 23:05:20 +0000303 // Make sure that the Later size is >= the Earlier size.
Pete Cooper856977c2011-11-09 23:07:35 +0000304 if (Later.Size >= Earlier.Size)
305 return OverwriteComplete;
Chris Lattner77d79fa2010-11-30 19:28:23 +0000306 }
Owen Anderson58704ee2011-09-06 18:14:09 +0000307
Chris Lattner903add82010-11-30 23:43:23 +0000308 // Check to see if the later store is to the entire object (either a global,
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000309 // an alloca, or a byval/inalloca argument). If so, then it clearly
310 // overwrites any other store to the same object.
Rafael Espindola5f57f462014-02-21 18:34:28 +0000311 const Value *UO1 = GetUnderlyingObject(P1, DL),
312 *UO2 = GetUnderlyingObject(P2, DL);
Owen Anderson58704ee2011-09-06 18:14:09 +0000313
Chris Lattner903add82010-11-30 23:43:23 +0000314 // If we can't resolve the same pointers to the same object, then we can't
315 // analyze them at all.
316 if (UO1 != UO2)
Pete Cooper856977c2011-11-09 23:07:35 +0000317 return OverwriteUnknown;
Owen Anderson58704ee2011-09-06 18:14:09 +0000318
Chris Lattner903add82010-11-30 23:43:23 +0000319 // If the "Later" store is to a recognizable object, get its size.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000320 uint64_t ObjectSize = getPointerSize(UO2, DL, TLI);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000321 if (ObjectSize != MemoryLocation::UnknownSize)
Pete Coopera4237c32011-11-10 20:22:08 +0000322 if (ObjectSize == Later.Size && ObjectSize >= Earlier.Size)
Pete Cooper856977c2011-11-09 23:07:35 +0000323 return OverwriteComplete;
Owen Anderson58704ee2011-09-06 18:14:09 +0000324
Chris Lattnerc0f33792010-11-30 23:05:20 +0000325 // Okay, we have stores to two completely different pointers. Try to
326 // decompose the pointer into a "base + constant_offset" form. If the base
327 // pointers are equal, then we can reason about the two stores.
Pete Cooper856977c2011-11-09 23:07:35 +0000328 EarlierOff = 0;
329 LaterOff = 0;
Rafael Espindola5f57f462014-02-21 18:34:28 +0000330 const Value *BP1 = GetPointerBaseWithConstantOffset(P1, EarlierOff, DL);
331 const Value *BP2 = GetPointerBaseWithConstantOffset(P2, LaterOff, DL);
Owen Anderson58704ee2011-09-06 18:14:09 +0000332
Chris Lattnerc0f33792010-11-30 23:05:20 +0000333 // If the base pointers still differ, we have two completely different stores.
334 if (BP1 != BP2)
Pete Cooper856977c2011-11-09 23:07:35 +0000335 return OverwriteUnknown;
Bill Wendlingdb40b5c2011-03-26 01:20:37 +0000336
Bill Wendling19f33b92011-03-26 08:02:59 +0000337 // The later store completely overlaps the earlier store if:
Owen Anderson58704ee2011-09-06 18:14:09 +0000338 //
Bill Wendling19f33b92011-03-26 08:02:59 +0000339 // 1. Both start at the same offset and the later one's size is greater than
340 // or equal to the earlier one's, or
341 //
342 // |--earlier--|
343 // |-- later --|
Owen Anderson58704ee2011-09-06 18:14:09 +0000344 //
Bill Wendling19f33b92011-03-26 08:02:59 +0000345 // 2. The earlier store has an offset greater than the later offset, but which
346 // still lies completely within the later store.
347 //
348 // |--earlier--|
349 // |----- later ------|
Bill Wendling50341592011-03-30 21:37:19 +0000350 //
351 // We have to be careful here as *Off is signed while *.Size is unsigned.
Bill Wendlingb5139922011-03-26 09:32:07 +0000352 if (EarlierOff >= LaterOff &&
Craig Topper2a404182012-08-14 07:32:05 +0000353 Later.Size >= Earlier.Size &&
Bill Wendling50341592011-03-30 21:37:19 +0000354 uint64_t(EarlierOff - LaterOff) + Earlier.Size <= Later.Size)
Pete Cooper856977c2011-11-09 23:07:35 +0000355 return OverwriteComplete;
Nadav Rotem465834c2012-07-24 10:51:42 +0000356
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000357 // Another interesting case is if the later store overwrites the end of the
358 // earlier store.
Pete Cooper856977c2011-11-09 23:07:35 +0000359 //
360 // |--earlier--|
361 // |-- later --|
362 //
363 // In this case we may want to trim the size of earlier to avoid generating
364 // writes to addresses which will definitely be overwritten later
365 if (LaterOff > EarlierOff &&
366 LaterOff < int64_t(EarlierOff + Earlier.Size) &&
Pete Coopere03fe832011-12-03 00:04:30 +0000367 int64_t(LaterOff + Later.Size) >= int64_t(EarlierOff + Earlier.Size))
Pete Cooper856977c2011-11-09 23:07:35 +0000368 return OverwriteEnd;
Bill Wendling19f33b92011-03-26 08:02:59 +0000369
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000370 // Finally, we also need to check if the later store overwrites the beginning
371 // of the earlier store.
372 //
373 // |--earlier--|
374 // |-- later --|
375 //
376 // In this case we may want to move the destination address and trim the size
377 // of earlier to avoid generating writes to addresses which will definitely
378 // be overwritten later.
379 if (LaterOff <= EarlierOff && int64_t(LaterOff + Later.Size) > EarlierOff) {
380 assert (int64_t(LaterOff + Later.Size) < int64_t(EarlierOff + Earlier.Size)
381 && "Expect to be handled as OverwriteComplete" );
382 return OverwriteBegin;
383 }
Bill Wendling19f33b92011-03-26 08:02:59 +0000384 // Otherwise, they don't completely overlap.
Pete Cooper856977c2011-11-09 23:07:35 +0000385 return OverwriteUnknown;
Nick Lewycky90271472009-11-10 06:46:40 +0000386}
387
Justin Bogner594e07b2016-05-17 21:38:13 +0000388/// If 'Inst' might be a self read (i.e. a noop copy of a
Chris Lattner94fbdf32010-12-06 01:48:06 +0000389/// memory region into an identical pointer) then it doesn't actually make its
Owen Anderson58704ee2011-09-06 18:14:09 +0000390/// input dead in the traditional sense. Consider this case:
Chris Lattner94fbdf32010-12-06 01:48:06 +0000391///
392/// memcpy(A <- B)
393/// memcpy(A <- A)
394///
395/// In this case, the second store to A does not make the first store to A dead.
396/// The usual situation isn't an explicit A<-A store like this (which can be
397/// trivially removed) but a case where two pointers may alias.
398///
399/// This function detects when it is unsafe to remove a dependent instruction
400/// because the DSE inducing instruction may be a self-read.
401static bool isPossibleSelfRead(Instruction *Inst,
Chandler Carruthac80dc72015-06-17 07:18:54 +0000402 const MemoryLocation &InstStoreLoc,
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000403 Instruction *DepWrite,
404 const TargetLibraryInfo &TLI,
405 AliasAnalysis &AA) {
Chris Lattner94fbdf32010-12-06 01:48:06 +0000406 // Self reads can only happen for instructions that read memory. Get the
407 // location read.
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000408 MemoryLocation InstReadLoc = getLocForRead(Inst, TLI);
Craig Topperf40110f2014-04-25 05:29:35 +0000409 if (!InstReadLoc.Ptr) return false; // Not a reading instruction.
Owen Anderson58704ee2011-09-06 18:14:09 +0000410
Chris Lattner94fbdf32010-12-06 01:48:06 +0000411 // If the read and written loc obviously don't alias, it isn't a read.
412 if (AA.isNoAlias(InstReadLoc, InstStoreLoc)) return false;
Owen Anderson58704ee2011-09-06 18:14:09 +0000413
Chris Lattner94fbdf32010-12-06 01:48:06 +0000414 // Okay, 'Inst' may copy over itself. However, we can still remove a the
415 // DepWrite instruction if we can prove that it reads from the same location
416 // as Inst. This handles useful cases like:
417 // memcpy(A <- B)
418 // memcpy(A <- B)
419 // Here we don't know if A/B may alias, but we do know that B/B are must
420 // aliases, so removing the first memcpy is safe (assuming it writes <= #
421 // bytes as the second one.
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000422 MemoryLocation DepReadLoc = getLocForRead(DepWrite, TLI);
Owen Anderson58704ee2011-09-06 18:14:09 +0000423
Chris Lattner94fbdf32010-12-06 01:48:06 +0000424 if (DepReadLoc.Ptr && AA.isMustAlias(InstReadLoc.Ptr, DepReadLoc.Ptr))
425 return false;
Owen Anderson58704ee2011-09-06 18:14:09 +0000426
Chris Lattner94fbdf32010-12-06 01:48:06 +0000427 // If DepWrite doesn't read memory or if we can't prove it is a must alias,
428 // then it can't be considered dead.
429 return true;
430}
431
Chris Lattner67122512010-11-30 21:58:14 +0000432
Justin Bogner594e07b2016-05-17 21:38:13 +0000433/// Returns true if the memory which is accessed by the second instruction is not
434/// modified between the first and the second instruction.
435/// Precondition: Second instruction must be dominated by the first
436/// instruction.
437static bool memoryIsNotModifiedBetween(Instruction *FirstI,
438 Instruction *SecondI,
439 AliasAnalysis *AA) {
440 SmallVector<BasicBlock *, 16> WorkList;
441 SmallPtrSet<BasicBlock *, 8> Visited;
442 BasicBlock::iterator FirstBBI(FirstI);
443 ++FirstBBI;
444 BasicBlock::iterator SecondBBI(SecondI);
445 BasicBlock *FirstBB = FirstI->getParent();
446 BasicBlock *SecondBB = SecondI->getParent();
447 MemoryLocation MemLoc = MemoryLocation::get(SecondI);
Chris Lattner67122512010-11-30 21:58:14 +0000448
Justin Bogner594e07b2016-05-17 21:38:13 +0000449 // Start checking the store-block.
450 WorkList.push_back(SecondBB);
451 bool isFirstBlock = true;
452
453 // Check all blocks going backward until we reach the load-block.
454 while (!WorkList.empty()) {
455 BasicBlock *B = WorkList.pop_back_val();
456
457 // Ignore instructions before LI if this is the FirstBB.
458 BasicBlock::iterator BI = (B == FirstBB ? FirstBBI : B->begin());
459
460 BasicBlock::iterator EI;
461 if (isFirstBlock) {
462 // Ignore instructions after SI if this is the first visit of SecondBB.
463 assert(B == SecondBB && "first block is not the store block");
464 EI = SecondBBI;
465 isFirstBlock = false;
466 } else {
467 // It's not SecondBB or (in case of a loop) the second visit of SecondBB.
468 // In this case we also have to look at instructions after SI.
469 EI = B->end();
470 }
471 for (; BI != EI; ++BI) {
472 Instruction *I = &*BI;
473 if (I->mayWriteToMemory() && I != SecondI) {
474 auto Res = AA->getModRefInfo(I, MemLoc);
475 if (Res != MRI_NoModRef)
476 return false;
477 }
478 }
479 if (B != FirstBB) {
480 assert(B != &FirstBB->getParent()->getEntryBlock() &&
481 "Should not hit the entry block because SI must be dominated by LI");
482 for (auto PredI = pred_begin(B), PE = pred_end(B); PredI != PE; ++PredI) {
483 if (!Visited.insert(*PredI).second)
484 continue;
485 WorkList.push_back(*PredI);
486 }
487 }
488 }
489 return true;
490}
491
492/// Find all blocks that will unconditionally lead to the block BB and append
493/// them to F.
494static void findUnconditionalPreds(SmallVectorImpl<BasicBlock *> &Blocks,
495 BasicBlock *BB, DominatorTree *DT) {
496 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
497 BasicBlock *Pred = *I;
498 if (Pred == BB) continue;
499 TerminatorInst *PredTI = Pred->getTerminator();
500 if (PredTI->getNumSuccessors() != 1)
501 continue;
502
503 if (DT->isReachableFromEntry(Pred))
504 Blocks.push_back(Pred);
505 }
506}
507
508/// Handle frees of entire structures whose dependency is a store
509/// to a field of that structure.
510static bool handleFree(CallInst *F, AliasAnalysis *AA,
511 MemoryDependenceResults *MD, DominatorTree *DT,
512 const TargetLibraryInfo *TLI) {
513 bool MadeChange = false;
514
515 MemoryLocation Loc = MemoryLocation(F->getOperand(0));
516 SmallVector<BasicBlock *, 16> Blocks;
517 Blocks.push_back(F->getParent());
518 const DataLayout &DL = F->getModule()->getDataLayout();
519
520 while (!Blocks.empty()) {
521 BasicBlock *BB = Blocks.pop_back_val();
522 Instruction *InstPt = BB->getTerminator();
523 if (BB == F->getParent()) InstPt = F;
524
525 MemDepResult Dep =
526 MD->getPointerDependencyFrom(Loc, false, InstPt->getIterator(), BB);
527 while (Dep.isDef() || Dep.isClobber()) {
528 Instruction *Dependency = Dep.getInst();
529 if (!hasMemoryWrite(Dependency, *TLI) || !isRemovable(Dependency))
530 break;
531
532 Value *DepPointer =
533 GetUnderlyingObject(getStoredPointerOperand(Dependency), DL);
534
535 // Check for aliasing.
536 if (!AA->isMustAlias(F->getArgOperand(0), DepPointer))
537 break;
538
539 auto Next = ++Dependency->getIterator();
540
Chad Rosier840b3ef2016-06-10 17:59:22 +0000541 // DCE instructions only used to calculate that store.
Justin Bogner594e07b2016-05-17 21:38:13 +0000542 deleteDeadInstruction(Dependency, *MD, *TLI);
543 ++NumFastStores;
544 MadeChange = true;
545
546 // Inst's old Dependency is now deleted. Compute the next dependency,
547 // which may also be dead, as in
548 // s[0] = 0;
549 // s[1] = 0; // This has just been deleted.
550 // free(s);
551 Dep = MD->getPointerDependencyFrom(Loc, false, Next, BB);
552 }
553
554 if (Dep.isNonLocal())
555 findUnconditionalPreds(Blocks, BB, DT);
556 }
557
558 return MadeChange;
559}
560
561/// Check to see if the specified location may alias any of the stack objects in
562/// the DeadStackObjects set. If so, they become live because the location is
563/// being loaded.
564static void removeAccessedObjects(const MemoryLocation &LoadedLoc,
565 SmallSetVector<Value *, 16> &DeadStackObjects,
566 const DataLayout &DL, AliasAnalysis *AA,
567 const TargetLibraryInfo *TLI) {
568 const Value *UnderlyingPointer = GetUnderlyingObject(LoadedLoc.Ptr, DL);
569
570 // A constant can't be in the dead pointer set.
571 if (isa<Constant>(UnderlyingPointer))
572 return;
573
574 // If the kill pointer can be easily reduced to an alloca, don't bother doing
575 // extraneous AA queries.
576 if (isa<AllocaInst>(UnderlyingPointer) || isa<Argument>(UnderlyingPointer)) {
577 DeadStackObjects.remove(const_cast<Value*>(UnderlyingPointer));
578 return;
579 }
580
581 // Remove objects that could alias LoadedLoc.
582 DeadStackObjects.remove_if([&](Value *I) {
583 // See if the loaded location could alias the stack location.
584 MemoryLocation StackLoc(I, getPointerSize(I, DL, *TLI));
585 return !AA->isNoAlias(StackLoc, LoadedLoc);
586 });
587}
588
589/// Remove dead stores to stack-allocated locations in the function end block.
590/// Ex:
591/// %A = alloca i32
592/// ...
593/// store i32 1, i32* %A
594/// ret void
595static bool handleEndBlock(BasicBlock &BB, AliasAnalysis *AA,
596 MemoryDependenceResults *MD,
597 const TargetLibraryInfo *TLI) {
598 bool MadeChange = false;
599
600 // Keep track of all of the stack objects that are dead at the end of the
601 // function.
602 SmallSetVector<Value*, 16> DeadStackObjects;
603
604 // Find all of the alloca'd pointers in the entry block.
605 BasicBlock &Entry = BB.getParent()->front();
606 for (Instruction &I : Entry) {
607 if (isa<AllocaInst>(&I))
608 DeadStackObjects.insert(&I);
609
610 // Okay, so these are dead heap objects, but if the pointer never escapes
611 // then it's leaked by this function anyways.
612 else if (isAllocLikeFn(&I, TLI) && !PointerMayBeCaptured(&I, true, true))
613 DeadStackObjects.insert(&I);
614 }
615
616 // Treat byval or inalloca arguments the same, stores to them are dead at the
617 // end of the function.
618 for (Argument &AI : BB.getParent()->args())
619 if (AI.hasByValOrInAllocaAttr())
620 DeadStackObjects.insert(&AI);
621
622 const DataLayout &DL = BB.getModule()->getDataLayout();
623
624 // Scan the basic block backwards
625 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
626 --BBI;
627
628 // If we find a store, check to see if it points into a dead stack value.
629 if (hasMemoryWrite(&*BBI, *TLI) && isRemovable(&*BBI)) {
630 // See through pointer-to-pointer bitcasts
631 SmallVector<Value *, 4> Pointers;
632 GetUnderlyingObjects(getStoredPointerOperand(&*BBI), Pointers, DL);
633
634 // Stores to stack values are valid candidates for removal.
635 bool AllDead = true;
636 for (SmallVectorImpl<Value *>::iterator I = Pointers.begin(),
637 E = Pointers.end(); I != E; ++I)
638 if (!DeadStackObjects.count(*I)) {
639 AllDead = false;
640 break;
641 }
642
643 if (AllDead) {
644 Instruction *Dead = &*BBI++;
645
646 DEBUG(dbgs() << "DSE: Dead Store at End of Block:\n DEAD: "
647 << *Dead << "\n Objects: ";
648 for (SmallVectorImpl<Value *>::iterator I = Pointers.begin(),
649 E = Pointers.end(); I != E; ++I) {
650 dbgs() << **I;
651 if (std::next(I) != E)
652 dbgs() << ", ";
653 }
654 dbgs() << '\n');
655
656 // DCE instructions only used to calculate that store.
657 deleteDeadInstruction(Dead, *MD, *TLI, &DeadStackObjects);
658 ++NumFastStores;
659 MadeChange = true;
660 continue;
661 }
662 }
663
664 // Remove any dead non-memory-mutating instructions.
665 if (isInstructionTriviallyDead(&*BBI, TLI)) {
666 Instruction *Inst = &*BBI++;
667 deleteDeadInstruction(Inst, *MD, *TLI, &DeadStackObjects);
668 ++NumFastOther;
669 MadeChange = true;
670 continue;
671 }
672
673 if (isa<AllocaInst>(BBI)) {
674 // Remove allocas from the list of dead stack objects; there can't be
675 // any references before the definition.
676 DeadStackObjects.remove(&*BBI);
677 continue;
678 }
679
680 if (auto CS = CallSite(&*BBI)) {
681 // Remove allocation function calls from the list of dead stack objects;
682 // there can't be any references before the definition.
683 if (isAllocLikeFn(&*BBI, TLI))
684 DeadStackObjects.remove(&*BBI);
685
686 // If this call does not access memory, it can't be loading any of our
687 // pointers.
688 if (AA->doesNotAccessMemory(CS))
689 continue;
690
691 // If the call might load from any of our allocas, then any store above
692 // the call is live.
693 DeadStackObjects.remove_if([&](Value *I) {
694 // See if the call site touches the value.
695 ModRefInfo A = AA->getModRefInfo(CS, I, getPointerSize(I, DL, *TLI));
696
697 return A == MRI_ModRef || A == MRI_Ref;
698 });
699
700 // If all of the allocas were clobbered by the call then we're not going
701 // to find anything else to process.
702 if (DeadStackObjects.empty())
703 break;
704
705 continue;
706 }
707
708 MemoryLocation LoadedLoc;
709
710 // If we encounter a use of the pointer, it is no longer considered dead
711 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
712 if (!L->isUnordered()) // Be conservative with atomic/volatile load
713 break;
714 LoadedLoc = MemoryLocation::get(L);
715 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
716 LoadedLoc = MemoryLocation::get(V);
717 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(BBI)) {
718 LoadedLoc = MemoryLocation::getForSource(MTI);
719 } else if (!BBI->mayReadFromMemory()) {
720 // Instruction doesn't read memory. Note that stores that weren't removed
721 // above will hit this case.
722 continue;
723 } else {
724 // Unknown inst; assume it clobbers everything.
725 break;
726 }
727
728 // Remove any allocas from the DeadPointer set that are loaded, as this
729 // makes any stores above the access live.
730 removeAccessedObjects(LoadedLoc, DeadStackObjects, DL, AA, TLI);
731
732 // If all of the allocas were clobbered by the access then we're not going
733 // to find anything else to process.
734 if (DeadStackObjects.empty())
735 break;
736 }
737
738 return MadeChange;
739}
740
741static bool eliminateDeadStores(BasicBlock &BB, AliasAnalysis *AA,
742 MemoryDependenceResults *MD, DominatorTree *DT,
743 const TargetLibraryInfo *TLI) {
Igor Laevsky029bd932015-09-23 11:38:44 +0000744 const DataLayout &DL = BB.getModule()->getDataLayout();
Owen Anderson5e72db32007-07-11 00:46:18 +0000745 bool MadeChange = false;
Owen Anderson58704ee2011-09-06 18:14:09 +0000746
Chris Lattner49162672009-09-02 06:31:02 +0000747 // Do a top-down walk on the BB.
Chris Lattnerf2a8ba42008-11-28 21:29:52 +0000748 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +0000749 Instruction *Inst = &*BBI++;
Owen Anderson58704ee2011-09-06 18:14:09 +0000750
Chris Lattner9d179d92010-11-30 01:28:33 +0000751 // Handle 'free' calls specially.
Nick Lewycky135ac9a2012-09-24 22:07:09 +0000752 if (CallInst *F = isFreeCall(Inst, TLI)) {
Justin Bogner594e07b2016-05-17 21:38:13 +0000753 MadeChange |= handleFree(F, AA, MD, DT, TLI);
Chris Lattner9d179d92010-11-30 01:28:33 +0000754 continue;
755 }
Owen Anderson58704ee2011-09-06 18:14:09 +0000756
Chris Lattner2227a8a2010-11-30 01:37:52 +0000757 // If we find something that writes memory, get its memory dependence.
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000758 if (!hasMemoryWrite(Inst, *TLI))
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000759 continue;
Chris Lattnerd4f10902010-11-30 00:01:19 +0000760
Rui Ueyamac487f772014-08-06 19:30:38 +0000761 // If we're storing the same value back to a pointer that we just
762 // loaded from, then the store can be removed.
Nick Lewycky90271472009-11-10 06:46:40 +0000763 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Igor Laevsky029bd932015-09-23 11:38:44 +0000764
765 auto RemoveDeadInstAndUpdateBBI = [&](Instruction *DeadInst) {
Justin Bogner594e07b2016-05-17 21:38:13 +0000766 // deleteDeadInstruction can delete the current instruction. Save BBI
Igor Laevsky029bd932015-09-23 11:38:44 +0000767 // in case we need it.
Duncan P. N. Exon Smith3a9c9e32015-10-13 18:26:00 +0000768 WeakVH NextInst(&*BBI);
Igor Laevsky029bd932015-09-23 11:38:44 +0000769
Justin Bogner594e07b2016-05-17 21:38:13 +0000770 deleteDeadInstruction(DeadInst, *MD, *TLI);
Igor Laevsky029bd932015-09-23 11:38:44 +0000771
772 if (!NextInst) // Next instruction deleted.
773 BBI = BB.begin();
774 else if (BBI != BB.begin()) // Revisit this instruction if possible.
775 --BBI;
776 ++NumRedundantStores;
777 MadeChange = true;
778 };
779
Erik Eckstein11fc8172015-08-13 15:36:11 +0000780 if (LoadInst *DepLoad = dyn_cast<LoadInst>(SI->getValueOperand())) {
Nick Lewycky90271472009-11-10 06:46:40 +0000781 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
Erik Eckstein11fc8172015-08-13 15:36:11 +0000782 isRemovable(SI) &&
Justin Bogner594e07b2016-05-17 21:38:13 +0000783 memoryIsNotModifiedBetween(DepLoad, SI, AA)) {
Erik Eckstein11fc8172015-08-13 15:36:11 +0000784
Chris Lattnerca335e32010-12-06 21:13:51 +0000785 DEBUG(dbgs() << "DSE: Remove Store Of Load from same pointer:\n "
786 << "LOAD: " << *DepLoad << "\n STORE: " << *SI << '\n');
Philip Reames00c9b642014-08-05 17:48:20 +0000787
Igor Laevsky029bd932015-09-23 11:38:44 +0000788 RemoveDeadInstAndUpdateBBI(SI);
789 continue;
790 }
791 }
Philip Reames00c9b642014-08-05 17:48:20 +0000792
Igor Laevsky029bd932015-09-23 11:38:44 +0000793 // Remove null stores into the calloc'ed objects
794 Constant *StoredConstant = dyn_cast<Constant>(SI->getValueOperand());
Rui Ueyamac487f772014-08-06 19:30:38 +0000795
Igor Laevsky029bd932015-09-23 11:38:44 +0000796 if (StoredConstant && StoredConstant->isNullValue() &&
797 isRemovable(SI)) {
798 Instruction *UnderlyingPointer = dyn_cast<Instruction>(
799 GetUnderlyingObject(SI->getPointerOperand(), DL));
800
801 if (UnderlyingPointer && isCallocLikeFn(UnderlyingPointer, TLI) &&
Justin Bogner594e07b2016-05-17 21:38:13 +0000802 memoryIsNotModifiedBetween(UnderlyingPointer, SI, AA)) {
Igor Laevsky029bd932015-09-23 11:38:44 +0000803 DEBUG(dbgs()
804 << "DSE: Remove null store to the calloc'ed object:\n DEAD: "
805 << *Inst << "\n OBJECT: " << *UnderlyingPointer << '\n');
806
807 RemoveDeadInstAndUpdateBBI(SI);
Rui Ueyamac487f772014-08-06 19:30:38 +0000808 continue;
809 }
Philip Reames00c9b642014-08-05 17:48:20 +0000810 }
Owen Anderson5e72db32007-07-11 00:46:18 +0000811 }
Owen Anderson58704ee2011-09-06 18:14:09 +0000812
Erik Eckstein11fc8172015-08-13 15:36:11 +0000813 MemDepResult InstDep = MD->getDependency(Inst);
814
Chad Rosierd7634fc2015-12-11 18:39:41 +0000815 // Ignore any store where we can't find a local dependence.
816 // FIXME: cross-block DSE would be fun. :)
817 if (!InstDep.isDef() && !InstDep.isClobber())
818 continue;
Erik Eckstein11fc8172015-08-13 15:36:11 +0000819
Chad Rosierd7634fc2015-12-11 18:39:41 +0000820 // Figure out what location is being stored to.
821 MemoryLocation Loc = getLocForWrite(Inst, *AA);
Chris Lattner58b779e2010-11-30 07:23:21 +0000822
Chad Rosierd7634fc2015-12-11 18:39:41 +0000823 // If we didn't get a useful location, fail.
824 if (!Loc.Ptr)
825 continue;
826
827 while (InstDep.isDef() || InstDep.isClobber()) {
828 // Get the memory clobbered by the instruction we depend on. MemDep will
829 // skip any instructions that 'Loc' clearly doesn't interact with. If we
830 // end up depending on a may- or must-aliased load, then we can't optimize
Chad Rosier844e2df2016-06-15 21:41:22 +0000831 // away the store and we bail out. However, if we depend on something
Chad Rosierd7634fc2015-12-11 18:39:41 +0000832 // that overwrites the memory location we *can* potentially optimize it.
833 //
834 // Find out what memory location the dependent instruction stores.
835 Instruction *DepWrite = InstDep.getInst();
836 MemoryLocation DepLoc = getLocForWrite(DepWrite, *AA);
837 // If we didn't get a useful location, or if it isn't a size, bail out.
838 if (!DepLoc.Ptr)
839 break;
840
841 // If we find a write that is a) removable (i.e., non-volatile), b) is
842 // completely obliterated by the store to 'Loc', and c) which we know that
843 // 'Inst' doesn't load from, then we can remove it.
844 if (isRemovable(DepWrite) &&
845 !isPossibleSelfRead(Inst, Loc, DepWrite, *TLI, *AA)) {
846 int64_t InstWriteOffset, DepWriteOffset;
847 OverwriteResult OR =
848 isOverwrite(Loc, DepLoc, DL, *TLI, DepWriteOffset, InstWriteOffset);
849 if (OR == OverwriteComplete) {
850 DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: "
851 << *DepWrite << "\n KILLER: " << *Inst << '\n');
852
853 // Delete the store and now-dead instructions that feed it.
Justin Bogner594e07b2016-05-17 21:38:13 +0000854 deleteDeadInstruction(DepWrite, *MD, *TLI);
Chad Rosierd7634fc2015-12-11 18:39:41 +0000855 ++NumFastStores;
856 MadeChange = true;
857
Justin Bogner594e07b2016-05-17 21:38:13 +0000858 // deleteDeadInstruction can delete the current instruction in loop
Chad Rosierd7634fc2015-12-11 18:39:41 +0000859 // cases, reset BBI.
860 BBI = Inst->getIterator();
861 if (BBI != BB.begin())
862 --BBI;
Pete Cooper856977c2011-11-09 23:07:35 +0000863 break;
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000864 } else if ((OR == OverwriteEnd && isShortenableAtTheEnd(DepWrite)) ||
865 ((OR == OverwriteBegin &&
866 isShortenableAtTheBeginning(DepWrite)))) {
Chad Rosierd7634fc2015-12-11 18:39:41 +0000867 // TODO: base this on the target vector size so that if the earlier
868 // store was too small to get vector writes anyway then its likely
869 // a good idea to shorten it
870 // Power of 2 vector writes are probably always a bad idea to optimize
871 // as any store/memset/memcpy is likely using vector instructions so
872 // shortening it to not vector size is likely to be slower
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000873 MemIntrinsic *DepIntrinsic = cast<MemIntrinsic>(DepWrite);
Chad Rosierd7634fc2015-12-11 18:39:41 +0000874 unsigned DepWriteAlign = DepIntrinsic->getAlignment();
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000875 bool IsOverwriteEnd = (OR == OverwriteEnd);
876 if (!IsOverwriteEnd)
877 InstWriteOffset = int64_t(InstWriteOffset + Loc.Size);
878
879 if ((llvm::isPowerOf2_64(InstWriteOffset) &&
880 DepWriteAlign <= InstWriteOffset) ||
Chad Rosierd7634fc2015-12-11 18:39:41 +0000881 ((DepWriteAlign != 0) && InstWriteOffset % DepWriteAlign == 0)) {
Nadav Rotem465834c2012-07-24 10:51:42 +0000882
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000883 DEBUG(dbgs() << "DSE: Remove Dead Store:\n OW "
884 << (IsOverwriteEnd ? "END" : "BEGIN") << ": "
885 << *DepWrite << "\n KILLER (offset "
886 << InstWriteOffset << ", " << DepLoc.Size << ")"
887 << *Inst << '\n');
Nadav Rotem465834c2012-07-24 10:51:42 +0000888
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000889 int64_t NewLength =
890 IsOverwriteEnd
891 ? InstWriteOffset - DepWriteOffset
892 : DepLoc.Size - (InstWriteOffset - DepWriteOffset);
893
894 Value *DepWriteLength = DepIntrinsic->getLength();
895 Value *TrimmedLength =
896 ConstantInt::get(DepWriteLength->getType(), NewLength);
Chad Rosierd7634fc2015-12-11 18:39:41 +0000897 DepIntrinsic->setLength(TrimmedLength);
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000898
899 if (!IsOverwriteEnd) {
900 int64_t OffsetMoved = (InstWriteOffset - DepWriteOffset);
901 Value *Indices[1] = {
902 ConstantInt::get(DepWriteLength->getType(), OffsetMoved)};
903 GetElementPtrInst *NewDestGEP = GetElementPtrInst::CreateInBounds(
904 DepIntrinsic->getRawDest(), Indices, "", DepWrite);
905 DepIntrinsic->setDest(NewDestGEP);
906 }
Pete Cooper856977c2011-11-09 23:07:35 +0000907 MadeChange = true;
908 }
909 }
Chris Lattner58b779e2010-11-30 07:23:21 +0000910 }
Chad Rosierd7634fc2015-12-11 18:39:41 +0000911
912 // If this is a may-aliased store that is clobbering the store value, we
913 // can keep searching past it for another must-aliased pointer that stores
914 // to the same location. For example, in:
915 // store -> P
916 // store -> Q
917 // store -> P
918 // we can remove the first store to P even though we don't know if P and Q
919 // alias.
920 if (DepWrite == &BB.front()) break;
921
922 // Can't look past this instruction if it might read 'Loc'.
923 if (AA->getModRefInfo(DepWrite, Loc) & MRI_Ref)
924 break;
925
926 InstDep = MD->getPointerDependencyFrom(Loc, false,
927 DepWrite->getIterator(), &BB);
Owen Anderson2b2bd282009-10-28 07:05:35 +0000928 }
Owen Anderson5e72db32007-07-11 00:46:18 +0000929 }
Owen Anderson58704ee2011-09-06 18:14:09 +0000930
Chris Lattnerf2a8ba42008-11-28 21:29:52 +0000931 // If this block ends in a return, unwind, or unreachable, all allocas are
932 // dead at its end, which means stores to them are also dead.
Owen Anderson32c4a052007-07-12 21:41:30 +0000933 if (BB.getTerminator()->getNumSuccessors() == 0)
Justin Bogner594e07b2016-05-17 21:38:13 +0000934 MadeChange |= handleEndBlock(BB, AA, MD, TLI);
Owen Anderson58704ee2011-09-06 18:14:09 +0000935
Owen Anderson5e72db32007-07-11 00:46:18 +0000936 return MadeChange;
937}
938
Justin Bogner594e07b2016-05-17 21:38:13 +0000939static bool eliminateDeadStores(Function &F, AliasAnalysis *AA,
940 MemoryDependenceResults *MD, DominatorTree *DT,
941 const TargetLibraryInfo *TLI) {
Eli Friedman7d58bc72011-06-15 00:47:34 +0000942 bool MadeChange = false;
Justin Bogner594e07b2016-05-17 21:38:13 +0000943 for (BasicBlock &BB : F)
944 // Only check non-dead blocks. Dead blocks may have strange pointer
945 // cycles that will confuse alias analysis.
946 if (DT->isReachableFromEntry(&BB))
947 MadeChange |= eliminateDeadStores(BB, AA, MD, DT, TLI);
Eli Friedman7d58bc72011-06-15 00:47:34 +0000948 return MadeChange;
Owen Andersonaa071722007-07-11 23:19:17 +0000949}
950
Justin Bogner594e07b2016-05-17 21:38:13 +0000951//===----------------------------------------------------------------------===//
952// DSE Pass
953//===----------------------------------------------------------------------===//
954PreservedAnalyses DSEPass::run(Function &F, FunctionAnalysisManager &AM) {
955 AliasAnalysis *AA = &AM.getResult<AAManager>(F);
956 DominatorTree *DT = &AM.getResult<DominatorTreeAnalysis>(F);
957 MemoryDependenceResults *MD = &AM.getResult<MemoryDependenceAnalysis>(F);
958 const TargetLibraryInfo *TLI = &AM.getResult<TargetLibraryAnalysis>(F);
Owen Anderson58704ee2011-09-06 18:14:09 +0000959
Justin Bogner594e07b2016-05-17 21:38:13 +0000960 if (!eliminateDeadStores(F, AA, MD, DT, TLI))
961 return PreservedAnalyses::all();
962 PreservedAnalyses PA;
963 PA.preserve<DominatorTreeAnalysis>();
964 PA.preserve<GlobalsAA>();
965 PA.preserve<MemoryDependenceAnalysis>();
966 return PA;
Owen Anderson32c4a052007-07-12 21:41:30 +0000967}
968
Justin Bogner594e07b2016-05-17 21:38:13 +0000969/// A legacy pass for the legacy pass manager that wraps \c DSEPass.
970class DSELegacyPass : public FunctionPass {
971public:
972 DSELegacyPass() : FunctionPass(ID) {
973 initializeDSELegacyPassPass(*PassRegistry::getPassRegistry());
Owen Andersonddf4aee2007-08-08 18:38:28 +0000974 }
Owen Anderson58704ee2011-09-06 18:14:09 +0000975
Justin Bogner594e07b2016-05-17 21:38:13 +0000976 bool runOnFunction(Function &F) override {
977 if (skipFunction(F))
978 return false;
979
980 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
981 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
982 MemoryDependenceResults *MD =
983 &getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
984 const TargetLibraryInfo *TLI =
985 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
986
987 return eliminateDeadStores(F, AA, MD, DT, TLI);
988 }
989
990 void getAnalysisUsage(AnalysisUsage &AU) const override {
991 AU.setPreservesCFG();
992 AU.addRequired<DominatorTreeWrapperPass>();
993 AU.addRequired<AAResultsWrapperPass>();
994 AU.addRequired<MemoryDependenceWrapperPass>();
995 AU.addRequired<TargetLibraryInfoWrapperPass>();
996 AU.addPreserved<DominatorTreeWrapperPass>();
997 AU.addPreserved<GlobalsAAWrapperPass>();
998 AU.addPreserved<MemoryDependenceWrapperPass>();
999 }
1000
1001 static char ID; // Pass identification, replacement for typeid
1002};
1003
1004char DSELegacyPass::ID = 0;
1005INITIALIZE_PASS_BEGIN(DSELegacyPass, "dse", "Dead Store Elimination", false,
1006 false)
1007INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1008INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
1009INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
1010INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
1011INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1012INITIALIZE_PASS_END(DSELegacyPass, "dse", "Dead Store Elimination", false,
1013 false)
1014
1015FunctionPass *llvm::createDeadStoreEliminationPass() {
1016 return new DSELegacyPass();
Owen Anderson32c4a052007-07-12 21:41:30 +00001017}