blob: ae25d38718df4bd0742623fea124adea6e704f0a [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 {
Dan Gohman67243a42009-07-24 18:13:53 +000040 TargetData *TD;
41
Owen Anderson5e72db32007-07-11 00:46:18 +000042 static char ID; // Pass identification, replacement for typeid
Dan Gohmana79db302008-09-04 17:05:41 +000043 DSE() : FunctionPass(&ID) {}
Owen Anderson5e72db32007-07-11 00:46:18 +000044
45 virtual bool runOnFunction(Function &F) {
46 bool Changed = false;
47 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
48 Changed |= runOnBasicBlock(*I);
49 return Changed;
50 }
Chris Lattnerde04e112008-11-29 01:43:36 +000051
Owen Anderson5e72db32007-07-11 00:46:18 +000052 bool runOnBasicBlock(BasicBlock &BB);
Victor Hernandeze2971492009-10-24 04:23:03 +000053 bool handleFreeWithNonTrivialDependency(Instruction *F, MemDepResult Dep);
Chris Lattner1adb6752008-11-28 00:27:14 +000054 bool handleEndBlock(BasicBlock &BB);
Chris Lattner57e91ea2008-12-06 00:53:22 +000055 bool RemoveUndeadPointers(Value* Ptr, uint64_t killPointerSize,
Owen Anderson32c4a052007-07-12 21:41:30 +000056 BasicBlock::iterator& BBI,
Chris Lattner1adb6752008-11-28 00:27:14 +000057 SmallPtrSet<Value*, 64>& deadPointers);
58 void DeleteDeadInstruction(Instruction *I,
59 SmallPtrSet<Value*, 64> *deadPointers = 0);
60
Owen Anderson5e72db32007-07-11 00:46:18 +000061
62 // getAnalysisUsage - We require post dominance frontiers (aka Control
63 // Dependence Graph)
64 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
65 AU.setPreservesCFG();
Owen Anderson3f338972008-07-28 16:14:26 +000066 AU.addRequired<DominatorTree>();
Owen Andersonaa071722007-07-11 23:19:17 +000067 AU.addRequired<AliasAnalysis>();
Owen Anderson5e72db32007-07-11 00:46:18 +000068 AU.addRequired<MemoryDependenceAnalysis>();
Owen Anderson3f338972008-07-28 16:14:26 +000069 AU.addPreserved<DominatorTree>();
Owen Andersonaa071722007-07-11 23:19:17 +000070 AU.addPreserved<AliasAnalysis>();
Owen Anderson5e72db32007-07-11 00:46:18 +000071 AU.addPreserved<MemoryDependenceAnalysis>();
72 }
73 };
Owen Anderson5e72db32007-07-11 00:46:18 +000074}
75
Dan Gohmand78c4002008-05-13 00:00:25 +000076char DSE::ID = 0;
77static RegisterPass<DSE> X("dse", "Dead Store Elimination");
78
Owen Anderson10e52ed2007-08-01 06:36:51 +000079FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
Owen Anderson5e72db32007-07-11 00:46:18 +000080
Nick Lewycky90271472009-11-10 06:46:40 +000081/// doesClobberMemory - Does this instruction clobber (write without reading)
82/// some memory?
83static bool doesClobberMemory(Instruction *I) {
84 if (isa<StoreInst>(I))
85 return true;
86 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
87 switch (II->getIntrinsicID()) {
88 default: return false;
89 case Intrinsic::memset: case Intrinsic::memmove: case Intrinsic::memcpy:
Duncan Sands1925d3a2009-11-10 13:49:50 +000090 case Intrinsic::init_trampoline: case Intrinsic::lifetime_end: return true;
Nick Lewycky90271472009-11-10 06:46:40 +000091 }
92 }
93 return false;
94}
95
Duncan Sands1925d3a2009-11-10 13:49:50 +000096/// isElidable - If the value of this instruction and the memory it writes to is
Nick Lewycky90271472009-11-10 06:46:40 +000097/// unused, may we delete this instrtction?
98static bool isElidable(Instruction *I) {
99 assert(doesClobberMemory(I));
100 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
101 return II->getIntrinsicID() != Intrinsic::lifetime_end;
102 if (StoreInst *SI = dyn_cast<StoreInst>(I))
103 return !SI->isVolatile();
104 return true;
105}
106
107/// getPointerOperand - Return the pointer that is being clobbered.
108static Value *getPointerOperand(Instruction *I) {
109 assert(doesClobberMemory(I));
110 if (StoreInst *SI = dyn_cast<StoreInst>(I))
111 return SI->getPointerOperand();
112 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
113 return MI->getOperand(1);
Duncan Sands1925d3a2009-11-10 13:49:50 +0000114 IntrinsicInst *II = cast<IntrinsicInst>(I);
115 switch (II->getIntrinsicID()) {
116 default:
117 assert(false && "Unexpected intrinsic!");
118 case Intrinsic::init_trampoline:
119 return II->getOperand(1);
120 case Intrinsic::lifetime_end:
121 return II->getOperand(2);
122 }
Nick Lewycky90271472009-11-10 06:46:40 +0000123}
124
125/// getStoreSize - Return the length in bytes of the write by the clobbering
126/// instruction. If variable or unknown, returns -1.
127static unsigned getStoreSize(Instruction *I, const TargetData *TD) {
128 assert(doesClobberMemory(I));
129 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
130 if (!TD) return -1u;
Nick Lewycky5b3def92009-11-10 07:00:43 +0000131 return TD->getTypeStoreSize(SI->getOperand(0)->getType());
Nick Lewycky90271472009-11-10 06:46:40 +0000132 }
133
134 Value *Len;
135 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
136 Len = MI->getLength();
137 } else {
138 IntrinsicInst *II = cast<IntrinsicInst>(I);
Duncan Sands1925d3a2009-11-10 13:49:50 +0000139 switch (II->getIntrinsicID()) {
140 default:
141 assert(false && "Unexpected intrinsic!");
142 case Intrinsic::init_trampoline:
143 return -1u;
144 case Intrinsic::lifetime_end:
145 Len = II->getOperand(0);
146 }
Nick Lewycky90271472009-11-10 06:46:40 +0000147 }
148 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(Len))
149 if (!LenCI->isAllOnesValue())
150 return LenCI->getZExtValue();
151 return -1u;
152}
153
154/// isStoreAtLeastAsWideAs - Return true if the size of the store in I1 is
155/// greater than or equal to the store in I2. This returns false if we don't
156/// know.
Chris Lattnera0906272009-11-04 23:20:12 +0000157///
Nick Lewycky90271472009-11-10 06:46:40 +0000158static bool isStoreAtLeastAsWideAs(Instruction *I1, Instruction *I2,
159 const TargetData *TD) {
160 const Type *I1Ty = getPointerOperand(I1)->getType();
161 const Type *I2Ty = getPointerOperand(I2)->getType();
Chris Lattnera0906272009-11-04 23:20:12 +0000162
163 // Exactly the same type, must have exactly the same size.
Nick Lewycky90271472009-11-10 06:46:40 +0000164 if (I1Ty == I2Ty) return true;
Chris Lattnera0906272009-11-04 23:20:12 +0000165
Nick Lewycky90271472009-11-10 06:46:40 +0000166 int I1Size = getStoreSize(I1, TD);
167 int I2Size = getStoreSize(I2, TD);
Chris Lattnera0906272009-11-04 23:20:12 +0000168
Nick Lewycky90271472009-11-10 06:46:40 +0000169 return I1Size != -1 && I2Size != -1 && I1Size >= I2Size;
Chris Lattnera0906272009-11-04 23:20:12 +0000170}
171
Owen Anderson10e52ed2007-08-01 06:36:51 +0000172bool DSE::runOnBasicBlock(BasicBlock &BB) {
Owen Anderson5e72db32007-07-11 00:46:18 +0000173 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
Dan Gohman67243a42009-07-24 18:13:53 +0000174 TD = getAnalysisIfAvailable<TargetData>();
Owen Anderson2ed651a2007-11-01 05:29:16 +0000175
Owen Anderson5e72db32007-07-11 00:46:18 +0000176 bool MadeChange = false;
177
Chris Lattner49162672009-09-02 06:31:02 +0000178 // Do a top-down walk on the BB.
Chris Lattnerf2a8ba42008-11-28 21:29:52 +0000179 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
180 Instruction *Inst = BBI++;
181
Dan Gohman67243a42009-07-24 18:13:53 +0000182 // If we find a store or a free, get its memory dependence.
Nick Lewycky90271472009-11-10 06:46:40 +0000183 if (!doesClobberMemory(Inst) && !isFreeCall(Inst))
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000184 continue;
Chris Lattner5df5b4c2008-12-07 00:25:15 +0000185
Chris Lattner57e91ea2008-12-06 00:53:22 +0000186 MemDepResult InstDep = MD.getDependency(Inst);
Chris Lattnerf2a8ba42008-11-28 21:29:52 +0000187
Chris Lattner57e91ea2008-12-06 00:53:22 +0000188 // Ignore non-local stores.
189 // FIXME: cross-block DSE would be fun. :)
190 if (InstDep.isNonLocal()) continue;
191
192 // Handle frees whose dependencies are non-trivial.
Victor Hernandezde5ad422009-10-26 23:43:48 +0000193 if (isFreeCall(Inst)) {
Victor Hernandeze2971492009-10-24 04:23:03 +0000194 MadeChange |= handleFreeWithNonTrivialDependency(Inst, InstDep);
Chris Lattner57e91ea2008-12-06 00:53:22 +0000195 continue;
196 }
197
Chris Lattner57e91ea2008-12-06 00:53:22 +0000198 // If not a definite must-alias dependency, ignore it.
199 if (!InstDep.isDef())
200 continue;
201
202 // If this is a store-store dependence, then the previous store is dead so
203 // long as this store is at least as big as it.
Nick Lewycky90271472009-11-10 06:46:40 +0000204 if (doesClobberMemory(InstDep.getInst())) {
205 Instruction *DepStore = InstDep.getInst();
206 if (isStoreAtLeastAsWideAs(Inst, DepStore, TD) &&
207 isElidable(DepStore)) {
Chris Lattner1adb6752008-11-28 00:27:14 +0000208 // Delete the store and now-dead instructions that feed it.
Chris Lattner57e91ea2008-12-06 00:53:22 +0000209 DeleteDeadInstruction(DepStore);
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000210 NumFastStores++;
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000211 MadeChange = true;
Chris Lattner49162672009-09-02 06:31:02 +0000212
213 // DeleteDeadInstruction can delete the current instruction in loop
214 // cases, reset BBI.
215 BBI = Inst;
Chris Lattner8c5ff512008-11-29 20:29:04 +0000216 if (BBI != BB.begin())
Chris Lattnerf3f6a802008-11-28 22:50:08 +0000217 --BBI;
Chris Lattnerf2a8ba42008-11-28 21:29:52 +0000218 continue;
219 }
Nick Lewycky90271472009-11-10 06:46:40 +0000220 }
221
222 if (!isElidable(Inst))
223 continue;
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000224
Chris Lattner57e91ea2008-12-06 00:53:22 +0000225 // If we're storing the same value back to a pointer that we just
226 // loaded from, then the store can be removed.
Nick Lewycky90271472009-11-10 06:46:40 +0000227 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
228 if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
229 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
230 SI->getOperand(0) == DepLoad) {
231 // DeleteDeadInstruction can delete the current instruction. Save BBI
232 // in case we need it.
233 WeakVH NextInst(BBI);
234
235 DeleteDeadInstruction(SI);
236
237 if (NextInst == 0) // Next instruction deleted.
238 BBI = BB.begin();
239 else if (BBI != BB.begin()) // Revisit this instruction if possible.
240 --BBI;
241 NumFastStores++;
242 MadeChange = true;
243 continue;
244 }
Chris Lattner0e3d6332008-12-05 21:04:20 +0000245 }
Owen Anderson5e72db32007-07-11 00:46:18 +0000246 }
Owen Anderson2b2bd282009-10-28 07:05:35 +0000247
248 // If this is a lifetime end marker, we can throw away the store.
Nick Lewycky90271472009-11-10 06:46:40 +0000249 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(InstDep.getInst())) {
Owen Anderson2b2bd282009-10-28 07:05:35 +0000250 if (II->getIntrinsicID() == Intrinsic::lifetime_end) {
251 // Delete the store and now-dead instructions that feed it.
252 // DeleteDeadInstruction can delete the current instruction. Save BBI
253 // in case we need it.
254 WeakVH NextInst(BBI);
255
Nick Lewycky90271472009-11-10 06:46:40 +0000256 DeleteDeadInstruction(Inst);
Owen Anderson2b2bd282009-10-28 07:05:35 +0000257
258 if (NextInst == 0) // Next instruction deleted.
259 BBI = BB.begin();
260 else if (BBI != BB.begin()) // Revisit this instruction if possible.
261 --BBI;
262 NumFastStores++;
263 MadeChange = true;
264 continue;
265 }
266 }
Owen Anderson5e72db32007-07-11 00:46:18 +0000267 }
268
Chris Lattnerf2a8ba42008-11-28 21:29:52 +0000269 // If this block ends in a return, unwind, or unreachable, all allocas are
270 // dead at its end, which means stores to them are also dead.
Owen Anderson32c4a052007-07-12 21:41:30 +0000271 if (BB.getTerminator()->getNumSuccessors() == 0)
Chris Lattner1adb6752008-11-28 00:27:14 +0000272 MadeChange |= handleEndBlock(BB);
Owen Anderson5e72db32007-07-11 00:46:18 +0000273
274 return MadeChange;
275}
276
Owen Andersonaa071722007-07-11 23:19:17 +0000277/// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
Chris Lattner1adb6752008-11-28 00:27:14 +0000278/// dependency is a store to a field of that structure.
Victor Hernandeze2971492009-10-24 04:23:03 +0000279bool DSE::handleFreeWithNonTrivialDependency(Instruction *F, MemDepResult Dep) {
Owen Andersonaa071722007-07-11 23:19:17 +0000280 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Owen Andersonaa071722007-07-11 23:19:17 +0000281
Nick Lewycky90271472009-11-10 06:46:40 +0000282 Instruction *Dependency = Dep.getInst();
283 if (!Dependency || !doesClobberMemory(Dependency) || !isElidable(Dependency))
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000284 return false;
Owen Andersond4451de2007-07-12 18:08:51 +0000285
Nick Lewycky90271472009-11-10 06:46:40 +0000286 Value *DepPointer = getPointerOperand(Dependency)->getUnderlyingObject();
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000287
Chris Lattner57e91ea2008-12-06 00:53:22 +0000288 // Check for aliasing.
Victor Hernandezde5ad422009-10-26 23:43:48 +0000289 if (AA.alias(F->getOperand(1), 1, DepPointer, 1) !=
Chris Lattner57e91ea2008-12-06 00:53:22 +0000290 AliasAnalysis::MustAlias)
Chris Lattner1adb6752008-11-28 00:27:14 +0000291 return false;
Owen Andersonaa071722007-07-11 23:19:17 +0000292
Chris Lattner1adb6752008-11-28 00:27:14 +0000293 // DCE instructions only used to calculate that store
Chris Lattner57e91ea2008-12-06 00:53:22 +0000294 DeleteDeadInstruction(Dependency);
Chris Lattner1adb6752008-11-28 00:27:14 +0000295 NumFastStores++;
296 return true;
Owen Andersonaa071722007-07-11 23:19:17 +0000297}
298
Owen Andersone3590582007-08-02 18:11:11 +0000299/// handleEndBlock - Remove dead stores to stack-allocated locations in the
Owen Anderson52aaabf2007-08-08 17:50:09 +0000300/// function end block. Ex:
301/// %A = alloca i32
302/// ...
303/// store i32 1, i32* %A
304/// ret void
Chris Lattner1adb6752008-11-28 00:27:14 +0000305bool DSE::handleEndBlock(BasicBlock &BB) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000306 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Owen Anderson32c4a052007-07-12 21:41:30 +0000307
308 bool MadeChange = false;
309
310 // Pointers alloca'd in this function are dead in the end block
Owen Anderson48d37802008-01-29 06:18:36 +0000311 SmallPtrSet<Value*, 64> deadPointers;
Owen Anderson32c4a052007-07-12 21:41:30 +0000312
Chris Lattner1adb6752008-11-28 00:27:14 +0000313 // Find all of the alloca'd pointers in the entry block.
Owen Anderson32c4a052007-07-12 21:41:30 +0000314 BasicBlock *Entry = BB.getParent()->begin();
315 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
316 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
317 deadPointers.insert(AI);
Chris Lattner1adb6752008-11-28 00:27:14 +0000318
319 // Treat byval arguments the same, stores to them are dead at the end of the
320 // function.
Owen Anderson48d37802008-01-29 06:18:36 +0000321 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
322 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
323 if (AI->hasByValAttr())
324 deadPointers.insert(AI);
Owen Anderson32c4a052007-07-12 21:41:30 +0000325
326 // Scan the basic block backwards
327 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
328 --BBI;
329
Chris Lattner1adb6752008-11-28 00:27:14 +0000330 // If we find a store whose pointer is dead.
Nick Lewycky90271472009-11-10 06:46:40 +0000331 if (doesClobberMemory(BBI)) {
332 if (isElidable(BBI)) {
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000333 // See through pointer-to-pointer bitcasts
Nick Lewycky90271472009-11-10 06:46:40 +0000334 Value *pointerOperand = getPointerOperand(BBI)->getUnderlyingObject();
Duncan Sandsd65a4da2008-10-01 15:25:41 +0000335
Owen Anderson6af19fd2008-01-25 10:10:33 +0000336 // Alloca'd pointers or byval arguments (which are functionally like
337 // alloca's) are valid candidates for removal.
Owen Anderson48d37802008-01-29 06:18:36 +0000338 if (deadPointers.count(pointerOperand)) {
Chris Lattner1adb6752008-11-28 00:27:14 +0000339 // DCE instructions only used to calculate that store.
Nick Lewycky90271472009-11-10 06:46:40 +0000340 Instruction *Dead = BBI;
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000341 BBI++;
Nick Lewycky90271472009-11-10 06:46:40 +0000342 DeleteDeadInstruction(Dead, &deadPointers);
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000343 NumFastStores++;
344 MadeChange = true;
Nick Lewycky90271472009-11-10 06:46:40 +0000345 continue;
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000346 }
Owen Anderson32c4a052007-07-12 21:41:30 +0000347 }
Owen Anderson52aaabf2007-08-08 17:50:09 +0000348
Nick Lewycky90271472009-11-10 06:46:40 +0000349 // Because a memcpy or memmove is also a load, we can't skip it if we
350 // didn't remove it.
351 if (!isa<MemTransferInst>(BBI))
Owen Anderson48d37802008-01-29 06:18:36 +0000352 continue;
Owen Anderson52aaabf2007-08-08 17:50:09 +0000353 }
354
355 Value* killPointer = 0;
Owen Andersona82c9932008-02-04 04:53:00 +0000356 uint64_t killPointerSize = ~0UL;
Owen Anderson32c4a052007-07-12 21:41:30 +0000357
358 // If we encounter a use of the pointer, it is no longer considered dead
Chris Lattner1adb6752008-11-28 00:27:14 +0000359 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
Nate Begeman53c5c622008-05-13 01:48:26 +0000360 // However, if this load is unused and not volatile, we can go ahead and
361 // remove it, and not have to worry about it making our pointer undead!
Dan Gohman8cb19d92008-04-28 19:51:27 +0000362 if (L->use_empty() && !L->isVolatile()) {
Owen Anderson4e4b1162008-01-30 01:24:47 +0000363 BBI++;
Chris Lattner1adb6752008-11-28 00:27:14 +0000364 DeleteDeadInstruction(L, &deadPointers);
Owen Anderson4e4b1162008-01-30 01:24:47 +0000365 NumFastOther++;
366 MadeChange = true;
Owen Anderson4e4b1162008-01-30 01:24:47 +0000367 continue;
368 }
369
Owen Anderson32c4a052007-07-12 21:41:30 +0000370 killPointer = L->getPointerOperand();
Owen Anderson32c4a052007-07-12 21:41:30 +0000371 } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
372 killPointer = V->getOperand(0);
Nick Lewycky90271472009-11-10 06:46:40 +0000373 } else if (isa<MemTransferInst>(BBI) &&
374 isa<ConstantInt>(cast<MemTransferInst>(BBI)->getLength())) {
375 killPointer = cast<MemTransferInst>(BBI)->getSource();
Owen Andersona82c9932008-02-04 04:53:00 +0000376 killPointerSize = cast<ConstantInt>(
Nick Lewycky90271472009-11-10 06:46:40 +0000377 cast<MemTransferInst>(BBI)->getLength())->getZExtValue();
Owen Anderson32c4a052007-07-12 21:41:30 +0000378 } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
379 deadPointers.erase(A);
Owen Anderson4e4b1162008-01-30 01:24:47 +0000380
381 // Dead alloca's can be DCE'd when we reach them
Nick Lewycky6b016702008-01-30 08:01:28 +0000382 if (A->use_empty()) {
Owen Anderson4e4b1162008-01-30 01:24:47 +0000383 BBI++;
Chris Lattner1adb6752008-11-28 00:27:14 +0000384 DeleteDeadInstruction(A, &deadPointers);
Owen Anderson4e4b1162008-01-30 01:24:47 +0000385 NumFastOther++;
386 MadeChange = true;
Owen Anderson4e4b1162008-01-30 01:24:47 +0000387 }
388
Owen Anderson32c4a052007-07-12 21:41:30 +0000389 continue;
390 } else if (CallSite::get(BBI).getInstruction() != 0) {
Owen Anderson50df9682007-08-08 17:58:56 +0000391 // If this call does not access memory, it can't
392 // be undeadifying any of our pointers.
393 CallSite CS = CallSite::get(BBI);
Duncan Sands68b6f502007-12-01 07:51:45 +0000394 if (AA.doesNotAccessMemory(CS))
Owen Anderson50df9682007-08-08 17:58:56 +0000395 continue;
396
Owen Andersonddf4aee2007-08-08 18:38:28 +0000397 unsigned modRef = 0;
398 unsigned other = 0;
399
Owen Anderson32c4a052007-07-12 21:41:30 +0000400 // Remove any pointers made undead by the call from the dead set
Owen Anderson48d37802008-01-29 06:18:36 +0000401 std::vector<Value*> dead;
402 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
Owen Anderson32c4a052007-07-12 21:41:30 +0000403 E = deadPointers.end(); I != E; ++I) {
Owen Andersonddf4aee2007-08-08 18:38:28 +0000404 // HACK: if we detect that our AA is imprecise, it's not
405 // worth it to scan the rest of the deadPointers set. Just
406 // assume that the AA will return ModRef for everything, and
407 // go ahead and bail.
408 if (modRef >= 16 && other == 0) {
409 deadPointers.clear();
410 return MadeChange;
411 }
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000412
Owen Anderson32c4a052007-07-12 21:41:30 +0000413 // Get size information for the alloca
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000414 unsigned pointerSize = ~0U;
Dan Gohman67243a42009-07-24 18:13:53 +0000415 if (TD) {
416 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
417 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
418 pointerSize = C->getZExtValue() *
419 TD->getTypeAllocSize(A->getAllocatedType());
420 } else {
421 const PointerType* PT = cast<PointerType>(
422 cast<Argument>(*I)->getType());
423 pointerSize = TD->getTypeAllocSize(PT->getElementType());
424 }
Owen Anderson48d37802008-01-29 06:18:36 +0000425 }
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000426
Owen Anderson32c4a052007-07-12 21:41:30 +0000427 // See if the call site touches it
Owen Anderson50df9682007-08-08 17:58:56 +0000428 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I, pointerSize);
Owen Andersonddf4aee2007-08-08 18:38:28 +0000429
430 if (A == AliasAnalysis::ModRef)
431 modRef++;
432 else
433 other++;
434
Owen Anderson9c9ef212007-07-13 18:26:26 +0000435 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
Owen Anderson32c4a052007-07-12 21:41:30 +0000436 dead.push_back(*I);
437 }
438
Owen Anderson48d37802008-01-29 06:18:36 +0000439 for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
Owen Anderson32c4a052007-07-12 21:41:30 +0000440 I != E; ++I)
Owen Anderson48d37802008-01-29 06:18:36 +0000441 deadPointers.erase(*I);
Owen Anderson32c4a052007-07-12 21:41:30 +0000442
443 continue;
Chris Lattner1adb6752008-11-28 00:27:14 +0000444 } else if (isInstructionTriviallyDead(BBI)) {
Owen Anderson4e4b1162008-01-30 01:24:47 +0000445 // For any non-memory-affecting non-terminators, DCE them as we reach them
Chris Lattner1adb6752008-11-28 00:27:14 +0000446 Instruction *Inst = BBI;
447 BBI++;
448 DeleteDeadInstruction(Inst, &deadPointers);
449 NumFastOther++;
450 MadeChange = true;
451 continue;
Owen Anderson32c4a052007-07-12 21:41:30 +0000452 }
453
454 if (!killPointer)
455 continue;
Duncan Sandsd65a4da2008-10-01 15:25:41 +0000456
457 killPointer = killPointer->getUnderlyingObject();
458
Owen Anderson32c4a052007-07-12 21:41:30 +0000459 // Deal with undead pointers
Owen Andersona82c9932008-02-04 04:53:00 +0000460 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
Chris Lattner1adb6752008-11-28 00:27:14 +0000461 deadPointers);
Owen Anderson32c4a052007-07-12 21:41:30 +0000462 }
463
464 return MadeChange;
465}
466
Owen Andersonddf4aee2007-08-08 18:38:28 +0000467/// RemoveUndeadPointers - check for uses of a pointer that make it
468/// undead when scanning for dead stores to alloca's.
Owen Andersona82c9932008-02-04 04:53:00 +0000469bool DSE::RemoveUndeadPointers(Value* killPointer, uint64_t killPointerSize,
Chris Lattner1adb6752008-11-28 00:27:14 +0000470 BasicBlock::iterator &BBI,
471 SmallPtrSet<Value*, 64>& deadPointers) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000472 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Owen Anderson32c4a052007-07-12 21:41:30 +0000473
Owen Andersonddf4aee2007-08-08 18:38:28 +0000474 // If the kill pointer can be easily reduced to an alloca,
Chris Lattner1adb6752008-11-28 00:27:14 +0000475 // don't bother doing extraneous AA queries.
Owen Anderson48d37802008-01-29 06:18:36 +0000476 if (deadPointers.count(killPointer)) {
477 deadPointers.erase(killPointer);
Owen Andersonddf4aee2007-08-08 18:38:28 +0000478 return false;
479 }
480
Chris Lattner1adb6752008-11-28 00:27:14 +0000481 // A global can't be in the dead pointer set.
482 if (isa<GlobalValue>(killPointer))
483 return false;
484
Owen Anderson32c4a052007-07-12 21:41:30 +0000485 bool MadeChange = false;
486
Chris Lattner1adb6752008-11-28 00:27:14 +0000487 SmallVector<Value*, 16> undead;
Owen Anderson32c4a052007-07-12 21:41:30 +0000488
Owen Anderson48d37802008-01-29 06:18:36 +0000489 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
Owen Anderson32c4a052007-07-12 21:41:30 +0000490 E = deadPointers.end(); I != E; ++I) {
Chris Lattner1adb6752008-11-28 00:27:14 +0000491 // Get size information for the alloca.
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000492 unsigned pointerSize = ~0U;
Dan Gohman67243a42009-07-24 18:13:53 +0000493 if (TD) {
494 if (AllocaInst* A = dyn_cast<AllocaInst>(*I)) {
495 if (ConstantInt* C = dyn_cast<ConstantInt>(A->getArraySize()))
496 pointerSize = C->getZExtValue() *
497 TD->getTypeAllocSize(A->getAllocatedType());
498 } else {
499 const PointerType* PT = cast<PointerType>(cast<Argument>(*I)->getType());
500 pointerSize = TD->getTypeAllocSize(PT->getElementType());
501 }
Owen Anderson48d37802008-01-29 06:18:36 +0000502 }
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000503
Owen Anderson32c4a052007-07-12 21:41:30 +0000504 // See if this pointer could alias it
Owen Andersone3590582007-08-02 18:11:11 +0000505 AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize,
Owen Andersona82c9932008-02-04 04:53:00 +0000506 killPointer, killPointerSize);
Owen Anderson32c4a052007-07-12 21:41:30 +0000507
508 // If it must-alias and a store, we can delete it
509 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
510 StoreInst* S = cast<StoreInst>(BBI);
511
512 // Remove it!
Owen Anderson32c4a052007-07-12 21:41:30 +0000513 BBI++;
Chris Lattner1adb6752008-11-28 00:27:14 +0000514 DeleteDeadInstruction(S, &deadPointers);
Owen Anderson32c4a052007-07-12 21:41:30 +0000515 NumFastStores++;
516 MadeChange = true;
517
518 continue;
519
520 // Otherwise, it is undead
Chris Lattner1adb6752008-11-28 00:27:14 +0000521 } else if (A != AliasAnalysis::NoAlias)
522 undead.push_back(*I);
Owen Anderson32c4a052007-07-12 21:41:30 +0000523 }
524
Chris Lattner1adb6752008-11-28 00:27:14 +0000525 for (SmallVector<Value*, 16>::iterator I = undead.begin(), E = undead.end();
Owen Anderson32c4a052007-07-12 21:41:30 +0000526 I != E; ++I)
Owen Anderson48d37802008-01-29 06:18:36 +0000527 deadPointers.erase(*I);
Owen Anderson32c4a052007-07-12 21:41:30 +0000528
529 return MadeChange;
530}
531
Chris Lattner1adb6752008-11-28 00:27:14 +0000532/// DeleteDeadInstruction - Delete this instruction. Before we do, go through
533/// and zero out all the operands of this instruction. If any of them become
534/// dead, delete them and the computation tree that feeds them.
535///
536/// If ValueSet is non-null, remove any deleted instructions from it as well.
537///
538void DSE::DeleteDeadInstruction(Instruction *I,
539 SmallPtrSet<Value*, 64> *ValueSet) {
540 SmallVector<Instruction*, 32> NowDeadInsts;
541
542 NowDeadInsts.push_back(I);
543 --NumFastOther;
Owen Anderson5e72db32007-07-11 00:46:18 +0000544
Chris Lattner1adb6752008-11-28 00:27:14 +0000545 // Before we touch this instruction, remove it from memdep!
546 MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>();
547 while (!NowDeadInsts.empty()) {
548 Instruction *DeadInst = NowDeadInsts.back();
549 NowDeadInsts.pop_back();
Owen Andersonbf971aa2007-07-11 19:03:09 +0000550
Chris Lattner1adb6752008-11-28 00:27:14 +0000551 ++NumFastOther;
552
553 // This instruction is dead, zap it, in stages. Start by removing it from
554 // MemDep, which needs to know the operands and needs it to be in the
555 // function.
556 MDA.removeInstruction(DeadInst);
557
558 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
559 Value *Op = DeadInst->getOperand(op);
560 DeadInst->setOperand(op, 0);
561
562 // If this operand just became dead, add it to the NowDeadInsts list.
563 if (!Op->use_empty()) continue;
564
565 if (Instruction *OpI = dyn_cast<Instruction>(Op))
566 if (isInstructionTriviallyDead(OpI))
567 NowDeadInsts.push_back(OpI);
568 }
569
570 DeadInst->eraseFromParent();
571
572 if (ValueSet) ValueSet->erase(DeadInst);
Owen Anderson5e72db32007-07-11 00:46:18 +0000573 }
Owen Anderson5e72db32007-07-11 00:46:18 +0000574}