blob: 53ceb89d4d04dcb92024f15d30ae5348c5896cb3 [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"
Eugene Zelenko3b879392017-10-13 21:17:07 +000019#include "llvm/ADT/APInt.h"
Hal Finkela1271032016-06-23 13:46:39 +000020#include "llvm/ADT/DenseMap.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/SetVector.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000022#include "llvm/ADT/SmallPtrSet.h"
23#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/ADT/Statistic.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000025#include "llvm/ADT/StringRef.h"
Owen Andersonaa071722007-07-11 23:19:17 +000026#include "llvm/Analysis/AliasAnalysis.h"
Nick Lewycky32f80512011-10-22 21:59:35 +000027#include "llvm/Analysis/CaptureTracking.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000028#include "llvm/Analysis/GlobalsModRef.h"
Victor Hernandezf390e042009-10-27 20:05:49 +000029#include "llvm/Analysis/MemoryBuiltins.h"
Owen Anderson5e72db32007-07-11 00:46:18 +000030#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000031#include "llvm/Analysis/MemoryLocation.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000032#include "llvm/Analysis/TargetLibraryInfo.h"
Chris Lattnerc0f33792010-11-30 23:05:20 +000033#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000034#include "llvm/IR/Argument.h"
35#include "llvm/IR/BasicBlock.h"
36#include "llvm/IR/CallSite.h"
37#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Constants.h"
39#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000040#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Function.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000042#include "llvm/IR/InstrTypes.h"
43#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000044#include "llvm/IR/Instructions.h"
45#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000046#include "llvm/IR/Intrinsics.h"
Sanjay Patel1d04b5b2017-09-26 13:54:28 +000047#include "llvm/IR/LLVMContext.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000048#include "llvm/IR/Module.h"
49#include "llvm/IR/PassManager.h"
50#include "llvm/IR/Value.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000051#include "llvm/Pass.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000052#include "llvm/Support/Casting.h"
Hal Finkela1271032016-06-23 13:46:39 +000053#include "llvm/Support/CommandLine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000054#include "llvm/Support/Debug.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000055#include "llvm/Support/ErrorHandling.h"
56#include "llvm/Support/MathExtras.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000057#include "llvm/Support/raw_ostream.h"
Justin Bogner594e07b2016-05-17 21:38:13 +000058#include "llvm/Transforms/Scalar.h"
Owen Anderson5e72db32007-07-11 00:46:18 +000059#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenko3b879392017-10-13 21:17:07 +000060#include <algorithm>
61#include <cassert>
62#include <cstdint>
63#include <cstddef>
64#include <iterator>
Hal Finkela1271032016-06-23 13:46:39 +000065#include <map>
Eugene Zelenko3b879392017-10-13 21:17:07 +000066#include <utility>
67
Owen Anderson5e72db32007-07-11 00:46:18 +000068using namespace llvm;
69
Chandler Carruth964daaa2014-04-22 02:55:47 +000070#define DEBUG_TYPE "dse"
71
Erik Eckstein11fc8172015-08-13 15:36:11 +000072STATISTIC(NumRedundantStores, "Number of redundant stores deleted");
Owen Anderson5e72db32007-07-11 00:46:18 +000073STATISTIC(NumFastStores, "Number of stores deleted");
74STATISTIC(NumFastOther , "Number of other instrs removed");
Hal Finkela1271032016-06-23 13:46:39 +000075STATISTIC(NumCompletePartials, "Number of stores dead by later partials");
Sanjay Patel1d04b5b2017-09-26 13:54:28 +000076STATISTIC(NumModifiedStores, "Number of stores modified");
Hal Finkela1271032016-06-23 13:46:39 +000077
78static cl::opt<bool>
79EnablePartialOverwriteTracking("enable-dse-partial-overwrite-tracking",
80 cl::init(true), cl::Hidden,
81 cl::desc("Enable partial-overwrite tracking in DSE"));
Owen Anderson5e72db32007-07-11 00:46:18 +000082
Sanjay Patel1d04b5b2017-09-26 13:54:28 +000083static cl::opt<bool>
84EnablePartialStoreMerging("enable-dse-partial-store-merging",
85 cl::init(true), cl::Hidden,
86 cl::desc("Enable partial store merging in DSE"));
87
Chris Lattner67122512010-11-30 21:58:14 +000088//===----------------------------------------------------------------------===//
89// Helper functions
90//===----------------------------------------------------------------------===//
Eugene Zelenko3b879392017-10-13 21:17:07 +000091using OverlapIntervalsTy = std::map<int64_t, int64_t>;
92using InstOverlapIntervalsTy = DenseMap<Instruction *, OverlapIntervalsTy>;
Chris Lattner67122512010-11-30 21:58:14 +000093
Chad Rosiera8bc5122016-06-10 17:58:01 +000094/// Delete this instruction. Before we do, go through and zero out all the
Justin Bogner594e07b2016-05-17 21:38:13 +000095/// operands of this instruction. If any of them become dead, delete them and
96/// the computation tree that feeds them.
Eric Christopher0efe9f62015-08-19 02:15:13 +000097/// If ValueSet is non-null, remove any deleted instructions from it as well.
Justin Bogner594e07b2016-05-17 21:38:13 +000098static void
Chad Rosierdcfce2d2016-07-06 19:48:52 +000099deleteDeadInstruction(Instruction *I, BasicBlock::iterator *BBI,
100 MemoryDependenceResults &MD, const TargetLibraryInfo &TLI,
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000101 InstOverlapIntervalsTy &IOL,
Eli Friedmana6707f52016-08-12 01:09:53 +0000102 DenseMap<Instruction*, size_t> *InstrOrdering,
Justin Bogner594e07b2016-05-17 21:38:13 +0000103 SmallSetVector<Value *, 16> *ValueSet = nullptr) {
Eric Christopher0efe9f62015-08-19 02:15:13 +0000104 SmallVector<Instruction*, 32> NowDeadInsts;
105
106 NowDeadInsts.push_back(I);
107 --NumFastOther;
108
Chad Rosierdcfce2d2016-07-06 19:48:52 +0000109 // Keeping the iterator straight is a pain, so we let this routine tell the
110 // caller what the next instruction is after we're done mucking about.
111 BasicBlock::iterator NewIter = *BBI;
112
Eric Christopher0efe9f62015-08-19 02:15:13 +0000113 // Before we touch this instruction, remove it from memdep!
114 do {
115 Instruction *DeadInst = NowDeadInsts.pop_back_val();
116 ++NumFastOther;
117
118 // This instruction is dead, zap it, in stages. Start by removing it from
119 // MemDep, which needs to know the operands and needs it to be in the
120 // function.
121 MD.removeInstruction(DeadInst);
122
123 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
124 Value *Op = DeadInst->getOperand(op);
125 DeadInst->setOperand(op, nullptr);
126
127 // If this operand just became dead, add it to the NowDeadInsts list.
128 if (!Op->use_empty()) continue;
129
130 if (Instruction *OpI = dyn_cast<Instruction>(Op))
131 if (isInstructionTriviallyDead(OpI, &TLI))
132 NowDeadInsts.push_back(OpI);
133 }
134
Eli Friedmana6707f52016-08-12 01:09:53 +0000135 if (ValueSet) ValueSet->remove(DeadInst);
136 InstrOrdering->erase(DeadInst);
137 IOL.erase(DeadInst);
Chad Rosierdcfce2d2016-07-06 19:48:52 +0000138
139 if (NewIter == DeadInst->getIterator())
140 NewIter = DeadInst->eraseFromParent();
141 else
142 DeadInst->eraseFromParent();
Eric Christopher0efe9f62015-08-19 02:15:13 +0000143 } while (!NowDeadInsts.empty());
Chad Rosierdcfce2d2016-07-06 19:48:52 +0000144 *BBI = NewIter;
Eric Christopher0efe9f62015-08-19 02:15:13 +0000145}
146
Justin Bogner594e07b2016-05-17 21:38:13 +0000147/// Does this instruction write some memory? This only returns true for things
148/// that we can analyze with other helpers below.
Philip Reames424e7a12018-01-21 01:44:33 +0000149static bool hasAnalyzableMemoryWrite(Instruction *I,
150 const TargetLibraryInfo &TLI) {
Nick Lewycky90271472009-11-10 06:46:40 +0000151 if (isa<StoreInst>(I))
152 return true;
153 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
154 switch (II->getIntrinsicID()) {
Chris Lattner2764b4d2009-12-02 06:35:55 +0000155 default:
156 return false;
157 case Intrinsic::memset:
158 case Intrinsic::memmove:
159 case Intrinsic::memcpy:
160 case Intrinsic::init_trampoline:
161 case Intrinsic::lifetime_end:
162 return true;
Nick Lewycky90271472009-11-10 06:46:40 +0000163 }
164 }
Benjamin Kramer3a09ef62015-04-10 14:50:08 +0000165 if (auto CS = CallSite(I)) {
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000166 if (Function *F = CS.getCalledFunction()) {
Chad Rosier624fee52016-06-16 17:06:04 +0000167 StringRef FnName = F->getName();
David L. Jonesd21529f2017-01-23 23:16:46 +0000168 if (TLI.has(LibFunc_strcpy) && FnName == TLI.getName(LibFunc_strcpy))
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000169 return true;
David L. Jonesd21529f2017-01-23 23:16:46 +0000170 if (TLI.has(LibFunc_strncpy) && FnName == TLI.getName(LibFunc_strncpy))
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000171 return true;
David L. Jonesd21529f2017-01-23 23:16:46 +0000172 if (TLI.has(LibFunc_strcat) && FnName == TLI.getName(LibFunc_strcat))
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000173 return true;
David L. Jonesd21529f2017-01-23 23:16:46 +0000174 if (TLI.has(LibFunc_strncat) && FnName == TLI.getName(LibFunc_strncat))
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000175 return true;
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000176 }
177 }
Nick Lewycky90271472009-11-10 06:46:40 +0000178 return false;
179}
180
Justin Bogner594e07b2016-05-17 21:38:13 +0000181/// Return a Location stored to by the specified instruction. If isRemovable
182/// returns true, this function and getLocForRead completely describe the memory
183/// operations for this instruction.
Philip Reamesf57714c2018-01-21 02:10:54 +0000184static MemoryLocation getLocForWrite(Instruction *Inst) {
Philip Reames424e7a12018-01-21 01:44:33 +0000185
Chris Lattner58b779e2010-11-30 07:23:21 +0000186 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
Chandler Carruth70c61c12015-06-04 02:03:15 +0000187 return MemoryLocation::get(SI);
Owen Anderson58704ee2011-09-06 18:14:09 +0000188
Chris Lattner58b779e2010-11-30 07:23:21 +0000189 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(Inst)) {
190 // memcpy/memmove/memset.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000191 MemoryLocation Loc = MemoryLocation::getForDest(MI);
Chris Lattner58b779e2010-11-30 07:23:21 +0000192 return Loc;
193 }
Owen Anderson58704ee2011-09-06 18:14:09 +0000194
Philip Reamesf57714c2018-01-21 02:10:54 +0000195 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
196 switch (II->getIntrinsicID()) {
197 default:
198 return MemoryLocation(); // Unhandled intrinsic.
199 case Intrinsic::init_trampoline:
200 return MemoryLocation(II->getArgOperand(0));
201 case Intrinsic::lifetime_end: {
202 uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
203 return MemoryLocation(II->getArgOperand(1), Len);
204 }
205 }
Chris Lattner58b779e2010-11-30 07:23:21 +0000206 }
Philip Reamesf57714c2018-01-21 02:10:54 +0000207 if (auto CS = CallSite(Inst))
208 // All the supported TLI functions so far happen to have dest as their
209 // first argument.
210 return MemoryLocation(CS.getArgument(0));
211 return MemoryLocation();
Chris Lattner58b779e2010-11-30 07:23:21 +0000212}
213
Philip Reames424e7a12018-01-21 01:44:33 +0000214/// Return the location read by the specified "hasAnalyzableMemoryWrite"
215/// instruction if any.
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000216static MemoryLocation getLocForRead(Instruction *Inst,
217 const TargetLibraryInfo &TLI) {
Philip Reames424e7a12018-01-21 01:44:33 +0000218 assert(hasAnalyzableMemoryWrite(Inst, TLI) && "Unknown instruction case");
Owen Anderson58704ee2011-09-06 18:14:09 +0000219
Chris Lattner94fbdf32010-12-06 01:48:06 +0000220 // The only instructions that both read and write are the mem transfer
221 // instructions (memcpy/memmove).
222 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(Inst))
Chandler Carruth70c61c12015-06-04 02:03:15 +0000223 return MemoryLocation::getForSource(MTI);
Chandler Carruthac80dc72015-06-17 07:18:54 +0000224 return MemoryLocation();
Chris Lattner94fbdf32010-12-06 01:48:06 +0000225}
226
Justin Bogner594e07b2016-05-17 21:38:13 +0000227/// If the value of this instruction and the memory it writes to is unused, may
228/// we delete this instruction?
Chris Lattner3590ef82010-11-30 05:30:45 +0000229static bool isRemovable(Instruction *I) {
Eli Friedman9a468152011-08-17 22:22:24 +0000230 // Don't remove volatile/atomic stores.
Nick Lewycky90271472009-11-10 06:46:40 +0000231 if (StoreInst *SI = dyn_cast<StoreInst>(I))
Eli Friedman9a468152011-08-17 22:22:24 +0000232 return SI->isUnordered();
Owen Anderson58704ee2011-09-06 18:14:09 +0000233
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000234 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
235 switch (II->getIntrinsicID()) {
Philip Reames424e7a12018-01-21 01:44:33 +0000236 default: llvm_unreachable("doesn't pass 'hasAnalyzableMemoryWrite' predicate");
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000237 case Intrinsic::lifetime_end:
238 // Never remove dead lifetime_end's, e.g. because it is followed by a
239 // free.
240 return false;
241 case Intrinsic::init_trampoline:
242 // Always safe to remove init_trampoline.
243 return true;
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000244 case Intrinsic::memset:
245 case Intrinsic::memmove:
246 case Intrinsic::memcpy:
247 // Don't remove volatile memory intrinsics.
248 return !cast<MemIntrinsic>(II)->isVolatile();
249 }
Chris Lattnerb63ba732010-11-30 19:12:10 +0000250 }
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000251
Philip Reames424e7a12018-01-21 01:44:33 +0000252 // note: only get here for calls with analyzable writes - i.e. libcalls
Benjamin Kramer3a09ef62015-04-10 14:50:08 +0000253 if (auto CS = CallSite(I))
Nick Lewycky42bca052012-09-25 01:55:59 +0000254 return CS.getInstruction()->use_empty();
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000255
256 return false;
Nick Lewycky90271472009-11-10 06:46:40 +0000257}
258
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000259/// Returns true if the end of this instruction can be safely shortened in
Pete Cooper856977c2011-11-09 23:07:35 +0000260/// length.
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000261static bool isShortenableAtTheEnd(Instruction *I) {
Pete Cooper856977c2011-11-09 23:07:35 +0000262 // Don't shorten stores for now
263 if (isa<StoreInst>(I))
264 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000265
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000266 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
267 switch (II->getIntrinsicID()) {
268 default: return false;
269 case Intrinsic::memset:
270 case Intrinsic::memcpy:
271 // Do shorten memory intrinsics.
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000272 // FIXME: Add memmove if it's also safe to transform.
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000273 return true;
274 }
Pete Cooper856977c2011-11-09 23:07:35 +0000275 }
Nick Lewycky9f4729d2012-09-24 22:09:10 +0000276
277 // Don't shorten libcalls calls for now.
278
279 return false;
Pete Cooper856977c2011-11-09 23:07:35 +0000280}
281
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000282/// Returns true if the beginning of this instruction can be safely shortened
283/// in length.
284static bool isShortenableAtTheBeginning(Instruction *I) {
285 // FIXME: Handle only memset for now. Supporting memcpy/memmove should be
286 // easily done by offsetting the source address.
287 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
288 return II && II->getIntrinsicID() == Intrinsic::memset;
289}
290
Justin Bogner594e07b2016-05-17 21:38:13 +0000291/// Return the pointer that is being written to.
Chris Lattner67122512010-11-30 21:58:14 +0000292static Value *getStoredPointerOperand(Instruction *I) {
Philip Reames424e7a12018-01-21 01:44:33 +0000293 //TODO: factor this to reuse getLocForWrite
Philip Reamesf57714c2018-01-21 02:10:54 +0000294 MemoryLocation Loc = getLocForWrite(I);
295 assert(Loc.Ptr &&
296 "unable to find pointer writen for analyzable instruction?");
297 // TODO: most APIs don't expect const Value *
298 return const_cast<Value*>(Loc.Ptr);
Nick Lewycky90271472009-11-10 06:46:40 +0000299}
300
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000301static uint64_t getPointerSize(const Value *V, const DataLayout &DL,
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000302 const TargetLibraryInfo &TLI) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000303 uint64_t Size;
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000304 if (getObjectSize(V, Size, DL, &TLI))
Nuno Lopes55fff832012-06-21 15:45:28 +0000305 return Size;
Chandler Carruthecbd1682015-06-17 07:21:38 +0000306 return MemoryLocation::UnknownSize;
Chris Lattner903add82010-11-30 23:43:23 +0000307}
Chris Lattner51c28a92010-11-30 19:34:42 +0000308
Pete Cooper856977c2011-11-09 23:07:35 +0000309namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +0000310
Sanjay Patel1d04b5b2017-09-26 13:54:28 +0000311enum OverwriteResult {
312 OW_Begin,
313 OW_Complete,
314 OW_End,
315 OW_PartialEarlierWithFullLater,
316 OW_Unknown
317};
Eugene Zelenko3b879392017-10-13 21:17:07 +0000318
319} // end anonymous namespace
Pete Cooper856977c2011-11-09 23:07:35 +0000320
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000321/// Return 'OW_Complete' if a store to the 'Later' location completely
322/// overwrites a store to the 'Earlier' location, 'OW_End' if the end of the
323/// 'Earlier' location is completely overwritten by 'Later', 'OW_Begin' if the
Sanjay Patel1d04b5b2017-09-26 13:54:28 +0000324/// beginning of the 'Earlier' location is overwritten by 'Later'.
325/// 'OW_PartialEarlierWithFullLater' means that an earlier (big) store was
326/// overwritten by a latter (smaller) store which doesn't write outside the big
327/// store's memory locations. Returns 'OW_Unknown' if nothing can be determined.
Chandler Carruthac80dc72015-06-17 07:18:54 +0000328static OverwriteResult isOverwrite(const MemoryLocation &Later,
329 const MemoryLocation &Earlier,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000330 const DataLayout &DL,
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000331 const TargetLibraryInfo &TLI,
Hal Finkela1271032016-06-23 13:46:39 +0000332 int64_t &EarlierOff, int64_t &LaterOff,
333 Instruction *DepWrite,
334 InstOverlapIntervalsTy &IOL) {
Chad Rosier72a793c2016-06-15 22:17:38 +0000335 // If we don't know the sizes of either access, then we can't do a comparison.
336 if (Later.Size == MemoryLocation::UnknownSize ||
337 Earlier.Size == MemoryLocation::UnknownSize)
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000338 return OW_Unknown;
Chad Rosier72a793c2016-06-15 22:17:38 +0000339
Chris Lattnerc0f33792010-11-30 23:05:20 +0000340 const Value *P1 = Earlier.Ptr->stripPointerCasts();
341 const Value *P2 = Later.Ptr->stripPointerCasts();
Owen Anderson58704ee2011-09-06 18:14:09 +0000342
Chris Lattnerc0f33792010-11-30 23:05:20 +0000343 // If the start pointers are the same, we just have to compare sizes to see if
344 // the later store was larger than the earlier store.
345 if (P1 == P2) {
Chris Lattnerc0f33792010-11-30 23:05:20 +0000346 // Make sure that the Later size is >= the Earlier size.
Pete Cooper856977c2011-11-09 23:07:35 +0000347 if (Later.Size >= Earlier.Size)
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000348 return OW_Complete;
Chris Lattner77d79fa2010-11-30 19:28:23 +0000349 }
Owen Anderson58704ee2011-09-06 18:14:09 +0000350
Chris Lattner903add82010-11-30 23:43:23 +0000351 // Check to see if the later store is to the entire object (either a global,
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000352 // an alloca, or a byval/inalloca argument). If so, then it clearly
353 // overwrites any other store to the same object.
Rafael Espindola5f57f462014-02-21 18:34:28 +0000354 const Value *UO1 = GetUnderlyingObject(P1, DL),
355 *UO2 = GetUnderlyingObject(P2, DL);
Owen Anderson58704ee2011-09-06 18:14:09 +0000356
Chris Lattner903add82010-11-30 23:43:23 +0000357 // If we can't resolve the same pointers to the same object, then we can't
358 // analyze them at all.
359 if (UO1 != UO2)
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000360 return OW_Unknown;
Owen Anderson58704ee2011-09-06 18:14:09 +0000361
Chris Lattner903add82010-11-30 23:43:23 +0000362 // If the "Later" store is to a recognizable object, get its size.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000363 uint64_t ObjectSize = getPointerSize(UO2, DL, TLI);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000364 if (ObjectSize != MemoryLocation::UnknownSize)
Pete Coopera4237c32011-11-10 20:22:08 +0000365 if (ObjectSize == Later.Size && ObjectSize >= Earlier.Size)
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000366 return OW_Complete;
Owen Anderson58704ee2011-09-06 18:14:09 +0000367
Chris Lattnerc0f33792010-11-30 23:05:20 +0000368 // Okay, we have stores to two completely different pointers. Try to
369 // decompose the pointer into a "base + constant_offset" form. If the base
370 // pointers are equal, then we can reason about the two stores.
Pete Cooper856977c2011-11-09 23:07:35 +0000371 EarlierOff = 0;
372 LaterOff = 0;
Rafael Espindola5f57f462014-02-21 18:34:28 +0000373 const Value *BP1 = GetPointerBaseWithConstantOffset(P1, EarlierOff, DL);
374 const Value *BP2 = GetPointerBaseWithConstantOffset(P2, LaterOff, DL);
Owen Anderson58704ee2011-09-06 18:14:09 +0000375
Chris Lattnerc0f33792010-11-30 23:05:20 +0000376 // If the base pointers still differ, we have two completely different stores.
377 if (BP1 != BP2)
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000378 return OW_Unknown;
Bill Wendlingdb40b5c2011-03-26 01:20:37 +0000379
Bill Wendling19f33b92011-03-26 08:02:59 +0000380 // The later store completely overlaps the earlier store if:
Owen Anderson58704ee2011-09-06 18:14:09 +0000381 //
Bill Wendling19f33b92011-03-26 08:02:59 +0000382 // 1. Both start at the same offset and the later one's size is greater than
383 // or equal to the earlier one's, or
384 //
385 // |--earlier--|
386 // |-- later --|
Owen Anderson58704ee2011-09-06 18:14:09 +0000387 //
Bill Wendling19f33b92011-03-26 08:02:59 +0000388 // 2. The earlier store has an offset greater than the later offset, but which
389 // still lies completely within the later store.
390 //
391 // |--earlier--|
392 // |----- later ------|
Bill Wendling50341592011-03-30 21:37:19 +0000393 //
394 // We have to be careful here as *Off is signed while *.Size is unsigned.
Bill Wendlingb5139922011-03-26 09:32:07 +0000395 if (EarlierOff >= LaterOff &&
Craig Topper2a404182012-08-14 07:32:05 +0000396 Later.Size >= Earlier.Size &&
Bill Wendling50341592011-03-30 21:37:19 +0000397 uint64_t(EarlierOff - LaterOff) + Earlier.Size <= Later.Size)
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000398 return OW_Complete;
Nadav Rotem465834c2012-07-24 10:51:42 +0000399
Hal Finkela1271032016-06-23 13:46:39 +0000400 // We may now overlap, although the overlap is not complete. There might also
401 // be other incomplete overlaps, and together, they might cover the complete
402 // earlier write.
403 // Note: The correctness of this logic depends on the fact that this function
404 // is not even called providing DepWrite when there are any intervening reads.
405 if (EnablePartialOverwriteTracking &&
406 LaterOff < int64_t(EarlierOff + Earlier.Size) &&
407 int64_t(LaterOff + Later.Size) >= EarlierOff) {
408
409 // Insert our part of the overlap into the map.
410 auto &IM = IOL[DepWrite];
411 DEBUG(dbgs() << "DSE: Partial overwrite: Earlier [" << EarlierOff << ", " <<
412 int64_t(EarlierOff + Earlier.Size) << ") Later [" <<
413 LaterOff << ", " << int64_t(LaterOff + Later.Size) << ")\n");
414
415 // Make sure that we only insert non-overlapping intervals and combine
416 // adjacent intervals. The intervals are stored in the map with the ending
417 // offset as the key (in the half-open sense) and the starting offset as
418 // the value.
419 int64_t LaterIntStart = LaterOff, LaterIntEnd = LaterOff + Later.Size;
420
421 // Find any intervals ending at, or after, LaterIntStart which start
422 // before LaterIntEnd.
423 auto ILI = IM.lower_bound(LaterIntStart);
Jun Bum Lim596a3bd2016-06-30 15:32:20 +0000424 if (ILI != IM.end() && ILI->second <= LaterIntEnd) {
425 // This existing interval is overlapped with the current store somewhere
426 // in [LaterIntStart, LaterIntEnd]. Merge them by erasing the existing
427 // intervals and adjusting our start and end.
Hal Finkela1271032016-06-23 13:46:39 +0000428 LaterIntStart = std::min(LaterIntStart, ILI->second);
429 LaterIntEnd = std::max(LaterIntEnd, ILI->first);
430 ILI = IM.erase(ILI);
431
Jun Bum Lim596a3bd2016-06-30 15:32:20 +0000432 // Continue erasing and adjusting our end in case other previous
433 // intervals are also overlapped with the current store.
434 //
435 // |--- ealier 1 ---| |--- ealier 2 ---|
436 // |------- later---------|
437 //
438 while (ILI != IM.end() && ILI->second <= LaterIntEnd) {
439 assert(ILI->second > LaterIntStart && "Unexpected interval");
Hal Finkela1271032016-06-23 13:46:39 +0000440 LaterIntEnd = std::max(LaterIntEnd, ILI->first);
Jun Bum Lim596a3bd2016-06-30 15:32:20 +0000441 ILI = IM.erase(ILI);
442 }
Hal Finkela1271032016-06-23 13:46:39 +0000443 }
444
445 IM[LaterIntEnd] = LaterIntStart;
446
447 ILI = IM.begin();
448 if (ILI->second <= EarlierOff &&
449 ILI->first >= int64_t(EarlierOff + Earlier.Size)) {
450 DEBUG(dbgs() << "DSE: Full overwrite from partials: Earlier [" <<
451 EarlierOff << ", " <<
452 int64_t(EarlierOff + Earlier.Size) <<
453 ") Composite Later [" <<
454 ILI->second << ", " << ILI->first << ")\n");
455 ++NumCompletePartials;
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000456 return OW_Complete;
Hal Finkela1271032016-06-23 13:46:39 +0000457 }
458 }
459
Sanjay Patel1d04b5b2017-09-26 13:54:28 +0000460 // Check for an earlier store which writes to all the memory locations that
461 // the later store writes to.
462 if (EnablePartialStoreMerging && LaterOff >= EarlierOff &&
463 int64_t(EarlierOff + Earlier.Size) > LaterOff &&
464 uint64_t(LaterOff - EarlierOff) + Later.Size <= Earlier.Size) {
465 DEBUG(dbgs() << "DSE: Partial overwrite an earlier load [" << EarlierOff
466 << ", " << int64_t(EarlierOff + Earlier.Size)
467 << ") by a later store [" << LaterOff << ", "
468 << int64_t(LaterOff + Later.Size) << ")\n");
469 // TODO: Maybe come up with a better name?
470 return OW_PartialEarlierWithFullLater;
471 }
472
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000473 // Another interesting case is if the later store overwrites the end of the
474 // earlier store.
Pete Cooper856977c2011-11-09 23:07:35 +0000475 //
476 // |--earlier--|
477 // |-- later --|
478 //
479 // In this case we may want to trim the size of earlier to avoid generating
480 // writes to addresses which will definitely be overwritten later
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000481 if (!EnablePartialOverwriteTracking &&
482 (LaterOff > EarlierOff && LaterOff < int64_t(EarlierOff + Earlier.Size) &&
483 int64_t(LaterOff + Later.Size) >= int64_t(EarlierOff + Earlier.Size)))
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000484 return OW_End;
Bill Wendling19f33b92011-03-26 08:02:59 +0000485
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000486 // Finally, we also need to check if the later store overwrites the beginning
487 // of the earlier store.
488 //
489 // |--earlier--|
490 // |-- later --|
491 //
492 // In this case we may want to move the destination address and trim the size
493 // of earlier to avoid generating writes to addresses which will definitely
494 // be overwritten later.
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000495 if (!EnablePartialOverwriteTracking &&
496 (LaterOff <= EarlierOff && int64_t(LaterOff + Later.Size) > EarlierOff)) {
497 assert(int64_t(LaterOff + Later.Size) <
498 int64_t(EarlierOff + Earlier.Size) &&
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000499 "Expect to be handled as OW_Complete");
500 return OW_Begin;
Jun Bum Limd29a24e2016-04-22 19:51:29 +0000501 }
Bill Wendling19f33b92011-03-26 08:02:59 +0000502 // Otherwise, they don't completely overlap.
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000503 return OW_Unknown;
Nick Lewycky90271472009-11-10 06:46:40 +0000504}
505
Justin Bogner594e07b2016-05-17 21:38:13 +0000506/// If 'Inst' might be a self read (i.e. a noop copy of a
Chris Lattner94fbdf32010-12-06 01:48:06 +0000507/// memory region into an identical pointer) then it doesn't actually make its
Owen Anderson58704ee2011-09-06 18:14:09 +0000508/// input dead in the traditional sense. Consider this case:
Chris Lattner94fbdf32010-12-06 01:48:06 +0000509///
510/// memcpy(A <- B)
511/// memcpy(A <- A)
512///
513/// In this case, the second store to A does not make the first store to A dead.
514/// The usual situation isn't an explicit A<-A store like this (which can be
515/// trivially removed) but a case where two pointers may alias.
516///
517/// This function detects when it is unsafe to remove a dependent instruction
518/// because the DSE inducing instruction may be a self-read.
519static bool isPossibleSelfRead(Instruction *Inst,
Chandler Carruthac80dc72015-06-17 07:18:54 +0000520 const MemoryLocation &InstStoreLoc,
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000521 Instruction *DepWrite,
522 const TargetLibraryInfo &TLI,
523 AliasAnalysis &AA) {
Chris Lattner94fbdf32010-12-06 01:48:06 +0000524 // Self reads can only happen for instructions that read memory. Get the
525 // location read.
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000526 MemoryLocation InstReadLoc = getLocForRead(Inst, TLI);
Craig Topperf40110f2014-04-25 05:29:35 +0000527 if (!InstReadLoc.Ptr) return false; // Not a reading instruction.
Owen Anderson58704ee2011-09-06 18:14:09 +0000528
Chris Lattner94fbdf32010-12-06 01:48:06 +0000529 // If the read and written loc obviously don't alias, it isn't a read.
530 if (AA.isNoAlias(InstReadLoc, InstStoreLoc)) return false;
Owen Anderson58704ee2011-09-06 18:14:09 +0000531
Chris Lattner94fbdf32010-12-06 01:48:06 +0000532 // Okay, 'Inst' may copy over itself. However, we can still remove a the
533 // DepWrite instruction if we can prove that it reads from the same location
534 // as Inst. This handles useful cases like:
535 // memcpy(A <- B)
536 // memcpy(A <- B)
537 // Here we don't know if A/B may alias, but we do know that B/B are must
538 // aliases, so removing the first memcpy is safe (assuming it writes <= #
539 // bytes as the second one.
Chandler Carruthdbe40fb2015-08-12 18:01:44 +0000540 MemoryLocation DepReadLoc = getLocForRead(DepWrite, TLI);
Owen Anderson58704ee2011-09-06 18:14:09 +0000541
Chris Lattner94fbdf32010-12-06 01:48:06 +0000542 if (DepReadLoc.Ptr && AA.isMustAlias(InstReadLoc.Ptr, DepReadLoc.Ptr))
543 return false;
Owen Anderson58704ee2011-09-06 18:14:09 +0000544
Chris Lattner94fbdf32010-12-06 01:48:06 +0000545 // If DepWrite doesn't read memory or if we can't prove it is a must alias,
546 // then it can't be considered dead.
547 return true;
548}
549
Justin Bogner594e07b2016-05-17 21:38:13 +0000550/// Returns true if the memory which is accessed by the second instruction is not
551/// modified between the first and the second instruction.
552/// Precondition: Second instruction must be dominated by the first
553/// instruction.
554static bool memoryIsNotModifiedBetween(Instruction *FirstI,
555 Instruction *SecondI,
556 AliasAnalysis *AA) {
557 SmallVector<BasicBlock *, 16> WorkList;
558 SmallPtrSet<BasicBlock *, 8> Visited;
559 BasicBlock::iterator FirstBBI(FirstI);
560 ++FirstBBI;
561 BasicBlock::iterator SecondBBI(SecondI);
562 BasicBlock *FirstBB = FirstI->getParent();
563 BasicBlock *SecondBB = SecondI->getParent();
564 MemoryLocation MemLoc = MemoryLocation::get(SecondI);
Chris Lattner67122512010-11-30 21:58:14 +0000565
Justin Bogner594e07b2016-05-17 21:38:13 +0000566 // Start checking the store-block.
567 WorkList.push_back(SecondBB);
568 bool isFirstBlock = true;
569
570 // Check all blocks going backward until we reach the load-block.
571 while (!WorkList.empty()) {
572 BasicBlock *B = WorkList.pop_back_val();
573
574 // Ignore instructions before LI if this is the FirstBB.
575 BasicBlock::iterator BI = (B == FirstBB ? FirstBBI : B->begin());
576
577 BasicBlock::iterator EI;
578 if (isFirstBlock) {
579 // Ignore instructions after SI if this is the first visit of SecondBB.
580 assert(B == SecondBB && "first block is not the store block");
581 EI = SecondBBI;
582 isFirstBlock = false;
583 } else {
584 // It's not SecondBB or (in case of a loop) the second visit of SecondBB.
585 // In this case we also have to look at instructions after SI.
586 EI = B->end();
587 }
588 for (; BI != EI; ++BI) {
589 Instruction *I = &*BI;
Alina Sbirlea63d22502017-12-05 20:12:23 +0000590 if (I->mayWriteToMemory() && I != SecondI)
591 if (isModSet(AA->getModRefInfo(I, MemLoc)))
Justin Bogner594e07b2016-05-17 21:38:13 +0000592 return false;
Justin Bogner594e07b2016-05-17 21:38:13 +0000593 }
594 if (B != FirstBB) {
595 assert(B != &FirstBB->getParent()->getEntryBlock() &&
596 "Should not hit the entry block because SI must be dominated by LI");
597 for (auto PredI = pred_begin(B), PE = pred_end(B); PredI != PE; ++PredI) {
598 if (!Visited.insert(*PredI).second)
599 continue;
600 WorkList.push_back(*PredI);
601 }
602 }
603 }
604 return true;
605}
606
607/// Find all blocks that will unconditionally lead to the block BB and append
608/// them to F.
609static void findUnconditionalPreds(SmallVectorImpl<BasicBlock *> &Blocks,
610 BasicBlock *BB, DominatorTree *DT) {
611 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
612 BasicBlock *Pred = *I;
613 if (Pred == BB) continue;
614 TerminatorInst *PredTI = Pred->getTerminator();
615 if (PredTI->getNumSuccessors() != 1)
616 continue;
617
618 if (DT->isReachableFromEntry(Pred))
619 Blocks.push_back(Pred);
620 }
621}
622
623/// Handle frees of entire structures whose dependency is a store
624/// to a field of that structure.
625static bool handleFree(CallInst *F, AliasAnalysis *AA,
626 MemoryDependenceResults *MD, DominatorTree *DT,
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000627 const TargetLibraryInfo *TLI,
Eli Friedmana6707f52016-08-12 01:09:53 +0000628 InstOverlapIntervalsTy &IOL,
629 DenseMap<Instruction*, size_t> *InstrOrdering) {
Justin Bogner594e07b2016-05-17 21:38:13 +0000630 bool MadeChange = false;
631
632 MemoryLocation Loc = MemoryLocation(F->getOperand(0));
633 SmallVector<BasicBlock *, 16> Blocks;
634 Blocks.push_back(F->getParent());
635 const DataLayout &DL = F->getModule()->getDataLayout();
636
637 while (!Blocks.empty()) {
638 BasicBlock *BB = Blocks.pop_back_val();
639 Instruction *InstPt = BB->getTerminator();
640 if (BB == F->getParent()) InstPt = F;
641
642 MemDepResult Dep =
643 MD->getPointerDependencyFrom(Loc, false, InstPt->getIterator(), BB);
644 while (Dep.isDef() || Dep.isClobber()) {
645 Instruction *Dependency = Dep.getInst();
Philip Reames424e7a12018-01-21 01:44:33 +0000646 if (!hasAnalyzableMemoryWrite(Dependency, *TLI) ||
647 !isRemovable(Dependency))
Justin Bogner594e07b2016-05-17 21:38:13 +0000648 break;
649
650 Value *DepPointer =
651 GetUnderlyingObject(getStoredPointerOperand(Dependency), DL);
652
653 // Check for aliasing.
654 if (!AA->isMustAlias(F->getArgOperand(0), DepPointer))
655 break;
656
Chad Rosier667b1ca2016-07-19 16:50:57 +0000657 DEBUG(dbgs() << "DSE: Dead Store to soon to be freed memory:\n DEAD: "
658 << *Dependency << '\n');
659
Chad Rosier840b3ef2016-06-10 17:59:22 +0000660 // DCE instructions only used to calculate that store.
Chad Rosierdcfce2d2016-07-06 19:48:52 +0000661 BasicBlock::iterator BBI(Dependency);
Eli Friedmana6707f52016-08-12 01:09:53 +0000662 deleteDeadInstruction(Dependency, &BBI, *MD, *TLI, IOL, InstrOrdering);
Justin Bogner594e07b2016-05-17 21:38:13 +0000663 ++NumFastStores;
664 MadeChange = true;
665
666 // Inst's old Dependency is now deleted. Compute the next dependency,
667 // which may also be dead, as in
668 // s[0] = 0;
669 // s[1] = 0; // This has just been deleted.
670 // free(s);
Chad Rosierdcfce2d2016-07-06 19:48:52 +0000671 Dep = MD->getPointerDependencyFrom(Loc, false, BBI, BB);
Justin Bogner594e07b2016-05-17 21:38:13 +0000672 }
673
674 if (Dep.isNonLocal())
675 findUnconditionalPreds(Blocks, BB, DT);
676 }
677
678 return MadeChange;
679}
680
681/// Check to see if the specified location may alias any of the stack objects in
682/// the DeadStackObjects set. If so, they become live because the location is
683/// being loaded.
684static void removeAccessedObjects(const MemoryLocation &LoadedLoc,
685 SmallSetVector<Value *, 16> &DeadStackObjects,
686 const DataLayout &DL, AliasAnalysis *AA,
687 const TargetLibraryInfo *TLI) {
688 const Value *UnderlyingPointer = GetUnderlyingObject(LoadedLoc.Ptr, DL);
689
690 // A constant can't be in the dead pointer set.
691 if (isa<Constant>(UnderlyingPointer))
692 return;
693
694 // If the kill pointer can be easily reduced to an alloca, don't bother doing
695 // extraneous AA queries.
696 if (isa<AllocaInst>(UnderlyingPointer) || isa<Argument>(UnderlyingPointer)) {
697 DeadStackObjects.remove(const_cast<Value*>(UnderlyingPointer));
698 return;
699 }
700
701 // Remove objects that could alias LoadedLoc.
702 DeadStackObjects.remove_if([&](Value *I) {
703 // See if the loaded location could alias the stack location.
704 MemoryLocation StackLoc(I, getPointerSize(I, DL, *TLI));
705 return !AA->isNoAlias(StackLoc, LoadedLoc);
706 });
707}
708
709/// Remove dead stores to stack-allocated locations in the function end block.
710/// Ex:
711/// %A = alloca i32
712/// ...
713/// store i32 1, i32* %A
714/// ret void
715static bool handleEndBlock(BasicBlock &BB, AliasAnalysis *AA,
716 MemoryDependenceResults *MD,
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000717 const TargetLibraryInfo *TLI,
Eli Friedmana6707f52016-08-12 01:09:53 +0000718 InstOverlapIntervalsTy &IOL,
719 DenseMap<Instruction*, size_t> *InstrOrdering) {
Justin Bogner594e07b2016-05-17 21:38:13 +0000720 bool MadeChange = false;
721
722 // Keep track of all of the stack objects that are dead at the end of the
723 // function.
724 SmallSetVector<Value*, 16> DeadStackObjects;
725
726 // Find all of the alloca'd pointers in the entry block.
727 BasicBlock &Entry = BB.getParent()->front();
728 for (Instruction &I : Entry) {
729 if (isa<AllocaInst>(&I))
730 DeadStackObjects.insert(&I);
731
732 // Okay, so these are dead heap objects, but if the pointer never escapes
733 // then it's leaked by this function anyways.
734 else if (isAllocLikeFn(&I, TLI) && !PointerMayBeCaptured(&I, true, true))
735 DeadStackObjects.insert(&I);
736 }
737
738 // Treat byval or inalloca arguments the same, stores to them are dead at the
739 // end of the function.
740 for (Argument &AI : BB.getParent()->args())
741 if (AI.hasByValOrInAllocaAttr())
742 DeadStackObjects.insert(&AI);
743
744 const DataLayout &DL = BB.getModule()->getDataLayout();
745
746 // Scan the basic block backwards
747 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
748 --BBI;
749
750 // If we find a store, check to see if it points into a dead stack value.
Philip Reames424e7a12018-01-21 01:44:33 +0000751 if (hasAnalyzableMemoryWrite(&*BBI, *TLI) && isRemovable(&*BBI)) {
Justin Bogner594e07b2016-05-17 21:38:13 +0000752 // See through pointer-to-pointer bitcasts
753 SmallVector<Value *, 4> Pointers;
754 GetUnderlyingObjects(getStoredPointerOperand(&*BBI), Pointers, DL);
755
756 // Stores to stack values are valid candidates for removal.
757 bool AllDead = true;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000758 for (Value *Pointer : Pointers)
759 if (!DeadStackObjects.count(Pointer)) {
Justin Bogner594e07b2016-05-17 21:38:13 +0000760 AllDead = false;
761 break;
762 }
763
764 if (AllDead) {
Chad Rosierdcfce2d2016-07-06 19:48:52 +0000765 Instruction *Dead = &*BBI;
Justin Bogner594e07b2016-05-17 21:38:13 +0000766
767 DEBUG(dbgs() << "DSE: Dead Store at End of Block:\n DEAD: "
768 << *Dead << "\n Objects: ";
769 for (SmallVectorImpl<Value *>::iterator I = Pointers.begin(),
770 E = Pointers.end(); I != E; ++I) {
771 dbgs() << **I;
772 if (std::next(I) != E)
773 dbgs() << ", ";
774 }
775 dbgs() << '\n');
776
777 // DCE instructions only used to calculate that store.
Eli Friedmana6707f52016-08-12 01:09:53 +0000778 deleteDeadInstruction(Dead, &BBI, *MD, *TLI, IOL, InstrOrdering, &DeadStackObjects);
Justin Bogner594e07b2016-05-17 21:38:13 +0000779 ++NumFastStores;
780 MadeChange = true;
781 continue;
782 }
783 }
784
785 // Remove any dead non-memory-mutating instructions.
786 if (isInstructionTriviallyDead(&*BBI, TLI)) {
Chad Rosier8b5fa7a2016-07-19 18:11:11 +0000787 DEBUG(dbgs() << "DSE: Removing trivially dead instruction:\n DEAD: "
788 << *&*BBI << '\n');
Eli Friedmana6707f52016-08-12 01:09:53 +0000789 deleteDeadInstruction(&*BBI, &BBI, *MD, *TLI, IOL, InstrOrdering, &DeadStackObjects);
Justin Bogner594e07b2016-05-17 21:38:13 +0000790 ++NumFastOther;
791 MadeChange = true;
792 continue;
793 }
794
795 if (isa<AllocaInst>(BBI)) {
796 // Remove allocas from the list of dead stack objects; there can't be
797 // any references before the definition.
798 DeadStackObjects.remove(&*BBI);
799 continue;
800 }
801
802 if (auto CS = CallSite(&*BBI)) {
803 // Remove allocation function calls from the list of dead stack objects;
804 // there can't be any references before the definition.
805 if (isAllocLikeFn(&*BBI, TLI))
806 DeadStackObjects.remove(&*BBI);
807
808 // If this call does not access memory, it can't be loading any of our
809 // pointers.
810 if (AA->doesNotAccessMemory(CS))
811 continue;
812
813 // If the call might load from any of our allocas, then any store above
814 // the call is live.
815 DeadStackObjects.remove_if([&](Value *I) {
816 // See if the call site touches the value.
Alina Sbirlea63d22502017-12-05 20:12:23 +0000817 return isRefSet(AA->getModRefInfo(CS, I, getPointerSize(I, DL, *TLI)));
Justin Bogner594e07b2016-05-17 21:38:13 +0000818 });
819
820 // If all of the allocas were clobbered by the call then we're not going
821 // to find anything else to process.
822 if (DeadStackObjects.empty())
823 break;
824
825 continue;
826 }
827
Anna Thomas6a78c782016-07-07 20:51:42 +0000828 // We can remove the dead stores, irrespective of the fence and its ordering
829 // (release/acquire/seq_cst). Fences only constraints the ordering of
830 // already visible stores, it does not make a store visible to other
831 // threads. So, skipping over a fence does not change a store from being
832 // dead.
833 if (isa<FenceInst>(*BBI))
834 continue;
835
Justin Bogner594e07b2016-05-17 21:38:13 +0000836 MemoryLocation LoadedLoc;
837
838 // If we encounter a use of the pointer, it is no longer considered dead
839 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
840 if (!L->isUnordered()) // Be conservative with atomic/volatile load
841 break;
842 LoadedLoc = MemoryLocation::get(L);
843 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
844 LoadedLoc = MemoryLocation::get(V);
845 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(BBI)) {
846 LoadedLoc = MemoryLocation::getForSource(MTI);
847 } else if (!BBI->mayReadFromMemory()) {
848 // Instruction doesn't read memory. Note that stores that weren't removed
849 // above will hit this case.
850 continue;
851 } else {
852 // Unknown inst; assume it clobbers everything.
853 break;
854 }
855
856 // Remove any allocas from the DeadPointer set that are loaded, as this
857 // makes any stores above the access live.
858 removeAccessedObjects(LoadedLoc, DeadStackObjects, DL, AA, TLI);
859
860 // If all of the allocas were clobbered by the access then we're not going
861 // to find anything else to process.
862 if (DeadStackObjects.empty())
863 break;
864 }
865
866 return MadeChange;
867}
868
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000869static bool tryToShorten(Instruction *EarlierWrite, int64_t &EarlierOffset,
870 int64_t &EarlierSize, int64_t LaterOffset,
871 int64_t LaterSize, bool IsOverwriteEnd) {
872 // TODO: base this on the target vector size so that if the earlier
873 // store was too small to get vector writes anyway then its likely
874 // a good idea to shorten it
875 // Power of 2 vector writes are probably always a bad idea to optimize
876 // as any store/memset/memcpy is likely using vector instructions so
877 // shortening it to not vector size is likely to be slower
878 MemIntrinsic *EarlierIntrinsic = cast<MemIntrinsic>(EarlierWrite);
Daniel Neilson83cdf682018-02-06 21:18:33 +0000879 unsigned EarlierWriteAlign = EarlierIntrinsic->getDestAlignment();
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000880 if (!IsOverwriteEnd)
881 LaterOffset = int64_t(LaterOffset + LaterSize);
882
Eugene Zelenko3b879392017-10-13 21:17:07 +0000883 if (!(isPowerOf2_64(LaterOffset) && EarlierWriteAlign <= LaterOffset) &&
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000884 !((EarlierWriteAlign != 0) && LaterOffset % EarlierWriteAlign == 0))
885 return false;
886
887 DEBUG(dbgs() << "DSE: Remove Dead Store:\n OW "
888 << (IsOverwriteEnd ? "END" : "BEGIN") << ": " << *EarlierWrite
889 << "\n KILLER (offset " << LaterOffset << ", " << EarlierSize
890 << ")\n");
891
892 int64_t NewLength = IsOverwriteEnd
893 ? LaterOffset - EarlierOffset
894 : EarlierSize - (LaterOffset - EarlierOffset);
895
896 Value *EarlierWriteLength = EarlierIntrinsic->getLength();
897 Value *TrimmedLength =
898 ConstantInt::get(EarlierWriteLength->getType(), NewLength);
899 EarlierIntrinsic->setLength(TrimmedLength);
900
901 EarlierSize = NewLength;
902 if (!IsOverwriteEnd) {
903 int64_t OffsetMoved = (LaterOffset - EarlierOffset);
904 Value *Indices[1] = {
905 ConstantInt::get(EarlierWriteLength->getType(), OffsetMoved)};
906 GetElementPtrInst *NewDestGEP = GetElementPtrInst::CreateInBounds(
907 EarlierIntrinsic->getRawDest(), Indices, "", EarlierWrite);
908 EarlierIntrinsic->setDest(NewDestGEP);
909 EarlierOffset = EarlierOffset + OffsetMoved;
910 }
911 return true;
912}
913
914static bool tryToShortenEnd(Instruction *EarlierWrite,
915 OverlapIntervalsTy &IntervalMap,
916 int64_t &EarlierStart, int64_t &EarlierSize) {
917 if (IntervalMap.empty() || !isShortenableAtTheEnd(EarlierWrite))
918 return false;
919
920 OverlapIntervalsTy::iterator OII = --IntervalMap.end();
921 int64_t LaterStart = OII->second;
922 int64_t LaterSize = OII->first - LaterStart;
923
924 if (LaterStart > EarlierStart && LaterStart < EarlierStart + EarlierSize &&
925 LaterStart + LaterSize >= EarlierStart + EarlierSize) {
926 if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart,
927 LaterSize, true)) {
928 IntervalMap.erase(OII);
929 return true;
930 }
931 }
932 return false;
933}
934
935static bool tryToShortenBegin(Instruction *EarlierWrite,
936 OverlapIntervalsTy &IntervalMap,
937 int64_t &EarlierStart, int64_t &EarlierSize) {
938 if (IntervalMap.empty() || !isShortenableAtTheBeginning(EarlierWrite))
939 return false;
940
941 OverlapIntervalsTy::iterator OII = IntervalMap.begin();
942 int64_t LaterStart = OII->second;
943 int64_t LaterSize = OII->first - LaterStart;
944
945 if (LaterStart <= EarlierStart && LaterStart + LaterSize > EarlierStart) {
946 assert(LaterStart + LaterSize < EarlierStart + EarlierSize &&
Filipe Cabecinhas8b942732017-03-29 14:42:27 +0000947 "Should have been handled as OW_Complete");
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000948 if (tryToShorten(EarlierWrite, EarlierStart, EarlierSize, LaterStart,
949 LaterSize, false)) {
950 IntervalMap.erase(OII);
951 return true;
952 }
953 }
954 return false;
955}
956
957static bool removePartiallyOverlappedStores(AliasAnalysis *AA,
958 const DataLayout &DL,
959 InstOverlapIntervalsTy &IOL) {
960 bool Changed = false;
961 for (auto OI : IOL) {
962 Instruction *EarlierWrite = OI.first;
Philip Reamesf57714c2018-01-21 02:10:54 +0000963 MemoryLocation Loc = getLocForWrite(EarlierWrite);
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000964 assert(isRemovable(EarlierWrite) && "Expect only removable instruction");
965 assert(Loc.Size != MemoryLocation::UnknownSize && "Unexpected mem loc");
966
967 const Value *Ptr = Loc.Ptr->stripPointerCasts();
968 int64_t EarlierStart = 0;
969 int64_t EarlierSize = int64_t(Loc.Size);
970 GetPointerBaseWithConstantOffset(Ptr, EarlierStart, DL);
971 OverlapIntervalsTy &IntervalMap = OI.second;
Jun Bum Lima0331392016-07-27 17:25:20 +0000972 Changed |=
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000973 tryToShortenEnd(EarlierWrite, IntervalMap, EarlierStart, EarlierSize);
974 if (IntervalMap.empty())
975 continue;
976 Changed |=
977 tryToShortenBegin(EarlierWrite, IntervalMap, EarlierStart, EarlierSize);
978 }
979 return Changed;
980}
981
Chad Rosier89c32a92016-07-08 16:48:40 +0000982static bool eliminateNoopStore(Instruction *Inst, BasicBlock::iterator &BBI,
983 AliasAnalysis *AA, MemoryDependenceResults *MD,
984 const DataLayout &DL,
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +0000985 const TargetLibraryInfo *TLI,
Eli Friedmana6707f52016-08-12 01:09:53 +0000986 InstOverlapIntervalsTy &IOL,
987 DenseMap<Instruction*, size_t> *InstrOrdering) {
Chad Rosier89c32a92016-07-08 16:48:40 +0000988 // Must be a store instruction.
989 StoreInst *SI = dyn_cast<StoreInst>(Inst);
990 if (!SI)
991 return false;
992
993 // If we're storing the same value back to a pointer that we just loaded from,
994 // then the store can be removed.
995 if (LoadInst *DepLoad = dyn_cast<LoadInst>(SI->getValueOperand())) {
996 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
997 isRemovable(SI) && memoryIsNotModifiedBetween(DepLoad, SI, AA)) {
998
999 DEBUG(dbgs() << "DSE: Remove Store Of Load from same pointer:\n LOAD: "
1000 << *DepLoad << "\n STORE: " << *SI << '\n');
1001
Eli Friedmana6707f52016-08-12 01:09:53 +00001002 deleteDeadInstruction(SI, &BBI, *MD, *TLI, IOL, InstrOrdering);
Chad Rosier89c32a92016-07-08 16:48:40 +00001003 ++NumRedundantStores;
1004 return true;
1005 }
1006 }
1007
1008 // Remove null stores into the calloc'ed objects
1009 Constant *StoredConstant = dyn_cast<Constant>(SI->getValueOperand());
1010 if (StoredConstant && StoredConstant->isNullValue() && isRemovable(SI)) {
1011 Instruction *UnderlyingPointer =
1012 dyn_cast<Instruction>(GetUnderlyingObject(SI->getPointerOperand(), DL));
1013
1014 if (UnderlyingPointer && isCallocLikeFn(UnderlyingPointer, TLI) &&
1015 memoryIsNotModifiedBetween(UnderlyingPointer, SI, AA)) {
1016 DEBUG(
1017 dbgs() << "DSE: Remove null store to the calloc'ed object:\n DEAD: "
1018 << *Inst << "\n OBJECT: " << *UnderlyingPointer << '\n');
1019
Eli Friedmana6707f52016-08-12 01:09:53 +00001020 deleteDeadInstruction(SI, &BBI, *MD, *TLI, IOL, InstrOrdering);
Chad Rosier89c32a92016-07-08 16:48:40 +00001021 ++NumRedundantStores;
1022 return true;
1023 }
1024 }
1025 return false;
1026}
1027
Justin Bogner594e07b2016-05-17 21:38:13 +00001028static bool eliminateDeadStores(BasicBlock &BB, AliasAnalysis *AA,
1029 MemoryDependenceResults *MD, DominatorTree *DT,
1030 const TargetLibraryInfo *TLI) {
Igor Laevsky029bd932015-09-23 11:38:44 +00001031 const DataLayout &DL = BB.getModule()->getDataLayout();
Owen Anderson5e72db32007-07-11 00:46:18 +00001032 bool MadeChange = false;
Owen Anderson58704ee2011-09-06 18:14:09 +00001033
Eli Friedmana6707f52016-08-12 01:09:53 +00001034 // FIXME: Maybe change this to use some abstraction like OrderedBasicBlock?
1035 // The current OrderedBasicBlock can't deal with mutation at the moment.
1036 size_t LastThrowingInstIndex = 0;
1037 DenseMap<Instruction*, size_t> InstrOrdering;
1038 size_t InstrIndex = 1;
1039
Hal Finkela1271032016-06-23 13:46:39 +00001040 // A map of interval maps representing partially-overwritten value parts.
1041 InstOverlapIntervalsTy IOL;
1042
Chris Lattner49162672009-09-02 06:31:02 +00001043 // Do a top-down walk on the BB.
Chris Lattnerf2a8ba42008-11-28 21:29:52 +00001044 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
Chris Lattner9d179d92010-11-30 01:28:33 +00001045 // Handle 'free' calls specially.
Chad Rosierdcfce2d2016-07-06 19:48:52 +00001046 if (CallInst *F = isFreeCall(&*BBI, TLI)) {
Eli Friedmana6707f52016-08-12 01:09:53 +00001047 MadeChange |= handleFree(F, AA, MD, DT, TLI, IOL, &InstrOrdering);
Chad Rosierdcfce2d2016-07-06 19:48:52 +00001048 // Increment BBI after handleFree has potentially deleted instructions.
1049 // This ensures we maintain a valid iterator.
1050 ++BBI;
Chris Lattner9d179d92010-11-30 01:28:33 +00001051 continue;
1052 }
Owen Anderson58704ee2011-09-06 18:14:09 +00001053
Chad Rosierdcfce2d2016-07-06 19:48:52 +00001054 Instruction *Inst = &*BBI++;
1055
Eli Friedmana6707f52016-08-12 01:09:53 +00001056 size_t CurInstNumber = InstrIndex++;
1057 InstrOrdering.insert(std::make_pair(Inst, CurInstNumber));
1058 if (Inst->mayThrow()) {
1059 LastThrowingInstIndex = CurInstNumber;
1060 continue;
1061 }
1062
Chad Rosier89c32a92016-07-08 16:48:40 +00001063 // Check to see if Inst writes to memory. If not, continue.
Philip Reames424e7a12018-01-21 01:44:33 +00001064 if (!hasAnalyzableMemoryWrite(Inst, *TLI))
Owen Anderson0aecf0e2007-08-08 04:52:29 +00001065 continue;
Chris Lattnerd4f10902010-11-30 00:01:19 +00001066
Chad Rosier89c32a92016-07-08 16:48:40 +00001067 // eliminateNoopStore will update in iterator, if necessary.
Eli Friedmana6707f52016-08-12 01:09:53 +00001068 if (eliminateNoopStore(Inst, BBI, AA, MD, DL, TLI, IOL, &InstrOrdering)) {
Chad Rosier89c32a92016-07-08 16:48:40 +00001069 MadeChange = true;
1070 continue;
Owen Anderson5e72db32007-07-11 00:46:18 +00001071 }
Owen Anderson58704ee2011-09-06 18:14:09 +00001072
Chad Rosier89c32a92016-07-08 16:48:40 +00001073 // If we find something that writes memory, get its memory dependence.
Erik Eckstein11fc8172015-08-13 15:36:11 +00001074 MemDepResult InstDep = MD->getDependency(Inst);
1075
Chad Rosierd7634fc2015-12-11 18:39:41 +00001076 // Ignore any store where we can't find a local dependence.
1077 // FIXME: cross-block DSE would be fun. :)
1078 if (!InstDep.isDef() && !InstDep.isClobber())
1079 continue;
Erik Eckstein11fc8172015-08-13 15:36:11 +00001080
Chad Rosierd7634fc2015-12-11 18:39:41 +00001081 // Figure out what location is being stored to.
Philip Reamesf57714c2018-01-21 02:10:54 +00001082 MemoryLocation Loc = getLocForWrite(Inst);
Chris Lattner58b779e2010-11-30 07:23:21 +00001083
Chad Rosierd7634fc2015-12-11 18:39:41 +00001084 // If we didn't get a useful location, fail.
1085 if (!Loc.Ptr)
1086 continue;
1087
Bob Haarman3db17642016-08-26 16:34:27 +00001088 // Loop until we find a store we can eliminate or a load that
1089 // invalidates the analysis. Without an upper bound on the number of
1090 // instructions examined, this analysis can become very time-consuming.
1091 // However, the potential gain diminishes as we process more instructions
1092 // without eliminating any of them. Therefore, we limit the number of
1093 // instructions we look at.
1094 auto Limit = MD->getDefaultBlockScanLimit();
Chad Rosierd7634fc2015-12-11 18:39:41 +00001095 while (InstDep.isDef() || InstDep.isClobber()) {
1096 // Get the memory clobbered by the instruction we depend on. MemDep will
1097 // skip any instructions that 'Loc' clearly doesn't interact with. If we
1098 // end up depending on a may- or must-aliased load, then we can't optimize
Chad Rosier844e2df2016-06-15 21:41:22 +00001099 // away the store and we bail out. However, if we depend on something
Chad Rosierd7634fc2015-12-11 18:39:41 +00001100 // that overwrites the memory location we *can* potentially optimize it.
1101 //
1102 // Find out what memory location the dependent instruction stores.
1103 Instruction *DepWrite = InstDep.getInst();
Philip Reamesf57714c2018-01-21 02:10:54 +00001104 if (!hasAnalyzableMemoryWrite(DepWrite, *TLI))
1105 break;
1106 MemoryLocation DepLoc = getLocForWrite(DepWrite);
Chad Rosierd7634fc2015-12-11 18:39:41 +00001107 // If we didn't get a useful location, or if it isn't a size, bail out.
1108 if (!DepLoc.Ptr)
1109 break;
1110
Eli Friedmana6707f52016-08-12 01:09:53 +00001111 // Make sure we don't look past a call which might throw. This is an
1112 // issue because MemoryDependenceAnalysis works in the wrong direction:
1113 // it finds instructions which dominate the current instruction, rather than
1114 // instructions which are post-dominated by the current instruction.
1115 //
1116 // If the underlying object is a non-escaping memory allocation, any store
1117 // to it is dead along the unwind edge. Otherwise, we need to preserve
1118 // the store.
1119 size_t DepIndex = InstrOrdering.lookup(DepWrite);
1120 assert(DepIndex && "Unexpected instruction");
1121 if (DepIndex <= LastThrowingInstIndex) {
1122 const Value* Underlying = GetUnderlyingObject(DepLoc.Ptr, DL);
1123 bool IsStoreDeadOnUnwind = isa<AllocaInst>(Underlying);
1124 if (!IsStoreDeadOnUnwind) {
1125 // We're looking for a call to an allocation function
1126 // where the allocation doesn't escape before the last
1127 // throwing instruction; PointerMayBeCaptured
1128 // reasonably fast approximation.
1129 IsStoreDeadOnUnwind = isAllocLikeFn(Underlying, TLI) &&
1130 !PointerMayBeCaptured(Underlying, false, true);
1131 }
1132 if (!IsStoreDeadOnUnwind)
1133 break;
1134 }
1135
Chad Rosierd7634fc2015-12-11 18:39:41 +00001136 // If we find a write that is a) removable (i.e., non-volatile), b) is
1137 // completely obliterated by the store to 'Loc', and c) which we know that
1138 // 'Inst' doesn't load from, then we can remove it.
Sanjay Patel1d04b5b2017-09-26 13:54:28 +00001139 // Also try to merge two stores if a later one only touches memory written
1140 // to by the earlier one.
Chad Rosierd7634fc2015-12-11 18:39:41 +00001141 if (isRemovable(DepWrite) &&
1142 !isPossibleSelfRead(Inst, Loc, DepWrite, *TLI, *AA)) {
1143 int64_t InstWriteOffset, DepWriteOffset;
1144 OverwriteResult OR =
Hal Finkela1271032016-06-23 13:46:39 +00001145 isOverwrite(Loc, DepLoc, DL, *TLI, DepWriteOffset, InstWriteOffset,
1146 DepWrite, IOL);
Filipe Cabecinhas8b942732017-03-29 14:42:27 +00001147 if (OR == OW_Complete) {
Chad Rosierd7634fc2015-12-11 18:39:41 +00001148 DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: "
1149 << *DepWrite << "\n KILLER: " << *Inst << '\n');
Alexander Kornienko63dd36f2016-07-18 15:51:31 +00001150
Chad Rosierd7634fc2015-12-11 18:39:41 +00001151 // Delete the store and now-dead instructions that feed it.
Eli Friedmana6707f52016-08-12 01:09:53 +00001152 deleteDeadInstruction(DepWrite, &BBI, *MD, *TLI, IOL, &InstrOrdering);
Chad Rosierd7634fc2015-12-11 18:39:41 +00001153 ++NumFastStores;
1154 MadeChange = true;
1155
Chad Rosierdcfce2d2016-07-06 19:48:52 +00001156 // We erased DepWrite; start over.
1157 InstDep = MD->getDependency(Inst);
1158 continue;
Filipe Cabecinhas8b942732017-03-29 14:42:27 +00001159 } else if ((OR == OW_End && isShortenableAtTheEnd(DepWrite)) ||
1160 ((OR == OW_Begin &&
Jun Bum Limd29a24e2016-04-22 19:51:29 +00001161 isShortenableAtTheBeginning(DepWrite)))) {
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +00001162 assert(!EnablePartialOverwriteTracking && "Do not expect to perform "
1163 "when partial-overwrite "
1164 "tracking is enabled");
1165 int64_t EarlierSize = DepLoc.Size;
1166 int64_t LaterSize = Loc.Size;
Filipe Cabecinhas8b942732017-03-29 14:42:27 +00001167 bool IsOverwriteEnd = (OR == OW_End);
Jun Bum Lima0331392016-07-27 17:25:20 +00001168 MadeChange |= tryToShorten(DepWrite, DepWriteOffset, EarlierSize,
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +00001169 InstWriteOffset, LaterSize, IsOverwriteEnd);
Sanjay Patel1d04b5b2017-09-26 13:54:28 +00001170 } else if (EnablePartialStoreMerging &&
1171 OR == OW_PartialEarlierWithFullLater) {
1172 auto *Earlier = dyn_cast<StoreInst>(DepWrite);
1173 auto *Later = dyn_cast<StoreInst>(Inst);
1174 if (Earlier && isa<ConstantInt>(Earlier->getValueOperand()) &&
Sanjay Patel1aef27f2018-01-30 13:53:59 +00001175 Later && isa<ConstantInt>(Later->getValueOperand()) &&
1176 memoryIsNotModifiedBetween(Earlier, Later, AA)) {
Sanjay Patel1d04b5b2017-09-26 13:54:28 +00001177 // If the store we find is:
1178 // a) partially overwritten by the store to 'Loc'
1179 // b) the later store is fully contained in the earlier one and
1180 // c) they both have a constant value
1181 // Merge the two stores, replacing the earlier store's value with a
1182 // merge of both values.
1183 // TODO: Deal with other constant types (vectors, etc), and probably
1184 // some mem intrinsics (if needed)
1185
1186 APInt EarlierValue =
1187 cast<ConstantInt>(Earlier->getValueOperand())->getValue();
1188 APInt LaterValue =
1189 cast<ConstantInt>(Later->getValueOperand())->getValue();
1190 unsigned LaterBits = LaterValue.getBitWidth();
1191 assert(EarlierValue.getBitWidth() > LaterValue.getBitWidth());
1192 LaterValue = LaterValue.zext(EarlierValue.getBitWidth());
1193
1194 // Offset of the smaller store inside the larger store
1195 unsigned BitOffsetDiff = (InstWriteOffset - DepWriteOffset) * 8;
1196 unsigned LShiftAmount =
1197 DL.isBigEndian()
1198 ? EarlierValue.getBitWidth() - BitOffsetDiff - LaterBits
1199 : BitOffsetDiff;
1200 APInt Mask =
1201 APInt::getBitsSet(EarlierValue.getBitWidth(), LShiftAmount,
1202 LShiftAmount + LaterBits);
1203 // Clear the bits we'll be replacing, then OR with the smaller
1204 // store, shifted appropriately.
1205 APInt Merged =
1206 (EarlierValue & ~Mask) | (LaterValue << LShiftAmount);
1207 DEBUG(dbgs() << "DSE: Merge Stores:\n Earlier: " << *DepWrite
1208 << "\n Later: " << *Inst
1209 << "\n Merged Value: " << Merged << '\n');
1210
1211 auto *SI = new StoreInst(
1212 ConstantInt::get(Earlier->getValueOperand()->getType(), Merged),
1213 Earlier->getPointerOperand(), false, Earlier->getAlignment(),
1214 Earlier->getOrdering(), Earlier->getSyncScopeID(), DepWrite);
1215
1216 unsigned MDToKeep[] = {LLVMContext::MD_dbg, LLVMContext::MD_tbaa,
1217 LLVMContext::MD_alias_scope,
1218 LLVMContext::MD_noalias,
1219 LLVMContext::MD_nontemporal};
1220 SI->copyMetadata(*DepWrite, MDToKeep);
1221 ++NumModifiedStores;
1222
1223 // Remove earlier, wider, store
1224 size_t Idx = InstrOrdering.lookup(DepWrite);
1225 InstrOrdering.erase(DepWrite);
1226 InstrOrdering.insert(std::make_pair(SI, Idx));
1227
1228 // Delete the old stores and now-dead instructions that feed them.
1229 deleteDeadInstruction(Inst, &BBI, *MD, *TLI, IOL, &InstrOrdering);
1230 deleteDeadInstruction(DepWrite, &BBI, *MD, *TLI, IOL,
1231 &InstrOrdering);
1232 MadeChange = true;
1233
1234 // We erased DepWrite and Inst (Loc); start over.
1235 break;
1236 }
Pete Cooper856977c2011-11-09 23:07:35 +00001237 }
Chris Lattner58b779e2010-11-30 07:23:21 +00001238 }
Chad Rosierd7634fc2015-12-11 18:39:41 +00001239
1240 // If this is a may-aliased store that is clobbering the store value, we
1241 // can keep searching past it for another must-aliased pointer that stores
1242 // to the same location. For example, in:
1243 // store -> P
1244 // store -> Q
1245 // store -> P
1246 // we can remove the first store to P even though we don't know if P and Q
1247 // alias.
1248 if (DepWrite == &BB.front()) break;
1249
1250 // Can't look past this instruction if it might read 'Loc'.
Alina Sbirlea63d22502017-12-05 20:12:23 +00001251 if (isRefSet(AA->getModRefInfo(DepWrite, Loc)))
Chad Rosierd7634fc2015-12-11 18:39:41 +00001252 break;
1253
Bob Haarman3db17642016-08-26 16:34:27 +00001254 InstDep = MD->getPointerDependencyFrom(Loc, /*isLoad=*/ false,
1255 DepWrite->getIterator(), &BB,
1256 /*QueryInst=*/ nullptr, &Limit);
Owen Anderson2b2bd282009-10-28 07:05:35 +00001257 }
Owen Anderson5e72db32007-07-11 00:46:18 +00001258 }
Owen Anderson58704ee2011-09-06 18:14:09 +00001259
Jun Bum Lim6a7dc5c2016-07-22 18:27:24 +00001260 if (EnablePartialOverwriteTracking)
1261 MadeChange |= removePartiallyOverlappedStores(AA, DL, IOL);
1262
Chris Lattnerf2a8ba42008-11-28 21:29:52 +00001263 // If this block ends in a return, unwind, or unreachable, all allocas are
1264 // dead at its end, which means stores to them are also dead.
Owen Anderson32c4a052007-07-12 21:41:30 +00001265 if (BB.getTerminator()->getNumSuccessors() == 0)
Eli Friedmana6707f52016-08-12 01:09:53 +00001266 MadeChange |= handleEndBlock(BB, AA, MD, TLI, IOL, &InstrOrdering);
Owen Anderson58704ee2011-09-06 18:14:09 +00001267
Owen Anderson5e72db32007-07-11 00:46:18 +00001268 return MadeChange;
1269}
1270
Justin Bogner594e07b2016-05-17 21:38:13 +00001271static bool eliminateDeadStores(Function &F, AliasAnalysis *AA,
1272 MemoryDependenceResults *MD, DominatorTree *DT,
1273 const TargetLibraryInfo *TLI) {
Eli Friedman7d58bc72011-06-15 00:47:34 +00001274 bool MadeChange = false;
Justin Bogner594e07b2016-05-17 21:38:13 +00001275 for (BasicBlock &BB : F)
1276 // Only check non-dead blocks. Dead blocks may have strange pointer
1277 // cycles that will confuse alias analysis.
1278 if (DT->isReachableFromEntry(&BB))
1279 MadeChange |= eliminateDeadStores(BB, AA, MD, DT, TLI);
Eli Friedmana6707f52016-08-12 01:09:53 +00001280
Eli Friedman7d58bc72011-06-15 00:47:34 +00001281 return MadeChange;
Owen Andersonaa071722007-07-11 23:19:17 +00001282}
1283
Justin Bogner594e07b2016-05-17 21:38:13 +00001284//===----------------------------------------------------------------------===//
1285// DSE Pass
1286//===----------------------------------------------------------------------===//
1287PreservedAnalyses DSEPass::run(Function &F, FunctionAnalysisManager &AM) {
1288 AliasAnalysis *AA = &AM.getResult<AAManager>(F);
1289 DominatorTree *DT = &AM.getResult<DominatorTreeAnalysis>(F);
1290 MemoryDependenceResults *MD = &AM.getResult<MemoryDependenceAnalysis>(F);
1291 const TargetLibraryInfo *TLI = &AM.getResult<TargetLibraryAnalysis>(F);
Owen Anderson58704ee2011-09-06 18:14:09 +00001292
Justin Bogner594e07b2016-05-17 21:38:13 +00001293 if (!eliminateDeadStores(F, AA, MD, DT, TLI))
1294 return PreservedAnalyses::all();
Chandler Carruthca68a3e2017-01-15 06:32:49 +00001295
Justin Bogner594e07b2016-05-17 21:38:13 +00001296 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +00001297 PA.preserveSet<CFGAnalyses>();
Justin Bogner594e07b2016-05-17 21:38:13 +00001298 PA.preserve<GlobalsAA>();
1299 PA.preserve<MemoryDependenceAnalysis>();
1300 return PA;
Owen Anderson32c4a052007-07-12 21:41:30 +00001301}
1302
Benjamin Kramer4d098922016-07-10 11:28:51 +00001303namespace {
Eugene Zelenko3b879392017-10-13 21:17:07 +00001304
Justin Bogner594e07b2016-05-17 21:38:13 +00001305/// A legacy pass for the legacy pass manager that wraps \c DSEPass.
1306class DSELegacyPass : public FunctionPass {
1307public:
Eugene Zelenko3b879392017-10-13 21:17:07 +00001308 static char ID; // Pass identification, replacement for typeid
1309
Justin Bogner594e07b2016-05-17 21:38:13 +00001310 DSELegacyPass() : FunctionPass(ID) {
1311 initializeDSELegacyPassPass(*PassRegistry::getPassRegistry());
Owen Andersonddf4aee2007-08-08 18:38:28 +00001312 }
Owen Anderson58704ee2011-09-06 18:14:09 +00001313
Justin Bogner594e07b2016-05-17 21:38:13 +00001314 bool runOnFunction(Function &F) override {
1315 if (skipFunction(F))
1316 return false;
1317
1318 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1319 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1320 MemoryDependenceResults *MD =
1321 &getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
1322 const TargetLibraryInfo *TLI =
1323 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1324
1325 return eliminateDeadStores(F, AA, MD, DT, TLI);
1326 }
1327
1328 void getAnalysisUsage(AnalysisUsage &AU) const override {
1329 AU.setPreservesCFG();
1330 AU.addRequired<DominatorTreeWrapperPass>();
1331 AU.addRequired<AAResultsWrapperPass>();
1332 AU.addRequired<MemoryDependenceWrapperPass>();
1333 AU.addRequired<TargetLibraryInfoWrapperPass>();
1334 AU.addPreserved<DominatorTreeWrapperPass>();
1335 AU.addPreserved<GlobalsAAWrapperPass>();
1336 AU.addPreserved<MemoryDependenceWrapperPass>();
1337 }
Justin Bogner594e07b2016-05-17 21:38:13 +00001338};
Eugene Zelenko3b879392017-10-13 21:17:07 +00001339
Benjamin Kramer4d098922016-07-10 11:28:51 +00001340} // end anonymous namespace
Justin Bogner594e07b2016-05-17 21:38:13 +00001341
1342char DSELegacyPass::ID = 0;
Eugene Zelenko3b879392017-10-13 21:17:07 +00001343
Justin Bogner594e07b2016-05-17 21:38:13 +00001344INITIALIZE_PASS_BEGIN(DSELegacyPass, "dse", "Dead Store Elimination", false,
1345 false)
1346INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1347INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
1348INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
1349INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
1350INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1351INITIALIZE_PASS_END(DSELegacyPass, "dse", "Dead Store Elimination", false,
1352 false)
1353
1354FunctionPass *llvm::createDeadStoreEliminationPass() {
1355 return new DSELegacyPass();
Owen Anderson32c4a052007-07-12 21:41:30 +00001356}