blob: 45985ba7175a74a1851fc45e201b2d7c07865b1b [file] [log] [blame]
Owen Anderson5e72db32007-07-11 00:46:18 +00001//===- DeadStoreElimination.cpp - Dead Store Elimination ------------------===//
2//
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
18#define DEBUG_TYPE "fdse"
19#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 {
38 struct VISIBILITY_HIDDEN FDSE : public FunctionPass {
39 static char ID; // Pass identification, replacement for typeid
40 FDSE() : FunctionPass((intptr_t)&ID) {}
41
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 Andersond4451de2007-07-12 18:08:51 +000050 bool handleFreeWithNonTrivialDependency(FreeInst* F, Instruction* dependency,
Owen Andersonaa071722007-07-11 23:19:17 +000051 SetVector<Instruction*>& possiblyDead);
Owen Anderson32c4a052007-07-12 21:41:30 +000052 bool handleEndBlock(BasicBlock& BB, SetVector<Instruction*>& possiblyDead);
53 bool RemoveUndeadPointers(Value* pointer, unsigned pointerSize,
54 BasicBlock::iterator& BBI,
55 SmallPtrSet<AllocaInst*, 4>& deadPointers,
56 SetVector<Instruction*>& possiblyDead);
Owen Anderson5e72db32007-07-11 00:46:18 +000057 void DeleteDeadInstructionChains(Instruction *I,
58 SetVector<Instruction*> &DeadInsts);
Owen Anderson9c9ef212007-07-13 18:26:26 +000059 void TranslatePointerBitCasts(Value*& v) {
60 assert(isa<PointerType>(v->getType()) && "Translating a non-pointer type?");
61
62 // See through pointer-to-pointer bitcasts
Owen Andersond975efa2007-07-13 22:50:48 +000063 while (isa<BitCastInst>(v) || isa<GetElementPtrInst>(v))
64 if (BitCastInst* C = dyn_cast<BitCastInst>(v)) {
65 if (isa<PointerType>(C->getSrcTy()))
66 v = C->getOperand(0);
67 else
68 break;
69 } else if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(v)) {
70 if (G->hasAllZeroIndices())
71 v = G->getOperand(0);
72 else
73 break;
74 }
Owen Anderson9c9ef212007-07-13 18:26:26 +000075 }
Owen Anderson5e72db32007-07-11 00:46:18 +000076
77 // getAnalysisUsage - We require post dominance frontiers (aka Control
78 // Dependence Graph)
79 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
80 AU.setPreservesCFG();
Owen Andersonaa071722007-07-11 23:19:17 +000081 AU.addRequired<TargetData>();
82 AU.addRequired<AliasAnalysis>();
Owen Anderson5e72db32007-07-11 00:46:18 +000083 AU.addRequired<MemoryDependenceAnalysis>();
Owen Andersonaa071722007-07-11 23:19:17 +000084 AU.addPreserved<AliasAnalysis>();
Owen Anderson5e72db32007-07-11 00:46:18 +000085 AU.addPreserved<MemoryDependenceAnalysis>();
86 }
87 };
88 char FDSE::ID = 0;
89 RegisterPass<FDSE> X("fdse", "Fast Dead Store Elimination");
90}
91
92FunctionPass *llvm::createFastDeadStoreEliminationPass() { return new FDSE(); }
93
94bool FDSE::runOnBasicBlock(BasicBlock &BB) {
95 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
96
Owen Andersonbf971aa2007-07-11 19:03:09 +000097 // Record the last-seen store to this pointer
Owen Anderson5e72db32007-07-11 00:46:18 +000098 DenseMap<Value*, StoreInst*> lastStore;
Owen Andersonbf971aa2007-07-11 19:03:09 +000099 // Record instructions possibly made dead by deleting a store
Owen Anderson5e72db32007-07-11 00:46:18 +0000100 SetVector<Instruction*> possiblyDead;
101
102 bool MadeChange = false;
103
104 // Do a top-down walk on the BB
105 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ++BBI) {
Owen Anderson14414702007-07-11 21:06:56 +0000106 // If we find a store or a free...
Owen Andersone7201442007-07-11 20:38:34 +0000107 if (isa<StoreInst>(BBI) || isa<FreeInst>(BBI)) {
108 Value* pointer = 0;
109 if (StoreInst* S = dyn_cast<StoreInst>(BBI))
110 pointer = S->getPointerOperand();
111 else if (FreeInst* F = dyn_cast<FreeInst>(BBI))
112 pointer = F->getPointerOperand();
Owen Anderson9c9ef212007-07-13 18:26:26 +0000113
Owen Andersone7201442007-07-11 20:38:34 +0000114 assert(pointer && "Not a free or a store?");
115
116 StoreInst*& last = lastStore[pointer];
Owen Andersond4451de2007-07-12 18:08:51 +0000117 bool deletedStore = false;
Owen Anderson5e72db32007-07-11 00:46:18 +0000118
119 // ... to a pointer that has been stored to before...
Owen Andersonbf971aa2007-07-11 19:03:09 +0000120 if (last) {
Owen Anderson5e72db32007-07-11 00:46:18 +0000121
Owen Anderson7fcaaad2007-07-16 21:52:50 +0000122 Instruction* dep = MD.getDependency(BBI);
123
Owen Anderson5e72db32007-07-11 00:46:18 +0000124 // ... and no other memory dependencies are between them....
Owen Anderson7fcaaad2007-07-16 21:52:50 +0000125 while (dep != MemoryDependenceAnalysis::None &&
126 dep != MemoryDependenceAnalysis::NonLocal &&
127 isa<StoreInst>(dep)) {
128 if (dep == last) {
129
130 // Remove it!
131 MD.removeInstruction(last);
Owen Andersone7201442007-07-11 20:38:34 +0000132
Owen Anderson7fcaaad2007-07-16 21:52:50 +0000133 // DCE instructions only used to calculate that store
134 if (Instruction* D = dyn_cast<Instruction>(last->getOperand(0)))
135 possiblyDead.insert(D);
136 if (Instruction* D = dyn_cast<Instruction>(last->getOperand(1)))
137 possiblyDead.insert(D);
Owen Anderson5e72db32007-07-11 00:46:18 +0000138
Owen Anderson7fcaaad2007-07-16 21:52:50 +0000139 last->eraseFromParent();
140 NumFastStores++;
141 deletedStore = true;
142 MadeChange = true;
143
144 break;
145 } else {
146 dep = MD.getDependency(BBI, dep);
147 }
Owen Andersond4451de2007-07-12 18:08:51 +0000148 }
Owen Anderson5e72db32007-07-11 00:46:18 +0000149 }
150
Owen Andersond4451de2007-07-12 18:08:51 +0000151 // Handle frees whose dependencies are non-trivial
152 if (FreeInst* F = dyn_cast<FreeInst>(BBI))
153 if (!deletedStore)
154 MadeChange |= handleFreeWithNonTrivialDependency(F, MD.getDependency(F),
155 possiblyDead);
156
Owen Anderson5e72db32007-07-11 00:46:18 +0000157 // Update our most-recent-store map
Owen Andersone7201442007-07-11 20:38:34 +0000158 if (StoreInst* S = dyn_cast<StoreInst>(BBI))
159 last = S;
160 else
161 last = 0;
Owen Anderson5e72db32007-07-11 00:46:18 +0000162 }
163 }
164
Owen Anderson32c4a052007-07-12 21:41:30 +0000165 // If this block ends in a return, unwind, unreachable, and eventually
166 // tailcall, then all allocas are dead at its end.
167 if (BB.getTerminator()->getNumSuccessors() == 0)
168 MadeChange |= handleEndBlock(BB, possiblyDead);
169
Owen Anderson5e72db32007-07-11 00:46:18 +0000170 // Do a trivial DCE
171 while (!possiblyDead.empty()) {
172 Instruction *I = possiblyDead.back();
173 possiblyDead.pop_back();
174 DeleteDeadInstructionChains(I, possiblyDead);
175 }
176
177 return MadeChange;
178}
179
Owen Andersonaa071722007-07-11 23:19:17 +0000180/// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
181/// dependency is a store to a field of that structure
Owen Andersond4451de2007-07-12 18:08:51 +0000182bool FDSE::handleFreeWithNonTrivialDependency(FreeInst* F, Instruction* dep,
Owen Andersonaa071722007-07-11 23:19:17 +0000183 SetVector<Instruction*>& possiblyDead) {
184 TargetData &TD = getAnalysis<TargetData>();
185 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
186 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
187
Owen Andersond4451de2007-07-12 18:08:51 +0000188 if (dep == MemoryDependenceAnalysis::None ||
189 dep == MemoryDependenceAnalysis::NonLocal)
190 return false;
191
192 StoreInst* dependency = dyn_cast<StoreInst>(dep);
193 if (!dependency)
194 return false;
195
Owen Andersonaa071722007-07-11 23:19:17 +0000196 Value* depPointer = dependency->getPointerOperand();
197 unsigned depPointerSize = TD.getTypeSize(dependency->getOperand(0)->getType());
Owen Anderson9c9ef212007-07-13 18:26:26 +0000198
Owen Andersonaa071722007-07-11 23:19:17 +0000199 // Check for aliasing
200 AliasAnalysis::AliasResult A = AA.alias(F->getPointerOperand(), ~0UL,
201 depPointer, depPointerSize);
202
203 if (A == AliasAnalysis::MustAlias) {
204 // Remove it!
205 MD.removeInstruction(dependency);
Owen Andersonaa071722007-07-11 23:19:17 +0000206
207 // DCE instructions only used to calculate that store
208 if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(0)))
209 possiblyDead.insert(D);
Owen Anderson9c9ef212007-07-13 18:26:26 +0000210 if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(1)))
211 possiblyDead.insert(D);
Owen Andersonaa071722007-07-11 23:19:17 +0000212
213 dependency->eraseFromParent();
214 NumFastStores++;
215 return true;
216 }
217
218 return false;
219}
220
Owen Anderson32c4a052007-07-12 21:41:30 +0000221/// handleEndBlock - Remove dead stores to stack-allocated locations in the function
222/// end block
223bool FDSE::handleEndBlock(BasicBlock& BB, SetVector<Instruction*>& possiblyDead) {
224 TargetData &TD = getAnalysis<TargetData>();
225 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
226 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
227
228 bool MadeChange = false;
229
230 // Pointers alloca'd in this function are dead in the end block
231 SmallPtrSet<AllocaInst*, 4> deadPointers;
232
233 // Find all of the alloca'd pointers in the entry block
234 BasicBlock *Entry = BB.getParent()->begin();
235 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
236 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
237 deadPointers.insert(AI);
238
239 // Scan the basic block backwards
240 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
241 --BBI;
242
243 if (deadPointers.empty())
244 break;
245
246 Value* killPointer = 0;
247 unsigned killPointerSize = 0;
248
249 // If we find a store whose pointer is dead...
250 if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
Owen Anderson9c9ef212007-07-13 18:26:26 +0000251 Value* pointerOperand = S->getPointerOperand();
252 // See through pointer-to-pointer bitcasts
253 TranslatePointerBitCasts(pointerOperand);
254
255 if (deadPointers.count(pointerOperand)){
Owen Anderson32c4a052007-07-12 21:41:30 +0000256 // Remove it!
257 MD.removeInstruction(S);
258
259 // DCE instructions only used to calculate that store
260 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
261 possiblyDead.insert(D);
Owen Anderson9c9ef212007-07-13 18:26:26 +0000262 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
263 possiblyDead.insert(D);
Owen Anderson32c4a052007-07-12 21:41:30 +0000264
265 BBI++;
266 S->eraseFromParent();
267 NumFastStores++;
268 MadeChange = true;
Owen Anderson32c4a052007-07-12 21:41:30 +0000269 }
270
271 // If we encounter a use of the pointer, it is no longer considered dead
272 } else if (LoadInst* L = dyn_cast<LoadInst>(BBI)) {
273 killPointer = L->getPointerOperand();
274 killPointerSize = TD.getTypeSize(L->getType());
275 } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
276 killPointer = V->getOperand(0);
277 killPointerSize = TD.getTypeSize(V->getType());
278 } else if (FreeInst* F = dyn_cast<FreeInst>(BBI)) {
279 killPointer = F->getPointerOperand();
280 killPointerSize = ~0UL;
281 } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
282 deadPointers.erase(A);
283 continue;
284 } else if (CallSite::get(BBI).getInstruction() != 0) {
285 // Remove any pointers made undead by the call from the dead set
286 std::vector<Instruction*> dead;
287 for (SmallPtrSet<AllocaInst*, 4>::iterator I = deadPointers.begin(),
288 E = deadPointers.end(); I != E; ++I) {
289 // Get size information for the alloca
290 unsigned pointerSize = ~0UL;
291 if (ConstantInt* C = dyn_cast<ConstantInt>((*I)->getArraySize()))
292 pointerSize = C->getZExtValue() * TD.getTypeSize((*I)->getAllocatedType());
293
294 // See if the call site touches it
295 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CallSite::get(BBI),
296 *I, pointerSize);
Owen Anderson9c9ef212007-07-13 18:26:26 +0000297 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
Owen Anderson32c4a052007-07-12 21:41:30 +0000298 dead.push_back(*I);
299 }
300
301 for (std::vector<Instruction*>::iterator I = dead.begin(), E = dead.end();
302 I != E; ++I)
303 deadPointers.erase(*I);
304
305 continue;
306 }
307
308 if (!killPointer)
309 continue;
310
311 // Deal with undead pointers
312 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
313 deadPointers, possiblyDead);
314 }
315
316 return MadeChange;
317}
318
319bool FDSE::RemoveUndeadPointers(Value* killPointer, unsigned killPointerSize,
320 BasicBlock::iterator& BBI,
321 SmallPtrSet<AllocaInst*, 4>& deadPointers,
322 SetVector<Instruction*>& possiblyDead) {
323 TargetData &TD = getAnalysis<TargetData>();
324 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
325 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
326
327 bool MadeChange = false;
328
329 std::vector<Instruction*> undead;
330
331 for (SmallPtrSet<AllocaInst*, 4>::iterator I = deadPointers.begin(),
332 E = deadPointers.end(); I != E; ++I) {
333 // Get size information for the alloca
334 unsigned pointerSize = ~0UL;
335 if (ConstantInt* C = dyn_cast<ConstantInt>((*I)->getArraySize()))
336 pointerSize = C->getZExtValue() * TD.getTypeSize((*I)->getAllocatedType());
337
338 // See if this pointer could alias it
339 AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize, killPointer, killPointerSize);
340
341 // If it must-alias and a store, we can delete it
342 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
343 StoreInst* S = cast<StoreInst>(BBI);
344
345 // Remove it!
346 MD.removeInstruction(S);
347
348 // DCE instructions only used to calculate that store
349 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
350 possiblyDead.insert(D);
Owen Anderson9c9ef212007-07-13 18:26:26 +0000351 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
352 possiblyDead.insert(D);
Owen Anderson32c4a052007-07-12 21:41:30 +0000353
354 BBI++;
355 S->eraseFromParent();
356 NumFastStores++;
357 MadeChange = true;
358
359 continue;
360
361 // Otherwise, it is undead
362 } else if (A != AliasAnalysis::NoAlias)
363 undead.push_back(*I);
364 }
365
366 for (std::vector<Instruction*>::iterator I = undead.begin(), E = undead.end();
367 I != E; ++I)
368 deadPointers.erase(*I);
369
370 return MadeChange;
371}
372
Owen Anderson5e72db32007-07-11 00:46:18 +0000373void FDSE::DeleteDeadInstructionChains(Instruction *I,
374 SetVector<Instruction*> &DeadInsts) {
375 // Instruction must be dead.
376 if (!I->use_empty() || !isInstructionTriviallyDead(I)) return;
377
378 // Let the memory dependence know
379 getAnalysis<MemoryDependenceAnalysis>().removeInstruction(I);
380
381 // See if this made any operands dead. We do it this way in case the
382 // instruction uses the same operand twice. We don't want to delete a
383 // value then reference it.
384 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Owen Andersonbf971aa2007-07-11 19:03:09 +0000385 if (I->getOperand(i)->hasOneUse())
386 if (Instruction* Op = dyn_cast<Instruction>(I->getOperand(i)))
387 DeadInsts.insert(Op); // Attempt to nuke it later.
388
Owen Anderson5e72db32007-07-11 00:46:18 +0000389 I->setOperand(i, 0); // Drop from the operand list.
390 }
391
392 I->eraseFromParent();
393 ++NumFastOther;
394}