blob: 6c2ea39896a682ae6815588afd5a211d452531d5 [file] [log] [blame]
Chris Lattner12be9362011-01-02 21:47:05 +00001//===- EarlyCSE.cpp - Simple and fast CSE pass ----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs a simple dominator tree walk that eliminates trivially
11// redundant instructions.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "early-cse"
16#include "llvm/Transforms/Scalar.h"
Chris Lattner91139cc2011-01-02 23:19:45 +000017#include "llvm/Instructions.h"
Chris Lattner12be9362011-01-02 21:47:05 +000018#include "llvm/Pass.h"
Chris Lattnercc9eab22011-01-02 23:04:14 +000019#include "llvm/Analysis/Dominators.h"
20#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattnercc9eab22011-01-02 23:04:14 +000021#include "llvm/Target/TargetData.h"
22#include "llvm/Transforms/Utils/Local.h"
Chris Lattner91139cc2011-01-02 23:19:45 +000023#include "llvm/Support/Debug.h"
Chris Lattner82dcd5e2011-01-03 01:42:46 +000024#include "llvm/Support/RecyclingAllocator.h"
Chris Lattnercc9eab22011-01-02 23:04:14 +000025#include "llvm/ADT/ScopedHashTable.h"
Chris Lattner91139cc2011-01-02 23:19:45 +000026#include "llvm/ADT/Statistic.h"
Chris Lattner12be9362011-01-02 21:47:05 +000027using namespace llvm;
28
Chris Lattnera60a8b02011-01-03 03:28:23 +000029STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
30STATISTIC(NumCSE, "Number of instructions CSE'd");
Chris Lattner85db6102011-01-03 03:41:27 +000031STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
32STATISTIC(NumCSECall, "Number of call instructions CSE'd");
Chris Lattner75637152011-01-03 04:17:24 +000033STATISTIC(NumDSE, "Number of trivial dead stores removed");
Chris Lattner8e7f0d72011-01-03 03:18:43 +000034
35static unsigned getHash(const void *V) {
36 return DenseMapInfo<const void*>::getHashValue(V);
37}
Chris Lattner91139cc2011-01-02 23:19:45 +000038
Chris Lattnerf1974592011-01-03 02:20:48 +000039//===----------------------------------------------------------------------===//
40// SimpleValue
41//===----------------------------------------------------------------------===//
42
Chris Lattner12be9362011-01-02 21:47:05 +000043namespace {
Chris Lattnerf1974592011-01-03 02:20:48 +000044 /// SimpleValue - Instances of this struct represent available values in the
Chris Lattnercc9eab22011-01-02 23:04:14 +000045 /// scoped hash table.
Chris Lattnerf1974592011-01-03 02:20:48 +000046 struct SimpleValue {
Chris Lattnercc9eab22011-01-02 23:04:14 +000047 Instruction *Inst;
48
Chris Lattnera60a8b02011-01-03 03:28:23 +000049 SimpleValue(Instruction *I) : Inst(I) {
50 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
51 }
52
Chris Lattnercc9eab22011-01-02 23:04:14 +000053 bool isSentinel() const {
54 return Inst == DenseMapInfo<Instruction*>::getEmptyKey() ||
55 Inst == DenseMapInfo<Instruction*>::getTombstoneKey();
56 }
57
58 static bool canHandle(Instruction *Inst) {
Chris Lattner91139cc2011-01-02 23:19:45 +000059 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
60 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
61 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
62 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
63 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
Chris Lattnercc9eab22011-01-02 23:04:14 +000064 }
Chris Lattnercc9eab22011-01-02 23:04:14 +000065 };
66}
67
68namespace llvm {
Chris Lattnerf1974592011-01-03 02:20:48 +000069// SimpleValue is POD.
70template<> struct isPodLike<SimpleValue> {
Chris Lattnercc9eab22011-01-02 23:04:14 +000071 static const bool value = true;
72};
73
Chris Lattnerf1974592011-01-03 02:20:48 +000074template<> struct DenseMapInfo<SimpleValue> {
75 static inline SimpleValue getEmptyKey() {
Chris Lattnera60a8b02011-01-03 03:28:23 +000076 return DenseMapInfo<Instruction*>::getEmptyKey();
Chris Lattnercc9eab22011-01-02 23:04:14 +000077 }
Chris Lattnerf1974592011-01-03 02:20:48 +000078 static inline SimpleValue getTombstoneKey() {
Chris Lattnera60a8b02011-01-03 03:28:23 +000079 return DenseMapInfo<Instruction*>::getTombstoneKey();
Chris Lattnercc9eab22011-01-02 23:04:14 +000080 }
Chris Lattnerf1974592011-01-03 02:20:48 +000081 static unsigned getHashValue(SimpleValue Val);
82 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
Chris Lattnercc9eab22011-01-02 23:04:14 +000083};
84}
85
Chris Lattnerf1974592011-01-03 02:20:48 +000086unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
Chris Lattnercc9eab22011-01-02 23:04:14 +000087 Instruction *Inst = Val.Inst;
Chris Lattnercc9eab22011-01-02 23:04:14 +000088
Chris Lattnerd957c712011-01-03 01:10:08 +000089 // Hash in all of the operands as pointers.
90 unsigned Res = 0;
91 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
92 Res ^= getHash(Inst->getOperand(i)) << i;
93
94 if (CastInst *CI = dyn_cast<CastInst>(Inst))
95 Res ^= getHash(CI->getType());
96 else if (CmpInst *CI = dyn_cast<CmpInst>(Inst))
97 Res ^= CI->getPredicate();
98 else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst)) {
99 for (ExtractValueInst::idx_iterator I = EVI->idx_begin(),
100 E = EVI->idx_end(); I != E; ++I)
101 Res ^= *I;
102 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst)) {
103 for (InsertValueInst::idx_iterator I = IVI->idx_begin(),
104 E = IVI->idx_end(); I != E; ++I)
105 Res ^= *I;
106 } else {
107 // nothing extra to hash in.
108 assert((isa<BinaryOperator>(Inst) || isa<GetElementPtrInst>(Inst) ||
109 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
110 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst)) &&
111 "Invalid/unknown instruction");
112 }
113
114 // Mix in the opcode.
Chris Lattnercc9eab22011-01-02 23:04:14 +0000115 return (Res << 1) ^ Inst->getOpcode();
116}
117
Chris Lattnerf1974592011-01-03 02:20:48 +0000118bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
Chris Lattnercc9eab22011-01-02 23:04:14 +0000119 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
120
121 if (LHS.isSentinel() || RHS.isSentinel())
122 return LHSI == RHSI;
123
124 if (LHSI->getOpcode() != RHSI->getOpcode()) return false;
125 return LHSI->isIdenticalTo(RHSI);
126}
127
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000128//===----------------------------------------------------------------------===//
Chris Lattner85db6102011-01-03 03:41:27 +0000129// CallValue
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000130//===----------------------------------------------------------------------===//
131
132namespace {
Chris Lattner85db6102011-01-03 03:41:27 +0000133 /// CallValue - Instances of this struct represent available call values in
134 /// the scoped hash table.
135 struct CallValue {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000136 Instruction *Inst;
137
Chris Lattner85db6102011-01-03 03:41:27 +0000138 CallValue(Instruction *I) : Inst(I) {
Chris Lattnera60a8b02011-01-03 03:28:23 +0000139 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
140 }
141
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000142 bool isSentinel() const {
143 return Inst == DenseMapInfo<Instruction*>::getEmptyKey() ||
144 Inst == DenseMapInfo<Instruction*>::getTombstoneKey();
145 }
146
147 static bool canHandle(Instruction *Inst) {
Chris Lattner10b883b2011-01-03 18:43:03 +0000148 // Don't value number anything that returns void.
149 if (Inst->getType()->isVoidTy())
150 return false;
151
Chris Lattnera12ba392011-01-03 18:28:15 +0000152 CallInst *CI = dyn_cast<CallInst>(Inst);
153 if (CI == 0 || !CI->onlyReadsMemory())
154 return false;
Chris Lattnera12ba392011-01-03 18:28:15 +0000155 return true;
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000156 }
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000157 };
158}
159
160namespace llvm {
Chris Lattner85db6102011-01-03 03:41:27 +0000161 // CallValue is POD.
162 template<> struct isPodLike<CallValue> {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000163 static const bool value = true;
164 };
165
Chris Lattner85db6102011-01-03 03:41:27 +0000166 template<> struct DenseMapInfo<CallValue> {
167 static inline CallValue getEmptyKey() {
Chris Lattnera60a8b02011-01-03 03:28:23 +0000168 return DenseMapInfo<Instruction*>::getEmptyKey();
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000169 }
Chris Lattner85db6102011-01-03 03:41:27 +0000170 static inline CallValue getTombstoneKey() {
Chris Lattnera60a8b02011-01-03 03:28:23 +0000171 return DenseMapInfo<Instruction*>::getTombstoneKey();
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000172 }
Chris Lattner85db6102011-01-03 03:41:27 +0000173 static unsigned getHashValue(CallValue Val);
174 static bool isEqual(CallValue LHS, CallValue RHS);
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000175 };
176}
Chris Lattner85db6102011-01-03 03:41:27 +0000177unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000178 Instruction *Inst = Val.Inst;
179 // Hash in all of the operands as pointers.
180 unsigned Res = 0;
Chris Lattner10b883b2011-01-03 18:43:03 +0000181 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i) {
182 assert(!Inst->getOperand(i)->getType()->isMetadataTy() &&
183 "Cannot value number calls with metadata operands");
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000184 Res ^= getHash(Inst->getOperand(i)) << i;
Chris Lattner10b883b2011-01-03 18:43:03 +0000185 }
186
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000187 // Mix in the opcode.
188 return (Res << 1) ^ Inst->getOpcode();
189}
190
Chris Lattner85db6102011-01-03 03:41:27 +0000191bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000192 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000193 if (LHS.isSentinel() || RHS.isSentinel())
194 return LHSI == RHSI;
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000195 return LHSI->isIdenticalTo(RHSI);
196}
197
Chris Lattnercc9eab22011-01-02 23:04:14 +0000198
Chris Lattnerf1974592011-01-03 02:20:48 +0000199//===----------------------------------------------------------------------===//
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000200// EarlyCSE pass.
Chris Lattnerf1974592011-01-03 02:20:48 +0000201//===----------------------------------------------------------------------===//
202
Chris Lattnercc9eab22011-01-02 23:04:14 +0000203namespace {
204
Chris Lattner12be9362011-01-02 21:47:05 +0000205/// EarlyCSE - This pass does a simple depth-first walk over the dominator
206/// tree, eliminating trivially redundant instructions and using instsimplify
207/// to canonicalize things as it goes. It is intended to be fast and catch
208/// obvious cases so that instcombine and other passes are more effective. It
209/// is expected that a later pass of GVN will catch the interesting/hard
210/// cases.
211class EarlyCSE : public FunctionPass {
212public:
Chris Lattnercc9eab22011-01-02 23:04:14 +0000213 const TargetData *TD;
214 DominatorTree *DT;
Chris Lattner82dcd5e2011-01-03 01:42:46 +0000215 typedef RecyclingAllocator<BumpPtrAllocator,
Chris Lattnerf1974592011-01-03 02:20:48 +0000216 ScopedHashTableVal<SimpleValue, Value*> > AllocatorTy;
217 typedef ScopedHashTable<SimpleValue, Value*, DenseMapInfo<SimpleValue>,
Chris Lattner82dcd5e2011-01-03 01:42:46 +0000218 AllocatorTy> ScopedHTType;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000219
Chris Lattnerf1974592011-01-03 02:20:48 +0000220 /// AvailableValues - This scoped hash table contains the current values of
221 /// all of our simple scalar expressions. As we walk down the domtree, we
222 /// look to see if instructions are in this: if so, we replace them with what
223 /// we find, otherwise we insert them so that dominated values can succeed in
224 /// their lookup.
225 ScopedHTType *AvailableValues;
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000226
Chris Lattner85db6102011-01-03 03:41:27 +0000227 /// AvailableLoads - This scoped hash table contains the current values
228 /// of loads. This allows us to get efficient access to dominating loads when
229 /// we have a fully redundant load. In addition to the most recent load, we
230 /// keep track of a generation count of the read, which is compared against
231 /// the current generation count. The current generation count is
232 /// incremented after every possibly writing memory operation, which ensures
233 /// that we only CSE loads with other loads that have no intervening store.
Chris Lattner71230ac2011-01-03 03:53:50 +0000234 typedef RecyclingAllocator<BumpPtrAllocator,
235 ScopedHashTableVal<Value*, std::pair<Value*, unsigned> > > LoadMapAllocator;
236 typedef ScopedHashTable<Value*, std::pair<Value*, unsigned>,
237 DenseMapInfo<Value*>, LoadMapAllocator> LoadHTType;
Chris Lattner85db6102011-01-03 03:41:27 +0000238 LoadHTType *AvailableLoads;
239
240 /// AvailableCalls - This scoped hash table contains the current values
241 /// of read-only call values. It uses the same generation count as loads.
242 typedef ScopedHashTable<CallValue, std::pair<Value*, unsigned> > CallHTType;
243 CallHTType *AvailableCalls;
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000244
245 /// CurrentGeneration - This is the current generation of the memory value.
246 unsigned CurrentGeneration;
247
Chris Lattner12be9362011-01-02 21:47:05 +0000248 static char ID;
Chris Lattnerf1974592011-01-03 02:20:48 +0000249 explicit EarlyCSE() : FunctionPass(ID) {
Chris Lattner12be9362011-01-02 21:47:05 +0000250 initializeEarlyCSEPass(*PassRegistry::getPassRegistry());
251 }
252
253 bool runOnFunction(Function &F);
254
255private:
Chris Lattnercc9eab22011-01-02 23:04:14 +0000256
257 bool processNode(DomTreeNode *Node);
258
Chris Lattner12be9362011-01-02 21:47:05 +0000259 // This transformation requires dominator postdominator info
260 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
261 AU.addRequired<DominatorTree>();
262 AU.setPreservesCFG();
263 }
264};
265}
266
267char EarlyCSE::ID = 0;
268
269// createEarlyCSEPass - The public interface to this file.
270FunctionPass *llvm::createEarlyCSEPass() {
271 return new EarlyCSE();
272}
273
274INITIALIZE_PASS_BEGIN(EarlyCSE, "early-cse", "Early CSE", false, false)
275INITIALIZE_PASS_DEPENDENCY(DominatorTree)
276INITIALIZE_PASS_END(EarlyCSE, "early-cse", "Early CSE", false, false)
277
Chris Lattnercc9eab22011-01-02 23:04:14 +0000278bool EarlyCSE::processNode(DomTreeNode *Node) {
Chris Lattnerf1974592011-01-03 02:20:48 +0000279 // Define a scope in the scoped hash table. When we are done processing this
280 // domtree node and recurse back up to our parent domtree node, this will pop
281 // off all the values we install.
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000282 ScopedHTType::ScopeTy Scope(*AvailableValues);
283
Chris Lattner85db6102011-01-03 03:41:27 +0000284 // Define a scope for the load values so that anything we add will get
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000285 // popped when we recurse back up to our parent domtree node.
Chris Lattner85db6102011-01-03 03:41:27 +0000286 LoadHTType::ScopeTy LoadScope(*AvailableLoads);
287
288 // Define a scope for the call values so that anything we add will get
289 // popped when we recurse back up to our parent domtree node.
290 CallHTType::ScopeTy CallScope(*AvailableCalls);
Chris Lattnercc9eab22011-01-02 23:04:14 +0000291
292 BasicBlock *BB = Node->getBlock();
293
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000294 // If this block has a single predecessor, then the predecessor is the parent
295 // of the domtree node and all of the live out memory values are still current
296 // in this block. If this block has multiple predecessors, then they could
297 // have invalidated the live-out memory values of our parent value. For now,
298 // just be conservative and invalidate memory if this block has multiple
299 // predecessors.
300 if (BB->getSinglePredecessor() == 0)
301 ++CurrentGeneration;
302
Chris Lattner75637152011-01-03 04:17:24 +0000303 /// LastStore - Keep track of the last non-volatile store that we saw... for
304 /// as long as there in no instruction that reads memory. If we see a store
305 /// to the same location, we delete the dead store. This zaps trivial dead
306 /// stores which can occur in bitfield code among other things.
307 StoreInst *LastStore = 0;
308
Chris Lattnercc9eab22011-01-02 23:04:14 +0000309 bool Changed = false;
310
311 // See if any instructions in the block can be eliminated. If so, do it. If
312 // not, add them to AvailableValues.
313 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
314 Instruction *Inst = I++;
315
316 // Dead instructions should just be removed.
317 if (isInstructionTriviallyDead(Inst)) {
Chris Lattner91139cc2011-01-02 23:19:45 +0000318 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
Chris Lattnercc9eab22011-01-02 23:04:14 +0000319 Inst->eraseFromParent();
320 Changed = true;
Chris Lattner91139cc2011-01-02 23:19:45 +0000321 ++NumSimplify;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000322 continue;
323 }
324
325 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
326 // its simpler value.
327 if (Value *V = SimplifyInstruction(Inst, TD, DT)) {
Chris Lattner91139cc2011-01-02 23:19:45 +0000328 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
Chris Lattnercc9eab22011-01-02 23:04:14 +0000329 Inst->replaceAllUsesWith(V);
330 Inst->eraseFromParent();
331 Changed = true;
Chris Lattner91139cc2011-01-02 23:19:45 +0000332 ++NumSimplify;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000333 continue;
334 }
335
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000336 // If this is a simple instruction that we can value number, process it.
337 if (SimpleValue::canHandle(Inst)) {
338 // See if the instruction has an available value. If so, use it.
Chris Lattnera60a8b02011-01-03 03:28:23 +0000339 if (Value *V = AvailableValues->lookup(Inst)) {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000340 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
341 Inst->replaceAllUsesWith(V);
342 Inst->eraseFromParent();
343 Changed = true;
344 ++NumCSE;
345 continue;
346 }
347
348 // Otherwise, just remember that this value is available.
Chris Lattnera60a8b02011-01-03 03:28:23 +0000349 AvailableValues->insert(Inst, Inst);
Chris Lattnercc9eab22011-01-02 23:04:14 +0000350 continue;
351 }
352
Chris Lattner85db6102011-01-03 03:41:27 +0000353 // If this is a non-volatile load, process it.
354 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
355 // Ignore volatile loads.
Chris Lattner75637152011-01-03 04:17:24 +0000356 if (LI->isVolatile()) {
357 LastStore = 0;
358 continue;
359 }
Chris Lattner85db6102011-01-03 03:41:27 +0000360
361 // If we have an available version of this load, and if it is the right
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000362 // generation, replace this instruction.
Chris Lattner85db6102011-01-03 03:41:27 +0000363 std::pair<Value*, unsigned> InVal =
364 AvailableLoads->lookup(Inst->getOperand(0));
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000365 if (InVal.first != 0 && InVal.second == CurrentGeneration) {
Chris Lattner85db6102011-01-03 03:41:27 +0000366 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst << " to: "
367 << *InVal.first << '\n');
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000368 if (!Inst->use_empty()) Inst->replaceAllUsesWith(InVal.first);
369 Inst->eraseFromParent();
370 Changed = true;
Chris Lattner85db6102011-01-03 03:41:27 +0000371 ++NumCSELoad;
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000372 continue;
373 }
374
375 // Otherwise, remember that we have this instruction.
Chris Lattner85db6102011-01-03 03:41:27 +0000376 AvailableLoads->insert(Inst->getOperand(0),
377 std::pair<Value*, unsigned>(Inst, CurrentGeneration));
Chris Lattner75637152011-01-03 04:17:24 +0000378 LastStore = 0;
Chris Lattner85db6102011-01-03 03:41:27 +0000379 continue;
380 }
381
Chris Lattner75637152011-01-03 04:17:24 +0000382 // If this instruction may read from memory, forget LastStore.
383 if (Inst->mayReadFromMemory())
384 LastStore = 0;
385
Chris Lattner85db6102011-01-03 03:41:27 +0000386 // If this is a read-only call, process it.
387 if (CallValue::canHandle(Inst)) {
388 // If we have an available version of this call, and if it is the right
389 // generation, replace this instruction.
390 std::pair<Value*, unsigned> InVal = AvailableCalls->lookup(Inst);
391 if (InVal.first != 0 && InVal.second == CurrentGeneration) {
392 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst << " to: "
393 << *InVal.first << '\n');
394 if (!Inst->use_empty()) Inst->replaceAllUsesWith(InVal.first);
395 Inst->eraseFromParent();
396 Changed = true;
397 ++NumCSECall;
398 continue;
399 }
400
401 // Otherwise, remember that we have this instruction.
402 AvailableCalls->insert(Inst,
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000403 std::pair<Value*, unsigned>(Inst, CurrentGeneration));
404 continue;
405 }
406
407 // Okay, this isn't something we can CSE at all. Check to see if it is
408 // something that could modify memory. If so, our available memory values
409 // cannot be used so bump the generation count.
Chris Lattneref87fc22011-01-03 03:46:34 +0000410 if (Inst->mayWriteToMemory()) {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000411 ++CurrentGeneration;
Chris Lattneref87fc22011-01-03 03:46:34 +0000412
Chris Lattneref87fc22011-01-03 03:46:34 +0000413 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattner75637152011-01-03 04:17:24 +0000414 // We do a trivial form of DSE if there are two stores to the same
415 // location with no intervening loads. Delete the earlier store.
416 if (LastStore &&
417 LastStore->getPointerOperand() == SI->getPointerOperand()) {
418 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore << " due to: "
Chris Lattnera12ba392011-01-03 18:28:15 +0000419 << *Inst << '\n');
Chris Lattner75637152011-01-03 04:17:24 +0000420 LastStore->eraseFromParent();
421 Changed = true;
422 ++NumDSE;
423 LastStore = 0;
424 continue;
425 }
426
427 // Okay, we just invalidated anything we knew about loaded values. Try
428 // to salvage *something* by remembering that the stored value is a live
429 // version of the pointer. It is safe to forward from volatile stores
430 // to non-volatile loads, so we don't have to check for volatility of
431 // the store.
Chris Lattneref87fc22011-01-03 03:46:34 +0000432 AvailableLoads->insert(SI->getPointerOperand(),
433 std::pair<Value*, unsigned>(SI->getValueOperand(), CurrentGeneration));
Chris Lattner75637152011-01-03 04:17:24 +0000434
435 // Remember that this was the last store we saw for DSE.
436 if (!SI->isVolatile())
437 LastStore = SI;
Chris Lattneref87fc22011-01-03 03:46:34 +0000438 }
439 }
Chris Lattnercc9eab22011-01-02 23:04:14 +0000440 }
441
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000442 unsigned LiveOutGeneration = CurrentGeneration;
443 for (DomTreeNode::iterator I = Node->begin(), E = Node->end(); I != E; ++I) {
Chris Lattnercc9eab22011-01-02 23:04:14 +0000444 Changed |= processNode(*I);
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000445 // Pop any generation changes off the stack from the recursive walk.
446 CurrentGeneration = LiveOutGeneration;
447 }
Chris Lattnercc9eab22011-01-02 23:04:14 +0000448 return Changed;
Chris Lattner12be9362011-01-02 21:47:05 +0000449}
Chris Lattnercc9eab22011-01-02 23:04:14 +0000450
451
452bool EarlyCSE::runOnFunction(Function &F) {
453 TD = getAnalysisIfAvailable<TargetData>();
454 DT = &getAnalysis<DominatorTree>();
Chris Lattner85db6102011-01-03 03:41:27 +0000455
456 // Tables that the pass uses when walking the domtree.
Chris Lattner82dcd5e2011-01-03 01:42:46 +0000457 ScopedHTType AVTable;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000458 AvailableValues = &AVTable;
Chris Lattner85db6102011-01-03 03:41:27 +0000459 LoadHTType LoadTable;
460 AvailableLoads = &LoadTable;
461 CallHTType CallTable;
462 AvailableCalls = &CallTable;
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000463
464 CurrentGeneration = 0;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000465 return processNode(DT->getRootNode());
466}