1 //===- FastDSE.cpp - Fast Dead Store Elimination --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Owen Anderson and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a trivial dead store elimination that only considers
11 // basic-block local redundant stores.
13 // FIXME: This should eventually be extended to be a post-dominator tree
14 // traversal. Doing so would be pretty trivial.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "fdse"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/Constants.h"
21 #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"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 #include "llvm/Support/Compiler.h"
34 STATISTIC(NumFastStores, "Number of stores deleted");
35 STATISTIC(NumFastOther , "Number of other instrs removed");
38 struct VISIBILITY_HIDDEN FDSE : public FunctionPass {
39 static char ID; // Pass identification, replacement for typeid
40 FDSE() : FunctionPass((intptr_t)&ID) {}
42 virtual bool runOnFunction(Function &F) {
44 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
45 Changed |= runOnBasicBlock(*I);
49 bool runOnBasicBlock(BasicBlock &BB);
50 bool handleFreeWithNonTrivialDependency(FreeInst* F, Instruction* dependency,
51 SetVector<Instruction*>& possiblyDead);
52 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);
57 void DeleteDeadInstructionChains(Instruction *I,
58 SetVector<Instruction*> &DeadInsts);
59 void TranslatePointerBitCasts(Value*& v) {
60 assert(isa<PointerType>(v->getType()) && "Translating a non-pointer type?");
62 // See through pointer-to-pointer bitcasts
63 while (isa<BitCastInst>(v) || isa<GetElementPtrInst>(v))
64 if (BitCastInst* C = dyn_cast<BitCastInst>(v))
66 else if (GetElementPtrInst* G = dyn_cast<GetElementPtrInst>(v))
70 // getAnalysisUsage - We require post dominance frontiers (aka Control
72 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
74 AU.addRequired<TargetData>();
75 AU.addRequired<AliasAnalysis>();
76 AU.addRequired<MemoryDependenceAnalysis>();
77 AU.addPreserved<AliasAnalysis>();
78 AU.addPreserved<MemoryDependenceAnalysis>();
82 RegisterPass<FDSE> X("fdse", "Fast Dead Store Elimination");
85 FunctionPass *llvm::createFastDeadStoreEliminationPass() { return new FDSE(); }
87 bool FDSE::runOnBasicBlock(BasicBlock &BB) {
88 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
90 // Record the last-seen store to this pointer
91 DenseMap<Value*, StoreInst*> lastStore;
92 // Record instructions possibly made dead by deleting a store
93 SetVector<Instruction*> possiblyDead;
95 bool MadeChange = false;
97 // Do a top-down walk on the BB
98 for (BasicBlock::iterator BBI = BB.begin(), BBE = BB.end(); BBI != BBE; ++BBI) {
99 // If we find a store or a free...
100 if (isa<StoreInst>(BBI) || isa<FreeInst>(BBI)) {
102 if (StoreInst* S = dyn_cast<StoreInst>(BBI))
103 pointer = S->getPointerOperand();
104 else if (FreeInst* F = dyn_cast<FreeInst>(BBI))
105 pointer = F->getPointerOperand();
107 assert(pointer && "Not a free or a store?");
109 StoreInst*& last = lastStore[pointer];
110 bool deletedStore = false;
112 // ... to a pointer that has been stored to before...
115 Instruction* dep = MD.getDependency(BBI);
117 // ... and no other memory dependencies are between them....
118 while (dep != MemoryDependenceAnalysis::None &&
119 dep != MemoryDependenceAnalysis::NonLocal &&
120 isa<StoreInst>(dep)) {
124 MD.removeInstruction(last);
126 // DCE instructions only used to calculate that store
127 if (Instruction* D = dyn_cast<Instruction>(last->getOperand(0)))
128 possiblyDead.insert(D);
129 if (Instruction* D = dyn_cast<Instruction>(last->getOperand(1)))
130 possiblyDead.insert(D);
132 last->eraseFromParent();
139 dep = MD.getDependency(BBI, dep);
144 // Handle frees whose dependencies are non-trivial
145 if (FreeInst* F = dyn_cast<FreeInst>(BBI))
147 MadeChange |= handleFreeWithNonTrivialDependency(F, MD.getDependency(F),
150 // Update our most-recent-store map
151 if (StoreInst* S = dyn_cast<StoreInst>(BBI))
158 // If this block ends in a return, unwind, unreachable, and eventually
159 // tailcall, then all allocas are dead at its end.
160 if (BB.getTerminator()->getNumSuccessors() == 0)
161 MadeChange |= handleEndBlock(BB, possiblyDead);
164 while (!possiblyDead.empty()) {
165 Instruction *I = possiblyDead.back();
166 possiblyDead.pop_back();
167 DeleteDeadInstructionChains(I, possiblyDead);
173 /// handleFreeWithNonTrivialDependency - Handle frees of entire structures whose
174 /// dependency is a store to a field of that structure
175 bool FDSE::handleFreeWithNonTrivialDependency(FreeInst* F, Instruction* dep,
176 SetVector<Instruction*>& possiblyDead) {
177 TargetData &TD = getAnalysis<TargetData>();
178 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
179 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
181 if (dep == MemoryDependenceAnalysis::None ||
182 dep == MemoryDependenceAnalysis::NonLocal)
185 StoreInst* dependency = dyn_cast<StoreInst>(dep);
189 Value* depPointer = dependency->getPointerOperand();
190 unsigned depPointerSize = TD.getTypeSize(dependency->getOperand(0)->getType());
192 // Check for aliasing
193 AliasAnalysis::AliasResult A = AA.alias(F->getPointerOperand(), ~0UL,
194 depPointer, depPointerSize);
196 if (A == AliasAnalysis::MustAlias) {
198 MD.removeInstruction(dependency);
200 // DCE instructions only used to calculate that store
201 if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(0)))
202 possiblyDead.insert(D);
203 if (Instruction* D = dyn_cast<Instruction>(dependency->getOperand(1)))
204 possiblyDead.insert(D);
206 dependency->eraseFromParent();
214 /// handleEndBlock - Remove dead stores to stack-allocated locations in the function
216 bool FDSE::handleEndBlock(BasicBlock& BB, SetVector<Instruction*>& possiblyDead) {
217 TargetData &TD = getAnalysis<TargetData>();
218 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
219 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
221 bool MadeChange = false;
223 // Pointers alloca'd in this function are dead in the end block
224 SmallPtrSet<AllocaInst*, 4> deadPointers;
226 // Find all of the alloca'd pointers in the entry block
227 BasicBlock *Entry = BB.getParent()->begin();
228 for (BasicBlock::iterator I = Entry->begin(), E = Entry->end(); I != E; ++I)
229 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
230 deadPointers.insert(AI);
232 // Scan the basic block backwards
233 for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ){
236 if (deadPointers.empty())
239 Value* killPointer = 0;
240 unsigned killPointerSize = 0;
242 // If we find a store whose pointer is dead...
243 if (StoreInst* S = dyn_cast<StoreInst>(BBI)) {
244 Value* pointerOperand = S->getPointerOperand();
245 // See through pointer-to-pointer bitcasts
246 TranslatePointerBitCasts(pointerOperand);
248 if (deadPointers.count(pointerOperand)){
250 MD.removeInstruction(S);
252 // DCE instructions only used to calculate that store
253 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
254 possiblyDead.insert(D);
255 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
256 possiblyDead.insert(D);
259 S->eraseFromParent();
264 // If we encounter a use of the pointer, it is no longer considered dead
265 } else if (LoadInst* L = dyn_cast<LoadInst>(BBI)) {
266 killPointer = L->getPointerOperand();
267 killPointerSize = TD.getTypeSize(L->getType());
268 } else if (VAArgInst* V = dyn_cast<VAArgInst>(BBI)) {
269 killPointer = V->getOperand(0);
270 killPointerSize = TD.getTypeSize(V->getType());
271 } else if (FreeInst* F = dyn_cast<FreeInst>(BBI)) {
272 killPointer = F->getPointerOperand();
273 killPointerSize = ~0UL;
274 } else if (AllocaInst* A = dyn_cast<AllocaInst>(BBI)) {
275 deadPointers.erase(A);
277 } else if (CallSite::get(BBI).getInstruction() != 0) {
278 // Remove any pointers made undead by the call from the dead set
279 std::vector<Instruction*> dead;
280 for (SmallPtrSet<AllocaInst*, 4>::iterator I = deadPointers.begin(),
281 E = deadPointers.end(); I != E; ++I) {
282 // Get size information for the alloca
283 unsigned pointerSize = ~0UL;
284 if (ConstantInt* C = dyn_cast<ConstantInt>((*I)->getArraySize()))
285 pointerSize = C->getZExtValue() * TD.getTypeSize((*I)->getAllocatedType());
287 // See if the call site touches it
288 AliasAnalysis::ModRefResult A = AA.getModRefInfo(CallSite::get(BBI),
290 if (A == AliasAnalysis::ModRef || A == AliasAnalysis::Ref)
294 for (std::vector<Instruction*>::iterator I = dead.begin(), E = dead.end();
296 deadPointers.erase(*I);
304 // Deal with undead pointers
305 MadeChange |= RemoveUndeadPointers(killPointer, killPointerSize, BBI,
306 deadPointers, possiblyDead);
312 bool FDSE::RemoveUndeadPointers(Value* killPointer, unsigned killPointerSize,
313 BasicBlock::iterator& BBI,
314 SmallPtrSet<AllocaInst*, 4>& deadPointers,
315 SetVector<Instruction*>& possiblyDead) {
316 TargetData &TD = getAnalysis<TargetData>();
317 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
318 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
320 bool MadeChange = false;
322 std::vector<Instruction*> undead;
324 for (SmallPtrSet<AllocaInst*, 4>::iterator I = deadPointers.begin(),
325 E = deadPointers.end(); I != E; ++I) {
326 // Get size information for the alloca
327 unsigned pointerSize = ~0UL;
328 if (ConstantInt* C = dyn_cast<ConstantInt>((*I)->getArraySize()))
329 pointerSize = C->getZExtValue() * TD.getTypeSize((*I)->getAllocatedType());
331 // See if this pointer could alias it
332 AliasAnalysis::AliasResult A = AA.alias(*I, pointerSize, killPointer, killPointerSize);
334 // If it must-alias and a store, we can delete it
335 if (isa<StoreInst>(BBI) && A == AliasAnalysis::MustAlias) {
336 StoreInst* S = cast<StoreInst>(BBI);
339 MD.removeInstruction(S);
341 // DCE instructions only used to calculate that store
342 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(0)))
343 possiblyDead.insert(D);
344 if (Instruction* D = dyn_cast<Instruction>(S->getOperand(1)))
345 possiblyDead.insert(D);
348 S->eraseFromParent();
354 // Otherwise, it is undead
355 } else if (A != AliasAnalysis::NoAlias)
356 undead.push_back(*I);
359 for (std::vector<Instruction*>::iterator I = undead.begin(), E = undead.end();
361 deadPointers.erase(*I);
366 void FDSE::DeleteDeadInstructionChains(Instruction *I,
367 SetVector<Instruction*> &DeadInsts) {
368 // Instruction must be dead.
369 if (!I->use_empty() || !isInstructionTriviallyDead(I)) return;
371 // Let the memory dependence know
372 getAnalysis<MemoryDependenceAnalysis>().removeInstruction(I);
374 // See if this made any operands dead. We do it this way in case the
375 // instruction uses the same operand twice. We don't want to delete a
376 // value then reference it.
377 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
378 if (I->getOperand(i)->hasOneUse())
379 if (Instruction* Op = dyn_cast<Instruction>(I->getOperand(i)))
380 DeadInsts.insert(Op); // Attempt to nuke it later.
382 I->setOperand(i, 0); // Drop from the operand list.
385 I->eraseFromParent();