blob: 39a0aba2c95dd1d98e23658ef0fffc8248f0d8c9 [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//
Owen Andersonbf971aa2007-07-11 19:03:09 +00005// This file was developed by Owen Anderson and is distributed under
Owen Anderson5e72db32007-07-11 00:46:18 +00006// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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"
23#include "llvm/Pass.h"
24#include "llvm/ADT/SetVector.h"
25#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 Anderson5e72db32007-07-11 00:46:18 +000028#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Owen Andersonaa071722007-07-11 23:19:17 +000029#include "llvm/Target/TargetData.h"
Owen Anderson5e72db32007-07-11 00:46:18 +000030#include "llvm/Transforms/Utils/Local.h"
31#include "llvm/Support/Compiler.h"
32using namespace llvm;
33
34STATISTIC(NumFastStores, "Number of stores deleted");
35STATISTIC(NumFastOther , "Number of other instrs removed");
36
37namespace {
Owen Anderson10e52ed2007-08-01 06:36:51 +000038 struct VISIBILITY_HIDDEN DSE : public FunctionPass {
Owen Anderson5e72db32007-07-11 00:46:18 +000039 static char ID; // Pass identification, replacement for typeid
Owen Anderson10e52ed2007-08-01 06:36:51 +000040 DSE() : FunctionPass((intptr_t)&ID) {}
Owen Anderson5e72db32007-07-11 00:46:18 +000041
42 virtual bool runOnFunction(Function &F) {
43 bool Changed = false;
44 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
45 Changed |= runOnBasicBlock(*I);
46 return Changed;
47 }
48
49 bool runOnBasicBlock(BasicBlock &BB);
Owen Andersone3590582007-08-02 18:11:11 +000050 bool handleFreeWithNonTrivialDependency(FreeInst* F,
51 Instruction* dependency,
52 SetVector<Instruction*>& possiblyDead);
Owen Anderson32c4a052007-07-12 21:41:30 +000053 bool handleEndBlock(BasicBlock& BB, SetVector<Instruction*>& possiblyDead);
Owen Anderson52aaabf2007-08-08 17:50:09 +000054 bool RemoveUndeadPointers(Value* pointer,
Owen Anderson32c4a052007-07-12 21:41:30 +000055 BasicBlock::iterator& BBI,
Owen Anderson52aaabf2007-08-08 17:50:09 +000056 SmallPtrSet<AllocaInst*, 64>& deadPointers,
Owen Anderson32c4a052007-07-12 21:41:30 +000057 SetVector<Instruction*>& possiblyDead);
Owen Anderson5e72db32007-07-11 00:46:18 +000058 void DeleteDeadInstructionChains(Instruction *I,
59 SetVector<Instruction*> &DeadInsts);
Owen Anderson0aecf0e2007-08-08 04:52:29 +000060
Owen Andersonb17ab032007-08-08 06:06:02 +000061 /// Find the base pointer that a pointer came from
62 /// Because this is used to find pointers that originate
63 /// from allocas, it is safe to ignore GEP indices, since
64 /// either the store will be in the alloca, and thus dead,
65 /// or beyond the end of the alloca, and thus undefined.
Owen Anderson9c9ef212007-07-13 18:26:26 +000066 void TranslatePointerBitCasts(Value*& v) {
Owen Andersone3590582007-08-02 18:11:11 +000067 assert(isa<PointerType>(v->getType()) &&
68 "Translating a non-pointer type?");
Owen Anderson0aecf0e2007-08-08 04:52:29 +000069 while (true) {
Owen Anderson09f86992007-07-16 23:34:39 +000070 if (BitCastInst* C = dyn_cast<BitCastInst>(v))
71 v = C->getOperand(0);
72 else if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(v))
73 v = G->getOperand(0);
Owen Anderson0aecf0e2007-08-08 04:52:29 +000074 else
75 break;
76 }
Owen Anderson9c9ef212007-07-13 18:26:26 +000077 }
Owen Anderson5e72db32007-07-11 00:46:18 +000078
79 // getAnalysisUsage - We require post dominance frontiers (aka Control
80 // Dependence Graph)
81 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
82 AU.setPreservesCFG();
Owen Andersonaa071722007-07-11 23:19:17 +000083 AU.addRequired<TargetData>();
84 AU.addRequired<AliasAnalysis>();
Owen Anderson5e72db32007-07-11 00:46:18 +000085 AU.addRequired<MemoryDependenceAnalysis>();
Owen Andersonaa071722007-07-11 23:19:17 +000086 AU.addPreserved<AliasAnalysis>();
Owen Anderson5e72db32007-07-11 00:46:18 +000087 AU.addPreserved<MemoryDependenceAnalysis>();
88 }
89 };
Owen Anderson10e52ed2007-08-01 06:36:51 +000090 char DSE::ID = 0;
91 RegisterPass<DSE> X("dse", "Dead Store Elimination");
Owen Anderson5e72db32007-07-11 00:46:18 +000092}
93
Owen Anderson10e52ed2007-08-01 06:36:51 +000094FunctionPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }
Owen Anderson5e72db32007-07-11 00:46:18 +000095
Owen Anderson10e52ed2007-08-01 06:36:51 +000096bool DSE::runOnBasicBlock(BasicBlock &BB) {
Owen Anderson5e72db32007-07-11 00:46:18 +000097 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
98
Owen Andersonbf971aa2007-07-11 19:03:09 +000099 // Record the last-seen store to this pointer
Owen Anderson5e72db32007-07-11 00:46:18 +0000100 DenseMap<Value*, StoreInst*> lastStore;
Owen Andersonbf971aa2007-07-11 19:03:09 +0000101 // Record instructions possibly made dead by deleting a store
Owen Anderson5e72db32007-07-11 00:46:18 +0000102 SetVector<Instruction*> possiblyDead;
103
104 bool MadeChange = false;
105
106 // Do a top-down walk on the BB
Owen Andersone3590582007-08-02 18:11:11 +0000107 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end();
108 BBI != BBE; ++BBI) {
Owen Anderson14414702007-07-11 21:06:56 +0000109 // If we find a store or a free...
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000110 if (!isa<StoreInst>(BBI) && !isa<FreeInst>(BBI))
111 continue;
Owen Anderson9c9ef212007-07-13 18:26:26 +0000112
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000113 Value* pointer = 0;
114 if (StoreInst* S = dyn_cast<StoreInst>(BBI))
115 pointer = S->getPointerOperand();
Owen Andersonb17ab032007-08-08 06:06:02 +0000116 else
117 pointer = cast<FreeInst>(BBI)->getPointerOperand();
Owen Anderson5e72db32007-07-11 00:46:18 +0000118
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000119 StoreInst*& last = lastStore[pointer];
120 bool deletedStore = false;
121
122 // ... to a pointer that has been stored to before...
123 if (last) {
124 Instruction* dep = MD.getDependency(BBI);
Owen Anderson5e72db32007-07-11 00:46:18 +0000125
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000126 // ... and no other memory dependencies are between them....
127 while (dep != MemoryDependenceAnalysis::None &&
128 dep != MemoryDependenceAnalysis::NonLocal &&
129 isa<StoreInst>(dep)) {
130 if (dep != last) {
131 dep = MD.getDependency(BBI, dep);
132 continue;
Owen Andersond4451de2007-07-12 18:08:51 +0000133 }
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000134
135 // Remove it!
136 MD.removeInstruction(last);
137
138 // DCE instructions only used to calculate that store
139 if (Instruction* D = dyn_cast<Instruction>(last->getOperand(0)))
140 possiblyDead.insert(D);
141 if (Instruction* D = dyn_cast<Instruction>(last->getOperand(1)))
142 possiblyDead.insert(D);
143
144 last->eraseFromParent();
145 NumFastStores++;
146 deletedStore = true;
147 MadeChange = true;
148
149 break;
Owen Anderson5e72db32007-07-11 00:46:18 +0000150 }
Owen Anderson0aecf0e2007-08-08 04:52:29 +0000151 }
152
153 // Handle frees whose dependencies are non-trivial.
154 if (FreeInst* F = dyn_cast<FreeInst>(BBI)) {
155 if (!deletedStore)
156 MadeChange |= handleFreeWithNonTrivialDependency(F,
157 MD.getDependency(F),
158 possiblyDead);
159 // No known stores after the free
160 last = 0;
161 } else {
162 // Update our most-recent-store map.
163 last = cast<StoreInst>(BBI);
Owen Anderson5e72db32007-07-11 00:46:18 +0000164 }
165 }
166
Owen Anderson32c4a052007-07-12 21:41:30 +0000167 // If this block ends in a return, unwind, unreachable, and eventually
168 // tailcall, then all allocas are dead at its end.
169 if (BB.getTerminator()->getNumSuccessors() == 0)
170 MadeChange |= handleEndBlock(BB, possiblyDead);
171
Owen Anderson5e72db32007-07-11 00:46:18 +0000172 // Do a trivial DCE
173 while (!possiblyDead.empty()) {
174 Instruction *I = possiblyDead.back();
175 possiblyDead.pop_back();
176 DeleteDeadInstructionChains(I, possiblyDead);
177 }
178
179 return MadeChange;
180}
181
Owen Andersonaa071722007-07-11 23:19:17 +0000182/// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
183/// dependency is a store to a field of that structure
Owen Anderson10e52ed2007-08-01 06:36:51 +0000184bool DSE::handleFreeWithNonTrivialDependency(FreeInst* F, Instruction* dep,
Owen Andersone3590582007-08-02 18:11:11 +0000185 SetVector<Instruction*>& possiblyDead) {
Owen Andersonaa071722007-07-11 23:19:17 +0000186 TargetData &TD = getAnalysis<TargetData>();
187 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
188 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
189
Owen Andersond4451de2007-07-12 18:08:51 +0000190 if (dep == MemoryDependenceAnalysis::None ||
191 dep == MemoryDependenceAnalysis::NonLocal)
192 return false;
193
194 StoreInst* dependency = dyn_cast<StoreInst>(dep);
195 if (!dependency)
196 return false;
197
Owen Andersonaa071722007-07-11 23:19:17 +0000198 Value* depPointer = dependency->getPointerOperand();
Owen Andersone3590582007-08-02 18:11:11 +0000199 const Type* depType = dependency->getOperand(0)->getType();
200 unsigned depPointerSize = TD.getTypeSize(depType);
Owen Anderson9c9ef212007-07-13 18:26:26 +0000201
Owen Andersonaa071722007-07-11 23:19:17 +0000202 // Check for aliasing
203 AliasAnalysis::AliasResult A = AA.alias(F->getPointerOperand(), ~0UL,
204 depPointer, depPointerSize);
205
206 if (A == AliasAnalysis::MustAlias) {
207 // Remove it!
208 MD.removeInstruction(dependency);
Owen Andersonaa071722007-07-11 23:19:17 +0000209
210 // DCE instructions only used to calculate that store
211 if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(0)))
212 possiblyDead.insert(D);
Owen Anderson9c9ef212007-07-13 18:26:26 +0000213 if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(1)))
214 possiblyDead.insert(D);
Owen Andersonaa071722007-07-11 23:19:17 +0000215
216 dependency->eraseFromParent();
217 NumFastStores++;
218 return true;
219 }
220
221 return false;
222}
223
Owen Andersone3590582007-08-02 18:11:11 +0000224/// handleEndBlock - Remove dead stores to stack-allocated locations in the
Owen Anderson52aaabf2007-08-08 17:50:09 +0000225/// function end block. Ex:
226/// %A = alloca i32
227/// ...
228/// store i32 1, i32* %A
229/// ret void
Owen Andersone3590582007-08-02 18:11:11 +0000230bool DSE::handleEndBlock(BasicBlock& BB,
231 SetVector<Instruction*>& possiblyDead) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000232 TargetData &TD = getAnalysis<TargetData>();
233 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
234 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
235
236 bool MadeChange = false;
237
238 // Pointers alloca'd in this function are dead in the end block
Owen Anderson52aaabf2007-08-08 17:50:09 +0000239 SmallPtrSet<AllocaInst*, 64> deadPointers;
Owen Anderson32c4a052007-07-12 21:41:30 +0000240
241 // Find all of the alloca'd pointers in the entry block
242 BasicBlock *Entry = BB.getParent()->begin();
243 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
244 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
245 deadPointers.insert(AI);
246
247 // Scan the basic block backwards
248 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
249 --BBI;
250
251 if (deadPointers.empty())
252 break;
253
Owen Anderson32c4a052007-07-12 21:41:30 +0000254 // If we find a store whose pointer is dead...
255 if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
Owen Anderson9c9ef212007-07-13 18:26:26 +0000256 Value* pointerOperand = S->getPointerOperand();
257 // See through pointer-to-pointer bitcasts
258 TranslatePointerBitCasts(pointerOperand);
259
260 if (deadPointers.count(pointerOperand)){
Owen Anderson32c4a052007-07-12 21:41:30 +0000261 // Remove it!
262 MD.removeInstruction(S);
263
264 // DCE instructions only used to calculate that store
265 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
266 possiblyDead.insert(D);
Owen Anderson9c9ef212007-07-13 18:26:26 +0000267 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
268 possiblyDead.insert(D);
Owen Anderson32c4a052007-07-12 21:41:30 +0000269
270 BBI++;
271 S->eraseFromParent();
272 NumFastStores++;
273 MadeChange = true;
Owen Anderson32c4a052007-07-12 21:41:30 +0000274 }
Owen Anderson52aaabf2007-08-08 17:50:09 +0000275
276 continue;
277 }
278
279 Value* killPointer = 0;
Owen Anderson32c4a052007-07-12 21:41:30 +0000280
281 // If we encounter a use of the pointer, it is no longer considered dead
Owen Anderson52aaabf2007-08-08 17:50:09 +0000282 if (LoadInst* L = dyn_cast<LoadInst>(BBI)) {
Owen Anderson32c4a052007-07-12 21:41:30 +0000283 killPointer = L->getPointerOperand();
Owen Anderson32c4a052007-07-12 21:41:30 +0000284 } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
285 killPointer = V->getOperand(0);
Owen Anderson32c4a052007-07-12 21:41:30 +0000286 } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
287 deadPointers.erase(A);
288 continue;
289 } else if (CallSite::get(BBI).getInstruction() != 0) {
290 // Remove any pointers made undead by the call from the dead set
291 std::vector<Instruction*> dead;
Owen Anderson52aaabf2007-08-08 17:50:09 +0000292 for (SmallPtrSet<AllocaInst*, 64>::iterator I = deadPointers.begin(),
Owen Anderson32c4a052007-07-12 21:41:30 +0000293 E = deadPointers.end(); I != E; ++I) {
294 // Get size information for the alloca
295 unsigned pointerSize = ~0UL;
296 if (ConstantInt* C = dyn_cast<ConstantInt>((*I)->getArraySize()))
Owen Andersone3590582007-08-02 18:11:11 +0000297 pointerSize = C->getZExtValue() * \
298 TD.getTypeSize((*I)->getAllocatedType());
Owen Anderson32c4a052007-07-12 21:41:30 +0000299
300 // See if the call site touches it
301 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CallSite::get(BBI),
302 *I, pointerSize);
Owen Anderson9c9ef212007-07-13 18:26:26 +0000303 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
Owen Anderson32c4a052007-07-12 21:41:30 +0000304 dead.push_back(*I);
305 }
306
307 for (std::vector<Instruction*>::iterator I = dead.begin(), E = dead.end();
308 I != E; ++I)
309 deadPointers.erase(*I);
310
311 continue;
312 }
313
314 if (!killPointer)
315 continue;
316
317 // Deal with undead pointers
Owen Anderson52aaabf2007-08-08 17:50:09 +0000318 MadeChange |= RemoveUndeadPointers(killPointer, BBI,
Owen Anderson32c4a052007-07-12 21:41:30 +0000319 deadPointers, possiblyDead);
320 }
321
322 return MadeChange;
323}
324
Owen Anderson52aaabf2007-08-08 17:50:09 +0000325/// RemoveUndeadPointers - takes an instruction and a setvector of
326/// dead instructions. If I is dead, it is erased, and its operands are
327/// checked for deadness. If they are dead, they are added to the dead
328/// setvector.
329bool DSE::RemoveUndeadPointers(Value* killPointer,
Owen Anderson32c4a052007-07-12 21:41:30 +0000330 BasicBlock::iterator& BBI,
Owen Anderson52aaabf2007-08-08 17:50:09 +0000331 SmallPtrSet<AllocaInst*, 64>& deadPointers,
Owen Anderson32c4a052007-07-12 21:41:30 +0000332 SetVector<Instruction*>& possiblyDead) {
333 TargetData &TD = getAnalysis<TargetData>();
334 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
335 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
336
337 bool MadeChange = false;
338
339 std::vector<Instruction*> undead;
340
Owen Anderson52aaabf2007-08-08 17:50:09 +0000341 for (SmallPtrSet<AllocaInst*, 64>::iterator I = deadPointers.begin(),
Owen Anderson32c4a052007-07-12 21:41:30 +0000342 E = deadPointers.end(); I != E; ++I) {
343 // Get size information for the alloca
344 unsigned pointerSize = ~0UL;
345 if (ConstantInt* C = dyn_cast<ConstantInt>((*I)->getArraySize()))
Owen Andersone3590582007-08-02 18:11:11 +0000346 pointerSize = C->getZExtValue() * \
347 TD.getTypeSize((*I)->getAllocatedType());
Owen Anderson32c4a052007-07-12 21:41:30 +0000348
349 // See if this pointer could alias it
Owen Andersone3590582007-08-02 18:11:11 +0000350 AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize,
Owen Anderson52aaabf2007-08-08 17:50:09 +0000351 killPointer, ~0UL);
Owen Anderson32c4a052007-07-12 21:41:30 +0000352
353 // If it must-alias and a store, we can delete it
354 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
355 StoreInst* S = cast<StoreInst>(BBI);
356
357 // Remove it!
358 MD.removeInstruction(S);
359
360 // DCE instructions only used to calculate that store
361 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
362 possiblyDead.insert(D);
Owen Anderson9c9ef212007-07-13 18:26:26 +0000363 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
364 possiblyDead.insert(D);
Owen Anderson32c4a052007-07-12 21:41:30 +0000365
366 BBI++;
367 S->eraseFromParent();
368 NumFastStores++;
369 MadeChange = true;
370
371 continue;
372
373 // Otherwise, it is undead
374 } else if (A != AliasAnalysis::NoAlias)
375 undead.push_back(*I);
376 }
377
378 for (std::vector<Instruction*>::iterator I = undead.begin(), E = undead.end();
379 I != E; ++I)
380 deadPointers.erase(*I);
381
382 return MadeChange;
383}
384
Owen Anderson52aaabf2007-08-08 17:50:09 +0000385/// DeleteDeadInstructionChains - takes an instruction and a setvector of
386/// dead instructions. If I is dead, it is erased, and its operands are
387/// checked for deadness. If they are dead, they are added to the dead
388/// setvector.
Owen Anderson10e52ed2007-08-01 06:36:51 +0000389void DSE::DeleteDeadInstructionChains(Instruction *I,
Owen Anderson5e72db32007-07-11 00:46:18 +0000390 SetVector<Instruction*> &DeadInsts) {
391 // Instruction must be dead.
392 if (!I->use_empty() || !isInstructionTriviallyDead(I)) return;
393
394 // Let the memory dependence know
395 getAnalysis<MemoryDependenceAnalysis>().removeInstruction(I);
396
397 // See if this made any operands dead. We do it this way in case the
398 // instruction uses the same operand twice. We don't want to delete a
399 // value then reference it.
400 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Owen Andersonbf971aa2007-07-11 19:03:09 +0000401 if (I->getOperand(i)->hasOneUse())
402 if (Instruction* Op = dyn_cast<Instruction>(I->getOperand(i)))
403 DeadInsts.insert(Op); // Attempt to nuke it later.
404
Owen Anderson5e72db32007-07-11 00:46:18 +0000405 I->setOperand(i, 0); // Drop from the operand list.
406 }
407
408 I->eraseFromParent();
409 ++NumFastOther;
410}