blob: 975954953b2909f184020d546f068b0ec433ed78 [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"
Lenny Maioranie0c7cfa2012-01-31 23:14:41 +000028#include <deque>
Chris Lattner12be9362011-01-02 21:47:05 +000029using namespace llvm;
30
Chris Lattnera60a8b02011-01-03 03:28:23 +000031STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
32STATISTIC(NumCSE, "Number of instructions CSE'd");
Chris Lattner85db6102011-01-03 03:41:27 +000033STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
34STATISTIC(NumCSECall, "Number of call instructions CSE'd");
Chris Lattner75637152011-01-03 04:17:24 +000035STATISTIC(NumDSE, "Number of trivial dead stores removed");
Chris Lattner8e7f0d72011-01-03 03:18:43 +000036
37static unsigned getHash(const void *V) {
38 return DenseMapInfo<const void*>::getHashValue(V);
39}
Chris Lattner91139cc2011-01-02 23:19:45 +000040
Chris Lattnerf1974592011-01-03 02:20:48 +000041//===----------------------------------------------------------------------===//
Nadav Rotema94d6e82012-07-24 10:51:42 +000042// SimpleValue
Chris Lattnerf1974592011-01-03 02:20:48 +000043//===----------------------------------------------------------------------===//
44
Chris Lattner12be9362011-01-02 21:47:05 +000045namespace {
Chris Lattnerf1974592011-01-03 02:20:48 +000046 /// SimpleValue - Instances of this struct represent available values in the
Chris Lattnercc9eab22011-01-02 23:04:14 +000047 /// scoped hash table.
Chris Lattnerf1974592011-01-03 02:20:48 +000048 struct SimpleValue {
Chris Lattnercc9eab22011-01-02 23:04:14 +000049 Instruction *Inst;
Nadav Rotema94d6e82012-07-24 10:51:42 +000050
Chris Lattnera60a8b02011-01-03 03:28:23 +000051 SimpleValue(Instruction *I) : Inst(I) {
52 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
53 }
Nadav Rotema94d6e82012-07-24 10:51:42 +000054
Chris Lattnercc9eab22011-01-02 23:04:14 +000055 bool isSentinel() const {
56 return Inst == DenseMapInfo<Instruction*>::getEmptyKey() ||
57 Inst == DenseMapInfo<Instruction*>::getTombstoneKey();
58 }
Nadav Rotema94d6e82012-07-24 10:51:42 +000059
Chris Lattnercc9eab22011-01-02 23:04:14 +000060 static bool canHandle(Instruction *Inst) {
Chris Lattnere508dd42011-01-03 23:38:13 +000061 // This can only handle non-void readnone functions.
62 if (CallInst *CI = dyn_cast<CallInst>(Inst))
63 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
Chris Lattner91139cc2011-01-02 23:19:45 +000064 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
65 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
66 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
67 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
68 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
Chris Lattnercc9eab22011-01-02 23:04:14 +000069 }
Chris Lattnercc9eab22011-01-02 23:04:14 +000070 };
71}
72
73namespace llvm {
Chris Lattnerf1974592011-01-03 02:20:48 +000074// SimpleValue is POD.
75template<> struct isPodLike<SimpleValue> {
Chris Lattnercc9eab22011-01-02 23:04:14 +000076 static const bool value = true;
77};
78
Chris Lattnerf1974592011-01-03 02:20:48 +000079template<> struct DenseMapInfo<SimpleValue> {
80 static inline SimpleValue getEmptyKey() {
Chris Lattnera60a8b02011-01-03 03:28:23 +000081 return DenseMapInfo<Instruction*>::getEmptyKey();
Chris Lattnercc9eab22011-01-02 23:04:14 +000082 }
Chris Lattnerf1974592011-01-03 02:20:48 +000083 static inline SimpleValue getTombstoneKey() {
Chris Lattnera60a8b02011-01-03 03:28:23 +000084 return DenseMapInfo<Instruction*>::getTombstoneKey();
Chris Lattnercc9eab22011-01-02 23:04:14 +000085 }
Chris Lattnerf1974592011-01-03 02:20:48 +000086 static unsigned getHashValue(SimpleValue Val);
87 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
Chris Lattnercc9eab22011-01-02 23:04:14 +000088};
89}
90
Chris Lattnerf1974592011-01-03 02:20:48 +000091unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
Chris Lattnercc9eab22011-01-02 23:04:14 +000092 Instruction *Inst = Val.Inst;
Nadav Rotema94d6e82012-07-24 10:51:42 +000093
Chris Lattnerd957c712011-01-03 01:10:08 +000094 // Hash in all of the operands as pointers.
95 unsigned Res = 0;
96 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
Eli Friedman18ead6b2011-10-12 22:00:26 +000097 Res ^= getHash(Inst->getOperand(i)) << (i & 0xF);
Chris Lattnerd957c712011-01-03 01:10:08 +000098
99 if (CastInst *CI = dyn_cast<CastInst>(Inst))
100 Res ^= getHash(CI->getType());
101 else if (CmpInst *CI = dyn_cast<CmpInst>(Inst))
102 Res ^= CI->getPredicate();
103 else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst)) {
104 for (ExtractValueInst::idx_iterator I = EVI->idx_begin(),
105 E = EVI->idx_end(); I != E; ++I)
106 Res ^= *I;
107 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst)) {
108 for (InsertValueInst::idx_iterator I = IVI->idx_begin(),
109 E = IVI->idx_end(); I != E; ++I)
110 Res ^= *I;
111 } else {
112 // nothing extra to hash in.
Chris Lattnere508dd42011-01-03 23:38:13 +0000113 assert((isa<CallInst>(Inst) ||
114 isa<BinaryOperator>(Inst) || isa<GetElementPtrInst>(Inst) ||
Chris Lattnerd957c712011-01-03 01:10:08 +0000115 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
116 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst)) &&
117 "Invalid/unknown instruction");
118 }
119
120 // Mix in the opcode.
Chris Lattnercc9eab22011-01-02 23:04:14 +0000121 return (Res << 1) ^ Inst->getOpcode();
122}
123
Chris Lattnerf1974592011-01-03 02:20:48 +0000124bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
Chris Lattnercc9eab22011-01-02 23:04:14 +0000125 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
126
127 if (LHS.isSentinel() || RHS.isSentinel())
128 return LHSI == RHSI;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000129
Chris Lattnercc9eab22011-01-02 23:04:14 +0000130 if (LHSI->getOpcode() != RHSI->getOpcode()) return false;
131 return LHSI->isIdenticalTo(RHSI);
132}
133
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000134//===----------------------------------------------------------------------===//
Nadav Rotema94d6e82012-07-24 10:51:42 +0000135// CallValue
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000136//===----------------------------------------------------------------------===//
137
138namespace {
Chris Lattner85db6102011-01-03 03:41:27 +0000139 /// CallValue - Instances of this struct represent available call values in
140 /// the scoped hash table.
141 struct CallValue {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000142 Instruction *Inst;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000143
Chris Lattner85db6102011-01-03 03:41:27 +0000144 CallValue(Instruction *I) : Inst(I) {
Chris Lattnera60a8b02011-01-03 03:28:23 +0000145 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
146 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000147
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000148 bool isSentinel() const {
149 return Inst == DenseMapInfo<Instruction*>::getEmptyKey() ||
150 Inst == DenseMapInfo<Instruction*>::getTombstoneKey();
151 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000152
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000153 static bool canHandle(Instruction *Inst) {
Chris Lattner10b883b2011-01-03 18:43:03 +0000154 // Don't value number anything that returns void.
155 if (Inst->getType()->isVoidTy())
156 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000157
Chris Lattnera12ba392011-01-03 18:28:15 +0000158 CallInst *CI = dyn_cast<CallInst>(Inst);
159 if (CI == 0 || !CI->onlyReadsMemory())
160 return false;
Chris Lattnera12ba392011-01-03 18:28:15 +0000161 return true;
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000162 }
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000163 };
164}
165
166namespace llvm {
Chris Lattner85db6102011-01-03 03:41:27 +0000167 // CallValue is POD.
168 template<> struct isPodLike<CallValue> {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000169 static const bool value = true;
170 };
Nadav Rotema94d6e82012-07-24 10:51:42 +0000171
Chris Lattner85db6102011-01-03 03:41:27 +0000172 template<> struct DenseMapInfo<CallValue> {
173 static inline CallValue getEmptyKey() {
Chris Lattnera60a8b02011-01-03 03:28:23 +0000174 return DenseMapInfo<Instruction*>::getEmptyKey();
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000175 }
Chris Lattner85db6102011-01-03 03:41:27 +0000176 static inline CallValue getTombstoneKey() {
Chris Lattnera60a8b02011-01-03 03:28:23 +0000177 return DenseMapInfo<Instruction*>::getTombstoneKey();
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000178 }
Chris Lattner85db6102011-01-03 03:41:27 +0000179 static unsigned getHashValue(CallValue Val);
180 static bool isEqual(CallValue LHS, CallValue RHS);
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000181 };
182}
Chris Lattner85db6102011-01-03 03:41:27 +0000183unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000184 Instruction *Inst = Val.Inst;
185 // Hash in all of the operands as pointers.
186 unsigned Res = 0;
Chris Lattner10b883b2011-01-03 18:43:03 +0000187 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i) {
188 assert(!Inst->getOperand(i)->getType()->isMetadataTy() &&
189 "Cannot value number calls with metadata operands");
Eli Friedman18ead6b2011-10-12 22:00:26 +0000190 Res ^= getHash(Inst->getOperand(i)) << (i & 0xF);
Chris Lattner10b883b2011-01-03 18:43:03 +0000191 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000192
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000193 // Mix in the opcode.
194 return (Res << 1) ^ Inst->getOpcode();
195}
196
Chris Lattner85db6102011-01-03 03:41:27 +0000197bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000198 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000199 if (LHS.isSentinel() || RHS.isSentinel())
200 return LHSI == RHSI;
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000201 return LHSI->isIdenticalTo(RHSI);
202}
203
Chris Lattnercc9eab22011-01-02 23:04:14 +0000204
Chris Lattnerf1974592011-01-03 02:20:48 +0000205//===----------------------------------------------------------------------===//
Nadav Rotema94d6e82012-07-24 10:51:42 +0000206// EarlyCSE pass.
Chris Lattnerf1974592011-01-03 02:20:48 +0000207//===----------------------------------------------------------------------===//
208
Chris Lattnercc9eab22011-01-02 23:04:14 +0000209namespace {
Nadav Rotema94d6e82012-07-24 10:51:42 +0000210
Chris Lattner12be9362011-01-02 21:47:05 +0000211/// EarlyCSE - This pass does a simple depth-first walk over the dominator
212/// tree, eliminating trivially redundant instructions and using instsimplify
213/// to canonicalize things as it goes. It is intended to be fast and catch
214/// obvious cases so that instcombine and other passes are more effective. It
215/// is expected that a later pass of GVN will catch the interesting/hard
216/// cases.
217class EarlyCSE : public FunctionPass {
218public:
Chris Lattnercc9eab22011-01-02 23:04:14 +0000219 const TargetData *TD;
Chad Rosier618c1db2011-12-01 03:08:23 +0000220 const TargetLibraryInfo *TLI;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000221 DominatorTree *DT;
Chris Lattner82dcd5e2011-01-03 01:42:46 +0000222 typedef RecyclingAllocator<BumpPtrAllocator,
Chris Lattnerf1974592011-01-03 02:20:48 +0000223 ScopedHashTableVal<SimpleValue, Value*> > AllocatorTy;
224 typedef ScopedHashTable<SimpleValue, Value*, DenseMapInfo<SimpleValue>,
Chris Lattner82dcd5e2011-01-03 01:42:46 +0000225 AllocatorTy> ScopedHTType;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000226
Chris Lattnerf1974592011-01-03 02:20:48 +0000227 /// AvailableValues - This scoped hash table contains the current values of
228 /// all of our simple scalar expressions. As we walk down the domtree, we
229 /// look to see if instructions are in this: if so, we replace them with what
230 /// we find, otherwise we insert them so that dominated values can succeed in
231 /// their lookup.
232 ScopedHTType *AvailableValues;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000233
Chris Lattner85db6102011-01-03 03:41:27 +0000234 /// AvailableLoads - This scoped hash table contains the current values
235 /// of loads. This allows us to get efficient access to dominating loads when
236 /// we have a fully redundant load. In addition to the most recent load, we
237 /// keep track of a generation count of the read, which is compared against
238 /// the current generation count. The current generation count is
239 /// incremented after every possibly writing memory operation, which ensures
240 /// that we only CSE loads with other loads that have no intervening store.
Chris Lattner71230ac2011-01-03 03:53:50 +0000241 typedef RecyclingAllocator<BumpPtrAllocator,
242 ScopedHashTableVal<Value*, std::pair<Value*, unsigned> > > LoadMapAllocator;
243 typedef ScopedHashTable<Value*, std::pair<Value*, unsigned>,
244 DenseMapInfo<Value*>, LoadMapAllocator> LoadHTType;
Chris Lattner85db6102011-01-03 03:41:27 +0000245 LoadHTType *AvailableLoads;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000246
Chris Lattner85db6102011-01-03 03:41:27 +0000247 /// AvailableCalls - This scoped hash table contains the current values
248 /// of read-only call values. It uses the same generation count as loads.
249 typedef ScopedHashTable<CallValue, std::pair<Value*, unsigned> > CallHTType;
250 CallHTType *AvailableCalls;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000251
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000252 /// CurrentGeneration - This is the current generation of the memory value.
253 unsigned CurrentGeneration;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000254
Chris Lattner12be9362011-01-02 21:47:05 +0000255 static char ID;
Chris Lattnerf1974592011-01-03 02:20:48 +0000256 explicit EarlyCSE() : FunctionPass(ID) {
Chris Lattner12be9362011-01-02 21:47:05 +0000257 initializeEarlyCSEPass(*PassRegistry::getPassRegistry());
258 }
259
260 bool runOnFunction(Function &F);
261
262private:
Lenny Maioranie0c7cfa2012-01-31 23:14:41 +0000263
264 // NodeScope - almost a POD, but needs to call the constructors for the
265 // scoped hash tables so that a new scope gets pushed on. These are RAII so
266 // that the scope gets popped when the NodeScope is destroyed.
267 class NodeScope {
268 public:
269 NodeScope(ScopedHTType *availableValues,
270 LoadHTType *availableLoads,
271 CallHTType *availableCalls) :
272 Scope(*availableValues),
273 LoadScope(*availableLoads),
274 CallScope(*availableCalls) {}
275
276 private:
277 NodeScope(const NodeScope&); // DO NOT IMPLEMENT
278
279 ScopedHTType::ScopeTy Scope;
280 LoadHTType::ScopeTy LoadScope;
281 CallHTType::ScopeTy CallScope;
282 };
283
284 // StackNode - contains all the needed information to create a stack for
285 // doing a depth first tranversal of the tree. This includes scopes for
286 // values, loads, and calls as well as the generation. There is a child
287 // iterator so that the children do not need to be store spearately.
288 class StackNode {
289 public:
290 StackNode(ScopedHTType *availableValues,
291 LoadHTType *availableLoads,
292 CallHTType *availableCalls,
293 unsigned cg, DomTreeNode *n,
294 DomTreeNode::iterator child, DomTreeNode::iterator end) :
295 CurrentGeneration(cg), ChildGeneration(cg), Node(n),
296 ChildIter(child), EndIter(end),
297 Scopes(availableValues, availableLoads, availableCalls),
298 Processed(false) {}
299
300 // Accessors.
301 unsigned currentGeneration() { return CurrentGeneration; }
302 unsigned childGeneration() { return ChildGeneration; }
303 void childGeneration(unsigned generation) { ChildGeneration = generation; }
304 DomTreeNode *node() { return Node; }
305 DomTreeNode::iterator childIter() { return ChildIter; }
306 DomTreeNode *nextChild() {
307 DomTreeNode *child = *ChildIter;
308 ++ChildIter;
309 return child;
310 }
311 DomTreeNode::iterator end() { return EndIter; }
312 bool isProcessed() { return Processed; }
313 void process() { Processed = true; }
314
315 private:
316 StackNode(const StackNode&); // DO NOT IMPLEMENT
317
318 // Members.
319 unsigned CurrentGeneration;
320 unsigned ChildGeneration;
321 DomTreeNode *Node;
322 DomTreeNode::iterator ChildIter;
323 DomTreeNode::iterator EndIter;
324 NodeScope Scopes;
325 bool Processed;
326 };
327
Chris Lattnercc9eab22011-01-02 23:04:14 +0000328 bool processNode(DomTreeNode *Node);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000329
Chris Lattner12be9362011-01-02 21:47:05 +0000330 // This transformation requires dominator postdominator info
331 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
332 AU.addRequired<DominatorTree>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000333 AU.addRequired<TargetLibraryInfo>();
Chris Lattner12be9362011-01-02 21:47:05 +0000334 AU.setPreservesCFG();
335 }
336};
337}
338
339char EarlyCSE::ID = 0;
340
341// createEarlyCSEPass - The public interface to this file.
342FunctionPass *llvm::createEarlyCSEPass() {
343 return new EarlyCSE();
344}
345
346INITIALIZE_PASS_BEGIN(EarlyCSE, "early-cse", "Early CSE", false, false)
347INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Chad Rosier618c1db2011-12-01 03:08:23 +0000348INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Chris Lattner12be9362011-01-02 21:47:05 +0000349INITIALIZE_PASS_END(EarlyCSE, "early-cse", "Early CSE", false, false)
350
Chris Lattnercc9eab22011-01-02 23:04:14 +0000351bool EarlyCSE::processNode(DomTreeNode *Node) {
Chris Lattnercc9eab22011-01-02 23:04:14 +0000352 BasicBlock *BB = Node->getBlock();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000353
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000354 // If this block has a single predecessor, then the predecessor is the parent
355 // of the domtree node and all of the live out memory values are still current
356 // in this block. If this block has multiple predecessors, then they could
357 // have invalidated the live-out memory values of our parent value. For now,
358 // just be conservative and invalidate memory if this block has multiple
359 // predecessors.
360 if (BB->getSinglePredecessor() == 0)
361 ++CurrentGeneration;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000362
Chris Lattner75637152011-01-03 04:17:24 +0000363 /// LastStore - Keep track of the last non-volatile store that we saw... for
364 /// as long as there in no instruction that reads memory. If we see a store
365 /// to the same location, we delete the dead store. This zaps trivial dead
366 /// stores which can occur in bitfield code among other things.
367 StoreInst *LastStore = 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000368
Chris Lattnercc9eab22011-01-02 23:04:14 +0000369 bool Changed = false;
370
371 // See if any instructions in the block can be eliminated. If so, do it. If
372 // not, add them to AvailableValues.
373 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
374 Instruction *Inst = I++;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000375
Chris Lattnercc9eab22011-01-02 23:04:14 +0000376 // Dead instructions should just be removed.
377 if (isInstructionTriviallyDead(Inst)) {
Chris Lattner91139cc2011-01-02 23:19:45 +0000378 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
Chris Lattnercc9eab22011-01-02 23:04:14 +0000379 Inst->eraseFromParent();
380 Changed = true;
Chris Lattner91139cc2011-01-02 23:19:45 +0000381 ++NumSimplify;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000382 continue;
383 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000384
Chris Lattnercc9eab22011-01-02 23:04:14 +0000385 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
386 // its simpler value.
Chad Rosier618c1db2011-12-01 03:08:23 +0000387 if (Value *V = SimplifyInstruction(Inst, TD, TLI, DT)) {
Chris Lattner91139cc2011-01-02 23:19:45 +0000388 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
Chris Lattnercc9eab22011-01-02 23:04:14 +0000389 Inst->replaceAllUsesWith(V);
390 Inst->eraseFromParent();
391 Changed = true;
Chris Lattner91139cc2011-01-02 23:19:45 +0000392 ++NumSimplify;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000393 continue;
394 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000395
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000396 // If this is a simple instruction that we can value number, process it.
397 if (SimpleValue::canHandle(Inst)) {
398 // See if the instruction has an available value. If so, use it.
Chris Lattnera60a8b02011-01-03 03:28:23 +0000399 if (Value *V = AvailableValues->lookup(Inst)) {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000400 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
401 Inst->replaceAllUsesWith(V);
402 Inst->eraseFromParent();
403 Changed = true;
404 ++NumCSE;
405 continue;
406 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000407
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000408 // Otherwise, just remember that this value is available.
Chris Lattnera60a8b02011-01-03 03:28:23 +0000409 AvailableValues->insert(Inst, Inst);
Chris Lattnercc9eab22011-01-02 23:04:14 +0000410 continue;
411 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000412
Chris Lattner85db6102011-01-03 03:41:27 +0000413 // If this is a non-volatile load, process it.
414 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
415 // Ignore volatile loads.
Eli Friedman2bc3d522011-09-12 20:23:13 +0000416 if (!LI->isSimple()) {
Chris Lattner75637152011-01-03 04:17:24 +0000417 LastStore = 0;
418 continue;
419 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000420
Chris Lattner85db6102011-01-03 03:41:27 +0000421 // If we have an available version of this load, and if it is the right
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000422 // generation, replace this instruction.
Chris Lattner85db6102011-01-03 03:41:27 +0000423 std::pair<Value*, unsigned> InVal =
424 AvailableLoads->lookup(Inst->getOperand(0));
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000425 if (InVal.first != 0 && InVal.second == CurrentGeneration) {
Chris Lattner85db6102011-01-03 03:41:27 +0000426 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst << " to: "
427 << *InVal.first << '\n');
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000428 if (!Inst->use_empty()) Inst->replaceAllUsesWith(InVal.first);
429 Inst->eraseFromParent();
430 Changed = true;
Chris Lattner85db6102011-01-03 03:41:27 +0000431 ++NumCSELoad;
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000432 continue;
433 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000434
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000435 // Otherwise, remember that we have this instruction.
Chris Lattner85db6102011-01-03 03:41:27 +0000436 AvailableLoads->insert(Inst->getOperand(0),
437 std::pair<Value*, unsigned>(Inst, CurrentGeneration));
Chris Lattner75637152011-01-03 04:17:24 +0000438 LastStore = 0;
Chris Lattner85db6102011-01-03 03:41:27 +0000439 continue;
440 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000441
Chris Lattner75637152011-01-03 04:17:24 +0000442 // If this instruction may read from memory, forget LastStore.
443 if (Inst->mayReadFromMemory())
444 LastStore = 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000445
Chris Lattner85db6102011-01-03 03:41:27 +0000446 // If this is a read-only call, process it.
447 if (CallValue::canHandle(Inst)) {
448 // If we have an available version of this call, and if it is the right
449 // generation, replace this instruction.
450 std::pair<Value*, unsigned> InVal = AvailableCalls->lookup(Inst);
451 if (InVal.first != 0 && InVal.second == CurrentGeneration) {
452 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst << " to: "
453 << *InVal.first << '\n');
454 if (!Inst->use_empty()) Inst->replaceAllUsesWith(InVal.first);
455 Inst->eraseFromParent();
456 Changed = true;
457 ++NumCSECall;
458 continue;
459 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000460
Chris Lattner85db6102011-01-03 03:41:27 +0000461 // Otherwise, remember that we have this instruction.
462 AvailableCalls->insert(Inst,
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000463 std::pair<Value*, unsigned>(Inst, CurrentGeneration));
464 continue;
465 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000466
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000467 // Okay, this isn't something we can CSE at all. Check to see if it is
468 // something that could modify memory. If so, our available memory values
469 // cannot be used so bump the generation count.
Chris Lattneref87fc22011-01-03 03:46:34 +0000470 if (Inst->mayWriteToMemory()) {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000471 ++CurrentGeneration;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000472
Chris Lattneref87fc22011-01-03 03:46:34 +0000473 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattner75637152011-01-03 04:17:24 +0000474 // We do a trivial form of DSE if there are two stores to the same
475 // location with no intervening loads. Delete the earlier store.
476 if (LastStore &&
477 LastStore->getPointerOperand() == SI->getPointerOperand()) {
478 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore << " due to: "
Chris Lattnera12ba392011-01-03 18:28:15 +0000479 << *Inst << '\n');
Chris Lattner75637152011-01-03 04:17:24 +0000480 LastStore->eraseFromParent();
481 Changed = true;
482 ++NumDSE;
483 LastStore = 0;
484 continue;
485 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000486
Chris Lattner75637152011-01-03 04:17:24 +0000487 // Okay, we just invalidated anything we knew about loaded values. Try
488 // to salvage *something* by remembering that the stored value is a live
489 // version of the pointer. It is safe to forward from volatile stores
490 // to non-volatile loads, so we don't have to check for volatility of
491 // the store.
Chris Lattneref87fc22011-01-03 03:46:34 +0000492 AvailableLoads->insert(SI->getPointerOperand(),
493 std::pair<Value*, unsigned>(SI->getValueOperand(), CurrentGeneration));
Nadav Rotema94d6e82012-07-24 10:51:42 +0000494
Chris Lattner75637152011-01-03 04:17:24 +0000495 // Remember that this was the last store we saw for DSE.
Eli Friedman2bc3d522011-09-12 20:23:13 +0000496 if (SI->isSimple())
Chris Lattner75637152011-01-03 04:17:24 +0000497 LastStore = SI;
Chris Lattneref87fc22011-01-03 03:46:34 +0000498 }
499 }
Chris Lattnercc9eab22011-01-02 23:04:14 +0000500 }
Lenny Maioranie0c7cfa2012-01-31 23:14:41 +0000501
Chris Lattnercc9eab22011-01-02 23:04:14 +0000502 return Changed;
Chris Lattner12be9362011-01-02 21:47:05 +0000503}
Chris Lattnercc9eab22011-01-02 23:04:14 +0000504
505
506bool EarlyCSE::runOnFunction(Function &F) {
Lenny Maioranie0c7cfa2012-01-31 23:14:41 +0000507 std::deque<StackNode *> nodesToProcess;
508
Chris Lattnercc9eab22011-01-02 23:04:14 +0000509 TD = getAnalysisIfAvailable<TargetData>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000510 TLI = &getAnalysis<TargetLibraryInfo>();
Chris Lattnercc9eab22011-01-02 23:04:14 +0000511 DT = &getAnalysis<DominatorTree>();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000512
Chris Lattner85db6102011-01-03 03:41:27 +0000513 // Tables that the pass uses when walking the domtree.
Chris Lattner82dcd5e2011-01-03 01:42:46 +0000514 ScopedHTType AVTable;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000515 AvailableValues = &AVTable;
Chris Lattner85db6102011-01-03 03:41:27 +0000516 LoadHTType LoadTable;
517 AvailableLoads = &LoadTable;
518 CallHTType CallTable;
519 AvailableCalls = &CallTable;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000520
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000521 CurrentGeneration = 0;
Lenny Maioranie0c7cfa2012-01-31 23:14:41 +0000522 bool Changed = false;
523
524 // Process the root node.
525 nodesToProcess.push_front(
526 new StackNode(AvailableValues, AvailableLoads, AvailableCalls,
527 CurrentGeneration, DT->getRootNode(),
528 DT->getRootNode()->begin(),
529 DT->getRootNode()->end()));
530
531 // Save the current generation.
532 unsigned LiveOutGeneration = CurrentGeneration;
533
534 // Process the stack.
535 while (!nodesToProcess.empty()) {
536 // Grab the first item off the stack. Set the current generation, remove
537 // the node from the stack, and process it.
538 StackNode *NodeToProcess = nodesToProcess.front();
539
540 // Initialize class members.
541 CurrentGeneration = NodeToProcess->currentGeneration();
542
543 // Check if the node needs to be processed.
544 if (!NodeToProcess->isProcessed()) {
545 // Process the node.
546 Changed |= processNode(NodeToProcess->node());
547 NodeToProcess->childGeneration(CurrentGeneration);
548 NodeToProcess->process();
549 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
550 // Push the next child onto the stack.
551 DomTreeNode *child = NodeToProcess->nextChild();
552 nodesToProcess.push_front(
553 new StackNode(AvailableValues,
554 AvailableLoads,
555 AvailableCalls,
556 NodeToProcess->childGeneration(), child,
557 child->begin(), child->end()));
558 } else {
559 // It has been processed, and there are no more children to process,
560 // so delete it and pop it off the stack.
561 delete NodeToProcess;
562 nodesToProcess.pop_front();
563 }
564 } // while (!nodes...)
565
566 // Reset the current generation.
567 CurrentGeneration = LiveOutGeneration;
568
569 return Changed;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000570}