blob: fb51333560df736f2f751954bb28f0a8b97165f5 [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//
10// 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.
15//
16//===----------------------------------------------------------------------===//
17
Owen Anderson10e52ed2007-08-01 06:36:51 +000018#define DEBUG_TYPE "dse"
Owen Anderson5e72db32007-07-11 00:46:18 +000019#include "llvm/Transforms/Scalar.h"
Owen Anderson32c4a052007-07-12 21:41:30 +000020#include "llvm/Constants.h"
Owen Anderson5e72db32007-07-11 00:46:18 +000021#include "llvm/Function.h"
22#include "llvm/Instructions.h"
Owen Anderson48d37802008-01-29 06:18:36 +000023#include "llvm/IntrinsicInst.h"
Owen Anderson5e72db32007-07-11 00:46:18 +000024#include "llvm/Pass.h"
Owen Anderson5e72db32007-07-11 00:46:18 +000025#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/ADT/Statistic.h"
Owen Andersonaa071722007-07-11 23:19:17 +000027#include "llvm/Analysis/AliasAnalysis.h"
Owen Anderson3f338972008-07-28 16:14:26 +000028#include "llvm/Analysis/Dominators.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"
Owen Andersonaa071722007-07-11 23:19:17 +000031#include "llvm/Target/TargetData.h"
Owen Anderson5e72db32007-07-11 00:46:18 +000032#include "llvm/Transforms/Utils/Local.h"
Owen Anderson5e72db32007-07-11 00:46:18 +000033using namespace llvm;
34
35STATISTIC(NumFastStores, "Number of stores deleted");
36STATISTIC(NumFastOther , "Number of other instrs removed");
37
38namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +000039 struct DSE : public FunctionPass {
Chris Lattner51c28a92010-11-30 19:34:42 +000040 AliasAnalysis *AA;
41 MemoryDependenceAnalysis *MD;
42
Owen Anderson5e72db32007-07-11 00:46:18 +000043 static char ID; // Pass identification, replacement for typeid
Chris Lattner51c28a92010-11-30 19:34:42 +000044 DSE() : FunctionPass(ID), AA(0), MD(0) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +000045 initializeDSEPass(*PassRegistry::getPassRegistry());
46 }
Owen Anderson5e72db32007-07-11 00:46:18 +000047
48 virtual bool runOnFunction(Function &F) {
Chris Lattner51c28a92010-11-30 19:34:42 +000049 AA = &getAnalysis<AliasAnalysis>();
50 MD = &getAnalysis<MemoryDependenceAnalysis>();
Chris Lattnerc053cbb2010-02-11 05:11:54 +000051 DominatorTree &DT = getAnalysis<DominatorTree>();
52
Chris Lattner51c28a92010-11-30 19:34:42 +000053 bool Changed = false;
Owen Anderson5e72db32007-07-11 00:46:18 +000054 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
Chris Lattnerc053cbb2010-02-11 05:11:54 +000055 // Only check non-dead blocks. Dead blocks may have strange pointer
56 // cycles that will confuse alias analysis.
57 if (DT.isReachableFromEntry(I))
58 Changed |= runOnBasicBlock(*I);
Chris Lattner51c28a92010-11-30 19:34:42 +000059
60 AA = 0; MD = 0;
Owen Anderson5e72db32007-07-11 00:46:18 +000061 return Changed;
62 }
Chris Lattnerde04e112008-11-29 01:43:36 +000063
Owen Anderson5e72db32007-07-11 00:46:18 +000064 bool runOnBasicBlock(BasicBlock &BB);
Chris Lattner9d179d92010-11-30 01:28:33 +000065 bool HandleFree(CallInst *F);
Chris Lattner1adb6752008-11-28 00:27:14 +000066 bool handleEndBlock(BasicBlock &BB);
Dan Gohmanf372cf82010-10-19 22:54:46 +000067 bool RemoveUndeadPointers(Value *Ptr, uint64_t killPointerSize,
Nick Lewycky475d3d12010-01-03 04:39:07 +000068 BasicBlock::iterator &BBI,
69 SmallPtrSet<Value*, 64> &deadPointers);
Chris Lattner1adb6752008-11-28 00:27:14 +000070 void DeleteDeadInstruction(Instruction *I,
71 SmallPtrSet<Value*, 64> *deadPointers = 0);
72
Owen Anderson5e72db32007-07-11 00:46:18 +000073
74 // getAnalysisUsage - We require post dominance frontiers (aka Control
75 // Dependence Graph)
76 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
77 AU.setPreservesCFG();
Owen Anderson3f338972008-07-28 16:14:26 +000078 AU.addRequired<DominatorTree>();
Owen Andersonaa071722007-07-11 23:19:17 +000079 AU.addRequired<AliasAnalysis>();
Owen Anderson5e72db32007-07-11 00:46:18 +000080 AU.addRequired<MemoryDependenceAnalysis>();
Chris Lattner51c28a92010-11-30 19:34:42 +000081 AU.addPreserved<AliasAnalysis>();
Owen Anderson3f338972008-07-28 16:14:26 +000082 AU.addPreserved<DominatorTree>();
Owen Anderson5e72db32007-07-11 00:46:18 +000083 AU.addPreserved<MemoryDependenceAnalysis>();
84 }
85 };
Owen Anderson5e72db32007-07-11 00:46:18 +000086}
87
Dan Gohmand78c4002008-05-13 00:00:25 +000088char DSE::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +000089INITIALIZE_PASS_BEGIN(DSE, "dse", "Dead Store Elimination", false, false)
90INITIALIZE_PASS_DEPENDENCY(DominatorTree)
91INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
92INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
93INITIALIZE_PASS_END(DSE, "dse", "Dead Store Elimination", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +000094
Owen Anderson10e52ed2007-08-01 06:36:51 +000095FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
Owen Anderson5e72db32007-07-11 00:46:18 +000096
Chris Lattner2227a8a2010-11-30 01:37:52 +000097/// hasMemoryWrite - Does this instruction write some memory? This only returns
98/// true for things that we can analyze with other helpers below.
99static bool hasMemoryWrite(Instruction *I) {
Nick Lewycky90271472009-11-10 06:46:40 +0000100 if (isa<StoreInst>(I))
101 return true;
102 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
103 switch (II->getIntrinsicID()) {
Chris Lattner2764b4d2009-12-02 06:35:55 +0000104 default:
105 return false;
106 case Intrinsic::memset:
107 case Intrinsic::memmove:
108 case Intrinsic::memcpy:
109 case Intrinsic::init_trampoline:
110 case Intrinsic::lifetime_end:
111 return true;
Nick Lewycky90271472009-11-10 06:46:40 +0000112 }
113 }
114 return false;
115}
116
Chris Lattner58b779e2010-11-30 07:23:21 +0000117/// getLocForWrite - Return a Location stored to by the specified instruction.
118static AliasAnalysis::Location
119getLocForWrite(Instruction *Inst, AliasAnalysis &AA) {
120 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
121 return AA.getLocation(SI);
122
123 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(Inst)) {
124 // memcpy/memmove/memset.
125 AliasAnalysis::Location Loc = AA.getLocationForDest(MI);
126 // If we don't have target data around, an unknown size in Location means
127 // that we should use the size of the pointee type. This isn't valid for
128 // memset/memcpy, which writes more than an i8.
129 if (Loc.Size == AliasAnalysis::UnknownSize && AA.getTargetData() == 0)
130 return AliasAnalysis::Location();
131 return Loc;
132 }
133
134 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
135 if (II == 0) return AliasAnalysis::Location();
136
137 switch (II->getIntrinsicID()) {
138 default: return AliasAnalysis::Location(); // Unhandled intrinsic.
139 case Intrinsic::init_trampoline:
140 // If we don't have target data around, an unknown size in Location means
141 // that we should use the size of the pointee type. This isn't valid for
142 // init.trampoline, which writes more than an i8.
143 if (AA.getTargetData() == 0) return AliasAnalysis::Location();
144
145 // FIXME: We don't know the size of the trampoline, so we can't really
146 // handle it here.
147 return AliasAnalysis::Location(II->getArgOperand(0));
148 case Intrinsic::lifetime_end: {
149 uint64_t Len = cast<ConstantInt>(II->getArgOperand(0))->getZExtValue();
150 return AliasAnalysis::Location(II->getArgOperand(1), Len);
151 }
152 }
153}
154
Chris Lattner3590ef82010-11-30 05:30:45 +0000155/// isRemovable - If the value of this instruction and the memory it writes to
156/// is unused, may we delete this instruction?
157static bool isRemovable(Instruction *I) {
Chris Lattnerb63ba732010-11-30 19:12:10 +0000158 // Don't remove volatile stores.
Nick Lewycky90271472009-11-10 06:46:40 +0000159 if (StoreInst *SI = dyn_cast<StoreInst>(I))
160 return !SI->isVolatile();
Chris Lattnerb63ba732010-11-30 19:12:10 +0000161
162 IntrinsicInst *II = cast<IntrinsicInst>(I);
163 switch (II->getIntrinsicID()) {
164 default: assert(0 && "doesn't pass 'hasMemoryWrite' predicate");
165 case Intrinsic::lifetime_end:
166 // Never remove dead lifetime_end's, e.g. because it is followed by a
167 // free.
168 return false;
169 case Intrinsic::init_trampoline:
170 // Always safe to remove init_trampoline.
171 return true;
172
173 case Intrinsic::memset:
174 case Intrinsic::memmove:
175 case Intrinsic::memcpy:
176 // Don't remove volatile memory intrinsics.
177 return !cast<MemIntrinsic>(II)->isVolatile();
178 }
Nick Lewycky90271472009-11-10 06:46:40 +0000179}
180
Chris Lattner9d179d92010-11-30 01:28:33 +0000181/// getPointerOperand - Return the pointer that is being written to.
Nick Lewycky90271472009-11-10 06:46:40 +0000182static Value *getPointerOperand(Instruction *I) {
Chris Lattner2227a8a2010-11-30 01:37:52 +0000183 assert(hasMemoryWrite(I));
Nick Lewycky90271472009-11-10 06:46:40 +0000184 if (StoreInst *SI = dyn_cast<StoreInst>(I))
185 return SI->getPointerOperand();
186 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
Gabor Greif91f95892010-06-24 12:03:56 +0000187 return MI->getArgOperand(0);
188
189 IntrinsicInst *II = cast<IntrinsicInst>(I);
190 switch (II->getIntrinsicID()) {
Chris Lattner2764b4d2009-12-02 06:35:55 +0000191 default: assert(false && "Unexpected intrinsic!");
192 case Intrinsic::init_trampoline:
Gabor Greif91f95892010-06-24 12:03:56 +0000193 return II->getArgOperand(0);
Eric Christopher7258dcd2010-04-16 23:37:20 +0000194 case Intrinsic::lifetime_end:
Gabor Greif91f95892010-06-24 12:03:56 +0000195 return II->getArgOperand(1);
Duncan Sands1925d3a2009-11-10 13:49:50 +0000196 }
Nick Lewycky90271472009-11-10 06:46:40 +0000197}
198
Chris Lattner51c28a92010-11-30 19:34:42 +0000199static uint64_t getPointerSize(Value *V, AliasAnalysis &AA) {
200 const TargetData *TD = AA.getTargetData();
201 if (TD == 0)
202 return AliasAnalysis::UnknownSize;
203
204 if (AllocaInst *A = dyn_cast<AllocaInst>(V)) {
205 // Get size information for the alloca
206 if (ConstantInt *C = dyn_cast<ConstantInt>(A->getArraySize()))
207 return C->getZExtValue() * TD->getTypeAllocSize(A->getAllocatedType());
208 return AliasAnalysis::UnknownSize;
209 }
210
211 assert(isa<Argument>(V) && "Expected AllocaInst or Argument!");
212 const PointerType *PT = cast<PointerType>(V->getType());
213 return TD->getTypeAllocSize(PT->getElementType());
214}
215
216
Chris Lattner58b779e2010-11-30 07:23:21 +0000217/// isCompleteOverwrite - Return true if a store to the 'Later' location
218/// completely overwrites a store to the 'Earlier' location.
219static bool isCompleteOverwrite(const AliasAnalysis::Location &Later,
220 const AliasAnalysis::Location &Earlier,
Chris Lattner77d79fa2010-11-30 19:28:23 +0000221 AliasAnalysis &AA) {
Chris Lattner58b779e2010-11-30 07:23:21 +0000222 const Value *P1 = Later.Ptr->stripPointerCasts();
223 const Value *P2 = Earlier.Ptr->stripPointerCasts();
224
225 // Make sure that the start pointers are the same.
226 if (P1 != P2)
227 return false;
Nick Lewycky90271472009-11-10 06:46:40 +0000228
Chris Lattner77d79fa2010-11-30 19:28:23 +0000229 // If we don't know the sizes of either access, then we can't do a comparison.
230 if (Later.Size == AliasAnalysis::UnknownSize ||
231 Earlier.Size == AliasAnalysis::UnknownSize) {
232 // If we have no TargetData information around, then the size of the store
233 // is inferrable from the pointee type. If they are the same type, then we
234 // know that the store is safe.
235 if (AA.getTargetData() == 0)
236 return Later.Ptr->getType() == Earlier.Ptr->getType();
237 return false;
238 }
Chris Lattner58b779e2010-11-30 07:23:21 +0000239
240 // Make sure that the Later size is >= the Earlier size.
241 if (Later.Size < Earlier.Size)
242 return false;
243
244 return true;
Nick Lewycky90271472009-11-10 06:46:40 +0000245}
246
Owen Anderson10e52ed2007-08-01 06:36:51 +0000247bool DSE::runOnBasicBlock(BasicBlock &BB) {
Owen Anderson5e72db32007-07-11 00:46:18 +0000248 bool MadeChange = false;
249
Chris Lattner49162672009-09-02 06:31:02 +0000250 // Do a top-down walk on the BB.
Chris Lattnerf2a8ba42008-11-28 21:29:52 +0000251 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
252 Instruction *Inst = BBI++;
253
Chris Lattner9d179d92010-11-30 01:28:33 +0000254 // Handle 'free' calls specially.
255 if (CallInst *F = isFreeCall(Inst)) {
256 MadeChange |= HandleFree(F);
257 continue;
258 }
259
Chris Lattner2227a8a2010-11-30 01:37:52 +0000260 // If we find something that writes memory, get its memory dependence.
261 if (!hasMemoryWrite(Inst))
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000262 continue;
Chris Lattnerd4f10902010-11-30 00:01:19 +0000263
Chris Lattner51c28a92010-11-30 19:34:42 +0000264 MemDepResult InstDep = MD->getDependency(Inst);
Chris Lattnerf2a8ba42008-11-28 21:29:52 +0000265
Chris Lattnerd4f10902010-11-30 00:01:19 +0000266 // Ignore non-local store liveness.
Chris Lattner57e91ea2008-12-06 00:53:22 +0000267 // FIXME: cross-block DSE would be fun. :)
Chris Lattner58b779e2010-11-30 07:23:21 +0000268 if (InstDep.isNonLocal() ||
269 // Ignore self dependence, which happens in the entry block of the
270 // function.
271 InstDep.getInst() == Inst)
272 continue;
Chris Lattner9d179d92010-11-30 01:28:33 +0000273
Chris Lattner57e91ea2008-12-06 00:53:22 +0000274 // If we're storing the same value back to a pointer that we just
275 // loaded from, then the store can be removed.
Nick Lewycky90271472009-11-10 06:46:40 +0000276 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
277 if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
278 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
Chris Lattnerc3c754f2010-11-30 00:12:39 +0000279 SI->getOperand(0) == DepLoad && !SI->isVolatile()) {
Nick Lewycky90271472009-11-10 06:46:40 +0000280 // DeleteDeadInstruction can delete the current instruction. Save BBI
281 // in case we need it.
282 WeakVH NextInst(BBI);
283
284 DeleteDeadInstruction(SI);
285
286 if (NextInst == 0) // Next instruction deleted.
287 BBI = BB.begin();
288 else if (BBI != BB.begin()) // Revisit this instruction if possible.
289 --BBI;
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000290 ++NumFastStores;
Nick Lewycky90271472009-11-10 06:46:40 +0000291 MadeChange = true;
292 continue;
293 }
Chris Lattner0e3d6332008-12-05 21:04:20 +0000294 }
Owen Anderson5e72db32007-07-11 00:46:18 +0000295 }
Chris Lattner3590ef82010-11-30 05:30:45 +0000296
Chris Lattner58b779e2010-11-30 07:23:21 +0000297 // Figure out what location is being stored to.
Chris Lattner51c28a92010-11-30 19:34:42 +0000298 AliasAnalysis::Location Loc = getLocForWrite(Inst, *AA);
Chris Lattner58b779e2010-11-30 07:23:21 +0000299
300 // If we didn't get a useful location, fail.
301 if (Loc.Ptr == 0)
302 continue;
303
304 while (!InstDep.isNonLocal()) {
305 // Get the memory clobbered by the instruction we depend on. MemDep will
306 // skip any instructions that 'Loc' clearly doesn't interact with. If we
307 // end up depending on a may- or must-aliased load, then we can't optimize
308 // away the store and we bail out. However, if we depend on on something
309 // that overwrites the memory location we *can* potentially optimize it.
310 //
311 // Find out what memory location the dependant instruction stores.
312 Instruction *DepWrite = InstDep.getInst();
Chris Lattner51c28a92010-11-30 19:34:42 +0000313 AliasAnalysis::Location DepLoc = getLocForWrite(DepWrite, *AA);
Chris Lattner58b779e2010-11-30 07:23:21 +0000314 // If we didn't get a useful location, or if it isn't a size, bail out.
315 if (DepLoc.Ptr == 0)
316 break;
317
318 // If we find a removable write that is completely obliterated by the
319 // store to 'Loc' then we can remove it.
Chris Lattner51c28a92010-11-30 19:34:42 +0000320 if (isRemovable(DepWrite) && isCompleteOverwrite(Loc, DepLoc, *AA)) {
Chris Lattner58b779e2010-11-30 07:23:21 +0000321 // Delete the store and now-dead instructions that feed it.
322 DeleteDeadInstruction(DepWrite);
323 ++NumFastStores;
324 MadeChange = true;
325
326 // DeleteDeadInstruction can delete the current instruction in loop
327 // cases, reset BBI.
328 BBI = Inst;
329 if (BBI != BB.begin())
330 --BBI;
331 break;
332 }
333
Chris Lattnerd4f10902010-11-30 00:01:19 +0000334 // If this is a may-aliased store that is clobbering the store value, we
335 // can keep searching past it for another must-aliased pointer that stores
336 // to the same location. For example, in:
337 // store -> P
338 // store -> Q
339 // store -> P
340 // we can remove the first store to P even though we don't know if P and Q
341 // alias.
Chris Lattner58b779e2010-11-30 07:23:21 +0000342 if (DepWrite == &BB.front()) break;
343
344 // Can't look past this instruction if it might read 'Loc'.
Chris Lattner51c28a92010-11-30 19:34:42 +0000345 if (AA->getModRefInfo(DepWrite, Loc) & AliasAnalysis::Ref)
Chris Lattner58b779e2010-11-30 07:23:21 +0000346 break;
Chris Lattner3590ef82010-11-30 05:30:45 +0000347
Chris Lattner51c28a92010-11-30 19:34:42 +0000348 InstDep = MD->getPointerDependencyFrom(Loc, false, DepWrite, &BB);
Owen Anderson2b2bd282009-10-28 07:05:35 +0000349 }
Owen Anderson5e72db32007-07-11 00:46:18 +0000350 }
351
Chris Lattnerf2a8ba42008-11-28 21:29:52 +0000352 // If this block ends in a return, unwind, or unreachable, all allocas are
353 // dead at its end, which means stores to them are also dead.
Owen Anderson32c4a052007-07-12 21:41:30 +0000354 if (BB.getTerminator()->getNumSuccessors() == 0)
Chris Lattner1adb6752008-11-28 00:27:14 +0000355 MadeChange |= handleEndBlock(BB);
Owen Anderson5e72db32007-07-11 00:46:18 +0000356
357 return MadeChange;
358}
359
Chris Lattner9d179d92010-11-30 01:28:33 +0000360/// HandleFree - Handle frees of entire structures whose dependency is a store
361/// to a field of that structure.
362bool DSE::HandleFree(CallInst *F) {
Chris Lattner51c28a92010-11-30 19:34:42 +0000363 MemDepResult Dep = MD->getDependency(F);
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000364 do {
Chris Lattner9d179d92010-11-30 01:28:33 +0000365 if (Dep.isNonLocal()) return false;
366
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000367 Instruction *Dependency = Dep.getInst();
Chris Lattner3590ef82010-11-30 05:30:45 +0000368 if (!hasMemoryWrite(Dependency) || !isRemovable(Dependency))
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000369 return false;
Owen Andersond4451de2007-07-12 18:08:51 +0000370
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000371 Value *DepPointer = getPointerOperand(Dependency)->getUnderlyingObject();
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000372
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000373 // Check for aliasing.
Chris Lattner51c28a92010-11-30 19:34:42 +0000374 if (AA->alias(F->getArgOperand(0), 1, DepPointer, 1) !=
Chris Lattner9d179d92010-11-30 01:28:33 +0000375 AliasAnalysis::MustAlias)
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000376 return false;
Owen Andersonaa071722007-07-11 23:19:17 +0000377
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000378 // DCE instructions only used to calculate that store
379 DeleteDeadInstruction(Dependency);
380 ++NumFastStores;
381
382 // Inst's old Dependency is now deleted. Compute the next dependency,
383 // which may also be dead, as in
384 // s[0] = 0;
385 // s[1] = 0; // This has just been deleted.
386 // free(s);
Chris Lattner51c28a92010-11-30 19:34:42 +0000387 Dep = MD->getDependency(F);
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000388 } while (!Dep.isNonLocal());
Chris Lattner9d179d92010-11-30 01:28:33 +0000389
Chris Lattner1adb6752008-11-28 00:27:14 +0000390 return true;
Owen Andersonaa071722007-07-11 23:19:17 +0000391}
392
Owen Andersone3590582007-08-02 18:11:11 +0000393/// handleEndBlock - Remove dead stores to stack-allocated locations in the
Owen Anderson52aaabf2007-08-08 17:50:09 +0000394/// function end block. Ex:
395/// %A = alloca i32
396/// ...
397/// store i32 1, i32* %A
398/// ret void
Chris Lattner1adb6752008-11-28 00:27:14 +0000399bool DSE::handleEndBlock(BasicBlock &BB) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000400 bool MadeChange = false;
401
402 // Pointers alloca'd in this function are dead in the end block
Owen Anderson48d37802008-01-29 06:18:36 +0000403 SmallPtrSet<Value*, 64> deadPointers;
Owen Anderson32c4a052007-07-12 21:41:30 +0000404
Chris Lattner1adb6752008-11-28 00:27:14 +0000405 // Find all of the alloca'd pointers in the entry block.
Owen Anderson32c4a052007-07-12 21:41:30 +0000406 BasicBlock *Entry = BB.getParent()->begin();
407 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
408 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
409 deadPointers.insert(AI);
Chris Lattner1adb6752008-11-28 00:27:14 +0000410
411 // Treat byval arguments the same, stores to them are dead at the end of the
412 // function.
Owen Anderson48d37802008-01-29 06:18:36 +0000413 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
414 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
415 if (AI->hasByValAttr())
416 deadPointers.insert(AI);
Owen Anderson32c4a052007-07-12 21:41:30 +0000417
418 // Scan the basic block backwards
419 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
420 --BBI;
421
Chris Lattner1adb6752008-11-28 00:27:14 +0000422 // If we find a store whose pointer is dead.
Chris Lattner2227a8a2010-11-30 01:37:52 +0000423 if (hasMemoryWrite(BBI)) {
Chris Lattner3590ef82010-11-30 05:30:45 +0000424 if (isRemovable(BBI)) {
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000425 // See through pointer-to-pointer bitcasts
Nick Lewycky90271472009-11-10 06:46:40 +0000426 Value *pointerOperand = getPointerOperand(BBI)->getUnderlyingObject();
Duncan Sandsd65a4da2008-10-01 15:25:41 +0000427
Owen Anderson6af19fd2008-01-25 10:10:33 +0000428 // Alloca'd pointers or byval arguments (which are functionally like
429 // alloca's) are valid candidates for removal.
Owen Anderson48d37802008-01-29 06:18:36 +0000430 if (deadPointers.count(pointerOperand)) {
Chris Lattner1adb6752008-11-28 00:27:14 +0000431 // DCE instructions only used to calculate that store.
Nick Lewycky90271472009-11-10 06:46:40 +0000432 Instruction *Dead = BBI;
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000433 ++BBI;
Nick Lewycky90271472009-11-10 06:46:40 +0000434 DeleteDeadInstruction(Dead, &deadPointers);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000435 ++NumFastStores;
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000436 MadeChange = true;
Nick Lewycky90271472009-11-10 06:46:40 +0000437 continue;
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000438 }
Owen Anderson32c4a052007-07-12 21:41:30 +0000439 }
Owen Anderson52aaabf2007-08-08 17:50:09 +0000440
Nick Lewycky90271472009-11-10 06:46:40 +0000441 // Because a memcpy or memmove is also a load, we can't skip it if we
442 // didn't remove it.
443 if (!isa<MemTransferInst>(BBI))
Owen Anderson48d37802008-01-29 06:18:36 +0000444 continue;
Owen Anderson52aaabf2007-08-08 17:50:09 +0000445 }
446
Nick Lewycky475d3d12010-01-03 04:39:07 +0000447 Value *killPointer = 0;
Dan Gohmanf372cf82010-10-19 22:54:46 +0000448 uint64_t killPointerSize = AliasAnalysis::UnknownSize;
Owen Anderson32c4a052007-07-12 21:41:30 +0000449
450 // If we encounter a use of the pointer, it is no longer considered dead
Chris Lattner1adb6752008-11-28 00:27:14 +0000451 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
Nate Begeman53c5c622008-05-13 01:48:26 +0000452 // However, if this load is unused and not volatile, we can go ahead and
453 // remove it, and not have to worry about it making our pointer undead!
Dan Gohman8cb19d92008-04-28 19:51:27 +0000454 if (L->use_empty() && !L->isVolatile()) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000455 ++BBI;
Chris Lattner1adb6752008-11-28 00:27:14 +0000456 DeleteDeadInstruction(L, &deadPointers);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000457 ++NumFastOther;
Owen Anderson4e4b1162008-01-30 01:24:47 +0000458 MadeChange = true;
Owen Anderson4e4b1162008-01-30 01:24:47 +0000459 continue;
460 }
461
Owen Anderson32c4a052007-07-12 21:41:30 +0000462 killPointer = L->getPointerOperand();
Nick Lewycky475d3d12010-01-03 04:39:07 +0000463 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000464 killPointer = V->getOperand(0);
Nick Lewycky90271472009-11-10 06:46:40 +0000465 } else if (isa<MemTransferInst>(BBI) &&
466 isa<ConstantInt>(cast<MemTransferInst>(BBI)->getLength())) {
467 killPointer = cast<MemTransferInst>(BBI)->getSource();
Owen Andersona82c9932008-02-04 04:53:00 +0000468 killPointerSize = cast<ConstantInt>(
Nick Lewycky90271472009-11-10 06:46:40 +0000469 cast<MemTransferInst>(BBI)->getLength())->getZExtValue();
Nick Lewycky475d3d12010-01-03 04:39:07 +0000470 } else if (AllocaInst *A = dyn_cast<AllocaInst>(BBI)) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000471 deadPointers.erase(A);
Owen Anderson4e4b1162008-01-30 01:24:47 +0000472
473 // Dead alloca's can be DCE'd when we reach them
Nick Lewycky6b016702008-01-30 08:01:28 +0000474 if (A->use_empty()) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000475 ++BBI;
Chris Lattner1adb6752008-11-28 00:27:14 +0000476 DeleteDeadInstruction(A, &deadPointers);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000477 ++NumFastOther;
Owen Anderson4e4b1162008-01-30 01:24:47 +0000478 MadeChange = true;
Owen Anderson4e4b1162008-01-30 01:24:47 +0000479 }
480
Owen Anderson32c4a052007-07-12 21:41:30 +0000481 continue;
Gabor Greif0a970692010-07-28 14:28:18 +0000482 } else if (CallSite CS = cast<Value>(BBI)) {
Owen Anderson50df9682007-08-08 17:58:56 +0000483 // If this call does not access memory, it can't
484 // be undeadifying any of our pointers.
Chris Lattner51c28a92010-11-30 19:34:42 +0000485 if (AA->doesNotAccessMemory(CS))
Owen Anderson50df9682007-08-08 17:58:56 +0000486 continue;
487
Owen Andersonddf4aee2007-08-08 18:38:28 +0000488 unsigned modRef = 0;
489 unsigned other = 0;
490
Owen Anderson32c4a052007-07-12 21:41:30 +0000491 // Remove any pointers made undead by the call from the dead set
Owen Anderson48d37802008-01-29 06:18:36 +0000492 std::vector<Value*> dead;
493 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
Owen Anderson32c4a052007-07-12 21:41:30 +0000494 E = deadPointers.end(); I != E; ++I) {
Owen Andersonddf4aee2007-08-08 18:38:28 +0000495 // HACK: if we detect that our AA is imprecise, it's not
496 // worth it to scan the rest of the deadPointers set. Just
497 // assume that the AA will return ModRef for everything, and
498 // go ahead and bail.
499 if (modRef >= 16 && other == 0) {
500 deadPointers.clear();
501 return MadeChange;
502 }
Nick Lewycky475d3d12010-01-03 04:39:07 +0000503
Owen Anderson32c4a052007-07-12 21:41:30 +0000504 // See if the call site touches it
Chris Lattner77d79fa2010-11-30 19:28:23 +0000505 AliasAnalysis::ModRefResult A =
Chris Lattner51c28a92010-11-30 19:34:42 +0000506 AA->getModRefInfo(CS, *I, getPointerSize(*I, *AA));
Owen Andersonddf4aee2007-08-08 18:38:28 +0000507
508 if (A == AliasAnalysis::ModRef)
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000509 ++modRef;
Owen Andersonddf4aee2007-08-08 18:38:28 +0000510 else
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000511 ++other;
Owen Andersonddf4aee2007-08-08 18:38:28 +0000512
Owen Anderson9c9ef212007-07-13 18:26:26 +0000513 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
Owen Anderson32c4a052007-07-12 21:41:30 +0000514 dead.push_back(*I);
515 }
516
Owen Anderson48d37802008-01-29 06:18:36 +0000517 for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
Owen Anderson32c4a052007-07-12 21:41:30 +0000518 I != E; ++I)
Owen Anderson48d37802008-01-29 06:18:36 +0000519 deadPointers.erase(*I);
Owen Anderson32c4a052007-07-12 21:41:30 +0000520
521 continue;
Chris Lattner1adb6752008-11-28 00:27:14 +0000522 } else if (isInstructionTriviallyDead(BBI)) {
Owen Anderson4e4b1162008-01-30 01:24:47 +0000523 // For any non-memory-affecting non-terminators, DCE them as we reach them
Chris Lattner1adb6752008-11-28 00:27:14 +0000524 Instruction *Inst = BBI;
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000525 ++BBI;
Chris Lattner1adb6752008-11-28 00:27:14 +0000526 DeleteDeadInstruction(Inst, &deadPointers);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000527 ++NumFastOther;
Chris Lattner1adb6752008-11-28 00:27:14 +0000528 MadeChange = true;
529 continue;
Owen Anderson32c4a052007-07-12 21:41:30 +0000530 }
531
532 if (!killPointer)
533 continue;
Duncan Sandsd65a4da2008-10-01 15:25:41 +0000534
535 killPointer = killPointer->getUnderlyingObject();
536
Owen Anderson32c4a052007-07-12 21:41:30 +0000537 // Deal with undead pointers
Owen Andersona82c9932008-02-04 04:53:00 +0000538 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
Chris Lattner1adb6752008-11-28 00:27:14 +0000539 deadPointers);
Owen Anderson32c4a052007-07-12 21:41:30 +0000540 }
541
542 return MadeChange;
543}
544
Owen Andersonddf4aee2007-08-08 18:38:28 +0000545/// RemoveUndeadPointers - check for uses of a pointer that make it
546/// undead when scanning for dead stores to alloca's.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000547bool DSE::RemoveUndeadPointers(Value *killPointer, uint64_t killPointerSize,
Chris Lattner1adb6752008-11-28 00:27:14 +0000548 BasicBlock::iterator &BBI,
Nick Lewycky475d3d12010-01-03 04:39:07 +0000549 SmallPtrSet<Value*, 64> &deadPointers) {
Owen Andersonddf4aee2007-08-08 18:38:28 +0000550 // If the kill pointer can be easily reduced to an alloca,
Chris Lattner1adb6752008-11-28 00:27:14 +0000551 // don't bother doing extraneous AA queries.
Owen Anderson48d37802008-01-29 06:18:36 +0000552 if (deadPointers.count(killPointer)) {
553 deadPointers.erase(killPointer);
Owen Andersonddf4aee2007-08-08 18:38:28 +0000554 return false;
555 }
556
Chris Lattner1adb6752008-11-28 00:27:14 +0000557 // A global can't be in the dead pointer set.
558 if (isa<GlobalValue>(killPointer))
559 return false;
560
Owen Anderson32c4a052007-07-12 21:41:30 +0000561 bool MadeChange = false;
562
Chris Lattner1adb6752008-11-28 00:27:14 +0000563 SmallVector<Value*, 16> undead;
Nick Lewycky475d3d12010-01-03 04:39:07 +0000564
Owen Anderson48d37802008-01-29 06:18:36 +0000565 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
Nick Lewycky475d3d12010-01-03 04:39:07 +0000566 E = deadPointers.end(); I != E; ++I) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000567 // See if this pointer could alias it
Chris Lattner51c28a92010-11-30 19:34:42 +0000568 AliasAnalysis::AliasResult A = AA->alias(*I, getPointerSize(*I, *AA),
569 killPointer, killPointerSize);
Owen Anderson32c4a052007-07-12 21:41:30 +0000570
571 // If it must-alias and a store, we can delete it
572 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
Nick Lewycky475d3d12010-01-03 04:39:07 +0000573 StoreInst *S = cast<StoreInst>(BBI);
Owen Anderson32c4a052007-07-12 21:41:30 +0000574
575 // Remove it!
Nick Lewycky475d3d12010-01-03 04:39:07 +0000576 ++BBI;
Chris Lattner1adb6752008-11-28 00:27:14 +0000577 DeleteDeadInstruction(S, &deadPointers);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000578 ++NumFastStores;
Owen Anderson32c4a052007-07-12 21:41:30 +0000579 MadeChange = true;
580
581 continue;
582
583 // Otherwise, it is undead
Chris Lattner1adb6752008-11-28 00:27:14 +0000584 } else if (A != AliasAnalysis::NoAlias)
585 undead.push_back(*I);
Owen Anderson32c4a052007-07-12 21:41:30 +0000586 }
587
Chris Lattner1adb6752008-11-28 00:27:14 +0000588 for (SmallVector<Value*, 16>::iterator I = undead.begin(), E = undead.end();
Owen Anderson32c4a052007-07-12 21:41:30 +0000589 I != E; ++I)
Chris Lattner77d79fa2010-11-30 19:28:23 +0000590 deadPointers.erase(*I);
Owen Anderson32c4a052007-07-12 21:41:30 +0000591
592 return MadeChange;
593}
594
Chris Lattner1adb6752008-11-28 00:27:14 +0000595/// DeleteDeadInstruction - Delete this instruction. Before we do, go through
596/// and zero out all the operands of this instruction. If any of them become
597/// dead, delete them and the computation tree that feeds them.
598///
599/// If ValueSet is non-null, remove any deleted instructions from it as well.
600///
601void DSE::DeleteDeadInstruction(Instruction *I,
602 SmallPtrSet<Value*, 64> *ValueSet) {
603 SmallVector<Instruction*, 32> NowDeadInsts;
604
605 NowDeadInsts.push_back(I);
606 --NumFastOther;
Owen Anderson5e72db32007-07-11 00:46:18 +0000607
Chris Lattner1adb6752008-11-28 00:27:14 +0000608 // Before we touch this instruction, remove it from memdep!
Dan Gohman28943872010-01-05 16:27:25 +0000609 do {
610 Instruction *DeadInst = NowDeadInsts.pop_back_val();
Owen Andersonbf971aa2007-07-11 19:03:09 +0000611
Chris Lattner1adb6752008-11-28 00:27:14 +0000612 ++NumFastOther;
613
614 // This instruction is dead, zap it, in stages. Start by removing it from
615 // MemDep, which needs to know the operands and needs it to be in the
616 // function.
Chris Lattner51c28a92010-11-30 19:34:42 +0000617 MD->removeInstruction(DeadInst);
Chris Lattner1adb6752008-11-28 00:27:14 +0000618
619 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
620 Value *Op = DeadInst->getOperand(op);
621 DeadInst->setOperand(op, 0);
622
623 // If this operand just became dead, add it to the NowDeadInsts list.
624 if (!Op->use_empty()) continue;
625
626 if (Instruction *OpI = dyn_cast<Instruction>(Op))
627 if (isInstructionTriviallyDead(OpI))
628 NowDeadInsts.push_back(OpI);
629 }
630
631 DeadInst->eraseFromParent();
632
633 if (ValueSet) ValueSet->erase(DeadInst);
Dan Gohman28943872010-01-05 16:27:25 +0000634 } while (!NowDeadInsts.empty());
Owen Anderson5e72db32007-07-11 00:46:18 +0000635}
Nick Lewycky475d3d12010-01-03 04:39:07 +0000636