blob: 3c08634bfe22625a9376c4db85789a63ed4f473f [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"
Michael Ilseman39285ab2012-10-09 16:57:38 +000017#include "llvm/ADT/Hashing.h"
Chris Lattnercc9eab22011-01-02 23:04:14 +000018#include "llvm/ADT/ScopedHashTable.h"
Chris Lattner91139cc2011-01-02 23:19:45 +000019#include "llvm/ADT/Statistic.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000020#include "llvm/Analysis/Dominators.h"
21#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000022#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/Instructions.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000024#include "llvm/Pass.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/RecyclingAllocator.h"
27#include "llvm/Target/TargetLibraryInfo.h"
28#include "llvm/Transforms/Utils/Local.h"
Lenny Maioranie0c7cfa2012-01-31 23:14:41 +000029#include <deque>
Chris Lattner12be9362011-01-02 21:47:05 +000030using namespace llvm;
31
Chris Lattnera60a8b02011-01-03 03:28:23 +000032STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
33STATISTIC(NumCSE, "Number of instructions CSE'd");
Chris Lattner85db6102011-01-03 03:41:27 +000034STATISTIC(NumCSELoad, "Number of load instructions CSE'd");
35STATISTIC(NumCSECall, "Number of call instructions CSE'd");
Chris Lattner75637152011-01-03 04:17:24 +000036STATISTIC(NumDSE, "Number of trivial dead stores removed");
Chris Lattner8e7f0d72011-01-03 03:18:43 +000037
38static unsigned getHash(const void *V) {
39 return DenseMapInfo<const void*>::getHashValue(V);
40}
Chris Lattner91139cc2011-01-02 23:19:45 +000041
Chris Lattnerf1974592011-01-03 02:20:48 +000042//===----------------------------------------------------------------------===//
Nadav Rotema94d6e82012-07-24 10:51:42 +000043// SimpleValue
Chris Lattnerf1974592011-01-03 02:20:48 +000044//===----------------------------------------------------------------------===//
45
Chris Lattner12be9362011-01-02 21:47:05 +000046namespace {
Chris Lattnerf1974592011-01-03 02:20:48 +000047 /// SimpleValue - Instances of this struct represent available values in the
Chris Lattnercc9eab22011-01-02 23:04:14 +000048 /// scoped hash table.
Chris Lattnerf1974592011-01-03 02:20:48 +000049 struct SimpleValue {
Chris Lattnercc9eab22011-01-02 23:04:14 +000050 Instruction *Inst;
Nadav Rotema94d6e82012-07-24 10:51:42 +000051
Chris Lattnera60a8b02011-01-03 03:28:23 +000052 SimpleValue(Instruction *I) : Inst(I) {
53 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
54 }
Nadav Rotema94d6e82012-07-24 10:51:42 +000055
Chris Lattnercc9eab22011-01-02 23:04:14 +000056 bool isSentinel() const {
57 return Inst == DenseMapInfo<Instruction*>::getEmptyKey() ||
58 Inst == DenseMapInfo<Instruction*>::getTombstoneKey();
59 }
Nadav Rotema94d6e82012-07-24 10:51:42 +000060
Chris Lattnercc9eab22011-01-02 23:04:14 +000061 static bool canHandle(Instruction *Inst) {
Chris Lattnere508dd42011-01-03 23:38:13 +000062 // This can only handle non-void readnone functions.
63 if (CallInst *CI = dyn_cast<CallInst>(Inst))
64 return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
Chris Lattner91139cc2011-01-02 23:19:45 +000065 return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
66 isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
67 isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
68 isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
69 isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
Chris Lattnercc9eab22011-01-02 23:04:14 +000070 }
Chris Lattnercc9eab22011-01-02 23:04:14 +000071 };
72}
73
74namespace llvm {
Chris Lattnerf1974592011-01-03 02:20:48 +000075// SimpleValue is POD.
76template<> struct isPodLike<SimpleValue> {
Chris Lattnercc9eab22011-01-02 23:04:14 +000077 static const bool value = true;
78};
79
Chris Lattnerf1974592011-01-03 02:20:48 +000080template<> struct DenseMapInfo<SimpleValue> {
81 static inline SimpleValue getEmptyKey() {
Chris Lattnera60a8b02011-01-03 03:28:23 +000082 return DenseMapInfo<Instruction*>::getEmptyKey();
Chris Lattnercc9eab22011-01-02 23:04:14 +000083 }
Chris Lattnerf1974592011-01-03 02:20:48 +000084 static inline SimpleValue getTombstoneKey() {
Chris Lattnera60a8b02011-01-03 03:28:23 +000085 return DenseMapInfo<Instruction*>::getTombstoneKey();
Chris Lattnercc9eab22011-01-02 23:04:14 +000086 }
Chris Lattnerf1974592011-01-03 02:20:48 +000087 static unsigned getHashValue(SimpleValue Val);
88 static bool isEqual(SimpleValue LHS, SimpleValue RHS);
Chris Lattnercc9eab22011-01-02 23:04:14 +000089};
90}
91
Chris Lattnerf1974592011-01-03 02:20:48 +000092unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
Chris Lattnercc9eab22011-01-02 23:04:14 +000093 Instruction *Inst = Val.Inst;
Chris Lattnerd957c712011-01-03 01:10:08 +000094 // Hash in all of the operands as pointers.
Michael Ilseman39285ab2012-10-09 16:57:38 +000095 if (BinaryOperator* BinOp = dyn_cast<BinaryOperator>(Inst)) {
96 Value *LHS = BinOp->getOperand(0);
97 Value *RHS = BinOp->getOperand(1);
98 if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
99 std::swap(LHS, RHS);
Chris Lattnerd957c712011-01-03 01:10:08 +0000100
Michael Ilseman39285ab2012-10-09 16:57:38 +0000101 if (isa<OverflowingBinaryOperator>(BinOp)) {
102 // Hash the overflow behavior
103 unsigned Overflow =
104 BinOp->hasNoSignedWrap() * OverflowingBinaryOperator::NoSignedWrap |
105 BinOp->hasNoUnsignedWrap() * OverflowingBinaryOperator::NoUnsignedWrap;
106 return hash_combine(BinOp->getOpcode(), Overflow, LHS, RHS);
107 }
108
109 return hash_combine(BinOp->getOpcode(), LHS, RHS);
Chris Lattnerd957c712011-01-03 01:10:08 +0000110 }
111
Michael Ilseman39285ab2012-10-09 16:57:38 +0000112 if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
113 Value *LHS = CI->getOperand(0);
114 Value *RHS = CI->getOperand(1);
115 CmpInst::Predicate Pred = CI->getPredicate();
116 if (Inst->getOperand(0) > Inst->getOperand(1)) {
117 std::swap(LHS, RHS);
118 Pred = CI->getSwappedPredicate();
119 }
120 return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
121 }
122
123 if (CastInst *CI = dyn_cast<CastInst>(Inst))
124 return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
125
126 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
127 return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
128 hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
129
130 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
131 return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
132 IVI->getOperand(1),
133 hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
134
135 assert((isa<CallInst>(Inst) || isa<BinaryOperator>(Inst) ||
136 isa<GetElementPtrInst>(Inst) || isa<SelectInst>(Inst) ||
137 isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
138 isa<ShuffleVectorInst>(Inst)) && "Invalid/unknown instruction");
139
Chris Lattnerd957c712011-01-03 01:10:08 +0000140 // Mix in the opcode.
Michael Ilseman39285ab2012-10-09 16:57:38 +0000141 return hash_combine(Inst->getOpcode(),
142 hash_combine_range(Inst->value_op_begin(),
143 Inst->value_op_end()));
Chris Lattnercc9eab22011-01-02 23:04:14 +0000144}
145
Chris Lattnerf1974592011-01-03 02:20:48 +0000146bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
Chris Lattnercc9eab22011-01-02 23:04:14 +0000147 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
148
149 if (LHS.isSentinel() || RHS.isSentinel())
150 return LHSI == RHSI;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000151
Chris Lattnercc9eab22011-01-02 23:04:14 +0000152 if (LHSI->getOpcode() != RHSI->getOpcode()) return false;
Michael Ilseman39285ab2012-10-09 16:57:38 +0000153 if (LHSI->isIdenticalTo(RHSI)) return true;
154
155 // If we're not strictly identical, we still might be a commutable instruction
156 if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
157 if (!LHSBinOp->isCommutative())
158 return false;
159
160 assert(isa<BinaryOperator>(RHSI)
161 && "same opcode, but different instruction type?");
162 BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
163
164 // Check overflow attributes
165 if (isa<OverflowingBinaryOperator>(LHSBinOp)) {
166 assert(isa<OverflowingBinaryOperator>(RHSBinOp)
167 && "same opcode, but different operator type?");
168 if (LHSBinOp->hasNoUnsignedWrap() != RHSBinOp->hasNoUnsignedWrap() ||
169 LHSBinOp->hasNoSignedWrap() != RHSBinOp->hasNoSignedWrap())
170 return false;
171 }
172
173 // Commuted equality
174 return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
175 LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
176 }
177 if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
178 assert(isa<CmpInst>(RHSI)
179 && "same opcode, but different instruction type?");
180 CmpInst *RHSCmp = cast<CmpInst>(RHSI);
181 // Commuted equality
182 return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
183 LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
184 LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
185 }
186
187 return false;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000188}
189
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000190//===----------------------------------------------------------------------===//
Nadav Rotema94d6e82012-07-24 10:51:42 +0000191// CallValue
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000192//===----------------------------------------------------------------------===//
193
194namespace {
Chris Lattner85db6102011-01-03 03:41:27 +0000195 /// CallValue - Instances of this struct represent available call values in
196 /// the scoped hash table.
197 struct CallValue {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000198 Instruction *Inst;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000199
Chris Lattner85db6102011-01-03 03:41:27 +0000200 CallValue(Instruction *I) : Inst(I) {
Chris Lattnera60a8b02011-01-03 03:28:23 +0000201 assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
202 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000203
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000204 bool isSentinel() const {
205 return Inst == DenseMapInfo<Instruction*>::getEmptyKey() ||
206 Inst == DenseMapInfo<Instruction*>::getTombstoneKey();
207 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000208
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000209 static bool canHandle(Instruction *Inst) {
Chris Lattner10b883b2011-01-03 18:43:03 +0000210 // Don't value number anything that returns void.
211 if (Inst->getType()->isVoidTy())
212 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000213
Chris Lattnera12ba392011-01-03 18:28:15 +0000214 CallInst *CI = dyn_cast<CallInst>(Inst);
215 if (CI == 0 || !CI->onlyReadsMemory())
216 return false;
Chris Lattnera12ba392011-01-03 18:28:15 +0000217 return true;
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000218 }
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000219 };
220}
221
222namespace llvm {
Chris Lattner85db6102011-01-03 03:41:27 +0000223 // CallValue is POD.
224 template<> struct isPodLike<CallValue> {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000225 static const bool value = true;
226 };
Nadav Rotema94d6e82012-07-24 10:51:42 +0000227
Chris Lattner85db6102011-01-03 03:41:27 +0000228 template<> struct DenseMapInfo<CallValue> {
229 static inline CallValue getEmptyKey() {
Chris Lattnera60a8b02011-01-03 03:28:23 +0000230 return DenseMapInfo<Instruction*>::getEmptyKey();
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000231 }
Chris Lattner85db6102011-01-03 03:41:27 +0000232 static inline CallValue getTombstoneKey() {
Chris Lattnera60a8b02011-01-03 03:28:23 +0000233 return DenseMapInfo<Instruction*>::getTombstoneKey();
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000234 }
Chris Lattner85db6102011-01-03 03:41:27 +0000235 static unsigned getHashValue(CallValue Val);
236 static bool isEqual(CallValue LHS, CallValue RHS);
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000237 };
238}
Chris Lattner85db6102011-01-03 03:41:27 +0000239unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000240 Instruction *Inst = Val.Inst;
241 // Hash in all of the operands as pointers.
242 unsigned Res = 0;
Chris Lattner10b883b2011-01-03 18:43:03 +0000243 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i) {
244 assert(!Inst->getOperand(i)->getType()->isMetadataTy() &&
245 "Cannot value number calls with metadata operands");
Eli Friedman18ead6b2011-10-12 22:00:26 +0000246 Res ^= getHash(Inst->getOperand(i)) << (i & 0xF);
Chris Lattner10b883b2011-01-03 18:43:03 +0000247 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000248
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000249 // Mix in the opcode.
250 return (Res << 1) ^ Inst->getOpcode();
251}
252
Chris Lattner85db6102011-01-03 03:41:27 +0000253bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000254 Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000255 if (LHS.isSentinel() || RHS.isSentinel())
256 return LHSI == RHSI;
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000257 return LHSI->isIdenticalTo(RHSI);
258}
259
Chris Lattnercc9eab22011-01-02 23:04:14 +0000260
Chris Lattnerf1974592011-01-03 02:20:48 +0000261//===----------------------------------------------------------------------===//
Nadav Rotema94d6e82012-07-24 10:51:42 +0000262// EarlyCSE pass.
Chris Lattnerf1974592011-01-03 02:20:48 +0000263//===----------------------------------------------------------------------===//
264
Chris Lattnercc9eab22011-01-02 23:04:14 +0000265namespace {
Nadav Rotema94d6e82012-07-24 10:51:42 +0000266
Chris Lattner12be9362011-01-02 21:47:05 +0000267/// EarlyCSE - This pass does a simple depth-first walk over the dominator
268/// tree, eliminating trivially redundant instructions and using instsimplify
269/// to canonicalize things as it goes. It is intended to be fast and catch
270/// obvious cases so that instcombine and other passes are more effective. It
271/// is expected that a later pass of GVN will catch the interesting/hard
272/// cases.
273class EarlyCSE : public FunctionPass {
274public:
Micah Villmow3574eca2012-10-08 16:38:25 +0000275 const DataLayout *TD;
Chad Rosier618c1db2011-12-01 03:08:23 +0000276 const TargetLibraryInfo *TLI;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000277 DominatorTree *DT;
Chris Lattner82dcd5e2011-01-03 01:42:46 +0000278 typedef RecyclingAllocator<BumpPtrAllocator,
Chris Lattnerf1974592011-01-03 02:20:48 +0000279 ScopedHashTableVal<SimpleValue, Value*> > AllocatorTy;
280 typedef ScopedHashTable<SimpleValue, Value*, DenseMapInfo<SimpleValue>,
Chris Lattner82dcd5e2011-01-03 01:42:46 +0000281 AllocatorTy> ScopedHTType;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000282
Chris Lattnerf1974592011-01-03 02:20:48 +0000283 /// AvailableValues - This scoped hash table contains the current values of
284 /// all of our simple scalar expressions. As we walk down the domtree, we
285 /// look to see if instructions are in this: if so, we replace them with what
286 /// we find, otherwise we insert them so that dominated values can succeed in
287 /// their lookup.
288 ScopedHTType *AvailableValues;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000289
Chris Lattner85db6102011-01-03 03:41:27 +0000290 /// AvailableLoads - This scoped hash table contains the current values
291 /// of loads. This allows us to get efficient access to dominating loads when
292 /// we have a fully redundant load. In addition to the most recent load, we
293 /// keep track of a generation count of the read, which is compared against
294 /// the current generation count. The current generation count is
295 /// incremented after every possibly writing memory operation, which ensures
296 /// that we only CSE loads with other loads that have no intervening store.
Chris Lattner71230ac2011-01-03 03:53:50 +0000297 typedef RecyclingAllocator<BumpPtrAllocator,
298 ScopedHashTableVal<Value*, std::pair<Value*, unsigned> > > LoadMapAllocator;
299 typedef ScopedHashTable<Value*, std::pair<Value*, unsigned>,
300 DenseMapInfo<Value*>, LoadMapAllocator> LoadHTType;
Chris Lattner85db6102011-01-03 03:41:27 +0000301 LoadHTType *AvailableLoads;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000302
Chris Lattner85db6102011-01-03 03:41:27 +0000303 /// AvailableCalls - This scoped hash table contains the current values
304 /// of read-only call values. It uses the same generation count as loads.
305 typedef ScopedHashTable<CallValue, std::pair<Value*, unsigned> > CallHTType;
306 CallHTType *AvailableCalls;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000307
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000308 /// CurrentGeneration - This is the current generation of the memory value.
309 unsigned CurrentGeneration;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000310
Chris Lattner12be9362011-01-02 21:47:05 +0000311 static char ID;
Chris Lattnerf1974592011-01-03 02:20:48 +0000312 explicit EarlyCSE() : FunctionPass(ID) {
Chris Lattner12be9362011-01-02 21:47:05 +0000313 initializeEarlyCSEPass(*PassRegistry::getPassRegistry());
314 }
315
316 bool runOnFunction(Function &F);
317
318private:
Lenny Maioranie0c7cfa2012-01-31 23:14:41 +0000319
320 // NodeScope - almost a POD, but needs to call the constructors for the
321 // scoped hash tables so that a new scope gets pushed on. These are RAII so
322 // that the scope gets popped when the NodeScope is destroyed.
323 class NodeScope {
324 public:
325 NodeScope(ScopedHTType *availableValues,
326 LoadHTType *availableLoads,
327 CallHTType *availableCalls) :
328 Scope(*availableValues),
329 LoadScope(*availableLoads),
330 CallScope(*availableCalls) {}
331
332 private:
Craig Topper86a1c322012-09-15 17:09:36 +0000333 NodeScope(const NodeScope&) LLVM_DELETED_FUNCTION;
334 void operator=(const NodeScope&) LLVM_DELETED_FUNCTION;
Lenny Maioranie0c7cfa2012-01-31 23:14:41 +0000335
336 ScopedHTType::ScopeTy Scope;
337 LoadHTType::ScopeTy LoadScope;
338 CallHTType::ScopeTy CallScope;
339 };
340
341 // StackNode - contains all the needed information to create a stack for
342 // doing a depth first tranversal of the tree. This includes scopes for
343 // values, loads, and calls as well as the generation. There is a child
344 // iterator so that the children do not need to be store spearately.
345 class StackNode {
346 public:
347 StackNode(ScopedHTType *availableValues,
348 LoadHTType *availableLoads,
349 CallHTType *availableCalls,
350 unsigned cg, DomTreeNode *n,
351 DomTreeNode::iterator child, DomTreeNode::iterator end) :
352 CurrentGeneration(cg), ChildGeneration(cg), Node(n),
353 ChildIter(child), EndIter(end),
354 Scopes(availableValues, availableLoads, availableCalls),
355 Processed(false) {}
356
357 // Accessors.
358 unsigned currentGeneration() { return CurrentGeneration; }
359 unsigned childGeneration() { return ChildGeneration; }
360 void childGeneration(unsigned generation) { ChildGeneration = generation; }
361 DomTreeNode *node() { return Node; }
362 DomTreeNode::iterator childIter() { return ChildIter; }
363 DomTreeNode *nextChild() {
364 DomTreeNode *child = *ChildIter;
365 ++ChildIter;
366 return child;
367 }
368 DomTreeNode::iterator end() { return EndIter; }
369 bool isProcessed() { return Processed; }
370 void process() { Processed = true; }
371
372 private:
Craig Topper86a1c322012-09-15 17:09:36 +0000373 StackNode(const StackNode&) LLVM_DELETED_FUNCTION;
374 void operator=(const StackNode&) LLVM_DELETED_FUNCTION;
Lenny Maioranie0c7cfa2012-01-31 23:14:41 +0000375
376 // Members.
377 unsigned CurrentGeneration;
378 unsigned ChildGeneration;
379 DomTreeNode *Node;
380 DomTreeNode::iterator ChildIter;
381 DomTreeNode::iterator EndIter;
382 NodeScope Scopes;
383 bool Processed;
384 };
385
Chris Lattnercc9eab22011-01-02 23:04:14 +0000386 bool processNode(DomTreeNode *Node);
Nadav Rotema94d6e82012-07-24 10:51:42 +0000387
Chris Lattner12be9362011-01-02 21:47:05 +0000388 // This transformation requires dominator postdominator info
389 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
390 AU.addRequired<DominatorTree>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000391 AU.addRequired<TargetLibraryInfo>();
Chris Lattner12be9362011-01-02 21:47:05 +0000392 AU.setPreservesCFG();
393 }
394};
395}
396
397char EarlyCSE::ID = 0;
398
399// createEarlyCSEPass - The public interface to this file.
400FunctionPass *llvm::createEarlyCSEPass() {
401 return new EarlyCSE();
402}
403
404INITIALIZE_PASS_BEGIN(EarlyCSE, "early-cse", "Early CSE", false, false)
405INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Chad Rosier618c1db2011-12-01 03:08:23 +0000406INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Chris Lattner12be9362011-01-02 21:47:05 +0000407INITIALIZE_PASS_END(EarlyCSE, "early-cse", "Early CSE", false, false)
408
Chris Lattnercc9eab22011-01-02 23:04:14 +0000409bool EarlyCSE::processNode(DomTreeNode *Node) {
Chris Lattnercc9eab22011-01-02 23:04:14 +0000410 BasicBlock *BB = Node->getBlock();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000411
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000412 // If this block has a single predecessor, then the predecessor is the parent
413 // of the domtree node and all of the live out memory values are still current
414 // in this block. If this block has multiple predecessors, then they could
415 // have invalidated the live-out memory values of our parent value. For now,
416 // just be conservative and invalidate memory if this block has multiple
417 // predecessors.
418 if (BB->getSinglePredecessor() == 0)
419 ++CurrentGeneration;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000420
Chris Lattner75637152011-01-03 04:17:24 +0000421 /// LastStore - Keep track of the last non-volatile store that we saw... for
422 /// as long as there in no instruction that reads memory. If we see a store
423 /// to the same location, we delete the dead store. This zaps trivial dead
424 /// stores which can occur in bitfield code among other things.
425 StoreInst *LastStore = 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000426
Chris Lattnercc9eab22011-01-02 23:04:14 +0000427 bool Changed = false;
428
429 // See if any instructions in the block can be eliminated. If so, do it. If
430 // not, add them to AvailableValues.
431 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
432 Instruction *Inst = I++;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000433
Chris Lattnercc9eab22011-01-02 23:04:14 +0000434 // Dead instructions should just be removed.
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000435 if (isInstructionTriviallyDead(Inst, TLI)) {
Chris Lattner91139cc2011-01-02 23:19:45 +0000436 DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
Chris Lattnercc9eab22011-01-02 23:04:14 +0000437 Inst->eraseFromParent();
438 Changed = true;
Chris Lattner91139cc2011-01-02 23:19:45 +0000439 ++NumSimplify;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000440 continue;
441 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000442
Chris Lattnercc9eab22011-01-02 23:04:14 +0000443 // If the instruction can be simplified (e.g. X+0 = X) then replace it with
444 // its simpler value.
Chad Rosier618c1db2011-12-01 03:08:23 +0000445 if (Value *V = SimplifyInstruction(Inst, TD, TLI, DT)) {
Chris Lattner91139cc2011-01-02 23:19:45 +0000446 DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << " to: " << *V << '\n');
Chris Lattnercc9eab22011-01-02 23:04:14 +0000447 Inst->replaceAllUsesWith(V);
448 Inst->eraseFromParent();
449 Changed = true;
Chris Lattner91139cc2011-01-02 23:19:45 +0000450 ++NumSimplify;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000451 continue;
452 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000453
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000454 // If this is a simple instruction that we can value number, process it.
455 if (SimpleValue::canHandle(Inst)) {
456 // See if the instruction has an available value. If so, use it.
Chris Lattnera60a8b02011-01-03 03:28:23 +0000457 if (Value *V = AvailableValues->lookup(Inst)) {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000458 DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << " to: " << *V << '\n');
459 Inst->replaceAllUsesWith(V);
460 Inst->eraseFromParent();
461 Changed = true;
462 ++NumCSE;
463 continue;
464 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000465
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000466 // Otherwise, just remember that this value is available.
Chris Lattnera60a8b02011-01-03 03:28:23 +0000467 AvailableValues->insert(Inst, Inst);
Chris Lattnercc9eab22011-01-02 23:04:14 +0000468 continue;
469 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000470
Chris Lattner85db6102011-01-03 03:41:27 +0000471 // If this is a non-volatile load, process it.
472 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
473 // Ignore volatile loads.
Eli Friedman2bc3d522011-09-12 20:23:13 +0000474 if (!LI->isSimple()) {
Chris Lattner75637152011-01-03 04:17:24 +0000475 LastStore = 0;
476 continue;
477 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000478
Chris Lattner85db6102011-01-03 03:41:27 +0000479 // If we have an available version of this load, and if it is the right
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000480 // generation, replace this instruction.
Chris Lattner85db6102011-01-03 03:41:27 +0000481 std::pair<Value*, unsigned> InVal =
482 AvailableLoads->lookup(Inst->getOperand(0));
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000483 if (InVal.first != 0 && InVal.second == CurrentGeneration) {
Chris Lattner85db6102011-01-03 03:41:27 +0000484 DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst << " to: "
485 << *InVal.first << '\n');
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000486 if (!Inst->use_empty()) Inst->replaceAllUsesWith(InVal.first);
487 Inst->eraseFromParent();
488 Changed = true;
Chris Lattner85db6102011-01-03 03:41:27 +0000489 ++NumCSELoad;
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000490 continue;
491 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000492
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000493 // Otherwise, remember that we have this instruction.
Chris Lattner85db6102011-01-03 03:41:27 +0000494 AvailableLoads->insert(Inst->getOperand(0),
495 std::pair<Value*, unsigned>(Inst, CurrentGeneration));
Chris Lattner75637152011-01-03 04:17:24 +0000496 LastStore = 0;
Chris Lattner85db6102011-01-03 03:41:27 +0000497 continue;
498 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000499
Chris Lattner75637152011-01-03 04:17:24 +0000500 // If this instruction may read from memory, forget LastStore.
501 if (Inst->mayReadFromMemory())
502 LastStore = 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000503
Chris Lattner85db6102011-01-03 03:41:27 +0000504 // If this is a read-only call, process it.
505 if (CallValue::canHandle(Inst)) {
506 // If we have an available version of this call, and if it is the right
507 // generation, replace this instruction.
508 std::pair<Value*, unsigned> InVal = AvailableCalls->lookup(Inst);
509 if (InVal.first != 0 && InVal.second == CurrentGeneration) {
510 DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst << " to: "
511 << *InVal.first << '\n');
512 if (!Inst->use_empty()) Inst->replaceAllUsesWith(InVal.first);
513 Inst->eraseFromParent();
514 Changed = true;
515 ++NumCSECall;
516 continue;
517 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000518
Chris Lattner85db6102011-01-03 03:41:27 +0000519 // Otherwise, remember that we have this instruction.
520 AvailableCalls->insert(Inst,
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000521 std::pair<Value*, unsigned>(Inst, CurrentGeneration));
522 continue;
523 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000524
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000525 // Okay, this isn't something we can CSE at all. Check to see if it is
526 // something that could modify memory. If so, our available memory values
527 // cannot be used so bump the generation count.
Chris Lattneref87fc22011-01-03 03:46:34 +0000528 if (Inst->mayWriteToMemory()) {
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000529 ++CurrentGeneration;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000530
Chris Lattneref87fc22011-01-03 03:46:34 +0000531 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattner75637152011-01-03 04:17:24 +0000532 // We do a trivial form of DSE if there are two stores to the same
533 // location with no intervening loads. Delete the earlier store.
534 if (LastStore &&
535 LastStore->getPointerOperand() == SI->getPointerOperand()) {
536 DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore << " due to: "
Chris Lattnera12ba392011-01-03 18:28:15 +0000537 << *Inst << '\n');
Chris Lattner75637152011-01-03 04:17:24 +0000538 LastStore->eraseFromParent();
539 Changed = true;
540 ++NumDSE;
541 LastStore = 0;
542 continue;
543 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000544
Chris Lattner75637152011-01-03 04:17:24 +0000545 // Okay, we just invalidated anything we knew about loaded values. Try
546 // to salvage *something* by remembering that the stored value is a live
547 // version of the pointer. It is safe to forward from volatile stores
548 // to non-volatile loads, so we don't have to check for volatility of
549 // the store.
Chris Lattneref87fc22011-01-03 03:46:34 +0000550 AvailableLoads->insert(SI->getPointerOperand(),
551 std::pair<Value*, unsigned>(SI->getValueOperand(), CurrentGeneration));
Nadav Rotema94d6e82012-07-24 10:51:42 +0000552
Chris Lattner75637152011-01-03 04:17:24 +0000553 // Remember that this was the last store we saw for DSE.
Eli Friedman2bc3d522011-09-12 20:23:13 +0000554 if (SI->isSimple())
Chris Lattner75637152011-01-03 04:17:24 +0000555 LastStore = SI;
Chris Lattneref87fc22011-01-03 03:46:34 +0000556 }
557 }
Chris Lattnercc9eab22011-01-02 23:04:14 +0000558 }
Lenny Maioranie0c7cfa2012-01-31 23:14:41 +0000559
Chris Lattnercc9eab22011-01-02 23:04:14 +0000560 return Changed;
Chris Lattner12be9362011-01-02 21:47:05 +0000561}
Chris Lattnercc9eab22011-01-02 23:04:14 +0000562
563
564bool EarlyCSE::runOnFunction(Function &F) {
Lenny Maioranie0c7cfa2012-01-31 23:14:41 +0000565 std::deque<StackNode *> nodesToProcess;
566
Micah Villmow3574eca2012-10-08 16:38:25 +0000567 TD = getAnalysisIfAvailable<DataLayout>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000568 TLI = &getAnalysis<TargetLibraryInfo>();
Chris Lattnercc9eab22011-01-02 23:04:14 +0000569 DT = &getAnalysis<DominatorTree>();
Nadav Rotema94d6e82012-07-24 10:51:42 +0000570
Chris Lattner85db6102011-01-03 03:41:27 +0000571 // Tables that the pass uses when walking the domtree.
Chris Lattner82dcd5e2011-01-03 01:42:46 +0000572 ScopedHTType AVTable;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000573 AvailableValues = &AVTable;
Chris Lattner85db6102011-01-03 03:41:27 +0000574 LoadHTType LoadTable;
575 AvailableLoads = &LoadTable;
576 CallHTType CallTable;
577 AvailableCalls = &CallTable;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000578
Chris Lattner8e7f0d72011-01-03 03:18:43 +0000579 CurrentGeneration = 0;
Lenny Maioranie0c7cfa2012-01-31 23:14:41 +0000580 bool Changed = false;
581
582 // Process the root node.
583 nodesToProcess.push_front(
584 new StackNode(AvailableValues, AvailableLoads, AvailableCalls,
585 CurrentGeneration, DT->getRootNode(),
586 DT->getRootNode()->begin(),
587 DT->getRootNode()->end()));
588
589 // Save the current generation.
590 unsigned LiveOutGeneration = CurrentGeneration;
591
592 // Process the stack.
593 while (!nodesToProcess.empty()) {
594 // Grab the first item off the stack. Set the current generation, remove
595 // the node from the stack, and process it.
596 StackNode *NodeToProcess = nodesToProcess.front();
597
598 // Initialize class members.
599 CurrentGeneration = NodeToProcess->currentGeneration();
600
601 // Check if the node needs to be processed.
602 if (!NodeToProcess->isProcessed()) {
603 // Process the node.
604 Changed |= processNode(NodeToProcess->node());
605 NodeToProcess->childGeneration(CurrentGeneration);
606 NodeToProcess->process();
607 } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
608 // Push the next child onto the stack.
609 DomTreeNode *child = NodeToProcess->nextChild();
610 nodesToProcess.push_front(
611 new StackNode(AvailableValues,
612 AvailableLoads,
613 AvailableCalls,
614 NodeToProcess->childGeneration(), child,
615 child->begin(), child->end()));
616 } else {
617 // It has been processed, and there are no more children to process,
618 // so delete it and pop it off the stack.
619 delete NodeToProcess;
620 nodesToProcess.pop_front();
621 }
622 } // while (!nodes...)
623
624 // Reset the current generation.
625 CurrentGeneration = LiveOutGeneration;
626
627 return Changed;
Chris Lattnercc9eab22011-01-02 23:04:14 +0000628}