blob: 46f54cf7bb9ecc510b23a34c19a5e130c960a6be [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
Owen Anderson6c18d1a2010-10-19 17:21:58 +000043 DSE() : FunctionPass(ID) {
44 initializeDSEPass(*PassRegistry::getPassRegistry());
45 }
Owen Anderson5e72db32007-07-11 00:46:18 +000046
47 virtual bool runOnFunction(Function &F) {
48 bool Changed = false;
Chris Lattnerc053cbb2010-02-11 05:11:54 +000049
50 DominatorTree &DT = getAnalysis<DominatorTree>();
51
Owen Anderson5e72db32007-07-11 00:46:18 +000052 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
Chris Lattnerc053cbb2010-02-11 05:11:54 +000053 // Only check non-dead blocks. Dead blocks may have strange pointer
54 // cycles that will confuse alias analysis.
55 if (DT.isReachableFromEntry(I))
56 Changed |= runOnBasicBlock(*I);
Owen Anderson5e72db32007-07-11 00:46:18 +000057 return Changed;
58 }
Chris Lattnerde04e112008-11-29 01:43:36 +000059
Owen Anderson5e72db32007-07-11 00:46:18 +000060 bool runOnBasicBlock(BasicBlock &BB);
Chris Lattner9d179d92010-11-30 01:28:33 +000061 bool HandleFree(CallInst *F);
Chris Lattner1adb6752008-11-28 00:27:14 +000062 bool handleEndBlock(BasicBlock &BB);
Dan Gohmanf372cf82010-10-19 22:54:46 +000063 bool RemoveUndeadPointers(Value *Ptr, uint64_t killPointerSize,
Nick Lewycky475d3d12010-01-03 04:39:07 +000064 BasicBlock::iterator &BBI,
65 SmallPtrSet<Value*, 64> &deadPointers);
Chris Lattner1adb6752008-11-28 00:27:14 +000066 void DeleteDeadInstruction(Instruction *I,
67 SmallPtrSet<Value*, 64> *deadPointers = 0);
68
Owen Anderson5e72db32007-07-11 00:46:18 +000069
70 // getAnalysisUsage - We require post dominance frontiers (aka Control
71 // Dependence Graph)
72 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73 AU.setPreservesCFG();
Owen Anderson3f338972008-07-28 16:14:26 +000074 AU.addRequired<DominatorTree>();
Owen Andersonaa071722007-07-11 23:19:17 +000075 AU.addRequired<AliasAnalysis>();
Owen Anderson5e72db32007-07-11 00:46:18 +000076 AU.addRequired<MemoryDependenceAnalysis>();
Owen Anderson3f338972008-07-28 16:14:26 +000077 AU.addPreserved<DominatorTree>();
Owen Anderson5e72db32007-07-11 00:46:18 +000078 AU.addPreserved<MemoryDependenceAnalysis>();
79 }
Nick Lewycky475d3d12010-01-03 04:39:07 +000080
Dan Gohmanf372cf82010-10-19 22:54:46 +000081 uint64_t getPointerSize(Value *V) const;
Owen Anderson5e72db32007-07-11 00:46:18 +000082 };
Owen Anderson5e72db32007-07-11 00:46:18 +000083}
84
Dan Gohmand78c4002008-05-13 00:00:25 +000085char DSE::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +000086INITIALIZE_PASS_BEGIN(DSE, "dse", "Dead Store Elimination", false, false)
87INITIALIZE_PASS_DEPENDENCY(DominatorTree)
88INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
89INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
90INITIALIZE_PASS_END(DSE, "dse", "Dead Store Elimination", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +000091
Owen Anderson10e52ed2007-08-01 06:36:51 +000092FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
Owen Anderson5e72db32007-07-11 00:46:18 +000093
Chris Lattner2227a8a2010-11-30 01:37:52 +000094/// hasMemoryWrite - Does this instruction write some memory? This only returns
95/// true for things that we can analyze with other helpers below.
96static bool hasMemoryWrite(Instruction *I) {
Nick Lewycky90271472009-11-10 06:46:40 +000097 if (isa<StoreInst>(I))
98 return true;
99 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
100 switch (II->getIntrinsicID()) {
Chris Lattner2764b4d2009-12-02 06:35:55 +0000101 default:
102 return false;
103 case Intrinsic::memset:
104 case Intrinsic::memmove:
105 case Intrinsic::memcpy:
106 case Intrinsic::init_trampoline:
107 case Intrinsic::lifetime_end:
108 return true;
Nick Lewycky90271472009-11-10 06:46:40 +0000109 }
110 }
111 return false;
112}
113
Chris Lattner3590ef82010-11-30 05:30:45 +0000114/// isRemovable - If the value of this instruction and the memory it writes to
115/// is unused, may we delete this instruction?
116static bool isRemovable(Instruction *I) {
Chris Lattner2227a8a2010-11-30 01:37:52 +0000117 assert(hasMemoryWrite(I));
Nick Lewycky90271472009-11-10 06:46:40 +0000118 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
119 return II->getIntrinsicID() != Intrinsic::lifetime_end;
120 if (StoreInst *SI = dyn_cast<StoreInst>(I))
121 return !SI->isVolatile();
122 return true;
123}
124
Chris Lattner9d179d92010-11-30 01:28:33 +0000125/// getPointerOperand - Return the pointer that is being written to.
Nick Lewycky90271472009-11-10 06:46:40 +0000126static Value *getPointerOperand(Instruction *I) {
Chris Lattner2227a8a2010-11-30 01:37:52 +0000127 assert(hasMemoryWrite(I));
Nick Lewycky90271472009-11-10 06:46:40 +0000128 if (StoreInst *SI = dyn_cast<StoreInst>(I))
129 return SI->getPointerOperand();
130 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
Gabor Greif91f95892010-06-24 12:03:56 +0000131 return MI->getArgOperand(0);
132
133 IntrinsicInst *II = cast<IntrinsicInst>(I);
134 switch (II->getIntrinsicID()) {
Chris Lattner2764b4d2009-12-02 06:35:55 +0000135 default: assert(false && "Unexpected intrinsic!");
136 case Intrinsic::init_trampoline:
Gabor Greif91f95892010-06-24 12:03:56 +0000137 return II->getArgOperand(0);
Eric Christopher7258dcd2010-04-16 23:37:20 +0000138 case Intrinsic::lifetime_end:
Gabor Greif91f95892010-06-24 12:03:56 +0000139 return II->getArgOperand(1);
Duncan Sands1925d3a2009-11-10 13:49:50 +0000140 }
Nick Lewycky90271472009-11-10 06:46:40 +0000141}
142
143/// getStoreSize - Return the length in bytes of the write by the clobbering
Dan Gohmanf372cf82010-10-19 22:54:46 +0000144/// instruction. If variable or unknown, returns AliasAnalysis::UnknownSize.
145static uint64_t getStoreSize(Instruction *I, const TargetData *TD) {
Chris Lattner2227a8a2010-11-30 01:37:52 +0000146 assert(hasMemoryWrite(I));
Nick Lewycky90271472009-11-10 06:46:40 +0000147 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Dan Gohmanf372cf82010-10-19 22:54:46 +0000148 if (!TD) return AliasAnalysis::UnknownSize;
Nick Lewycky5b3def92009-11-10 07:00:43 +0000149 return TD->getTypeStoreSize(SI->getOperand(0)->getType());
Nick Lewycky90271472009-11-10 06:46:40 +0000150 }
151
152 Value *Len;
153 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
154 Len = MI->getLength();
155 } else {
Gabor Greif91f95892010-06-24 12:03:56 +0000156 IntrinsicInst *II = cast<IntrinsicInst>(I);
157 switch (II->getIntrinsicID()) {
Chris Lattner2764b4d2009-12-02 06:35:55 +0000158 default: assert(false && "Unexpected intrinsic!");
159 case Intrinsic::init_trampoline:
Dan Gohmanf372cf82010-10-19 22:54:46 +0000160 return AliasAnalysis::UnknownSize;
Chris Lattner2764b4d2009-12-02 06:35:55 +0000161 case Intrinsic::lifetime_end:
Gabor Greif91f95892010-06-24 12:03:56 +0000162 Len = II->getArgOperand(0);
Chris Lattner2764b4d2009-12-02 06:35:55 +0000163 break;
Duncan Sands1925d3a2009-11-10 13:49:50 +0000164 }
Nick Lewycky90271472009-11-10 06:46:40 +0000165 }
166 if (ConstantInt *LenCI = dyn_cast<ConstantInt>(Len))
167 if (!LenCI->isAllOnesValue())
168 return LenCI->getZExtValue();
Dan Gohmanf372cf82010-10-19 22:54:46 +0000169 return AliasAnalysis::UnknownSize;
Nick Lewycky90271472009-11-10 06:46:40 +0000170}
171
172/// isStoreAtLeastAsWideAs - Return true if the size of the store in I1 is
173/// greater than or equal to the store in I2. This returns false if we don't
174/// know.
Chris Lattnera0906272009-11-04 23:20:12 +0000175///
Nick Lewycky90271472009-11-10 06:46:40 +0000176static bool isStoreAtLeastAsWideAs(Instruction *I1, Instruction *I2,
177 const TargetData *TD) {
178 const Type *I1Ty = getPointerOperand(I1)->getType();
179 const Type *I2Ty = getPointerOperand(I2)->getType();
Chris Lattnera0906272009-11-04 23:20:12 +0000180
181 // Exactly the same type, must have exactly the same size.
Nick Lewycky90271472009-11-10 06:46:40 +0000182 if (I1Ty == I2Ty) return true;
Chris Lattnera0906272009-11-04 23:20:12 +0000183
Dan Gohmanf372cf82010-10-19 22:54:46 +0000184 uint64_t I1Size = getStoreSize(I1, TD);
185 uint64_t I2Size = getStoreSize(I2, TD);
Chris Lattnera0906272009-11-04 23:20:12 +0000186
Dan Gohmanf372cf82010-10-19 22:54:46 +0000187 return I1Size != AliasAnalysis::UnknownSize &&
188 I2Size != AliasAnalysis::UnknownSize &&
189 I1Size >= I2Size;
Chris Lattnera0906272009-11-04 23:20:12 +0000190}
191
Chris Lattner9a146372010-11-30 00:28:45 +0000192
Owen Anderson10e52ed2007-08-01 06:36:51 +0000193bool DSE::runOnBasicBlock(BasicBlock &BB) {
Nick Lewycky475d3d12010-01-03 04:39:07 +0000194 MemoryDependenceAnalysis &MD = getAnalysis<MemoryDependenceAnalysis>();
Chris Lattner3590ef82010-11-30 05:30:45 +0000195 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Dan Gohman67243a42009-07-24 18:13:53 +0000196 TD = getAnalysisIfAvailable<TargetData>();
Owen Anderson2ed651a2007-11-01 05:29:16 +0000197
Owen Anderson5e72db32007-07-11 00:46:18 +0000198 bool MadeChange = false;
199
Chris Lattner49162672009-09-02 06:31:02 +0000200 // Do a top-down walk on the BB.
Chris Lattnerf2a8ba42008-11-28 21:29:52 +0000201 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ) {
202 Instruction *Inst = BBI++;
203
Chris Lattner9d179d92010-11-30 01:28:33 +0000204 // Handle 'free' calls specially.
205 if (CallInst *F = isFreeCall(Inst)) {
206 MadeChange |= HandleFree(F);
207 continue;
208 }
209
Chris Lattner2227a8a2010-11-30 01:37:52 +0000210 // If we find something that writes memory, get its memory dependence.
211 if (!hasMemoryWrite(Inst))
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000212 continue;
Chris Lattnerd4f10902010-11-30 00:01:19 +0000213
Chris Lattner57e91ea2008-12-06 00:53:22 +0000214 MemDepResult InstDep = MD.getDependency(Inst);
Chris Lattnerf2a8ba42008-11-28 21:29:52 +0000215
Chris Lattnerd4f10902010-11-30 00:01:19 +0000216 // Ignore non-local store liveness.
Chris Lattner57e91ea2008-12-06 00:53:22 +0000217 // FIXME: cross-block DSE would be fun. :)
218 if (InstDep.isNonLocal()) continue;
Chris Lattner9d179d92010-11-30 01:28:33 +0000219
Chris Lattner57e91ea2008-12-06 00:53:22 +0000220 // If we're storing the same value back to a pointer that we just
221 // loaded from, then the store can be removed.
Nick Lewycky90271472009-11-10 06:46:40 +0000222 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
223 if (LoadInst *DepLoad = dyn_cast<LoadInst>(InstDep.getInst())) {
224 if (SI->getPointerOperand() == DepLoad->getPointerOperand() &&
Chris Lattnerc3c754f2010-11-30 00:12:39 +0000225 SI->getOperand(0) == DepLoad && !SI->isVolatile()) {
Nick Lewycky90271472009-11-10 06:46:40 +0000226 // DeleteDeadInstruction can delete the current instruction. Save BBI
227 // in case we need it.
228 WeakVH NextInst(BBI);
229
230 DeleteDeadInstruction(SI);
231
232 if (NextInst == 0) // Next instruction deleted.
233 BBI = BB.begin();
234 else if (BBI != BB.begin()) // Revisit this instruction if possible.
235 --BBI;
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000236 ++NumFastStores;
Nick Lewycky90271472009-11-10 06:46:40 +0000237 MadeChange = true;
238 continue;
239 }
Chris Lattner0e3d6332008-12-05 21:04:20 +0000240 }
Owen Anderson5e72db32007-07-11 00:46:18 +0000241 }
Chris Lattner3590ef82010-11-30 05:30:45 +0000242
Chris Lattnerd4f10902010-11-30 00:01:19 +0000243 if (!InstDep.isDef()) {
244 // If this is a may-aliased store that is clobbering the store value, we
245 // can keep searching past it for another must-aliased pointer that stores
246 // to the same location. For example, in:
247 // store -> P
248 // store -> Q
249 // store -> P
250 // we can remove the first store to P even though we don't know if P and Q
251 // alias.
252 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattner9a146372010-11-30 00:28:45 +0000253 AliasAnalysis::Location Loc = AA.getLocation(SI);
254 while (InstDep.isClobber() && InstDep.getInst() != &BB.front()) {
255 // Can't look past this instruction if it might read 'Loc'.
256 if (AA.getModRefInfo(InstDep.getInst(), Loc) & AliasAnalysis::Ref)
257 break;
258
259 InstDep = MD.getPointerDependencyFrom(Loc, false,
260 InstDep.getInst(), &BB);
261 }
Chris Lattnerd4f10902010-11-30 00:01:19 +0000262 }
263 }
Owen Anderson2b2bd282009-10-28 07:05:35 +0000264
Chris Lattnerd4f10902010-11-30 00:01:19 +0000265 // If this is a store-store dependence, then the previous store is dead so
266 // long as this store is at least as big as it.
Chris Lattner2227a8a2010-11-30 01:37:52 +0000267 if (InstDep.isDef() && hasMemoryWrite(InstDep.getInst())) {
Chris Lattnerd4f10902010-11-30 00:01:19 +0000268 Instruction *DepStore = InstDep.getInst();
Chris Lattner3590ef82010-11-30 05:30:45 +0000269 if (!isRemovable(DepStore) ||
270 !isStoreAtLeastAsWideAs(Inst, DepStore, TD))
Owen Anderson2b2bd282009-10-28 07:05:35 +0000271 continue;
Chris Lattner3590ef82010-11-30 05:30:45 +0000272
273 // Delete the store and now-dead instructions that feed it.
274 DeleteDeadInstruction(DepStore);
275 ++NumFastStores;
276 MadeChange = true;
277
278 // DeleteDeadInstruction can delete the current instruction in loop
279 // cases, reset BBI.
280 BBI = Inst;
281 if (BBI != BB.begin())
282 --BBI;
283 continue;
Owen Anderson2b2bd282009-10-28 07:05:35 +0000284 }
Owen Anderson5e72db32007-07-11 00:46:18 +0000285 }
286
Chris Lattnerf2a8ba42008-11-28 21:29:52 +0000287 // If this block ends in a return, unwind, or unreachable, all allocas are
288 // dead at its end, which means stores to them are also dead.
Owen Anderson32c4a052007-07-12 21:41:30 +0000289 if (BB.getTerminator()->getNumSuccessors() == 0)
Chris Lattner1adb6752008-11-28 00:27:14 +0000290 MadeChange |= handleEndBlock(BB);
Owen Anderson5e72db32007-07-11 00:46:18 +0000291
292 return MadeChange;
293}
294
Chris Lattner9d179d92010-11-30 01:28:33 +0000295/// HandleFree - Handle frees of entire structures whose dependency is a store
296/// to a field of that structure.
297bool DSE::HandleFree(CallInst *F) {
Owen Andersonaa071722007-07-11 23:19:17 +0000298 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000299 MemoryDependenceAnalysis &MD = getAnalysis<MemoryDependenceAnalysis>();
Chris Lattner9d179d92010-11-30 01:28:33 +0000300
301 MemDepResult Dep = MD.getDependency(F);
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000302 do {
Chris Lattner9d179d92010-11-30 01:28:33 +0000303 if (Dep.isNonLocal()) return false;
304
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000305 Instruction *Dependency = Dep.getInst();
Chris Lattner3590ef82010-11-30 05:30:45 +0000306 if (!hasMemoryWrite(Dependency) || !isRemovable(Dependency))
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000307 return false;
Owen Andersond4451de2007-07-12 18:08:51 +0000308
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000309 Value *DepPointer = getPointerOperand(Dependency)->getUnderlyingObject();
Duncan Sandsfe3bef02008-01-20 10:49:23 +0000310
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000311 // Check for aliasing.
312 if (AA.alias(F->getArgOperand(0), 1, DepPointer, 1) !=
Chris Lattner9d179d92010-11-30 01:28:33 +0000313 AliasAnalysis::MustAlias)
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000314 return false;
Owen Andersonaa071722007-07-11 23:19:17 +0000315
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000316 // DCE instructions only used to calculate that store
317 DeleteDeadInstruction(Dependency);
318 ++NumFastStores;
319
320 // Inst's old Dependency is now deleted. Compute the next dependency,
321 // which may also be dead, as in
322 // s[0] = 0;
323 // s[1] = 0; // This has just been deleted.
324 // free(s);
Chris Lattner9d179d92010-11-30 01:28:33 +0000325 Dep = MD.getDependency(F);
Dan Gohmand4b7fff2010-11-12 02:19:17 +0000326 } while (!Dep.isNonLocal());
Chris Lattner9d179d92010-11-30 01:28:33 +0000327
Chris Lattner1adb6752008-11-28 00:27:14 +0000328 return true;
Owen Andersonaa071722007-07-11 23:19:17 +0000329}
330
Owen Andersone3590582007-08-02 18:11:11 +0000331/// handleEndBlock - Remove dead stores to stack-allocated locations in the
Owen Anderson52aaabf2007-08-08 17:50:09 +0000332/// function end block. Ex:
333/// %A = alloca i32
334/// ...
335/// store i32 1, i32* %A
336/// ret void
Chris Lattner1adb6752008-11-28 00:27:14 +0000337bool DSE::handleEndBlock(BasicBlock &BB) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000338 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Owen Anderson32c4a052007-07-12 21:41:30 +0000339
340 bool MadeChange = false;
341
342 // Pointers alloca'd in this function are dead in the end block
Owen Anderson48d37802008-01-29 06:18:36 +0000343 SmallPtrSet<Value*, 64> deadPointers;
Owen Anderson32c4a052007-07-12 21:41:30 +0000344
Chris Lattner1adb6752008-11-28 00:27:14 +0000345 // Find all of the alloca'd pointers in the entry block.
Owen Anderson32c4a052007-07-12 21:41:30 +0000346 BasicBlock *Entry = BB.getParent()->begin();
347 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
348 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
349 deadPointers.insert(AI);
Chris Lattner1adb6752008-11-28 00:27:14 +0000350
351 // Treat byval arguments the same, stores to them are dead at the end of the
352 // function.
Owen Anderson48d37802008-01-29 06:18:36 +0000353 for (Function::arg_iterator AI = BB.getParent()->arg_begin(),
354 AE = BB.getParent()->arg_end(); AI != AE; ++AI)
355 if (AI->hasByValAttr())
356 deadPointers.insert(AI);
Owen Anderson32c4a052007-07-12 21:41:30 +0000357
358 // Scan the basic block backwards
359 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
360 --BBI;
361
Chris Lattner1adb6752008-11-28 00:27:14 +0000362 // If we find a store whose pointer is dead.
Chris Lattner2227a8a2010-11-30 01:37:52 +0000363 if (hasMemoryWrite(BBI)) {
Chris Lattner3590ef82010-11-30 05:30:45 +0000364 if (isRemovable(BBI)) {
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000365 // See through pointer-to-pointer bitcasts
Nick Lewycky90271472009-11-10 06:46:40 +0000366 Value *pointerOperand = getPointerOperand(BBI)->getUnderlyingObject();
Duncan Sandsd65a4da2008-10-01 15:25:41 +0000367
Owen Anderson6af19fd2008-01-25 10:10:33 +0000368 // Alloca'd pointers or byval arguments (which are functionally like
369 // alloca's) are valid candidates for removal.
Owen Anderson48d37802008-01-29 06:18:36 +0000370 if (deadPointers.count(pointerOperand)) {
Chris Lattner1adb6752008-11-28 00:27:14 +0000371 // DCE instructions only used to calculate that store.
Nick Lewycky90271472009-11-10 06:46:40 +0000372 Instruction *Dead = BBI;
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000373 ++BBI;
Nick Lewycky90271472009-11-10 06:46:40 +0000374 DeleteDeadInstruction(Dead, &deadPointers);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000375 ++NumFastStores;
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000376 MadeChange = true;
Nick Lewycky90271472009-11-10 06:46:40 +0000377 continue;
Owen Anderson2b9ec7f2007-08-26 21:14:47 +0000378 }
Owen Anderson32c4a052007-07-12 21:41:30 +0000379 }
Owen Anderson52aaabf2007-08-08 17:50:09 +0000380
Nick Lewycky90271472009-11-10 06:46:40 +0000381 // Because a memcpy or memmove is also a load, we can't skip it if we
382 // didn't remove it.
383 if (!isa<MemTransferInst>(BBI))
Owen Anderson48d37802008-01-29 06:18:36 +0000384 continue;
Owen Anderson52aaabf2007-08-08 17:50:09 +0000385 }
386
Nick Lewycky475d3d12010-01-03 04:39:07 +0000387 Value *killPointer = 0;
Dan Gohmanf372cf82010-10-19 22:54:46 +0000388 uint64_t killPointerSize = AliasAnalysis::UnknownSize;
Owen Anderson32c4a052007-07-12 21:41:30 +0000389
390 // If we encounter a use of the pointer, it is no longer considered dead
Chris Lattner1adb6752008-11-28 00:27:14 +0000391 if (LoadInst *L = dyn_cast<LoadInst>(BBI)) {
Nate Begeman53c5c622008-05-13 01:48:26 +0000392 // However, if this load is unused and not volatile, we can go ahead and
393 // remove it, and not have to worry about it making our pointer undead!
Dan Gohman8cb19d92008-04-28 19:51:27 +0000394 if (L->use_empty() && !L->isVolatile()) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000395 ++BBI;
Chris Lattner1adb6752008-11-28 00:27:14 +0000396 DeleteDeadInstruction(L, &deadPointers);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000397 ++NumFastOther;
Owen Anderson4e4b1162008-01-30 01:24:47 +0000398 MadeChange = true;
Owen Anderson4e4b1162008-01-30 01:24:47 +0000399 continue;
400 }
401
Owen Anderson32c4a052007-07-12 21:41:30 +0000402 killPointer = L->getPointerOperand();
Nick Lewycky475d3d12010-01-03 04:39:07 +0000403 } else if (VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000404 killPointer = V->getOperand(0);
Nick Lewycky90271472009-11-10 06:46:40 +0000405 } else if (isa<MemTransferInst>(BBI) &&
406 isa<ConstantInt>(cast<MemTransferInst>(BBI)->getLength())) {
407 killPointer = cast<MemTransferInst>(BBI)->getSource();
Owen Andersona82c9932008-02-04 04:53:00 +0000408 killPointerSize = cast<ConstantInt>(
Nick Lewycky90271472009-11-10 06:46:40 +0000409 cast<MemTransferInst>(BBI)->getLength())->getZExtValue();
Nick Lewycky475d3d12010-01-03 04:39:07 +0000410 } else if (AllocaInst *A = dyn_cast<AllocaInst>(BBI)) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000411 deadPointers.erase(A);
Owen Anderson4e4b1162008-01-30 01:24:47 +0000412
413 // Dead alloca's can be DCE'd when we reach them
Nick Lewycky6b016702008-01-30 08:01:28 +0000414 if (A->use_empty()) {
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000415 ++BBI;
Chris Lattner1adb6752008-11-28 00:27:14 +0000416 DeleteDeadInstruction(A, &deadPointers);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000417 ++NumFastOther;
Owen Anderson4e4b1162008-01-30 01:24:47 +0000418 MadeChange = true;
Owen Anderson4e4b1162008-01-30 01:24:47 +0000419 }
420
Owen Anderson32c4a052007-07-12 21:41:30 +0000421 continue;
Gabor Greif0a970692010-07-28 14:28:18 +0000422 } else if (CallSite CS = cast<Value>(BBI)) {
Owen Anderson50df9682007-08-08 17:58:56 +0000423 // If this call does not access memory, it can't
424 // be undeadifying any of our pointers.
Duncan Sands68b6f502007-12-01 07:51:45 +0000425 if (AA.doesNotAccessMemory(CS))
Owen Anderson50df9682007-08-08 17:58:56 +0000426 continue;
427
Owen Andersonddf4aee2007-08-08 18:38:28 +0000428 unsigned modRef = 0;
429 unsigned other = 0;
430
Owen Anderson32c4a052007-07-12 21:41:30 +0000431 // Remove any pointers made undead by the call from the dead set
Owen Anderson48d37802008-01-29 06:18:36 +0000432 std::vector<Value*> dead;
433 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
Owen Anderson32c4a052007-07-12 21:41:30 +0000434 E = deadPointers.end(); I != E; ++I) {
Owen Andersonddf4aee2007-08-08 18:38:28 +0000435 // HACK: if we detect that our AA is imprecise, it's not
436 // worth it to scan the rest of the deadPointers set. Just
437 // assume that the AA will return ModRef for everything, and
438 // go ahead and bail.
439 if (modRef >= 16 && other == 0) {
440 deadPointers.clear();
441 return MadeChange;
442 }
Nick Lewycky475d3d12010-01-03 04:39:07 +0000443
Owen Anderson32c4a052007-07-12 21:41:30 +0000444 // See if the call site touches it
Nick Lewycky475d3d12010-01-03 04:39:07 +0000445 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CS, *I,
446 getPointerSize(*I));
Owen Andersonddf4aee2007-08-08 18:38:28 +0000447
448 if (A == AliasAnalysis::ModRef)
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000449 ++modRef;
Owen Andersonddf4aee2007-08-08 18:38:28 +0000450 else
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000451 ++other;
Owen Andersonddf4aee2007-08-08 18:38:28 +0000452
Owen Anderson9c9ef212007-07-13 18:26:26 +0000453 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
Owen Anderson32c4a052007-07-12 21:41:30 +0000454 dead.push_back(*I);
455 }
456
Owen Anderson48d37802008-01-29 06:18:36 +0000457 for (std::vector<Value*>::iterator I = dead.begin(), E = dead.end();
Owen Anderson32c4a052007-07-12 21:41:30 +0000458 I != E; ++I)
Owen Anderson48d37802008-01-29 06:18:36 +0000459 deadPointers.erase(*I);
Owen Anderson32c4a052007-07-12 21:41:30 +0000460
461 continue;
Chris Lattner1adb6752008-11-28 00:27:14 +0000462 } else if (isInstructionTriviallyDead(BBI)) {
Owen Anderson4e4b1162008-01-30 01:24:47 +0000463 // For any non-memory-affecting non-terminators, DCE them as we reach them
Chris Lattner1adb6752008-11-28 00:27:14 +0000464 Instruction *Inst = BBI;
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000465 ++BBI;
Chris Lattner1adb6752008-11-28 00:27:14 +0000466 DeleteDeadInstruction(Inst, &deadPointers);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000467 ++NumFastOther;
Chris Lattner1adb6752008-11-28 00:27:14 +0000468 MadeChange = true;
469 continue;
Owen Anderson32c4a052007-07-12 21:41:30 +0000470 }
471
472 if (!killPointer)
473 continue;
Duncan Sandsd65a4da2008-10-01 15:25:41 +0000474
475 killPointer = killPointer->getUnderlyingObject();
476
Owen Anderson32c4a052007-07-12 21:41:30 +0000477 // Deal with undead pointers
Owen Andersona82c9932008-02-04 04:53:00 +0000478 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
Chris Lattner1adb6752008-11-28 00:27:14 +0000479 deadPointers);
Owen Anderson32c4a052007-07-12 21:41:30 +0000480 }
481
482 return MadeChange;
483}
484
Owen Andersonddf4aee2007-08-08 18:38:28 +0000485/// RemoveUndeadPointers - check for uses of a pointer that make it
486/// undead when scanning for dead stores to alloca's.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000487bool DSE::RemoveUndeadPointers(Value *killPointer, uint64_t killPointerSize,
Chris Lattner1adb6752008-11-28 00:27:14 +0000488 BasicBlock::iterator &BBI,
Nick Lewycky475d3d12010-01-03 04:39:07 +0000489 SmallPtrSet<Value*, 64> &deadPointers) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000490 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Nick Lewycky475d3d12010-01-03 04:39:07 +0000491
Owen Andersonddf4aee2007-08-08 18:38:28 +0000492 // If the kill pointer can be easily reduced to an alloca,
Chris Lattner1adb6752008-11-28 00:27:14 +0000493 // don't bother doing extraneous AA queries.
Owen Anderson48d37802008-01-29 06:18:36 +0000494 if (deadPointers.count(killPointer)) {
495 deadPointers.erase(killPointer);
Owen Andersonddf4aee2007-08-08 18:38:28 +0000496 return false;
497 }
498
Chris Lattner1adb6752008-11-28 00:27:14 +0000499 // A global can't be in the dead pointer set.
500 if (isa<GlobalValue>(killPointer))
501 return false;
502
Owen Anderson32c4a052007-07-12 21:41:30 +0000503 bool MadeChange = false;
504
Chris Lattner1adb6752008-11-28 00:27:14 +0000505 SmallVector<Value*, 16> undead;
Nick Lewycky475d3d12010-01-03 04:39:07 +0000506
Owen Anderson48d37802008-01-29 06:18:36 +0000507 for (SmallPtrSet<Value*, 64>::iterator I = deadPointers.begin(),
Nick Lewycky475d3d12010-01-03 04:39:07 +0000508 E = deadPointers.end(); I != E; ++I) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000509 // See if this pointer could alias it
Nick Lewycky475d3d12010-01-03 04:39:07 +0000510 AliasAnalysis::AliasResult A = AA.alias(*I, getPointerSize(*I),
Owen Andersona82c9932008-02-04 04:53:00 +0000511 killPointer, killPointerSize);
Owen Anderson32c4a052007-07-12 21:41:30 +0000512
513 // If it must-alias and a store, we can delete it
514 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
Nick Lewycky475d3d12010-01-03 04:39:07 +0000515 StoreInst *S = cast<StoreInst>(BBI);
Owen Anderson32c4a052007-07-12 21:41:30 +0000516
517 // Remove it!
Nick Lewycky475d3d12010-01-03 04:39:07 +0000518 ++BBI;
Chris Lattner1adb6752008-11-28 00:27:14 +0000519 DeleteDeadInstruction(S, &deadPointers);
Dan Gohmand2d1ae12010-06-22 15:08:57 +0000520 ++NumFastStores;
Owen Anderson32c4a052007-07-12 21:41:30 +0000521 MadeChange = true;
522
523 continue;
524
525 // Otherwise, it is undead
Chris Lattner1adb6752008-11-28 00:27:14 +0000526 } else if (A != AliasAnalysis::NoAlias)
527 undead.push_back(*I);
Owen Anderson32c4a052007-07-12 21:41:30 +0000528 }
529
Chris Lattner1adb6752008-11-28 00:27:14 +0000530 for (SmallVector<Value*, 16>::iterator I = undead.begin(), E = undead.end();
Owen Anderson32c4a052007-07-12 21:41:30 +0000531 I != E; ++I)
Owen Anderson48d37802008-01-29 06:18:36 +0000532 deadPointers.erase(*I);
Owen Anderson32c4a052007-07-12 21:41:30 +0000533
534 return MadeChange;
535}
536
Chris Lattner1adb6752008-11-28 00:27:14 +0000537/// DeleteDeadInstruction - Delete this instruction. Before we do, go through
538/// and zero out all the operands of this instruction. If any of them become
539/// dead, delete them and the computation tree that feeds them.
540///
541/// If ValueSet is non-null, remove any deleted instructions from it as well.
542///
543void DSE::DeleteDeadInstruction(Instruction *I,
544 SmallPtrSet<Value*, 64> *ValueSet) {
545 SmallVector<Instruction*, 32> NowDeadInsts;
546
547 NowDeadInsts.push_back(I);
548 --NumFastOther;
Owen Anderson5e72db32007-07-11 00:46:18 +0000549
Chris Lattner1adb6752008-11-28 00:27:14 +0000550 // Before we touch this instruction, remove it from memdep!
551 MemoryDependenceAnalysis &MDA = getAnalysis<MemoryDependenceAnalysis>();
Dan Gohman28943872010-01-05 16:27:25 +0000552 do {
553 Instruction *DeadInst = NowDeadInsts.pop_back_val();
Owen Andersonbf971aa2007-07-11 19:03:09 +0000554
Chris Lattner1adb6752008-11-28 00:27:14 +0000555 ++NumFastOther;
556
557 // This instruction is dead, zap it, in stages. Start by removing it from
558 // MemDep, which needs to know the operands and needs it to be in the
559 // function.
560 MDA.removeInstruction(DeadInst);
561
562 for (unsigned op = 0, e = DeadInst->getNumOperands(); op != e; ++op) {
563 Value *Op = DeadInst->getOperand(op);
564 DeadInst->setOperand(op, 0);
565
566 // If this operand just became dead, add it to the NowDeadInsts list.
567 if (!Op->use_empty()) continue;
568
569 if (Instruction *OpI = dyn_cast<Instruction>(Op))
570 if (isInstructionTriviallyDead(OpI))
571 NowDeadInsts.push_back(OpI);
572 }
573
574 DeadInst->eraseFromParent();
575
576 if (ValueSet) ValueSet->erase(DeadInst);
Dan Gohman28943872010-01-05 16:27:25 +0000577 } while (!NowDeadInsts.empty());
Owen Anderson5e72db32007-07-11 00:46:18 +0000578}
Nick Lewycky475d3d12010-01-03 04:39:07 +0000579
Dan Gohmanf372cf82010-10-19 22:54:46 +0000580uint64_t DSE::getPointerSize(Value *V) const {
Nick Lewycky475d3d12010-01-03 04:39:07 +0000581 if (TD) {
582 if (AllocaInst *A = dyn_cast<AllocaInst>(V)) {
583 // Get size information for the alloca
584 if (ConstantInt *C = dyn_cast<ConstantInt>(A->getArraySize()))
585 return C->getZExtValue() * TD->getTypeAllocSize(A->getAllocatedType());
586 } else {
587 assert(isa<Argument>(V) && "Expected AllocaInst or Argument!");
588 const PointerType *PT = cast<PointerType>(V->getType());
589 return TD->getTypeAllocSize(PT->getElementType());
590 }
591 }
Dan Gohman14fe8cf22010-10-19 17:06:23 +0000592 return AliasAnalysis::UnknownSize;
Nick Lewycky475d3d12010-01-03 04:39:07 +0000593}