blob: 5241e11b39c152780de22c991ba38abb5a625a76 [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"
Chad Rosier618c1db2011-12-01 03:08:23 +000022#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattnercc9eab22011-01-02 23:04:14 +000023#include "llvm/Transforms/Utils/Local.h"
Chris Lattner91139cc2011-01-02 23:19:45 +000024#include "llvm/Support/Debug.h"
Chris Lattner82dcd5e2011-01-03 01:42:46 +000025#include "llvm/Support/RecyclingAllocator.h"
Chris Lattnercc9eab22011-01-02 23:04:14 +000026#include "llvm/ADT/ScopedHashTable.h"
Chris Lattner91139cc2011-01-02 23:19:45 +000027#include "llvm/ADT/Statistic.h"
Chris Lattner12be9362011-01-02 21:47:05 +000028using namespace llvm;
29
Chris Lattnera60a8b02011-01-03 03:28:23 +000030STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
31STATISTIC(NumCSE, "Number of instructions CSE'd");
Chris Lattner85db6102011-01-03 03:41:27 +000032STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
33STATISTIC(NumCSECall, "Number of call instructions CSE'd");
Chris Lattner75637152011-01-03 04:17:24 +000034STATISTIC(NumDSE, "Number of trivial dead stores removed");
Chris Lattner8e7f0d72011-01-03 03:18:43 +000035
36static unsigned getHash(const void *V) {
37 return DenseMapInfo<const void*>::getHashValue(V);
38}
Chris Lattner91139cc2011-01-02 23:19:45 +000039
Chris Lattnerf1974592011-01-03 02:20:48 +000040//===----------------------------------------------------------------------===//
41// SimpleValue
42//===----------------------------------------------------------------------===//
43
Chris Lattner12be9362011-01-02 21:47:05 +000044namespace {
Chris Lattnerf1974592011-01-03 02:20:48 +000045 /// SimpleValue - Instances of this struct represent available values in the
Chris Lattnercc9eab22011-01-02 23:04:14 +000046 /// scoped hash table.
Chris Lattnerf1974592011-01-03 02:20:48 +000047 struct SimpleValue {
Chris Lattnercc9eab22011-01-02 23:04:14 +000048 Instruction *Inst;
49
Chris Lattnera60a8b02011-01-03 03:28:23 +000050 SimpleValue(Instruction *I) : Inst(I) {
51 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
52 }
53
Chris Lattnercc9eab22011-01-02 23:04:14 +000054 bool isSentinel() const {
55 return Inst == DenseMapInfo<Instruction*>::getEmptyKey() ||
56 Inst == DenseMapInfo<Instruction*>::getTombstoneKey();
57 }
58
59 static bool canHandle(Instruction *Inst) {
Chris Lattnere508dd42011-01-03 23:38:13 +000060 // This can only handle non-void readnone functions.
61 if (CallInst *CI = dyn_cast<CallInst>(Inst))
62 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
Chris Lattner91139cc2011-01-02 23:19:45 +000063 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
64 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
65 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
66 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
67 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
Chris Lattnercc9eab22011-01-02 23:04:14 +000068 }
Chris Lattnercc9eab22011-01-02 23:04:14 +000069 };
70}
71
72namespace llvm {
Chris Lattnerf1974592011-01-03 02:20:48 +000073// SimpleValue is POD.
74template<> struct isPodLike<SimpleValue> {
Chris Lattnercc9eab22011-01-02 23:04:14 +000075 static const bool value = true;
76};
77
Chris Lattnerf1974592011-01-03 02:20:48 +000078template<> struct DenseMapInfo<SimpleValue> {
79 static inline SimpleValue getEmptyKey() {
Chris Lattnera60a8b02011-01-03 03:28:23 +000080 return DenseMapInfo<Instruction*>::getEmptyKey();
Chris Lattnercc9eab22011-01-02 23:04:14 +000081 }
Chris Lattnerf1974592011-01-03 02:20:48 +000082 static inline SimpleValue getTombstoneKey() {
Chris Lattnera60a8b02011-01-03 03:28:23 +000083 return DenseMapInfo<Instruction*>::getTombstoneKey();
Chris Lattnercc9eab22011-01-02 23:04:14 +000084 }
Chris Lattnerf1974592011-01-03 02:20:48 +000085 static unsigned getHashValue(SimpleValue Val);
86 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
Chris Lattnercc9eab22011-01-02 23:04:14 +000087};
88}
89
Chris Lattnerf1974592011-01-03 02:20:48 +000090unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
Chris Lattnercc9eab22011-01-02 23:04:14 +000091 Instruction *Inst = Val.Inst;
Chris Lattnercc9eab22011-01-02 23:04:14 +000092
Chris Lattnerd957c712011-01-03 01:10:08 +000093 // Hash in all of the operands as pointers.
94 unsigned Res = 0;
95 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
Eli Friedman18ead6b2011-10-12 22:00:26 +000096 Res ^= getHash(Inst->getOperand(i)) << (i & 0xF);
Chris Lattnerd957c712011-01-03 01:10:08 +000097
98 if (CastInst *CI = dyn_cast<CastInst>(Inst))
99 Res ^= getHash(CI->getType());
100 else if (CmpInst *CI = dyn_cast<CmpInst>(Inst))
101 Res ^= CI->getPredicate();
102 else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst)) {
103 for (ExtractValueInst::idx_iterator I = EVI->idx_begin(),
104 E = EVI->idx_end(); I != E; ++I)
105 Res ^= *I;
106 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst)) {
107 for (InsertValueInst::idx_iterator I = IVI->idx_begin(),
108 E = IVI->idx_end(); I != E; ++I)
109 Res ^= *I;
110 } else {
111 // nothing extra to hash in.
Chris Lattnere508dd42011-01-03 23:38:13 +0000112 assert((isa<CallInst>(Inst) ||
113 isa<BinaryOperator>(Inst) || isa<GetElementPtrInst>(Inst) ||
Chris Lattnerd957c712011-01-03 01:10:08 +0000114 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
115 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst)) &&
116 "Invalid/unknown instruction");
117 }
118
119 // Mix in the opcode.
Chris Lattnercc9eab22011-01-02 23:04:14 +0000120 return (Res << 1) ^ Inst->getOpcode();
121}
122
Chris Lattnerf1974592011-01-03 02:20:48 +0000123bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
Chris Lattnercc9eab22011-01-02 23:04:14 +0000124 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
125
126 if (LHS.isSentinel() || RHS.isSentinel())
127 return LHSI == RHSI;
128
129 if (LHSI->getOpcode() != RHSI->getOpcode()) return false;
130 return LHSI->isIdenticalTo(RHSI);
131}
132
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000133//===----------------------------------------------------------------------===//
Chris Lattner85db6102011-01-03 03:41:27 +0000134// CallValue
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000135//===----------------------------------------------------------------------===//
136
137namespace {
Chris Lattner85db6102011-01-03 03:41:27 +0000138 /// CallValue - Instances of this struct represent available call values in
139 /// the scoped hash table.
140 struct CallValue {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000141 Instruction *Inst;
142
Chris Lattner85db6102011-01-03 03:41:27 +0000143 CallValue(Instruction *I) : Inst(I) {
Chris Lattnera60a8b02011-01-03 03:28:23 +0000144 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
145 }
146
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000147 bool isSentinel() const {
148 return Inst == DenseMapInfo<Instruction*>::getEmptyKey() ||
149 Inst == DenseMapInfo<Instruction*>::getTombstoneKey();
150 }
151
152 static bool canHandle(Instruction *Inst) {
Chris Lattner10b883b2011-01-03 18:43:03 +0000153 // Don't value number anything that returns void.
154 if (Inst->getType()->isVoidTy())
155 return false;
156
Chris Lattnera12ba392011-01-03 18:28:15 +0000157 CallInst *CI = dyn_cast<CallInst>(Inst);
158 if (CI == 0 || !CI->onlyReadsMemory())
159 return false;
Chris Lattnera12ba392011-01-03 18:28:15 +0000160 return true;
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000161 }
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000162 };
163}
164
165namespace llvm {
Chris Lattner85db6102011-01-03 03:41:27 +0000166 // CallValue is POD.
167 template<> struct isPodLike<CallValue> {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000168 static const bool value = true;
169 };
170
Chris Lattner85db6102011-01-03 03:41:27 +0000171 template<> struct DenseMapInfo<CallValue> {
172 static inline CallValue getEmptyKey() {
Chris Lattnera60a8b02011-01-03 03:28:23 +0000173 return DenseMapInfo<Instruction*>::getEmptyKey();
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000174 }
Chris Lattner85db6102011-01-03 03:41:27 +0000175 static inline CallValue getTombstoneKey() {
Chris Lattnera60a8b02011-01-03 03:28:23 +0000176 return DenseMapInfo<Instruction*>::getTombstoneKey();
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000177 }
Chris Lattner85db6102011-01-03 03:41:27 +0000178 static unsigned getHashValue(CallValue Val);
179 static bool isEqual(CallValue LHS, CallValue RHS);
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000180 };
181}
Chris Lattner85db6102011-01-03 03:41:27 +0000182unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000183 Instruction *Inst = Val.Inst;
184 // Hash in all of the operands as pointers.
185 unsigned Res = 0;
Chris Lattner10b883b2011-01-03 18:43:03 +0000186 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i) {
187 assert(!Inst->getOperand(i)->getType()->isMetadataTy() &&
188 "Cannot value number calls with metadata operands");
Eli Friedman18ead6b2011-10-12 22:00:26 +0000189 Res ^= getHash(Inst->getOperand(i)) << (i & 0xF);
Chris Lattner10b883b2011-01-03 18:43:03 +0000190 }
191
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000192 // Mix in the opcode.
193 return (Res << 1) ^ Inst->getOpcode();
194}
195
Chris Lattner85db6102011-01-03 03:41:27 +0000196bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000197 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000198 if (LHS.isSentinel() || RHS.isSentinel())
199 return LHSI == RHSI;
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000200 return LHSI->isIdenticalTo(RHSI);
201}
202
Chris Lattnercc9eab22011-01-02 23:04:14 +0000203
Chris Lattnerf1974592011-01-03 02:20:48 +0000204//===----------------------------------------------------------------------===//
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000205// EarlyCSE pass.
Chris Lattnerf1974592011-01-03 02:20:48 +0000206//===----------------------------------------------------------------------===//
207
Chris Lattnercc9eab22011-01-02 23:04:14 +0000208namespace {
209
Chris Lattner12be9362011-01-02 21:47:05 +0000210/// EarlyCSE - This pass does a simple depth-first walk over the dominator
211/// tree, eliminating trivially redundant instructions and using instsimplify
212/// to canonicalize things as it goes. It is intended to be fast and catch
213/// obvious cases so that instcombine and other passes are more effective. It
214/// is expected that a later pass of GVN will catch the interesting/hard
215/// cases.
216class EarlyCSE : public FunctionPass {
217public:
Chris Lattnercc9eab22011-01-02 23:04:14 +0000218 const TargetData *TD;
Chad Rosier618c1db2011-12-01 03:08:23 +0000219 const TargetLibraryInfo *TLI;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000220 DominatorTree *DT;
Chris Lattner82dcd5e2011-01-03 01:42:46 +0000221 typedef RecyclingAllocator<BumpPtrAllocator,
Chris Lattnerf1974592011-01-03 02:20:48 +0000222 ScopedHashTableVal<SimpleValue, Value*> > AllocatorTy;
223 typedef ScopedHashTable<SimpleValue, Value*, DenseMapInfo<SimpleValue>,
Chris Lattner82dcd5e2011-01-03 01:42:46 +0000224 AllocatorTy> ScopedHTType;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000225
Chris Lattnerf1974592011-01-03 02:20:48 +0000226 /// AvailableValues - This scoped hash table contains the current values of
227 /// all of our simple scalar expressions. As we walk down the domtree, we
228 /// look to see if instructions are in this: if so, we replace them with what
229 /// we find, otherwise we insert them so that dominated values can succeed in
230 /// their lookup.
231 ScopedHTType *AvailableValues;
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000232
Chris Lattner85db6102011-01-03 03:41:27 +0000233 /// AvailableLoads - This scoped hash table contains the current values
234 /// of loads. This allows us to get efficient access to dominating loads when
235 /// we have a fully redundant load. In addition to the most recent load, we
236 /// keep track of a generation count of the read, which is compared against
237 /// the current generation count. The current generation count is
238 /// incremented after every possibly writing memory operation, which ensures
239 /// that we only CSE loads with other loads that have no intervening store.
Chris Lattner71230ac2011-01-03 03:53:50 +0000240 typedef RecyclingAllocator<BumpPtrAllocator,
241 ScopedHashTableVal<Value*, std::pair<Value*, unsigned> > > LoadMapAllocator;
242 typedef ScopedHashTable<Value*, std::pair<Value*, unsigned>,
243 DenseMapInfo<Value*>, LoadMapAllocator> LoadHTType;
Chris Lattner85db6102011-01-03 03:41:27 +0000244 LoadHTType *AvailableLoads;
245
246 /// AvailableCalls - This scoped hash table contains the current values
247 /// of read-only call values. It uses the same generation count as loads.
248 typedef ScopedHashTable<CallValue, std::pair<Value*, unsigned> > CallHTType;
249 CallHTType *AvailableCalls;
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000250
251 /// CurrentGeneration - This is the current generation of the memory value.
252 unsigned CurrentGeneration;
253
Chris Lattner12be9362011-01-02 21:47:05 +0000254 static char ID;
Chris Lattnerf1974592011-01-03 02:20:48 +0000255 explicit EarlyCSE() : FunctionPass(ID) {
Chris Lattner12be9362011-01-02 21:47:05 +0000256 initializeEarlyCSEPass(*PassRegistry::getPassRegistry());
257 }
258
259 bool runOnFunction(Function &F);
260
261private:
Chris Lattnercc9eab22011-01-02 23:04:14 +0000262
263 bool processNode(DomTreeNode *Node);
264
Chris Lattner12be9362011-01-02 21:47:05 +0000265 // This transformation requires dominator postdominator info
266 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
267 AU.addRequired<DominatorTree>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000268 AU.addRequired<TargetLibraryInfo>();
Chris Lattner12be9362011-01-02 21:47:05 +0000269 AU.setPreservesCFG();
270 }
271};
272}
273
274char EarlyCSE::ID = 0;
275
276// createEarlyCSEPass - The public interface to this file.
277FunctionPass *llvm::createEarlyCSEPass() {
278 return new EarlyCSE();
279}
280
281INITIALIZE_PASS_BEGIN(EarlyCSE, "early-cse", "Early CSE", false, false)
282INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Chad Rosier618c1db2011-12-01 03:08:23 +0000283INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Chris Lattner12be9362011-01-02 21:47:05 +0000284INITIALIZE_PASS_END(EarlyCSE, "early-cse", "Early CSE", false, false)
285
Chris Lattnercc9eab22011-01-02 23:04:14 +0000286bool EarlyCSE::processNode(DomTreeNode *Node) {
Chris Lattnerf1974592011-01-03 02:20:48 +0000287 // Define a scope in the scoped hash table. When we are done processing this
288 // domtree node and recurse back up to our parent domtree node, this will pop
289 // off all the values we install.
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000290 ScopedHTType::ScopeTy Scope(*AvailableValues);
291
Chris Lattner85db6102011-01-03 03:41:27 +0000292 // Define a scope for the load values so that anything we add will get
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000293 // popped when we recurse back up to our parent domtree node.
Chris Lattner85db6102011-01-03 03:41:27 +0000294 LoadHTType::ScopeTy LoadScope(*AvailableLoads);
295
296 // Define a scope for the call values so that anything we add will get
297 // popped when we recurse back up to our parent domtree node.
298 CallHTType::ScopeTy CallScope(*AvailableCalls);
Chris Lattnercc9eab22011-01-02 23:04:14 +0000299
300 BasicBlock *BB = Node->getBlock();
301
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000302 // If this block has a single predecessor, then the predecessor is the parent
303 // of the domtree node and all of the live out memory values are still current
304 // in this block. If this block has multiple predecessors, then they could
305 // have invalidated the live-out memory values of our parent value. For now,
306 // just be conservative and invalidate memory if this block has multiple
307 // predecessors.
308 if (BB->getSinglePredecessor() == 0)
309 ++CurrentGeneration;
310
Chris Lattner75637152011-01-03 04:17:24 +0000311 /// LastStore - Keep track of the last non-volatile store that we saw... for
312 /// as long as there in no instruction that reads memory. If we see a store
313 /// to the same location, we delete the dead store. This zaps trivial dead
314 /// stores which can occur in bitfield code among other things.
315 StoreInst *LastStore = 0;
316
Chris Lattnercc9eab22011-01-02 23:04:14 +0000317 bool Changed = false;
318
319 // See if any instructions in the block can be eliminated. If so, do it. If
320 // not, add them to AvailableValues.
321 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
322 Instruction *Inst = I++;
323
324 // Dead instructions should just be removed.
325 if (isInstructionTriviallyDead(Inst)) {
Chris Lattner91139cc2011-01-02 23:19:45 +0000326 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
Chris Lattnercc9eab22011-01-02 23:04:14 +0000327 Inst->eraseFromParent();
328 Changed = true;
Chris Lattner91139cc2011-01-02 23:19:45 +0000329 ++NumSimplify;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000330 continue;
331 }
332
333 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
334 // its simpler value.
Chad Rosier618c1db2011-12-01 03:08:23 +0000335 if (Value *V = SimplifyInstruction(Inst, TD, TLI, DT)) {
Chris Lattner91139cc2011-01-02 23:19:45 +0000336 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
Chris Lattnercc9eab22011-01-02 23:04:14 +0000337 Inst->replaceAllUsesWith(V);
338 Inst->eraseFromParent();
339 Changed = true;
Chris Lattner91139cc2011-01-02 23:19:45 +0000340 ++NumSimplify;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000341 continue;
342 }
343
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000344 // If this is a simple instruction that we can value number, process it.
345 if (SimpleValue::canHandle(Inst)) {
346 // See if the instruction has an available value. If so, use it.
Chris Lattnera60a8b02011-01-03 03:28:23 +0000347 if (Value *V = AvailableValues->lookup(Inst)) {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000348 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
349 Inst->replaceAllUsesWith(V);
350 Inst->eraseFromParent();
351 Changed = true;
352 ++NumCSE;
353 continue;
354 }
355
356 // Otherwise, just remember that this value is available.
Chris Lattnera60a8b02011-01-03 03:28:23 +0000357 AvailableValues->insert(Inst, Inst);
Chris Lattnercc9eab22011-01-02 23:04:14 +0000358 continue;
359 }
360
Chris Lattner85db6102011-01-03 03:41:27 +0000361 // If this is a non-volatile load, process it.
362 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
363 // Ignore volatile loads.
Eli Friedman2bc3d522011-09-12 20:23:13 +0000364 if (!LI->isSimple()) {
Chris Lattner75637152011-01-03 04:17:24 +0000365 LastStore = 0;
366 continue;
367 }
Chris Lattner85db6102011-01-03 03:41:27 +0000368
369 // If we have an available version of this load, and if it is the right
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000370 // generation, replace this instruction.
Chris Lattner85db6102011-01-03 03:41:27 +0000371 std::pair<Value*, unsigned> InVal =
372 AvailableLoads->lookup(Inst->getOperand(0));
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000373 if (InVal.first != 0 && InVal.second == CurrentGeneration) {
Chris Lattner85db6102011-01-03 03:41:27 +0000374 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst << " to: "
375 << *InVal.first << '\n');
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000376 if (!Inst->use_empty()) Inst->replaceAllUsesWith(InVal.first);
377 Inst->eraseFromParent();
378 Changed = true;
Chris Lattner85db6102011-01-03 03:41:27 +0000379 ++NumCSELoad;
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000380 continue;
381 }
382
383 // Otherwise, remember that we have this instruction.
Chris Lattner85db6102011-01-03 03:41:27 +0000384 AvailableLoads->insert(Inst->getOperand(0),
385 std::pair<Value*, unsigned>(Inst, CurrentGeneration));
Chris Lattner75637152011-01-03 04:17:24 +0000386 LastStore = 0;
Chris Lattner85db6102011-01-03 03:41:27 +0000387 continue;
388 }
389
Chris Lattner75637152011-01-03 04:17:24 +0000390 // If this instruction may read from memory, forget LastStore.
391 if (Inst->mayReadFromMemory())
392 LastStore = 0;
393
Chris Lattner85db6102011-01-03 03:41:27 +0000394 // If this is a read-only call, process it.
395 if (CallValue::canHandle(Inst)) {
396 // If we have an available version of this call, and if it is the right
397 // generation, replace this instruction.
398 std::pair<Value*, unsigned> InVal = AvailableCalls->lookup(Inst);
399 if (InVal.first != 0 && InVal.second == CurrentGeneration) {
400 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst << " to: "
401 << *InVal.first << '\n');
402 if (!Inst->use_empty()) Inst->replaceAllUsesWith(InVal.first);
403 Inst->eraseFromParent();
404 Changed = true;
405 ++NumCSECall;
406 continue;
407 }
408
409 // Otherwise, remember that we have this instruction.
410 AvailableCalls->insert(Inst,
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000411 std::pair<Value*, unsigned>(Inst, CurrentGeneration));
412 continue;
413 }
414
415 // Okay, this isn't something we can CSE at all. Check to see if it is
416 // something that could modify memory. If so, our available memory values
417 // cannot be used so bump the generation count.
Chris Lattneref87fc22011-01-03 03:46:34 +0000418 if (Inst->mayWriteToMemory()) {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000419 ++CurrentGeneration;
Chris Lattneref87fc22011-01-03 03:46:34 +0000420
Chris Lattneref87fc22011-01-03 03:46:34 +0000421 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattner75637152011-01-03 04:17:24 +0000422 // We do a trivial form of DSE if there are two stores to the same
423 // location with no intervening loads. Delete the earlier store.
424 if (LastStore &&
425 LastStore->getPointerOperand() == SI->getPointerOperand()) {
426 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore << " due to: "
Chris Lattnera12ba392011-01-03 18:28:15 +0000427 << *Inst << '\n');
Chris Lattner75637152011-01-03 04:17:24 +0000428 LastStore->eraseFromParent();
429 Changed = true;
430 ++NumDSE;
431 LastStore = 0;
432 continue;
433 }
434
435 // Okay, we just invalidated anything we knew about loaded values. Try
436 // to salvage *something* by remembering that the stored value is a live
437 // version of the pointer. It is safe to forward from volatile stores
438 // to non-volatile loads, so we don't have to check for volatility of
439 // the store.
Chris Lattneref87fc22011-01-03 03:46:34 +0000440 AvailableLoads->insert(SI->getPointerOperand(),
441 std::pair<Value*, unsigned>(SI->getValueOperand(), CurrentGeneration));
Chris Lattner75637152011-01-03 04:17:24 +0000442
443 // Remember that this was the last store we saw for DSE.
Eli Friedman2bc3d522011-09-12 20:23:13 +0000444 if (SI->isSimple())
Chris Lattner75637152011-01-03 04:17:24 +0000445 LastStore = SI;
Chris Lattneref87fc22011-01-03 03:46:34 +0000446 }
447 }
Chris Lattnercc9eab22011-01-02 23:04:14 +0000448 }
449
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000450 unsigned LiveOutGeneration = CurrentGeneration;
451 for (DomTreeNode::iterator I = Node->begin(), E = Node->end(); I != E; ++I) {
Chris Lattnercc9eab22011-01-02 23:04:14 +0000452 Changed |= processNode(*I);
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000453 // Pop any generation changes off the stack from the recursive walk.
454 CurrentGeneration = LiveOutGeneration;
455 }
Chris Lattnercc9eab22011-01-02 23:04:14 +0000456 return Changed;
Chris Lattner12be9362011-01-02 21:47:05 +0000457}
Chris Lattnercc9eab22011-01-02 23:04:14 +0000458
459
460bool EarlyCSE::runOnFunction(Function &F) {
461 TD = getAnalysisIfAvailable<TargetData>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000462 TLI = &getAnalysis<TargetLibraryInfo>();
Chris Lattnercc9eab22011-01-02 23:04:14 +0000463 DT = &getAnalysis<DominatorTree>();
Chris Lattner85db6102011-01-03 03:41:27 +0000464
465 // Tables that the pass uses when walking the domtree.
Chris Lattner82dcd5e2011-01-03 01:42:46 +0000466 ScopedHTType AVTable;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000467 AvailableValues = &AVTable;
Chris Lattner85db6102011-01-03 03:41:27 +0000468 LoadHTType LoadTable;
469 AvailableLoads = &LoadTable;
470 CallHTType CallTable;
471 AvailableCalls = &CallTable;
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000472
473 CurrentGeneration = 0;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000474 return processNode(DT->getRootNode());
475}