blob: 162ee2b5cea115352d7c8e5e8fa8c8859a3e2db9 [file] [log] [blame]
Chris Lattner72bc70d2008-12-05 07:49:08 +00001//===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
Owen Anderson1ad2cb72007-07-24 17:55:58 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Owen Anderson1ad2cb72007-07-24 17:55:58 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs global value numbering to eliminate fully redundant
11// instructions. It also performs simple dead load elimination.
12//
John Criswell090c0a22009-03-10 15:04:53 +000013// Note that this pass does the value numbering itself; it does not use the
Matthijs Kooijman845f5242008-06-05 07:55:49 +000014// ValueNumbering analysis passes.
15//
Owen Anderson1ad2cb72007-07-24 17:55:58 +000016//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "gvn"
Owen Anderson1ad2cb72007-07-24 17:55:58 +000019#include "llvm/Transforms/Scalar.h"
Chris Lattnera53cfd12009-12-28 21:28:46 +000020#include "llvm/GlobalVariable.h"
Devang Patelc64bc162009-03-06 02:59:27 +000021#include "llvm/IntrinsicInst.h"
Dan Gohmanf4177aa2010-12-15 23:53:55 +000022#include "llvm/LLVMContext.h"
Owen Andersonb388ca92007-10-18 19:39:33 +000023#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattnerbc9a28d2009-12-06 05:29:56 +000024#include "llvm/Analysis/ConstantFolding.h"
25#include "llvm/Analysis/Dominators.h"
Duncan Sands88c3df72010-11-12 21:10:24 +000026#include "llvm/Analysis/InstructionSimplify.h"
Dan Gohmandd9344f2010-05-28 16:19:17 +000027#include "llvm/Analysis/Loads.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000028#include "llvm/Analysis/MemoryBuiltins.h"
Owen Anderson1ad2cb72007-07-24 17:55:58 +000029#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Chris Lattner05e15f82009-12-09 01:59:31 +000030#include "llvm/Analysis/PHITransAddr.h"
Chris Lattnered58a6f2010-11-30 22:25:26 +000031#include "llvm/Analysis/ValueTracking.h"
Chris Lattner9fc5cdf2011-01-02 22:09:33 +000032#include "llvm/Assembly/Writer.h"
Chris Lattnered58a6f2010-11-30 22:25:26 +000033#include "llvm/Target/TargetData.h"
Chad Rosier618c1db2011-12-01 03:08:23 +000034#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattnered58a6f2010-11-30 22:25:26 +000035#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnered58a6f2010-11-30 22:25:26 +000036#include "llvm/Transforms/Utils/SSAUpdater.h"
37#include "llvm/ADT/DenseMap.h"
38#include "llvm/ADT/DepthFirstIterator.h"
Chris Lattnered58a6f2010-11-30 22:25:26 +000039#include "llvm/ADT/SmallPtrSet.h"
40#include "llvm/ADT/Statistic.h"
Owen Andersona04a0642010-11-18 18:32:40 +000041#include "llvm/Support/Allocator.h"
Owen Andersonaa0b6342008-06-19 19:57:25 +000042#include "llvm/Support/CommandLine.h"
Chris Lattner9f8a6a72008-03-29 04:36:18 +000043#include "llvm/Support/Debug.h"
Chris Lattnerfaf815b2009-12-06 01:57:02 +000044#include "llvm/Support/IRBuilder.h"
Duncan Sands02b5e722011-10-05 14:28:49 +000045#include "llvm/Support/PatternMatch.h"
Owen Anderson1ad2cb72007-07-24 17:55:58 +000046using namespace llvm;
Duncan Sands02b5e722011-10-05 14:28:49 +000047using namespace PatternMatch;
Owen Anderson1ad2cb72007-07-24 17:55:58 +000048
Bill Wendling70ded192008-12-22 22:14:07 +000049STATISTIC(NumGVNInstr, "Number of instructions deleted");
50STATISTIC(NumGVNLoad, "Number of loads deleted");
51STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
Owen Anderson961edc82008-07-15 16:28:06 +000052STATISTIC(NumGVNBlocks, "Number of blocks merged");
Duncan Sands02b5e722011-10-05 14:28:49 +000053STATISTIC(NumGVNSimpl, "Number of instructions simplified");
54STATISTIC(NumGVNEqProp, "Number of equalities propagated");
Bill Wendling70ded192008-12-22 22:14:07 +000055STATISTIC(NumPRELoad, "Number of loads PRE'd");
Chris Lattnerd27290d2008-03-22 04:13:49 +000056
Evan Cheng88d11c02008-06-20 01:01:07 +000057static cl::opt<bool> EnablePRE("enable-pre",
Owen Andersonc2b856e2008-07-17 19:41:00 +000058 cl::init(true), cl::Hidden);
Dan Gohmanc915c952009-06-15 18:30:15 +000059static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
Owen Andersonaa0b6342008-06-19 19:57:25 +000060
Owen Anderson1ad2cb72007-07-24 17:55:58 +000061//===----------------------------------------------------------------------===//
62// ValueTable Class
63//===----------------------------------------------------------------------===//
64
65/// This class holds the mapping between values and value numbers. It is used
66/// as an efficient mechanism to determine the expression-wise equivalence of
67/// two values.
68namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000069 struct Expression {
Owen Anderson30f4a552011-01-03 19:00:11 +000070 uint32_t opcode;
Chris Lattnerdb125cf2011-07-18 04:54:35 +000071 Type *type;
Owen Anderson1ad2cb72007-07-24 17:55:58 +000072 SmallVector<uint32_t, 4> varargs;
Daniel Dunbara279bc32009-09-20 02:20:51 +000073
Chris Lattnerad3ba6a2011-04-28 18:08:21 +000074 Expression(uint32_t o = ~2U) : opcode(o) { }
Daniel Dunbara279bc32009-09-20 02:20:51 +000075
Owen Anderson1ad2cb72007-07-24 17:55:58 +000076 bool operator==(const Expression &other) const {
77 if (opcode != other.opcode)
78 return false;
Chris Lattnerad3ba6a2011-04-28 18:08:21 +000079 if (opcode == ~0U || opcode == ~1U)
Owen Anderson1ad2cb72007-07-24 17:55:58 +000080 return true;
Chris Lattnerad3ba6a2011-04-28 18:08:21 +000081 if (type != other.type)
Owen Anderson1ad2cb72007-07-24 17:55:58 +000082 return false;
Chris Lattnerad3ba6a2011-04-28 18:08:21 +000083 if (varargs != other.varargs)
Benjamin Krameraad94aa2010-12-21 21:30:19 +000084 return false;
85 return true;
Owen Anderson1ad2cb72007-07-24 17:55:58 +000086 }
Owen Anderson1ad2cb72007-07-24 17:55:58 +000087 };
Daniel Dunbara279bc32009-09-20 02:20:51 +000088
Chris Lattner3e8b6632009-09-02 06:11:42 +000089 class ValueTable {
Chris Lattnerad3ba6a2011-04-28 18:08:21 +000090 DenseMap<Value*, uint32_t> valueNumbering;
91 DenseMap<Expression, uint32_t> expressionNumbering;
92 AliasAnalysis *AA;
93 MemoryDependenceAnalysis *MD;
94 DominatorTree *DT;
Daniel Dunbara279bc32009-09-20 02:20:51 +000095
Chris Lattnerad3ba6a2011-04-28 18:08:21 +000096 uint32_t nextValueNumber;
Daniel Dunbara279bc32009-09-20 02:20:51 +000097
Chris Lattnerad3ba6a2011-04-28 18:08:21 +000098 Expression create_expression(Instruction* I);
Lang Hames1fb09552011-07-08 01:50:54 +000099 Expression create_extractvalue_expression(ExtractValueInst* EI);
Chris Lattnerad3ba6a2011-04-28 18:08:21 +0000100 uint32_t lookup_or_add_call(CallInst* C);
101 public:
102 ValueTable() : nextValueNumber(1) { }
103 uint32_t lookup_or_add(Value *V);
104 uint32_t lookup(Value *V) const;
105 void add(Value *V, uint32_t num);
106 void clear();
107 void erase(Value *v);
108 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
109 AliasAnalysis *getAliasAnalysis() const { return AA; }
110 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
111 void setDomTree(DominatorTree* D) { DT = D; }
112 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
113 void verifyRemoved(const Value *) const;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000114 };
115}
116
117namespace llvm {
Chris Lattner76c1b972007-09-17 18:34:04 +0000118template <> struct DenseMapInfo<Expression> {
Owen Anderson830db6a2007-08-02 18:16:06 +0000119 static inline Expression getEmptyKey() {
Owen Anderson30f4a552011-01-03 19:00:11 +0000120 return ~0U;
Owen Anderson830db6a2007-08-02 18:16:06 +0000121 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000122
Owen Anderson830db6a2007-08-02 18:16:06 +0000123 static inline Expression getTombstoneKey() {
Owen Anderson30f4a552011-01-03 19:00:11 +0000124 return ~1U;
Owen Anderson830db6a2007-08-02 18:16:06 +0000125 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000126
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000127 static unsigned getHashValue(const Expression e) {
128 unsigned hash = e.opcode;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000129
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000130 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
Owen Andersond41ed4e2009-10-19 22:14:22 +0000131 (unsigned)((uintptr_t)e.type >> 9));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000132
Owen Anderson830db6a2007-08-02 18:16:06 +0000133 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
134 E = e.varargs.end(); I != E; ++I)
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000135 hash = *I + hash * 37;
Owen Anderson30f4a552011-01-03 19:00:11 +0000136
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000137 return hash;
138 }
Chris Lattner76c1b972007-09-17 18:34:04 +0000139 static bool isEqual(const Expression &LHS, const Expression &RHS) {
140 return LHS == RHS;
141 }
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000142};
Chris Lattner4bbf4ee2009-12-15 07:26:43 +0000143
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000144}
145
146//===----------------------------------------------------------------------===//
147// ValueTable Internal Functions
148//===----------------------------------------------------------------------===//
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000149
Owen Anderson30f4a552011-01-03 19:00:11 +0000150Expression ValueTable::create_expression(Instruction *I) {
151 Expression e;
152 e.type = I->getType();
153 e.opcode = I->getOpcode();
154 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
155 OI != OE; ++OI)
156 e.varargs.push_back(lookup_or_add(*OI));
Duncan Sandse170c762012-02-24 15:16:31 +0000157 if (I->isCommutative()) {
158 // Ensure that commutative instructions that only differ by a permutation
159 // of their operands get the same value number by sorting the operand value
160 // numbers. Since all commutative instructions have two operands it is more
161 // efficient to sort by hand rather than using, say, std::sort.
162 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
163 if (e.varargs[0] > e.varargs[1])
164 std::swap(e.varargs[0], e.varargs[1]);
165 }
Owen Anderson30f4a552011-01-03 19:00:11 +0000166
Lang Hames1fb09552011-07-08 01:50:54 +0000167 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
Duncan Sandse170c762012-02-24 15:16:31 +0000168 // Sort the operand value numbers so x<y and y>x get the same value number.
169 CmpInst::Predicate Predicate = C->getPredicate();
170 if (e.varargs[0] > e.varargs[1]) {
171 std::swap(e.varargs[0], e.varargs[1]);
172 Predicate = CmpInst::getSwappedPredicate(Predicate);
173 }
174 e.opcode = (C->getOpcode() << 8) | Predicate;
Owen Anderson30f4a552011-01-03 19:00:11 +0000175 } else if (InsertValueInst *E = dyn_cast<InsertValueInst>(I)) {
176 for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
177 II != IE; ++II)
178 e.varargs.push_back(*II);
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000179 }
Owen Anderson30f4a552011-01-03 19:00:11 +0000180
Owen Andersond41ed4e2009-10-19 22:14:22 +0000181 return e;
182}
183
Lang Hames1fb09552011-07-08 01:50:54 +0000184Expression ValueTable::create_extractvalue_expression(ExtractValueInst *EI) {
185 assert(EI != 0 && "Not an ExtractValueInst?");
186 Expression e;
187 e.type = EI->getType();
188 e.opcode = 0;
189
190 IntrinsicInst *I = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
191 if (I != 0 && EI->getNumIndices() == 1 && *EI->idx_begin() == 0 ) {
192 // EI might be an extract from one of our recognised intrinsics. If it
193 // is we'll synthesize a semantically equivalent expression instead on
194 // an extract value expression.
195 switch (I->getIntrinsicID()) {
Lang Hamesbd1828c2011-07-09 00:25:11 +0000196 case Intrinsic::sadd_with_overflow:
Lang Hames1fb09552011-07-08 01:50:54 +0000197 case Intrinsic::uadd_with_overflow:
198 e.opcode = Instruction::Add;
199 break;
Lang Hamesbd1828c2011-07-09 00:25:11 +0000200 case Intrinsic::ssub_with_overflow:
Lang Hames1fb09552011-07-08 01:50:54 +0000201 case Intrinsic::usub_with_overflow:
202 e.opcode = Instruction::Sub;
203 break;
Lang Hamesbd1828c2011-07-09 00:25:11 +0000204 case Intrinsic::smul_with_overflow:
Lang Hames1fb09552011-07-08 01:50:54 +0000205 case Intrinsic::umul_with_overflow:
206 e.opcode = Instruction::Mul;
207 break;
208 default:
209 break;
210 }
211
212 if (e.opcode != 0) {
213 // Intrinsic recognized. Grab its args to finish building the expression.
214 assert(I->getNumArgOperands() == 2 &&
215 "Expect two args for recognised intrinsics.");
216 e.varargs.push_back(lookup_or_add(I->getArgOperand(0)));
217 e.varargs.push_back(lookup_or_add(I->getArgOperand(1)));
218 return e;
219 }
220 }
221
222 // Not a recognised intrinsic. Fall back to producing an extract value
223 // expression.
224 e.opcode = EI->getOpcode();
225 for (Instruction::op_iterator OI = EI->op_begin(), OE = EI->op_end();
226 OI != OE; ++OI)
227 e.varargs.push_back(lookup_or_add(*OI));
228
229 for (ExtractValueInst::idx_iterator II = EI->idx_begin(), IE = EI->idx_end();
230 II != IE; ++II)
231 e.varargs.push_back(*II);
232
233 return e;
234}
235
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000236//===----------------------------------------------------------------------===//
237// ValueTable External Functions
238//===----------------------------------------------------------------------===//
239
Owen Andersonb2303722008-06-18 21:41:49 +0000240/// add - Insert a value into the table with a specified value number.
Chris Lattnerb2412a82009-09-21 02:42:51 +0000241void ValueTable::add(Value *V, uint32_t num) {
Owen Andersonb2303722008-06-18 21:41:49 +0000242 valueNumbering.insert(std::make_pair(V, num));
243}
244
Owen Andersond41ed4e2009-10-19 22:14:22 +0000245uint32_t ValueTable::lookup_or_add_call(CallInst* C) {
246 if (AA->doesNotAccessMemory(C)) {
247 Expression exp = create_expression(C);
248 uint32_t& e = expressionNumbering[exp];
249 if (!e) e = nextValueNumber++;
250 valueNumbering[C] = e;
251 return e;
252 } else if (AA->onlyReadsMemory(C)) {
253 Expression exp = create_expression(C);
254 uint32_t& e = expressionNumbering[exp];
255 if (!e) {
256 e = nextValueNumber++;
257 valueNumbering[C] = e;
258 return e;
259 }
Dan Gohman4ec01b22009-11-14 02:27:51 +0000260 if (!MD) {
261 e = nextValueNumber++;
262 valueNumbering[C] = e;
263 return e;
264 }
Owen Andersond41ed4e2009-10-19 22:14:22 +0000265
266 MemDepResult local_dep = MD->getDependency(C);
267
268 if (!local_dep.isDef() && !local_dep.isNonLocal()) {
269 valueNumbering[C] = nextValueNumber;
270 return nextValueNumber++;
271 }
272
273 if (local_dep.isDef()) {
274 CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
275
Gabor Greif237e1da2010-06-30 09:17:53 +0000276 if (local_cdep->getNumArgOperands() != C->getNumArgOperands()) {
Owen Andersond41ed4e2009-10-19 22:14:22 +0000277 valueNumbering[C] = nextValueNumber;
278 return nextValueNumber++;
279 }
280
Gabor Greifd883a9d2010-06-24 10:17:17 +0000281 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
282 uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
283 uint32_t cd_vn = lookup_or_add(local_cdep->getArgOperand(i));
Owen Andersond41ed4e2009-10-19 22:14:22 +0000284 if (c_vn != cd_vn) {
285 valueNumbering[C] = nextValueNumber;
286 return nextValueNumber++;
287 }
288 }
289
290 uint32_t v = lookup_or_add(local_cdep);
291 valueNumbering[C] = v;
292 return v;
293 }
294
295 // Non-local case.
296 const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
297 MD->getNonLocalCallDependency(CallSite(C));
Eli Friedmana990e072011-06-15 00:47:34 +0000298 // FIXME: Move the checking logic to MemDep!
Owen Andersond41ed4e2009-10-19 22:14:22 +0000299 CallInst* cdep = 0;
300
301 // Check to see if we have a single dominating call instruction that is
302 // identical to C.
303 for (unsigned i = 0, e = deps.size(); i != e; ++i) {
Chris Lattnere18b9712009-12-09 07:08:01 +0000304 const NonLocalDepEntry *I = &deps[i];
Chris Lattnere18b9712009-12-09 07:08:01 +0000305 if (I->getResult().isNonLocal())
Owen Andersond41ed4e2009-10-19 22:14:22 +0000306 continue;
307
Eli Friedmana990e072011-06-15 00:47:34 +0000308 // We don't handle non-definitions. If we already have a call, reject
Owen Andersond41ed4e2009-10-19 22:14:22 +0000309 // instruction dependencies.
Eli Friedmana990e072011-06-15 00:47:34 +0000310 if (!I->getResult().isDef() || cdep != 0) {
Owen Andersond41ed4e2009-10-19 22:14:22 +0000311 cdep = 0;
312 break;
313 }
314
Chris Lattnere18b9712009-12-09 07:08:01 +0000315 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst());
Owen Andersond41ed4e2009-10-19 22:14:22 +0000316 // FIXME: All duplicated with non-local case.
Chris Lattnere18b9712009-12-09 07:08:01 +0000317 if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){
Owen Andersond41ed4e2009-10-19 22:14:22 +0000318 cdep = NonLocalDepCall;
319 continue;
320 }
321
322 cdep = 0;
323 break;
324 }
325
326 if (!cdep) {
327 valueNumbering[C] = nextValueNumber;
328 return nextValueNumber++;
329 }
330
Gabor Greif237e1da2010-06-30 09:17:53 +0000331 if (cdep->getNumArgOperands() != C->getNumArgOperands()) {
Owen Andersond41ed4e2009-10-19 22:14:22 +0000332 valueNumbering[C] = nextValueNumber;
333 return nextValueNumber++;
334 }
Gabor Greifd883a9d2010-06-24 10:17:17 +0000335 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
336 uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
337 uint32_t cd_vn = lookup_or_add(cdep->getArgOperand(i));
Owen Andersond41ed4e2009-10-19 22:14:22 +0000338 if (c_vn != cd_vn) {
339 valueNumbering[C] = nextValueNumber;
340 return nextValueNumber++;
341 }
342 }
343
344 uint32_t v = lookup_or_add(cdep);
345 valueNumbering[C] = v;
346 return v;
347
348 } else {
349 valueNumbering[C] = nextValueNumber;
350 return nextValueNumber++;
351 }
352}
353
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000354/// lookup_or_add - Returns the value number for the specified value, assigning
355/// it a new number if it did not have one before.
Chris Lattnerb2412a82009-09-21 02:42:51 +0000356uint32_t ValueTable::lookup_or_add(Value *V) {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000357 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
358 if (VI != valueNumbering.end())
359 return VI->second;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000360
Owen Andersond41ed4e2009-10-19 22:14:22 +0000361 if (!isa<Instruction>(V)) {
Owen Anderson158d86e2009-10-19 21:14:57 +0000362 valueNumbering[V] = nextValueNumber;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000363 return nextValueNumber++;
364 }
Owen Andersond41ed4e2009-10-19 22:14:22 +0000365
366 Instruction* I = cast<Instruction>(V);
367 Expression exp;
368 switch (I->getOpcode()) {
369 case Instruction::Call:
370 return lookup_or_add_call(cast<CallInst>(I));
371 case Instruction::Add:
372 case Instruction::FAdd:
373 case Instruction::Sub:
374 case Instruction::FSub:
375 case Instruction::Mul:
376 case Instruction::FMul:
377 case Instruction::UDiv:
378 case Instruction::SDiv:
379 case Instruction::FDiv:
380 case Instruction::URem:
381 case Instruction::SRem:
382 case Instruction::FRem:
383 case Instruction::Shl:
384 case Instruction::LShr:
385 case Instruction::AShr:
386 case Instruction::And:
387 case Instruction::Or :
388 case Instruction::Xor:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000389 case Instruction::ICmp:
390 case Instruction::FCmp:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000391 case Instruction::Trunc:
392 case Instruction::ZExt:
393 case Instruction::SExt:
394 case Instruction::FPToUI:
395 case Instruction::FPToSI:
396 case Instruction::UIToFP:
397 case Instruction::SIToFP:
398 case Instruction::FPTrunc:
399 case Instruction::FPExt:
400 case Instruction::PtrToInt:
401 case Instruction::IntToPtr:
402 case Instruction::BitCast:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000403 case Instruction::Select:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000404 case Instruction::ExtractElement:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000405 case Instruction::InsertElement:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000406 case Instruction::ShuffleVector:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000407 case Instruction::InsertValue:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000408 case Instruction::GetElementPtr:
Owen Anderson30f4a552011-01-03 19:00:11 +0000409 exp = create_expression(I);
Owen Andersond41ed4e2009-10-19 22:14:22 +0000410 break;
Lang Hames1fb09552011-07-08 01:50:54 +0000411 case Instruction::ExtractValue:
412 exp = create_extractvalue_expression(cast<ExtractValueInst>(I));
413 break;
Owen Andersond41ed4e2009-10-19 22:14:22 +0000414 default:
415 valueNumbering[V] = nextValueNumber;
416 return nextValueNumber++;
417 }
418
419 uint32_t& e = expressionNumbering[exp];
420 if (!e) e = nextValueNumber++;
421 valueNumbering[V] = e;
422 return e;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000423}
424
425/// lookup - Returns the value number of the specified value. Fails if
426/// the value has not yet been numbered.
Chris Lattnerb2412a82009-09-21 02:42:51 +0000427uint32_t ValueTable::lookup(Value *V) const {
Jeffrey Yasskin81cf4322009-11-10 01:02:17 +0000428 DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
Chris Lattner88365bb2008-03-21 21:14:38 +0000429 assert(VI != valueNumbering.end() && "Value not numbered?");
430 return VI->second;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000431}
432
Chris Lattnerad3ba6a2011-04-28 18:08:21 +0000433/// clear - Remove all entries from the ValueTable.
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000434void ValueTable::clear() {
435 valueNumbering.clear();
436 expressionNumbering.clear();
437 nextValueNumber = 1;
438}
439
Chris Lattnerad3ba6a2011-04-28 18:08:21 +0000440/// erase - Remove a value from the value numbering.
Chris Lattnerb2412a82009-09-21 02:42:51 +0000441void ValueTable::erase(Value *V) {
Owen Andersonbf7d0bc2007-07-31 23:27:13 +0000442 valueNumbering.erase(V);
443}
444
Bill Wendling246dbbb2008-12-22 21:36:08 +0000445/// verifyRemoved - Verify that the value is removed from all internal data
446/// structures.
447void ValueTable::verifyRemoved(const Value *V) const {
Jeffrey Yasskin81cf4322009-11-10 01:02:17 +0000448 for (DenseMap<Value*, uint32_t>::const_iterator
Bill Wendling246dbbb2008-12-22 21:36:08 +0000449 I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
450 assert(I->first != V && "Inst still occurs in value numbering map!");
451 }
452}
453
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000454//===----------------------------------------------------------------------===//
Bill Wendling30788b82008-12-22 22:32:22 +0000455// GVN Pass
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000456//===----------------------------------------------------------------------===//
457
458namespace {
459
Chris Lattner3e8b6632009-09-02 06:11:42 +0000460 class GVN : public FunctionPass {
Dan Gohman4ec01b22009-11-14 02:27:51 +0000461 bool NoLoads;
Chris Lattner663e4412008-12-01 00:40:32 +0000462 MemoryDependenceAnalysis *MD;
463 DominatorTree *DT;
Chris Lattner4756ecb2011-04-28 16:36:48 +0000464 const TargetData *TD;
Chad Rosier618c1db2011-12-01 03:08:23 +0000465 const TargetLibraryInfo *TLI;
466
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000467 ValueTable VN;
Owen Andersona04a0642010-11-18 18:32:40 +0000468
Owen Andersonb1602ab2011-01-04 19:29:46 +0000469 /// LeaderTable - A mapping from value numbers to lists of Value*'s that
Owen Anderson7a75d612011-01-04 19:13:25 +0000470 /// have that value number. Use findLeader to query it.
471 struct LeaderTableEntry {
Owen Andersonf0568382010-12-21 23:54:34 +0000472 Value *Val;
473 BasicBlock *BB;
Owen Anderson7a75d612011-01-04 19:13:25 +0000474 LeaderTableEntry *Next;
Owen Andersonf0568382010-12-21 23:54:34 +0000475 };
Owen Andersonb1602ab2011-01-04 19:29:46 +0000476 DenseMap<uint32_t, LeaderTableEntry> LeaderTable;
Owen Andersona04a0642010-11-18 18:32:40 +0000477 BumpPtrAllocator TableAllocator;
Owen Anderson68c26392010-11-19 22:48:40 +0000478
Chris Lattnerf07054d2011-04-28 16:18:52 +0000479 SmallVector<Instruction*, 8> InstrsToErase;
Chris Lattner4756ecb2011-04-28 16:36:48 +0000480 public:
481 static char ID; // Pass identification, replacement for typeid
482 explicit GVN(bool noloads = false)
483 : FunctionPass(ID), NoLoads(noloads), MD(0) {
484 initializeGVNPass(*PassRegistry::getPassRegistry());
485 }
486
487 bool runOnFunction(Function &F);
Chris Lattnerf07054d2011-04-28 16:18:52 +0000488
Chris Lattner4756ecb2011-04-28 16:36:48 +0000489 /// markInstructionForDeletion - This removes the specified instruction from
490 /// our various maps and marks it for deletion.
491 void markInstructionForDeletion(Instruction *I) {
492 VN.erase(I);
493 InstrsToErase.push_back(I);
494 }
495
496 const TargetData *getTargetData() const { return TD; }
497 DominatorTree &getDominatorTree() const { return *DT; }
498 AliasAnalysis *getAliasAnalysis() const { return VN.getAliasAnalysis(); }
Chris Lattnerad3ba6a2011-04-28 18:08:21 +0000499 MemoryDependenceAnalysis &getMemDep() const { return *MD; }
Chris Lattner4756ecb2011-04-28 16:36:48 +0000500 private:
Owen Andersonb1602ab2011-01-04 19:29:46 +0000501 /// addToLeaderTable - Push a new Value to the LeaderTable onto the list for
Owen Anderson68c26392010-11-19 22:48:40 +0000502 /// its value number.
Owen Anderson7a75d612011-01-04 19:13:25 +0000503 void addToLeaderTable(uint32_t N, Value *V, BasicBlock *BB) {
Chris Lattner0a9e3d62011-04-28 18:15:47 +0000504 LeaderTableEntry &Curr = LeaderTable[N];
Owen Andersonf0568382010-12-21 23:54:34 +0000505 if (!Curr.Val) {
506 Curr.Val = V;
507 Curr.BB = BB;
Owen Andersona04a0642010-11-18 18:32:40 +0000508 return;
509 }
510
Chris Lattner0a9e3d62011-04-28 18:15:47 +0000511 LeaderTableEntry *Node = TableAllocator.Allocate<LeaderTableEntry>();
Owen Andersonf0568382010-12-21 23:54:34 +0000512 Node->Val = V;
513 Node->BB = BB;
514 Node->Next = Curr.Next;
515 Curr.Next = Node;
Owen Andersona04a0642010-11-18 18:32:40 +0000516 }
517
Owen Andersonb1602ab2011-01-04 19:29:46 +0000518 /// removeFromLeaderTable - Scan the list of values corresponding to a given
519 /// value number, and remove the given value if encountered.
Owen Anderson7a75d612011-01-04 19:13:25 +0000520 void removeFromLeaderTable(uint32_t N, Value *V, BasicBlock *BB) {
521 LeaderTableEntry* Prev = 0;
Owen Andersonb1602ab2011-01-04 19:29:46 +0000522 LeaderTableEntry* Curr = &LeaderTable[N];
Owen Andersona04a0642010-11-18 18:32:40 +0000523
Owen Andersonf0568382010-12-21 23:54:34 +0000524 while (Curr->Val != V || Curr->BB != BB) {
Owen Andersona04a0642010-11-18 18:32:40 +0000525 Prev = Curr;
Owen Andersonf0568382010-12-21 23:54:34 +0000526 Curr = Curr->Next;
Owen Andersona04a0642010-11-18 18:32:40 +0000527 }
528
529 if (Prev) {
Owen Andersonf0568382010-12-21 23:54:34 +0000530 Prev->Next = Curr->Next;
Owen Andersona04a0642010-11-18 18:32:40 +0000531 } else {
Owen Andersonf0568382010-12-21 23:54:34 +0000532 if (!Curr->Next) {
533 Curr->Val = 0;
534 Curr->BB = 0;
Owen Andersona04a0642010-11-18 18:32:40 +0000535 } else {
Owen Anderson7a75d612011-01-04 19:13:25 +0000536 LeaderTableEntry* Next = Curr->Next;
Owen Andersonf0568382010-12-21 23:54:34 +0000537 Curr->Val = Next->Val;
538 Curr->BB = Next->BB;
Owen Anderson680ac4f2011-01-04 19:10:54 +0000539 Curr->Next = Next->Next;
Owen Andersona04a0642010-11-18 18:32:40 +0000540 }
541 }
542 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000543
Bob Wilson484d4a32010-02-16 19:51:59 +0000544 // List of critical edges to be split between iterations.
545 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
546
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000547 // This transformation requires dominator postdominator info
548 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000549 AU.addRequired<DominatorTree>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000550 AU.addRequired<TargetLibraryInfo>();
Dan Gohman4ec01b22009-11-14 02:27:51 +0000551 if (!NoLoads)
552 AU.addRequired<MemoryDependenceAnalysis>();
Owen Andersonb388ca92007-10-18 19:39:33 +0000553 AU.addRequired<AliasAnalysis>();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000554
Owen Andersonb70a5712008-06-23 17:49:45 +0000555 AU.addPreserved<DominatorTree>();
Owen Andersonb388ca92007-10-18 19:39:33 +0000556 AU.addPreserved<AliasAnalysis>();
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000557 }
Chris Lattner4756ecb2011-04-28 16:36:48 +0000558
Daniel Dunbara279bc32009-09-20 02:20:51 +0000559
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000560 // Helper fuctions
561 // FIXME: eliminate or document these better
Chris Lattnerf07054d2011-04-28 16:18:52 +0000562 bool processLoad(LoadInst *L);
563 bool processInstruction(Instruction *I);
564 bool processNonLocalLoad(LoadInst *L);
Chris Lattnerb2412a82009-09-21 02:42:51 +0000565 bool processBlock(BasicBlock *BB);
Chris Lattnerf07054d2011-04-28 16:18:52 +0000566 void dump(DenseMap<uint32_t, Value*> &d);
Owen Anderson3e75a422007-08-14 18:04:11 +0000567 bool iterateOnFunction(Function &F);
Chris Lattnerf07054d2011-04-28 16:18:52 +0000568 bool performPRE(Function &F);
Owen Anderson7a75d612011-01-04 19:13:25 +0000569 Value *findLeader(BasicBlock *BB, uint32_t num);
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +0000570 void cleanupGlobalSets();
Bill Wendling246dbbb2008-12-22 21:36:08 +0000571 void verifyRemoved(const Instruction *I) const;
Bob Wilson484d4a32010-02-16 19:51:59 +0000572 bool splitCriticalEdges();
Duncan Sands02b5e722011-10-05 14:28:49 +0000573 unsigned replaceAllDominatedUsesWith(Value *From, Value *To,
574 BasicBlock *Root);
575 bool propagateEquality(Value *LHS, Value *RHS, BasicBlock *Root);
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000576 };
Daniel Dunbara279bc32009-09-20 02:20:51 +0000577
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000578 char GVN::ID = 0;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000579}
580
581// createGVNPass - The public interface to this file...
Bob Wilsonb29d7d22010-02-28 05:34:05 +0000582FunctionPass *llvm::createGVNPass(bool NoLoads) {
583 return new GVN(NoLoads);
Dan Gohman4ec01b22009-11-14 02:27:51 +0000584}
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000585
Owen Anderson2ab36d32010-10-12 19:48:12 +0000586INITIALIZE_PASS_BEGIN(GVN, "gvn", "Global Value Numbering", false, false)
587INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
588INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Chad Rosier618c1db2011-12-01 03:08:23 +0000589INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000590INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
591INITIALIZE_PASS_END(GVN, "gvn", "Global Value Numbering", false, false)
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000592
Owen Andersonb2303722008-06-18 21:41:49 +0000593void GVN::dump(DenseMap<uint32_t, Value*>& d) {
Dan Gohmanad12b262009-12-18 03:25:51 +0000594 errs() << "{\n";
Owen Andersonb2303722008-06-18 21:41:49 +0000595 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
Owen Anderson0cd32032007-07-25 19:57:03 +0000596 E = d.end(); I != E; ++I) {
Dan Gohmanad12b262009-12-18 03:25:51 +0000597 errs() << I->first << "\n";
Owen Anderson0cd32032007-07-25 19:57:03 +0000598 I->second->dump();
599 }
Dan Gohmanad12b262009-12-18 03:25:51 +0000600 errs() << "}\n";
Owen Anderson0cd32032007-07-25 19:57:03 +0000601}
602
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000603/// IsValueFullyAvailableInBlock - Return true if we can prove that the value
604/// we're analyzing is fully available in the specified block. As we go, keep
Chris Lattner72bc70d2008-12-05 07:49:08 +0000605/// track of which blocks we know are fully alive in FullyAvailableBlocks. This
606/// map is actually a tri-state map with the following values:
607/// 0) we know the block *is not* fully available.
608/// 1) we know the block *is* fully available.
609/// 2) we do not know whether the block is fully available or not, but we are
610/// currently speculating that it will be.
611/// 3) we are speculating for this block and have used that to speculate for
612/// other blocks.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000613static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
Chris Lattner72bc70d2008-12-05 07:49:08 +0000614 DenseMap<BasicBlock*, char> &FullyAvailableBlocks) {
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000615 // Optimistically assume that the block is fully available and check to see
616 // if we already know about this block in one lookup.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000617 std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
Chris Lattner72bc70d2008-12-05 07:49:08 +0000618 FullyAvailableBlocks.insert(std::make_pair(BB, 2));
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000619
620 // If the entry already existed for this block, return the precomputed value.
Chris Lattner72bc70d2008-12-05 07:49:08 +0000621 if (!IV.second) {
622 // If this is a speculative "available" value, mark it as being used for
623 // speculation of other blocks.
624 if (IV.first->second == 2)
625 IV.first->second = 3;
626 return IV.first->second != 0;
627 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000628
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000629 // Otherwise, see if it is fully available in all predecessors.
630 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000631
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000632 // If this block has no predecessors, it isn't live-in here.
633 if (PI == PE)
Chris Lattner72bc70d2008-12-05 07:49:08 +0000634 goto SpeculationFailure;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000635
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000636 for (; PI != PE; ++PI)
637 // If the value isn't fully available in one of our predecessors, then it
638 // isn't fully available in this block either. Undo our previous
639 // optimistic assumption and bail out.
640 if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
Chris Lattner72bc70d2008-12-05 07:49:08 +0000641 goto SpeculationFailure;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000642
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000643 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000644
Chris Lattner72bc70d2008-12-05 07:49:08 +0000645// SpeculationFailure - If we get here, we found out that this is not, after
646// all, a fully-available block. We have a problem if we speculated on this and
647// used the speculation to mark other blocks as available.
648SpeculationFailure:
649 char &BBVal = FullyAvailableBlocks[BB];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000650
Chris Lattner72bc70d2008-12-05 07:49:08 +0000651 // If we didn't speculate on this, just return with it set to false.
652 if (BBVal == 2) {
653 BBVal = 0;
654 return false;
655 }
656
657 // If we did speculate on this value, we could have blocks set to 1 that are
658 // incorrect. Walk the (transitive) successors of this block and mark them as
659 // 0 if set to one.
660 SmallVector<BasicBlock*, 32> BBWorklist;
661 BBWorklist.push_back(BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000662
Dan Gohman321a8132010-01-05 16:27:25 +0000663 do {
Chris Lattner72bc70d2008-12-05 07:49:08 +0000664 BasicBlock *Entry = BBWorklist.pop_back_val();
665 // Note that this sets blocks to 0 (unavailable) if they happen to not
666 // already be in FullyAvailableBlocks. This is safe.
667 char &EntryVal = FullyAvailableBlocks[Entry];
668 if (EntryVal == 0) continue; // Already unavailable.
669
670 // Mark as unavailable.
671 EntryVal = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000672
Chris Lattner72bc70d2008-12-05 07:49:08 +0000673 for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I)
674 BBWorklist.push_back(*I);
Dan Gohman321a8132010-01-05 16:27:25 +0000675 } while (!BBWorklist.empty());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000676
Chris Lattner72bc70d2008-12-05 07:49:08 +0000677 return false;
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000678}
679
Chris Lattner771a5422009-09-20 20:09:34 +0000680
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000681/// CanCoerceMustAliasedValueToLoad - Return true if
682/// CoerceAvailableValueToLoadType will succeed.
683static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000684 Type *LoadTy,
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000685 const TargetData &TD) {
686 // If the loaded or stored value is an first class array or struct, don't try
687 // to transform them. We need to be able to bitcast to integer.
Duncan Sands1df98592010-02-16 11:11:14 +0000688 if (LoadTy->isStructTy() || LoadTy->isArrayTy() ||
689 StoredVal->getType()->isStructTy() ||
690 StoredVal->getType()->isArrayTy())
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000691 return false;
692
693 // The store has to be at least as big as the load.
694 if (TD.getTypeSizeInBits(StoredVal->getType()) <
695 TD.getTypeSizeInBits(LoadTy))
696 return false;
697
698 return true;
699}
700
701
Chris Lattner771a5422009-09-20 20:09:34 +0000702/// CoerceAvailableValueToLoadType - If we saw a store of a value to memory, and
703/// then a load from a must-aliased pointer of a different type, try to coerce
704/// the stored value. LoadedTy is the type of the load we want to replace and
705/// InsertPt is the place to insert new instructions.
706///
707/// If we can't do it, return null.
708static Value *CoerceAvailableValueToLoadType(Value *StoredVal,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000709 Type *LoadedTy,
Chris Lattner771a5422009-09-20 20:09:34 +0000710 Instruction *InsertPt,
711 const TargetData &TD) {
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000712 if (!CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, TD))
713 return 0;
714
Chris Lattner4034e142011-04-28 07:29:08 +0000715 // If this is already the right type, just return it.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000716 Type *StoredValTy = StoredVal->getType();
Chris Lattner771a5422009-09-20 20:09:34 +0000717
Jakub Staszak8cec7592011-09-02 14:57:37 +0000718 uint64_t StoreSize = TD.getTypeSizeInBits(StoredValTy);
719 uint64_t LoadSize = TD.getTypeSizeInBits(LoadedTy);
Chris Lattner771a5422009-09-20 20:09:34 +0000720
721 // If the store and reload are the same size, we can always reuse it.
722 if (StoreSize == LoadSize) {
Chris Lattner1f821512011-04-26 01:21:15 +0000723 // Pointer to Pointer -> use bitcast.
724 if (StoredValTy->isPointerTy() && LoadedTy->isPointerTy())
Chris Lattner771a5422009-09-20 20:09:34 +0000725 return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
Chris Lattner771a5422009-09-20 20:09:34 +0000726
727 // Convert source pointers to integers, which can be bitcast.
Duncan Sands1df98592010-02-16 11:11:14 +0000728 if (StoredValTy->isPointerTy()) {
Chris Lattner771a5422009-09-20 20:09:34 +0000729 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
730 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
731 }
732
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000733 Type *TypeToCastTo = LoadedTy;
Duncan Sands1df98592010-02-16 11:11:14 +0000734 if (TypeToCastTo->isPointerTy())
Chris Lattner771a5422009-09-20 20:09:34 +0000735 TypeToCastTo = TD.getIntPtrType(StoredValTy->getContext());
736
737 if (StoredValTy != TypeToCastTo)
738 StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
739
740 // Cast to pointer if the load needs a pointer type.
Duncan Sands1df98592010-02-16 11:11:14 +0000741 if (LoadedTy->isPointerTy())
Chris Lattner771a5422009-09-20 20:09:34 +0000742 StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
743
744 return StoredVal;
745 }
746
747 // If the loaded value is smaller than the available value, then we can
748 // extract out a piece from it. If the available value is too small, then we
749 // can't do anything.
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000750 assert(StoreSize >= LoadSize && "CanCoerceMustAliasedValueToLoad fail");
Chris Lattner771a5422009-09-20 20:09:34 +0000751
752 // Convert source pointers to integers, which can be manipulated.
Duncan Sands1df98592010-02-16 11:11:14 +0000753 if (StoredValTy->isPointerTy()) {
Chris Lattner771a5422009-09-20 20:09:34 +0000754 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
755 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
756 }
757
758 // Convert vectors and fp to integer, which can be manipulated.
Duncan Sands1df98592010-02-16 11:11:14 +0000759 if (!StoredValTy->isIntegerTy()) {
Chris Lattner771a5422009-09-20 20:09:34 +0000760 StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
761 StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
762 }
763
764 // If this is a big-endian system, we need to shift the value down to the low
765 // bits so that a truncate will work.
766 if (TD.isBigEndian()) {
767 Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
768 StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
769 }
770
771 // Truncate the integer to the right size now.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000772 Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
Chris Lattner771a5422009-09-20 20:09:34 +0000773 StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
774
775 if (LoadedTy == NewIntTy)
776 return StoredVal;
777
778 // If the result is a pointer, inttoptr.
Duncan Sands1df98592010-02-16 11:11:14 +0000779 if (LoadedTy->isPointerTy())
Chris Lattner771a5422009-09-20 20:09:34 +0000780 return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
781
782 // Otherwise, bitcast.
783 return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
784}
785
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000786/// AnalyzeLoadFromClobberingWrite - This function is called when we have a
787/// memdep query of a load that ends up being a clobbering memory write (store,
788/// memset, memcpy, memmove). This means that the write *may* provide bits used
789/// by the load but we can't be sure because the pointers don't mustalias.
790///
791/// Check this case to see if there is anything more we can do before we give
792/// up. This returns -1 if we have to give up, or a byte number in the stored
793/// value of the piece that feeds the load.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000794static int AnalyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr,
Chris Lattner03f17da2009-12-09 07:34:10 +0000795 Value *WritePtr,
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000796 uint64_t WriteSizeInBits,
Chris Lattner4fbd14e2009-09-21 06:48:08 +0000797 const TargetData &TD) {
Chad Rosier0cf6b992012-01-30 22:44:13 +0000798 // If the loaded or stored value is a first class array or struct, don't try
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000799 // to transform them. We need to be able to bitcast to integer.
Duncan Sands1df98592010-02-16 11:11:14 +0000800 if (LoadTy->isStructTy() || LoadTy->isArrayTy())
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000801 return -1;
802
Chris Lattnerca749402009-09-21 06:24:16 +0000803 int64_t StoreOffset = 0, LoadOffset = 0;
Chris Lattnered58a6f2010-11-30 22:25:26 +0000804 Value *StoreBase = GetPointerBaseWithConstantOffset(WritePtr, StoreOffset,TD);
805 Value *LoadBase = GetPointerBaseWithConstantOffset(LoadPtr, LoadOffset, TD);
Chris Lattnerca749402009-09-21 06:24:16 +0000806 if (StoreBase != LoadBase)
807 return -1;
808
809 // If the load and store are to the exact same address, they should have been
810 // a must alias. AA must have gotten confused.
Chris Lattner219d7742010-03-25 05:58:19 +0000811 // FIXME: Study to see if/when this happens. One case is forwarding a memset
812 // to a load from the base of the memset.
Chris Lattnerca749402009-09-21 06:24:16 +0000813#if 0
Chris Lattner219d7742010-03-25 05:58:19 +0000814 if (LoadOffset == StoreOffset) {
David Greenebf7f78e2010-01-05 01:27:17 +0000815 dbgs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
Chris Lattnerca749402009-09-21 06:24:16 +0000816 << "Base = " << *StoreBase << "\n"
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000817 << "Store Ptr = " << *WritePtr << "\n"
818 << "Store Offs = " << StoreOffset << "\n"
Chris Lattnerb6760b42009-12-10 00:04:46 +0000819 << "Load Ptr = " << *LoadPtr << "\n";
Chris Lattnerb3f927f2009-12-09 02:41:54 +0000820 abort();
Chris Lattnerca749402009-09-21 06:24:16 +0000821 }
Chris Lattner219d7742010-03-25 05:58:19 +0000822#endif
Chris Lattnerca749402009-09-21 06:24:16 +0000823
824 // If the load and store don't overlap at all, the store doesn't provide
825 // anything to the load. In this case, they really don't alias at all, AA
826 // must have gotten confused.
Chris Lattner03f17da2009-12-09 07:34:10 +0000827 uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy);
Chris Lattnerca749402009-09-21 06:24:16 +0000828
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000829 if ((WriteSizeInBits & 7) | (LoadSize & 7))
Chris Lattnerca749402009-09-21 06:24:16 +0000830 return -1;
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000831 uint64_t StoreSize = WriteSizeInBits >> 3; // Convert to bytes.
Chris Lattnerca749402009-09-21 06:24:16 +0000832 LoadSize >>= 3;
833
834
835 bool isAAFailure = false;
Chris Lattner219d7742010-03-25 05:58:19 +0000836 if (StoreOffset < LoadOffset)
Chris Lattnerca749402009-09-21 06:24:16 +0000837 isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
Chris Lattner219d7742010-03-25 05:58:19 +0000838 else
Chris Lattnerca749402009-09-21 06:24:16 +0000839 isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
Chris Lattner219d7742010-03-25 05:58:19 +0000840
Chris Lattnerca749402009-09-21 06:24:16 +0000841 if (isAAFailure) {
842#if 0
David Greenebf7f78e2010-01-05 01:27:17 +0000843 dbgs() << "STORE LOAD DEP WITH COMMON BASE:\n"
Chris Lattnerca749402009-09-21 06:24:16 +0000844 << "Base = " << *StoreBase << "\n"
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000845 << "Store Ptr = " << *WritePtr << "\n"
846 << "Store Offs = " << StoreOffset << "\n"
Chris Lattnerb6760b42009-12-10 00:04:46 +0000847 << "Load Ptr = " << *LoadPtr << "\n";
Chris Lattnerb3f927f2009-12-09 02:41:54 +0000848 abort();
Chris Lattnerca749402009-09-21 06:24:16 +0000849#endif
850 return -1;
851 }
852
853 // If the Load isn't completely contained within the stored bits, we don't
854 // have all the bits to feed it. We could do something crazy in the future
855 // (issue a smaller load then merge the bits in) but this seems unlikely to be
856 // valuable.
857 if (StoreOffset > LoadOffset ||
858 StoreOffset+StoreSize < LoadOffset+LoadSize)
859 return -1;
860
861 // Okay, we can do this transformation. Return the number of bytes into the
862 // store that the load is.
863 return LoadOffset-StoreOffset;
864}
865
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000866/// AnalyzeLoadFromClobberingStore - This function is called when we have a
867/// memdep query of a load that ends up being a clobbering store.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000868static int AnalyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr,
Chris Lattner4ca70fe2009-12-09 07:37:07 +0000869 StoreInst *DepSI,
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000870 const TargetData &TD) {
871 // Cannot handle reading from store of first-class aggregate yet.
Dan Gohman3355c4e2010-11-10 19:03:33 +0000872 if (DepSI->getValueOperand()->getType()->isStructTy() ||
873 DepSI->getValueOperand()->getType()->isArrayTy())
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000874 return -1;
875
876 Value *StorePtr = DepSI->getPointerOperand();
Dan Gohman3355c4e2010-11-10 19:03:33 +0000877 uint64_t StoreSize =TD.getTypeSizeInBits(DepSI->getValueOperand()->getType());
Chris Lattner4ca70fe2009-12-09 07:37:07 +0000878 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
Chris Lattner03f17da2009-12-09 07:34:10 +0000879 StorePtr, StoreSize, TD);
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000880}
881
Chris Lattner1f821512011-04-26 01:21:15 +0000882/// AnalyzeLoadFromClobberingLoad - This function is called when we have a
883/// memdep query of a load that ends up being clobbered by another load. See if
884/// the other load can feed into the second load.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000885static int AnalyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr,
Chris Lattner1f821512011-04-26 01:21:15 +0000886 LoadInst *DepLI, const TargetData &TD){
887 // Cannot handle reading from store of first-class aggregate yet.
888 if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy())
889 return -1;
890
891 Value *DepPtr = DepLI->getPointerOperand();
892 uint64_t DepSize = TD.getTypeSizeInBits(DepLI->getType());
Chris Lattner4034e142011-04-28 07:29:08 +0000893 int R = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, TD);
894 if (R != -1) return R;
895
896 // If we have a load/load clobber an DepLI can be widened to cover this load,
897 // then we should widen it!
898 int64_t LoadOffs = 0;
899 const Value *LoadBase =
900 GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, TD);
901 unsigned LoadSize = TD.getTypeStoreSize(LoadTy);
902
903 unsigned Size = MemoryDependenceAnalysis::
904 getLoadLoadClobberFullWidthSize(LoadBase, LoadOffs, LoadSize, DepLI, TD);
905 if (Size == 0) return -1;
906
907 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size*8, TD);
Chris Lattner1f821512011-04-26 01:21:15 +0000908}
909
910
911
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000912static int AnalyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr,
Chris Lattner4ca70fe2009-12-09 07:37:07 +0000913 MemIntrinsic *MI,
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000914 const TargetData &TD) {
915 // If the mem operation is a non-constant size, we can't handle it.
916 ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength());
917 if (SizeCst == 0) return -1;
918 uint64_t MemSizeInBits = SizeCst->getZExtValue()*8;
Chris Lattnerbc9a28d2009-12-06 05:29:56 +0000919
920 // If this is memset, we just need to see if the offset is valid in the size
921 // of the memset..
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000922 if (MI->getIntrinsicID() == Intrinsic::memset)
Chris Lattner4ca70fe2009-12-09 07:37:07 +0000923 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
924 MemSizeInBits, TD);
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000925
Chris Lattnerbc9a28d2009-12-06 05:29:56 +0000926 // If we have a memcpy/memmove, the only case we can handle is if this is a
927 // copy from constant memory. In that case, we can read directly from the
928 // constant memory.
929 MemTransferInst *MTI = cast<MemTransferInst>(MI);
930
931 Constant *Src = dyn_cast<Constant>(MTI->getSource());
932 if (Src == 0) return -1;
933
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000934 GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Src, &TD));
Chris Lattnerbc9a28d2009-12-06 05:29:56 +0000935 if (GV == 0 || !GV->isConstant()) return -1;
936
937 // See if the access is within the bounds of the transfer.
Chris Lattner4ca70fe2009-12-09 07:37:07 +0000938 int Offset = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
939 MI->getDest(), MemSizeInBits, TD);
Chris Lattnerbc9a28d2009-12-06 05:29:56 +0000940 if (Offset == -1)
941 return Offset;
942
943 // Otherwise, see if we can constant fold a load from the constant with the
944 // offset applied as appropriate.
945 Src = ConstantExpr::getBitCast(Src,
946 llvm::Type::getInt8PtrTy(Src->getContext()));
947 Constant *OffsetCst =
948 ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
Jay Foaddab3d292011-07-21 14:31:17 +0000949 Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
Chris Lattner4ca70fe2009-12-09 07:37:07 +0000950 Src = ConstantExpr::getBitCast(Src, PointerType::getUnqual(LoadTy));
Chris Lattnerbc9a28d2009-12-06 05:29:56 +0000951 if (ConstantFoldLoadFromConstPtr(Src, &TD))
952 return Offset;
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000953 return -1;
954}
955
Chris Lattnerca749402009-09-21 06:24:16 +0000956
957/// GetStoreValueForLoad - This function is called when we have a
958/// memdep query of a load that ends up being a clobbering store. This means
Chris Lattner4034e142011-04-28 07:29:08 +0000959/// that the store provides bits used by the load but we the pointers don't
960/// mustalias. Check this case to see if there is anything more we can do
961/// before we give up.
Chris Lattner4fbd14e2009-09-21 06:48:08 +0000962static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000963 Type *LoadTy,
Chris Lattner4fbd14e2009-09-21 06:48:08 +0000964 Instruction *InsertPt, const TargetData &TD){
Chris Lattnerca749402009-09-21 06:24:16 +0000965 LLVMContext &Ctx = SrcVal->getType()->getContext();
966
Chris Lattner7944c212010-05-08 20:01:44 +0000967 uint64_t StoreSize = (TD.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
968 uint64_t LoadSize = (TD.getTypeSizeInBits(LoadTy) + 7) / 8;
Chris Lattnerca749402009-09-21 06:24:16 +0000969
Chris Lattnerb2c6ae82009-12-09 18:13:28 +0000970 IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
Chris Lattnerca749402009-09-21 06:24:16 +0000971
972 // Compute which bits of the stored value are being used by the load. Convert
973 // to an integer type to start with.
Duncan Sands1df98592010-02-16 11:11:14 +0000974 if (SrcVal->getType()->isPointerTy())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000975 SrcVal = Builder.CreatePtrToInt(SrcVal, TD.getIntPtrType(Ctx));
Duncan Sands1df98592010-02-16 11:11:14 +0000976 if (!SrcVal->getType()->isIntegerTy())
Benjamin Kramera9390a42011-09-27 20:39:19 +0000977 SrcVal = Builder.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize*8));
Chris Lattnerca749402009-09-21 06:24:16 +0000978
979 // Shift the bits to the least significant depending on endianness.
980 unsigned ShiftAmt;
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000981 if (TD.isLittleEndian())
Chris Lattnerca749402009-09-21 06:24:16 +0000982 ShiftAmt = Offset*8;
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000983 else
Chris Lattner19ad7842009-09-21 17:55:47 +0000984 ShiftAmt = (StoreSize-LoadSize-Offset)*8;
Chris Lattnerca749402009-09-21 06:24:16 +0000985
Chris Lattner4fbd14e2009-09-21 06:48:08 +0000986 if (ShiftAmt)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000987 SrcVal = Builder.CreateLShr(SrcVal, ShiftAmt);
Chris Lattnerca749402009-09-21 06:24:16 +0000988
Chris Lattner4fbd14e2009-09-21 06:48:08 +0000989 if (LoadSize != StoreSize)
Benjamin Kramera9390a42011-09-27 20:39:19 +0000990 SrcVal = Builder.CreateTrunc(SrcVal, IntegerType::get(Ctx, LoadSize*8));
Chris Lattnerca749402009-09-21 06:24:16 +0000991
Chris Lattner4fbd14e2009-09-21 06:48:08 +0000992 return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, TD);
Chris Lattnerca749402009-09-21 06:24:16 +0000993}
994
Chad Rosier431985a2012-01-30 21:13:22 +0000995/// GetLoadValueForLoad - This function is called when we have a
Chris Lattner4034e142011-04-28 07:29:08 +0000996/// memdep query of a load that ends up being a clobbering load. This means
997/// that the load *may* provide bits used by the load but we can't be sure
998/// because the pointers don't mustalias. Check this case to see if there is
999/// anything more we can do before we give up.
1000static Value *GetLoadValueForLoad(LoadInst *SrcVal, unsigned Offset,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001001 Type *LoadTy, Instruction *InsertPt,
Chris Lattner4756ecb2011-04-28 16:36:48 +00001002 GVN &gvn) {
1003 const TargetData &TD = *gvn.getTargetData();
Chris Lattner4034e142011-04-28 07:29:08 +00001004 // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to
1005 // widen SrcVal out to a larger load.
1006 unsigned SrcValSize = TD.getTypeStoreSize(SrcVal->getType());
1007 unsigned LoadSize = TD.getTypeStoreSize(LoadTy);
1008 if (Offset+LoadSize > SrcValSize) {
Eli Friedman56efe242011-08-17 22:22:24 +00001009 assert(SrcVal->isSimple() && "Cannot widen volatile/atomic load!");
1010 assert(SrcVal->getType()->isIntegerTy() && "Can't widen non-integer load");
Chris Lattner4034e142011-04-28 07:29:08 +00001011 // If we have a load/load clobber an DepLI can be widened to cover this
1012 // load, then we should widen it to the next power of 2 size big enough!
1013 unsigned NewLoadSize = Offset+LoadSize;
1014 if (!isPowerOf2_32(NewLoadSize))
1015 NewLoadSize = NextPowerOf2(NewLoadSize);
1016
1017 Value *PtrVal = SrcVal->getPointerOperand();
1018
Chris Lattner0a9e3d62011-04-28 18:15:47 +00001019 // Insert the new load after the old load. This ensures that subsequent
1020 // memdep queries will find the new load. We can't easily remove the old
1021 // load completely because it is already in the value numbering table.
1022 IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001023 Type *DestPTy =
Chris Lattner4034e142011-04-28 07:29:08 +00001024 IntegerType::get(LoadTy->getContext(), NewLoadSize*8);
1025 DestPTy = PointerType::get(DestPTy,
1026 cast<PointerType>(PtrVal->getType())->getAddressSpace());
Devang Patel0f18d972011-05-04 23:58:50 +00001027 Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc());
Chris Lattner4034e142011-04-28 07:29:08 +00001028 PtrVal = Builder.CreateBitCast(PtrVal, DestPTy);
1029 LoadInst *NewLoad = Builder.CreateLoad(PtrVal);
1030 NewLoad->takeName(SrcVal);
1031 NewLoad->setAlignment(SrcVal->getAlignment());
Devang Patel0f18d972011-05-04 23:58:50 +00001032
Chris Lattner4034e142011-04-28 07:29:08 +00001033 DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n");
1034 DEBUG(dbgs() << "TO: " << *NewLoad << "\n");
1035
1036 // Replace uses of the original load with the wider load. On a big endian
1037 // system, we need to shift down to get the relevant bits.
1038 Value *RV = NewLoad;
1039 if (TD.isBigEndian())
1040 RV = Builder.CreateLShr(RV,
1041 NewLoadSize*8-SrcVal->getType()->getPrimitiveSizeInBits());
1042 RV = Builder.CreateTrunc(RV, SrcVal->getType());
1043 SrcVal->replaceAllUsesWith(RV);
Chris Lattner1e4f44b2011-04-28 20:02:57 +00001044
1045 // We would like to use gvn.markInstructionForDeletion here, but we can't
1046 // because the load is already memoized into the leader map table that GVN
1047 // tracks. It is potentially possible to remove the load from the table,
1048 // but then there all of the operations based on it would need to be
1049 // rehashed. Just leave the dead load around.
Chris Lattnerad3ba6a2011-04-28 18:08:21 +00001050 gvn.getMemDep().removeInstruction(SrcVal);
Chris Lattner4034e142011-04-28 07:29:08 +00001051 SrcVal = NewLoad;
1052 }
1053
1054 return GetStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, TD);
1055}
1056
1057
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001058/// GetMemInstValueForLoad - This function is called when we have a
1059/// memdep query of a load that ends up being a clobbering mem intrinsic.
1060static Value *GetMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001061 Type *LoadTy, Instruction *InsertPt,
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001062 const TargetData &TD){
1063 LLVMContext &Ctx = LoadTy->getContext();
1064 uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy)/8;
1065
1066 IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
1067
1068 // We know that this method is only called when the mem transfer fully
1069 // provides the bits for the load.
1070 if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) {
1071 // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
1072 // independently of what the offset is.
1073 Value *Val = MSI->getValue();
1074 if (LoadSize != 1)
1075 Val = Builder.CreateZExt(Val, IntegerType::get(Ctx, LoadSize*8));
1076
1077 Value *OneElt = Val;
1078
1079 // Splat the value out to the right number of bits.
1080 for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize; ) {
1081 // If we can double the number of bytes set, do it.
1082 if (NumBytesSet*2 <= LoadSize) {
1083 Value *ShVal = Builder.CreateShl(Val, NumBytesSet*8);
1084 Val = Builder.CreateOr(Val, ShVal);
1085 NumBytesSet <<= 1;
1086 continue;
1087 }
1088
1089 // Otherwise insert one byte at a time.
1090 Value *ShVal = Builder.CreateShl(Val, 1*8);
1091 Val = Builder.CreateOr(OneElt, ShVal);
1092 ++NumBytesSet;
1093 }
1094
1095 return CoerceAvailableValueToLoadType(Val, LoadTy, InsertPt, TD);
1096 }
Chris Lattnerbc9a28d2009-12-06 05:29:56 +00001097
1098 // Otherwise, this is a memcpy/memmove from a constant global.
1099 MemTransferInst *MTI = cast<MemTransferInst>(SrcInst);
1100 Constant *Src = cast<Constant>(MTI->getSource());
1101
1102 // Otherwise, see if we can constant fold a load from the constant with the
1103 // offset applied as appropriate.
1104 Src = ConstantExpr::getBitCast(Src,
1105 llvm::Type::getInt8PtrTy(Src->getContext()));
1106 Constant *OffsetCst =
1107 ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
Jay Foaddab3d292011-07-21 14:31:17 +00001108 Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
Chris Lattnerbc9a28d2009-12-06 05:29:56 +00001109 Src = ConstantExpr::getBitCast(Src, PointerType::getUnqual(LoadTy));
1110 return ConstantFoldLoadFromConstPtr(Src, &TD);
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001111}
1112
Dan Gohmanb3579832010-04-15 17:08:50 +00001113namespace {
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001114
Chris Lattner87913512009-09-21 06:30:24 +00001115struct AvailableValueInBlock {
1116 /// BB - The basic block in question.
1117 BasicBlock *BB;
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001118 enum ValType {
1119 SimpleVal, // A simple offsetted value that is accessed.
Chris Lattner4034e142011-04-28 07:29:08 +00001120 LoadVal, // A value produced by a load.
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001121 MemIntrin // A memory intrinsic which is loaded from.
1122 };
1123
Chris Lattner87913512009-09-21 06:30:24 +00001124 /// V - The value that is live out of the block.
Chris Lattner4034e142011-04-28 07:29:08 +00001125 PointerIntPair<Value *, 2, ValType> Val;
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001126
1127 /// Offset - The byte offset in Val that is interesting for the load query.
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001128 unsigned Offset;
Chris Lattner87913512009-09-21 06:30:24 +00001129
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001130 static AvailableValueInBlock get(BasicBlock *BB, Value *V,
1131 unsigned Offset = 0) {
Chris Lattner87913512009-09-21 06:30:24 +00001132 AvailableValueInBlock Res;
1133 Res.BB = BB;
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001134 Res.Val.setPointer(V);
1135 Res.Val.setInt(SimpleVal);
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001136 Res.Offset = Offset;
Chris Lattner87913512009-09-21 06:30:24 +00001137 return Res;
1138 }
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001139
1140 static AvailableValueInBlock getMI(BasicBlock *BB, MemIntrinsic *MI,
1141 unsigned Offset = 0) {
1142 AvailableValueInBlock Res;
1143 Res.BB = BB;
1144 Res.Val.setPointer(MI);
1145 Res.Val.setInt(MemIntrin);
1146 Res.Offset = Offset;
1147 return Res;
1148 }
1149
Chris Lattner4034e142011-04-28 07:29:08 +00001150 static AvailableValueInBlock getLoad(BasicBlock *BB, LoadInst *LI,
1151 unsigned Offset = 0) {
1152 AvailableValueInBlock Res;
1153 Res.BB = BB;
1154 Res.Val.setPointer(LI);
1155 Res.Val.setInt(LoadVal);
1156 Res.Offset = Offset;
1157 return Res;
1158 }
1159
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001160 bool isSimpleValue() const { return Val.getInt() == SimpleVal; }
Chris Lattner4034e142011-04-28 07:29:08 +00001161 bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; }
1162 bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; }
1163
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001164 Value *getSimpleValue() const {
1165 assert(isSimpleValue() && "Wrong accessor");
1166 return Val.getPointer();
1167 }
1168
Chris Lattner4034e142011-04-28 07:29:08 +00001169 LoadInst *getCoercedLoadValue() const {
1170 assert(isCoercedLoadValue() && "Wrong accessor");
1171 return cast<LoadInst>(Val.getPointer());
1172 }
1173
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001174 MemIntrinsic *getMemIntrinValue() const {
Chris Lattner4034e142011-04-28 07:29:08 +00001175 assert(isMemIntrinValue() && "Wrong accessor");
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001176 return cast<MemIntrinsic>(Val.getPointer());
1177 }
Chris Lattner5362c542009-12-21 23:04:33 +00001178
1179 /// MaterializeAdjustedValue - Emit code into this block to adjust the value
1180 /// defined here to the specified type. This handles various coercion cases.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001181 Value *MaterializeAdjustedValue(Type *LoadTy, GVN &gvn) const {
Chris Lattner5362c542009-12-21 23:04:33 +00001182 Value *Res;
1183 if (isSimpleValue()) {
1184 Res = getSimpleValue();
1185 if (Res->getType() != LoadTy) {
Chris Lattner4756ecb2011-04-28 16:36:48 +00001186 const TargetData *TD = gvn.getTargetData();
Chris Lattner5362c542009-12-21 23:04:33 +00001187 assert(TD && "Need target data to handle type mismatch case");
1188 Res = GetStoreValueForLoad(Res, Offset, LoadTy, BB->getTerminator(),
1189 *TD);
1190
Chris Lattner4034e142011-04-28 07:29:08 +00001191 DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset << " "
Chris Lattner5362c542009-12-21 23:04:33 +00001192 << *getSimpleValue() << '\n'
1193 << *Res << '\n' << "\n\n\n");
1194 }
Chris Lattner4034e142011-04-28 07:29:08 +00001195 } else if (isCoercedLoadValue()) {
1196 LoadInst *Load = getCoercedLoadValue();
1197 if (Load->getType() == LoadTy && Offset == 0) {
1198 Res = Load;
1199 } else {
Chris Lattner4034e142011-04-28 07:29:08 +00001200 Res = GetLoadValueForLoad(Load, Offset, LoadTy, BB->getTerminator(),
Chris Lattner4756ecb2011-04-28 16:36:48 +00001201 gvn);
Chris Lattner4034e142011-04-28 07:29:08 +00001202
1203 DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset << " "
1204 << *getCoercedLoadValue() << '\n'
1205 << *Res << '\n' << "\n\n\n");
1206 }
Chris Lattner5362c542009-12-21 23:04:33 +00001207 } else {
Chris Lattner4756ecb2011-04-28 16:36:48 +00001208 const TargetData *TD = gvn.getTargetData();
1209 assert(TD && "Need target data to handle type mismatch case");
Chris Lattner5362c542009-12-21 23:04:33 +00001210 Res = GetMemInstValueForLoad(getMemIntrinValue(), Offset,
1211 LoadTy, BB->getTerminator(), *TD);
Chris Lattner4034e142011-04-28 07:29:08 +00001212 DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
Chris Lattner5362c542009-12-21 23:04:33 +00001213 << " " << *getMemIntrinValue() << '\n'
1214 << *Res << '\n' << "\n\n\n");
1215 }
1216 return Res;
1217 }
Chris Lattner87913512009-09-21 06:30:24 +00001218};
1219
Chris Lattner4034e142011-04-28 07:29:08 +00001220} // end anonymous namespace
Dan Gohmanb3579832010-04-15 17:08:50 +00001221
Chris Lattnera09fbf02009-10-10 23:50:30 +00001222/// ConstructSSAForLoadSet - Given a set of loads specified by ValuesPerBlock,
1223/// construct SSA form, allowing us to eliminate LI. This returns the value
1224/// that should be used at LI's definition site.
1225static Value *ConstructSSAForLoadSet(LoadInst *LI,
1226 SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
Chris Lattner4756ecb2011-04-28 16:36:48 +00001227 GVN &gvn) {
Chris Lattnerd2191e52009-12-21 23:15:48 +00001228 // Check for the fully redundant, dominating load case. In this case, we can
1229 // just use the dominating value directly.
1230 if (ValuesPerBlock.size() == 1 &&
Chris Lattner4756ecb2011-04-28 16:36:48 +00001231 gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
1232 LI->getParent()))
1233 return ValuesPerBlock[0].MaterializeAdjustedValue(LI->getType(), gvn);
Chris Lattnerd2191e52009-12-21 23:15:48 +00001234
1235 // Otherwise, we have to construct SSA form.
Chris Lattnera09fbf02009-10-10 23:50:30 +00001236 SmallVector<PHINode*, 8> NewPHIs;
1237 SSAUpdater SSAUpdate(&NewPHIs);
Duncan Sandsfc6e29d2010-09-02 08:14:03 +00001238 SSAUpdate.Initialize(LI->getType(), LI->getName());
Chris Lattnera09fbf02009-10-10 23:50:30 +00001239
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001240 Type *LoadTy = LI->getType();
Chris Lattnera09fbf02009-10-10 23:50:30 +00001241
Chris Lattner771a5422009-09-20 20:09:34 +00001242 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001243 const AvailableValueInBlock &AV = ValuesPerBlock[i];
1244 BasicBlock *BB = AV.BB;
Chris Lattner771a5422009-09-20 20:09:34 +00001245
Chris Lattnera09fbf02009-10-10 23:50:30 +00001246 if (SSAUpdate.HasValueForBlock(BB))
1247 continue;
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001248
Chris Lattner4756ecb2011-04-28 16:36:48 +00001249 SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LoadTy, gvn));
Chris Lattner771a5422009-09-20 20:09:34 +00001250 }
Chris Lattnera09fbf02009-10-10 23:50:30 +00001251
1252 // Perform PHI construction.
1253 Value *V = SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
1254
1255 // If new PHI nodes were created, notify alias analysis.
Chris Lattner4756ecb2011-04-28 16:36:48 +00001256 if (V->getType()->isPointerTy()) {
1257 AliasAnalysis *AA = gvn.getAliasAnalysis();
1258
Chris Lattnera09fbf02009-10-10 23:50:30 +00001259 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
1260 AA->copyValue(LI, NewPHIs[i]);
Owen Anderson392249f2011-01-03 23:51:43 +00001261
1262 // Now that we've copied information to the new PHIs, scan through
1263 // them again and inform alias analysis that we've added potentially
1264 // escaping uses to any values that are operands to these PHIs.
1265 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i) {
1266 PHINode *P = NewPHIs[i];
Jay Foadc1371202011-06-20 14:18:48 +00001267 for (unsigned ii = 0, ee = P->getNumIncomingValues(); ii != ee; ++ii) {
1268 unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
1269 AA->addEscapingUse(P->getOperandUse(jj));
1270 }
Owen Anderson392249f2011-01-03 23:51:43 +00001271 }
Chris Lattner4756ecb2011-04-28 16:36:48 +00001272 }
Chris Lattnera09fbf02009-10-10 23:50:30 +00001273
1274 return V;
Chris Lattner771a5422009-09-20 20:09:34 +00001275}
1276
Gabor Greifea3eec92010-04-09 10:57:00 +00001277static bool isLifetimeStart(const Instruction *Inst) {
1278 if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
Owen Anderson9ff5a232009-12-02 07:35:19 +00001279 return II->getIntrinsicID() == Intrinsic::lifetime_start;
Chris Lattner720e7902009-12-02 06:44:58 +00001280 return false;
1281}
1282
Owen Anderson62bc33c2007-08-16 22:02:55 +00001283/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
1284/// non-local by performing PHI construction.
Chris Lattnerf07054d2011-04-28 16:18:52 +00001285bool GVN::processNonLocalLoad(LoadInst *LI) {
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001286 // Find the non-local dependencies of the load.
Chris Lattner0ee443d2009-12-22 04:25:02 +00001287 SmallVector<NonLocalDepResult, 64> Deps;
Dan Gohman6d8eb152010-11-11 21:50:19 +00001288 AliasAnalysis::Location Loc = VN.getAliasAnalysis()->getLocation(LI);
1289 MD->getNonLocalPointerDependency(Loc, true, LI->getParent(), Deps);
David Greenebf7f78e2010-01-05 01:27:17 +00001290 //DEBUG(dbgs() << "INVESTIGATING NONLOCAL LOAD: "
Dan Gohman2a298992009-07-31 20:24:18 +00001291 // << Deps.size() << *LI << '\n');
Daniel Dunbara279bc32009-09-20 02:20:51 +00001292
Owen Anderson516eb1c2008-08-26 22:07:42 +00001293 // If we had to process more than one hundred blocks to find the
1294 // dependencies, this load isn't worth worrying about. Optimizing
1295 // it will be too expensive.
Bill Wendling5d8ab0f2012-01-31 06:57:53 +00001296 unsigned NumDeps = Deps.size();
1297 if (NumDeps > 100)
Owen Anderson516eb1c2008-08-26 22:07:42 +00001298 return false;
Chris Lattner5f4f84b2008-12-18 00:51:32 +00001299
1300 // If we had a phi translation failure, we'll have a single entry which is a
1301 // clobber in the current block. Reject this early.
Bill Wendling5d8ab0f2012-01-31 06:57:53 +00001302 if (NumDeps == 1 &&
1303 !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
Torok Edwin4306b1a2009-06-17 18:48:18 +00001304 DEBUG(
David Greenebf7f78e2010-01-05 01:27:17 +00001305 dbgs() << "GVN: non-local load ";
1306 WriteAsOperand(dbgs(), LI);
Eli Friedmana990e072011-06-15 00:47:34 +00001307 dbgs() << " has unknown dependencies\n";
Torok Edwin4306b1a2009-06-17 18:48:18 +00001308 );
Chris Lattner5f4f84b2008-12-18 00:51:32 +00001309 return false;
Torok Edwin4306b1a2009-06-17 18:48:18 +00001310 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001311
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001312 // Filter out useless results (non-locals, etc). Keep track of the blocks
1313 // where we have a value available in repl, also keep track of whether we see
1314 // dependencies that produce an unknown value for the load (such as a call
1315 // that could potentially clobber the load).
Bill Wendlingb319f122012-01-31 07:04:52 +00001316 SmallVector<AvailableValueInBlock, 64> ValuesPerBlock;
1317 SmallVector<BasicBlock*, 64> UnavailableBlocks;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001318
Bill Wendling5d8ab0f2012-01-31 06:57:53 +00001319 for (unsigned i = 0, e = NumDeps; i != e; ++i) {
Chris Lattnere18b9712009-12-09 07:08:01 +00001320 BasicBlock *DepBB = Deps[i].getBB();
1321 MemDepResult DepInfo = Deps[i].getResult();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001322
Eli Friedmanb4141422011-10-13 22:14:57 +00001323 if (!DepInfo.isDef() && !DepInfo.isClobber()) {
Eli Friedmana990e072011-06-15 00:47:34 +00001324 UnavailableBlocks.push_back(DepBB);
1325 continue;
1326 }
1327
Chris Lattnerb51deb92008-12-05 21:04:20 +00001328 if (DepInfo.isClobber()) {
Chris Lattneraf064ae2009-12-09 18:21:46 +00001329 // The address being loaded in this non-local block may not be the same as
1330 // the pointer operand of the load if PHI translation occurs. Make sure
1331 // to consider the right address.
1332 Value *Address = Deps[i].getAddress();
1333
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001334 // If the dependence is to a store that writes to a superset of the bits
1335 // read by the load, we can extract the bits we need for the load from the
1336 // stored value.
1337 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
Chris Lattneraf064ae2009-12-09 18:21:46 +00001338 if (TD && Address) {
1339 int Offset = AnalyzeLoadFromClobberingStore(LI->getType(), Address,
Chris Lattner4ca70fe2009-12-09 07:37:07 +00001340 DepSI, *TD);
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001341 if (Offset != -1) {
1342 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
Dan Gohman3355c4e2010-11-10 19:03:33 +00001343 DepSI->getValueOperand(),
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001344 Offset));
1345 continue;
1346 }
1347 }
1348 }
Chris Lattner1f821512011-04-26 01:21:15 +00001349
1350 // Check to see if we have something like this:
1351 // load i32* P
1352 // load i8* (P+1)
1353 // if we have this, replace the later with an extraction from the former.
1354 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInfo.getInst())) {
1355 // If this is a clobber and L is the first instruction in its block, then
1356 // we have the first instruction in the entry block.
1357 if (DepLI != LI && Address && TD) {
1358 int Offset = AnalyzeLoadFromClobberingLoad(LI->getType(),
1359 LI->getPointerOperand(),
1360 DepLI, *TD);
1361
1362 if (Offset != -1) {
Chris Lattner4034e142011-04-28 07:29:08 +00001363 ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB,DepLI,
1364 Offset));
Chris Lattner1f821512011-04-26 01:21:15 +00001365 continue;
1366 }
1367 }
1368 }
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001369
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001370 // If the clobbering value is a memset/memcpy/memmove, see if we can
1371 // forward a value on from it.
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001372 if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInfo.getInst())) {
Chris Lattneraf064ae2009-12-09 18:21:46 +00001373 if (TD && Address) {
1374 int Offset = AnalyzeLoadFromClobberingMemInst(LI->getType(), Address,
Chris Lattner4ca70fe2009-12-09 07:37:07 +00001375 DepMI, *TD);
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001376 if (Offset != -1) {
1377 ValuesPerBlock.push_back(AvailableValueInBlock::getMI(DepBB, DepMI,
1378 Offset));
1379 continue;
1380 }
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001381 }
1382 }
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001383
Chris Lattnerb51deb92008-12-05 21:04:20 +00001384 UnavailableBlocks.push_back(DepBB);
1385 continue;
1386 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001387
Eli Friedmanb4141422011-10-13 22:14:57 +00001388 // DepInfo.isDef() here
Eli Friedmana990e072011-06-15 00:47:34 +00001389
Chris Lattnerb51deb92008-12-05 21:04:20 +00001390 Instruction *DepInst = DepInfo.getInst();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001391
Chris Lattnerb51deb92008-12-05 21:04:20 +00001392 // Loading the allocation -> undef.
Chris Lattner720e7902009-12-02 06:44:58 +00001393 if (isa<AllocaInst>(DepInst) || isMalloc(DepInst) ||
Owen Anderson9ff5a232009-12-02 07:35:19 +00001394 // Loading immediately after lifetime begin -> undef.
1395 isLifetimeStart(DepInst)) {
Chris Lattner87913512009-09-21 06:30:24 +00001396 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1397 UndefValue::get(LI->getType())));
Chris Lattnerbf145d62008-12-01 01:15:42 +00001398 continue;
1399 }
Owen Andersonb62f7922009-10-28 07:05:35 +00001400
Chris Lattner87913512009-09-21 06:30:24 +00001401 if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00001402 // Reject loads and stores that are to the same address but are of
Chris Lattner771a5422009-09-20 20:09:34 +00001403 // different types if we have to.
Dan Gohman3355c4e2010-11-10 19:03:33 +00001404 if (S->getValueOperand()->getType() != LI->getType()) {
Chris Lattner771a5422009-09-20 20:09:34 +00001405 // If the stored value is larger or equal to the loaded value, we can
1406 // reuse it.
Dan Gohman3355c4e2010-11-10 19:03:33 +00001407 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(S->getValueOperand(),
Chris Lattner8b2bc3d2009-09-21 17:24:04 +00001408 LI->getType(), *TD)) {
Chris Lattner771a5422009-09-20 20:09:34 +00001409 UnavailableBlocks.push_back(DepBB);
1410 continue;
1411 }
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001412 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001413
Chris Lattner87913512009-09-21 06:30:24 +00001414 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
Dan Gohman3355c4e2010-11-10 19:03:33 +00001415 S->getValueOperand()));
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001416 continue;
1417 }
1418
1419 if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
Chris Lattner771a5422009-09-20 20:09:34 +00001420 // If the types mismatch and we can't handle it, reject reuse of the load.
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001421 if (LD->getType() != LI->getType()) {
Chris Lattner771a5422009-09-20 20:09:34 +00001422 // If the stored value is larger or equal to the loaded value, we can
1423 // reuse it.
Chris Lattner8b2bc3d2009-09-21 17:24:04 +00001424 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(LD, LI->getType(),*TD)){
Chris Lattner771a5422009-09-20 20:09:34 +00001425 UnavailableBlocks.push_back(DepBB);
1426 continue;
1427 }
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001428 }
Chris Lattner4034e142011-04-28 07:29:08 +00001429 ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB, LD));
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001430 continue;
Owen Anderson0cd32032007-07-25 19:57:03 +00001431 }
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001432
1433 UnavailableBlocks.push_back(DepBB);
1434 continue;
Chris Lattner88365bb2008-03-21 21:14:38 +00001435 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001436
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001437 // If we have no predecessors that produce a known value for this load, exit
1438 // early.
1439 if (ValuesPerBlock.empty()) return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001440
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001441 // If all of the instructions we depend on produce a known value for this
1442 // load, then it is fully redundant and we can use PHI insertion to compute
1443 // its value. Insert PHIs and remove the fully redundant value now.
1444 if (UnavailableBlocks.empty()) {
David Greenebf7f78e2010-01-05 01:27:17 +00001445 DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
Chris Lattner771a5422009-09-20 20:09:34 +00001446
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001447 // Perform PHI construction.
Chris Lattner4756ecb2011-04-28 16:36:48 +00001448 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
Chris Lattner771a5422009-09-20 20:09:34 +00001449 LI->replaceAllUsesWith(V);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001450
Chris Lattner771a5422009-09-20 20:09:34 +00001451 if (isa<PHINode>(V))
1452 V->takeName(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001453 if (V->getType()->isPointerTy())
Chris Lattner771a5422009-09-20 20:09:34 +00001454 MD->invalidateCachedPointerInfo(V);
Chris Lattner4756ecb2011-04-28 16:36:48 +00001455 markInstructionForDeletion(LI);
Dan Gohmanfe601042010-06-22 15:08:57 +00001456 ++NumGVNLoad;
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001457 return true;
1458 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001459
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001460 if (!EnablePRE || !EnableLoadPRE)
1461 return false;
1462
1463 // Okay, we have *some* definitions of the value. This means that the value
1464 // is available in some of our (transitive) predecessors. Lets think about
1465 // doing PRE of this load. This will involve inserting a new load into the
1466 // predecessor when it's not available. We could do this in general, but
1467 // prefer to not increase code size. As such, we only do this when we know
1468 // that we only have to insert *one* load (which means we're basically moving
1469 // the load, not inserting a new one).
Daniel Dunbara279bc32009-09-20 02:20:51 +00001470
Owen Anderson88554df2009-05-31 09:03:40 +00001471 SmallPtrSet<BasicBlock *, 4> Blockers;
1472 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1473 Blockers.insert(UnavailableBlocks[i]);
1474
Bill Wendling795cf5e2011-08-17 21:32:02 +00001475 // Let's find the first basic block with more than one predecessor. Walk
1476 // backwards through predecessors if needed.
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001477 BasicBlock *LoadBB = LI->getParent();
Owen Anderson88554df2009-05-31 09:03:40 +00001478 BasicBlock *TmpBB = LoadBB;
1479
1480 bool isSinglePred = false;
Dale Johannesen42c3f552009-06-17 20:48:23 +00001481 bool allSingleSucc = true;
Owen Anderson88554df2009-05-31 09:03:40 +00001482 while (TmpBB->getSinglePredecessor()) {
1483 isSinglePred = true;
1484 TmpBB = TmpBB->getSinglePredecessor();
Owen Anderson88554df2009-05-31 09:03:40 +00001485 if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1486 return false;
1487 if (Blockers.count(TmpBB))
1488 return false;
Owen Andersonb0ba0f42010-09-25 05:26:18 +00001489
1490 // If any of these blocks has more than one successor (i.e. if the edge we
1491 // just traversed was critical), then there are other paths through this
1492 // block along which the load may not be anticipated. Hoisting the load
1493 // above this block would be adding the load to execution paths along
1494 // which it was not previously executed.
Dale Johannesen42c3f552009-06-17 20:48:23 +00001495 if (TmpBB->getTerminator()->getNumSuccessors() != 1)
Owen Andersonb0ba0f42010-09-25 05:26:18 +00001496 return false;
Owen Anderson88554df2009-05-31 09:03:40 +00001497 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001498
Owen Anderson88554df2009-05-31 09:03:40 +00001499 assert(TmpBB);
1500 LoadBB = TmpBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001501
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001502 // FIXME: It is extremely unclear what this loop is doing, other than
1503 // artificially restricting loadpre.
Owen Anderson88554df2009-05-31 09:03:40 +00001504 if (isSinglePred) {
1505 bool isHot = false;
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001506 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
1507 const AvailableValueInBlock &AV = ValuesPerBlock[i];
1508 if (AV.isSimpleValue())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001509 // "Hot" Instruction is in some loop (because it dominates its dep.
1510 // instruction).
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001511 if (Instruction *I = dyn_cast<Instruction>(AV.getSimpleValue()))
1512 if (DT->dominates(LI, I)) {
1513 isHot = true;
1514 break;
1515 }
1516 }
Owen Anderson88554df2009-05-31 09:03:40 +00001517
1518 // We are interested only in "hot" instructions. We don't want to do any
1519 // mis-optimizations here.
1520 if (!isHot)
1521 return false;
1522 }
1523
Bob Wilson6cad4172010-02-01 21:17:14 +00001524 // Check to see how many predecessors have the loaded value fully
1525 // available.
1526 DenseMap<BasicBlock*, Value*> PredLoads;
Chris Lattner72bc70d2008-12-05 07:49:08 +00001527 DenseMap<BasicBlock*, char> FullyAvailableBlocks;
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001528 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
Chris Lattner87913512009-09-21 06:30:24 +00001529 FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001530 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1531 FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1532
Bob Wilson34414a62010-05-04 20:03:21 +00001533 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> NeedToSplit;
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001534 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1535 PI != E; ++PI) {
Bob Wilson6cad4172010-02-01 21:17:14 +00001536 BasicBlock *Pred = *PI;
1537 if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks)) {
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001538 continue;
Bob Wilson6cad4172010-02-01 21:17:14 +00001539 }
1540 PredLoads[Pred] = 0;
Bob Wilson484d4a32010-02-16 19:51:59 +00001541
Bob Wilson6cad4172010-02-01 21:17:14 +00001542 if (Pred->getTerminator()->getNumSuccessors() != 1) {
Bob Wilson484d4a32010-02-16 19:51:59 +00001543 if (isa<IndirectBrInst>(Pred->getTerminator())) {
1544 DEBUG(dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
1545 << Pred->getName() << "': " << *LI << '\n');
1546 return false;
1547 }
Bill Wendling795cf5e2011-08-17 21:32:02 +00001548
1549 if (LoadBB->isLandingPad()) {
1550 DEBUG(dbgs()
1551 << "COULD NOT PRE LOAD BECAUSE OF LANDING PAD CRITICAL EDGE '"
1552 << Pred->getName() << "': " << *LI << '\n');
1553 return false;
1554 }
1555
Bob Wilsonae23daf2010-02-16 21:06:42 +00001556 unsigned SuccNum = GetSuccessorNumber(Pred, LoadBB);
Bob Wilson34414a62010-05-04 20:03:21 +00001557 NeedToSplit.push_back(std::make_pair(Pred->getTerminator(), SuccNum));
Bob Wilson6cad4172010-02-01 21:17:14 +00001558 }
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001559 }
Bill Wendling795cf5e2011-08-17 21:32:02 +00001560
Bob Wilson34414a62010-05-04 20:03:21 +00001561 if (!NeedToSplit.empty()) {
Bob Wilsonbc786532010-05-05 20:44:15 +00001562 toSplit.append(NeedToSplit.begin(), NeedToSplit.end());
Bob Wilson70704972010-03-01 23:37:32 +00001563 return false;
Bob Wilson34414a62010-05-04 20:03:21 +00001564 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001565
Bob Wilson6cad4172010-02-01 21:17:14 +00001566 // Decide whether PRE is profitable for this load.
1567 unsigned NumUnavailablePreds = PredLoads.size();
1568 assert(NumUnavailablePreds != 0 &&
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001569 "Fully available value should be eliminated above!");
Owen Anderson7267e142010-10-01 20:02:55 +00001570
1571 // If this load is unavailable in multiple predecessors, reject it.
1572 // FIXME: If we could restructure the CFG, we could make a common pred with
1573 // all the preds that don't have an available LI and insert a new load into
1574 // that one block.
1575 if (NumUnavailablePreds != 1)
Bob Wilson6cad4172010-02-01 21:17:14 +00001576 return false;
Bob Wilson6cad4172010-02-01 21:17:14 +00001577
1578 // Check if the load can safely be moved to all the unavailable predecessors.
1579 bool CanDoPRE = true;
Chris Lattnerdd696052009-11-28 15:39:14 +00001580 SmallVector<Instruction*, 8> NewInsts;
Bob Wilson6cad4172010-02-01 21:17:14 +00001581 for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1582 E = PredLoads.end(); I != E; ++I) {
1583 BasicBlock *UnavailablePred = I->first;
1584
1585 // Do PHI translation to get its value in the predecessor if necessary. The
1586 // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
1587
1588 // If all preds have a single successor, then we know it is safe to insert
1589 // the load on the pred (?!?), so we can insert code to materialize the
1590 // pointer if it is not available.
Dan Gohman3355c4e2010-11-10 19:03:33 +00001591 PHITransAddr Address(LI->getPointerOperand(), TD);
Bob Wilson6cad4172010-02-01 21:17:14 +00001592 Value *LoadPtr = 0;
1593 if (allSingleSucc) {
1594 LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred,
1595 *DT, NewInsts);
1596 } else {
Daniel Dunbar6d8f2ca2010-02-24 08:48:04 +00001597 Address.PHITranslateValue(LoadBB, UnavailablePred, DT);
Bob Wilson6cad4172010-02-01 21:17:14 +00001598 LoadPtr = Address.getAddr();
Bob Wilson6cad4172010-02-01 21:17:14 +00001599 }
1600
1601 // If we couldn't find or insert a computation of this phi translated value,
1602 // we fail PRE.
1603 if (LoadPtr == 0) {
1604 DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
Dan Gohman3355c4e2010-11-10 19:03:33 +00001605 << *LI->getPointerOperand() << "\n");
Bob Wilson6cad4172010-02-01 21:17:14 +00001606 CanDoPRE = false;
1607 break;
1608 }
1609
1610 // Make sure it is valid to move this load here. We have to watch out for:
1611 // @1 = getelementptr (i8* p, ...
1612 // test p and branch if == 0
1613 // load @1
Owen Andersonb1602ab2011-01-04 19:29:46 +00001614 // It is valid to have the getelementptr before the test, even if p can
1615 // be 0, as getelementptr only does address arithmetic.
Bob Wilson6cad4172010-02-01 21:17:14 +00001616 // If we are not pushing the value through any multiple-successor blocks
1617 // we do not have this case. Otherwise, check that the load is safe to
1618 // put anywhere; this can be improved, but should be conservatively safe.
1619 if (!allSingleSucc &&
1620 // FIXME: REEVALUTE THIS.
1621 !isSafeToLoadUnconditionally(LoadPtr,
1622 UnavailablePred->getTerminator(),
1623 LI->getAlignment(), TD)) {
1624 CanDoPRE = false;
1625 break;
1626 }
1627
1628 I->second = LoadPtr;
Chris Lattner05e15f82009-12-09 01:59:31 +00001629 }
1630
Bob Wilson6cad4172010-02-01 21:17:14 +00001631 if (!CanDoPRE) {
Chris Lattner3077ca92011-01-11 08:19:16 +00001632 while (!NewInsts.empty()) {
1633 Instruction *I = NewInsts.pop_back_val();
1634 if (MD) MD->removeInstruction(I);
1635 I->eraseFromParent();
1636 }
Dale Johannesen42c3f552009-06-17 20:48:23 +00001637 return false;
Chris Lattner0c264b12009-11-28 16:08:18 +00001638 }
Dale Johannesen42c3f552009-06-17 20:48:23 +00001639
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001640 // Okay, we can eliminate this load by inserting a reload in the predecessor
1641 // and using PHI construction to get the value in the other predecessors, do
1642 // it.
David Greenebf7f78e2010-01-05 01:27:17 +00001643 DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
Chris Lattner0c264b12009-11-28 16:08:18 +00001644 DEBUG(if (!NewInsts.empty())
David Greenebf7f78e2010-01-05 01:27:17 +00001645 dbgs() << "INSERTED " << NewInsts.size() << " INSTS: "
Chris Lattner0c264b12009-11-28 16:08:18 +00001646 << *NewInsts.back() << '\n');
1647
Bob Wilson6cad4172010-02-01 21:17:14 +00001648 // Assign value numbers to the new instructions.
1649 for (unsigned i = 0, e = NewInsts.size(); i != e; ++i) {
1650 // FIXME: We really _ought_ to insert these value numbers into their
1651 // parent's availability map. However, in doing so, we risk getting into
1652 // ordering issues. If a block hasn't been processed yet, we would be
1653 // marking a value as AVAIL-IN, which isn't what we intend.
1654 VN.lookup_or_add(NewInsts[i]);
1655 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001656
Bob Wilson6cad4172010-02-01 21:17:14 +00001657 for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1658 E = PredLoads.end(); I != E; ++I) {
1659 BasicBlock *UnavailablePred = I->first;
1660 Value *LoadPtr = I->second;
1661
Dan Gohmanf4177aa2010-12-15 23:53:55 +00001662 Instruction *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1663 LI->getAlignment(),
1664 UnavailablePred->getTerminator());
1665
1666 // Transfer the old load's TBAA tag to the new load.
1667 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa))
1668 NewLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
Bob Wilson6cad4172010-02-01 21:17:14 +00001669
Devang Pateld9b49962011-05-17 19:43:38 +00001670 // Transfer DebugLoc.
1671 NewLoad->setDebugLoc(LI->getDebugLoc());
1672
Bob Wilson6cad4172010-02-01 21:17:14 +00001673 // Add the newly created load.
1674 ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,
1675 NewLoad));
Bob Wilson188f4282010-02-23 05:55:00 +00001676 MD->invalidateCachedPointerInfo(LoadPtr);
1677 DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
Bob Wilson6cad4172010-02-01 21:17:14 +00001678 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001679
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001680 // Perform PHI construction.
Chris Lattner4756ecb2011-04-28 16:36:48 +00001681 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
Chris Lattner771a5422009-09-20 20:09:34 +00001682 LI->replaceAllUsesWith(V);
1683 if (isa<PHINode>(V))
1684 V->takeName(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001685 if (V->getType()->isPointerTy())
Chris Lattner771a5422009-09-20 20:09:34 +00001686 MD->invalidateCachedPointerInfo(V);
Chris Lattner4756ecb2011-04-28 16:36:48 +00001687 markInstructionForDeletion(LI);
Dan Gohmanfe601042010-06-22 15:08:57 +00001688 ++NumPRELoad;
Owen Anderson0cd32032007-07-25 19:57:03 +00001689 return true;
1690}
1691
Owen Anderson62bc33c2007-08-16 22:02:55 +00001692/// processLoad - Attempt to eliminate a load, first by eliminating it
1693/// locally, and then attempting non-local elimination if that fails.
Chris Lattnerf07054d2011-04-28 16:18:52 +00001694bool GVN::processLoad(LoadInst *L) {
Dan Gohman4ec01b22009-11-14 02:27:51 +00001695 if (!MD)
1696 return false;
1697
Eli Friedman56efe242011-08-17 22:22:24 +00001698 if (!L->isSimple())
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001699 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001700
Chris Lattner9e7bc052011-05-22 07:03:34 +00001701 if (L->use_empty()) {
1702 markInstructionForDeletion(L);
1703 return true;
1704 }
1705
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001706 // ... to a pointer that has been loaded from before...
Chris Lattnerb2412a82009-09-21 02:42:51 +00001707 MemDepResult Dep = MD->getDependency(L);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001708
Chris Lattner1f821512011-04-26 01:21:15 +00001709 // If we have a clobber and target data is around, see if this is a clobber
1710 // that we can fix up through code synthesis.
1711 if (Dep.isClobber() && TD) {
Chris Lattnereed919b2009-09-21 05:57:11 +00001712 // Check to see if we have something like this:
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001713 // store i32 123, i32* %P
1714 // %A = bitcast i32* %P to i8*
1715 // %B = gep i8* %A, i32 1
1716 // %C = load i8* %B
1717 //
1718 // We could do that by recognizing if the clobber instructions are obviously
1719 // a common base + constant offset, and if the previous store (or memset)
1720 // completely covers this load. This sort of thing can happen in bitfield
1721 // access code.
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001722 Value *AvailVal = 0;
Chris Lattner1f821512011-04-26 01:21:15 +00001723 if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst())) {
1724 int Offset = AnalyzeLoadFromClobberingStore(L->getType(),
1725 L->getPointerOperand(),
1726 DepSI, *TD);
1727 if (Offset != -1)
1728 AvailVal = GetStoreValueForLoad(DepSI->getValueOperand(), Offset,
1729 L->getType(), L, *TD);
1730 }
1731
1732 // Check to see if we have something like this:
1733 // load i32* P
1734 // load i8* (P+1)
1735 // if we have this, replace the later with an extraction from the former.
1736 if (LoadInst *DepLI = dyn_cast<LoadInst>(Dep.getInst())) {
1737 // If this is a clobber and L is the first instruction in its block, then
1738 // we have the first instruction in the entry block.
1739 if (DepLI == L)
1740 return false;
1741
1742 int Offset = AnalyzeLoadFromClobberingLoad(L->getType(),
1743 L->getPointerOperand(),
1744 DepLI, *TD);
1745 if (Offset != -1)
Chris Lattner4756ecb2011-04-28 16:36:48 +00001746 AvailVal = GetLoadValueForLoad(DepLI, Offset, L->getType(), L, *this);
Chris Lattner1f821512011-04-26 01:21:15 +00001747 }
Chris Lattnereed919b2009-09-21 05:57:11 +00001748
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001749 // If the clobbering value is a memset/memcpy/memmove, see if we can forward
1750 // a value on from it.
1751 if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(Dep.getInst())) {
Chris Lattner1f821512011-04-26 01:21:15 +00001752 int Offset = AnalyzeLoadFromClobberingMemInst(L->getType(),
1753 L->getPointerOperand(),
1754 DepMI, *TD);
1755 if (Offset != -1)
1756 AvailVal = GetMemInstValueForLoad(DepMI, Offset, L->getType(), L, *TD);
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001757 }
1758
1759 if (AvailVal) {
David Greenebf7f78e2010-01-05 01:27:17 +00001760 DEBUG(dbgs() << "GVN COERCED INST:\n" << *Dep.getInst() << '\n'
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001761 << *AvailVal << '\n' << *L << "\n\n\n");
1762
1763 // Replace the load!
1764 L->replaceAllUsesWith(AvailVal);
Duncan Sands1df98592010-02-16 11:11:14 +00001765 if (AvailVal->getType()->isPointerTy())
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001766 MD->invalidateCachedPointerInfo(AvailVal);
Chris Lattner4756ecb2011-04-28 16:36:48 +00001767 markInstructionForDeletion(L);
Dan Gohmanfe601042010-06-22 15:08:57 +00001768 ++NumGVNLoad;
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001769 return true;
1770 }
Chris Lattner1f821512011-04-26 01:21:15 +00001771 }
1772
1773 // If the value isn't available, don't do anything!
1774 if (Dep.isClobber()) {
Torok Edwin3f3c6d42009-05-29 09:46:03 +00001775 DEBUG(
Chris Lattner1f821512011-04-26 01:21:15 +00001776 // fast print dep, using operator<< on instruction is too slow.
David Greenebf7f78e2010-01-05 01:27:17 +00001777 dbgs() << "GVN: load ";
1778 WriteAsOperand(dbgs(), L);
Chris Lattnerb2412a82009-09-21 02:42:51 +00001779 Instruction *I = Dep.getInst();
David Greenebf7f78e2010-01-05 01:27:17 +00001780 dbgs() << " is clobbered by " << *I << '\n';
Torok Edwin3f3c6d42009-05-29 09:46:03 +00001781 );
Chris Lattnerb51deb92008-12-05 21:04:20 +00001782 return false;
Torok Edwin3f3c6d42009-05-29 09:46:03 +00001783 }
Chris Lattnerb51deb92008-12-05 21:04:20 +00001784
Eli Friedmanb4141422011-10-13 22:14:57 +00001785 // If it is defined in another block, try harder.
1786 if (Dep.isNonLocal())
1787 return processNonLocalLoad(L);
1788
1789 if (!Dep.isDef()) {
Eli Friedmana990e072011-06-15 00:47:34 +00001790 DEBUG(
1791 // fast print dep, using operator<< on instruction is too slow.
1792 dbgs() << "GVN: load ";
1793 WriteAsOperand(dbgs(), L);
1794 dbgs() << " has unknown dependence\n";
1795 );
1796 return false;
1797 }
1798
Chris Lattnerb2412a82009-09-21 02:42:51 +00001799 Instruction *DepInst = Dep.getInst();
Chris Lattnerb51deb92008-12-05 21:04:20 +00001800 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
Dan Gohman3355c4e2010-11-10 19:03:33 +00001801 Value *StoredVal = DepSI->getValueOperand();
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001802
1803 // The store and load are to a must-aliased pointer, but they may not
1804 // actually have the same type. See if we know how to reuse the stored
1805 // value (depending on its type).
Chris Lattnera52fce42009-10-21 04:11:19 +00001806 if (StoredVal->getType() != L->getType()) {
Duncan Sands88c3df72010-11-12 21:10:24 +00001807 if (TD) {
Chris Lattnera52fce42009-10-21 04:11:19 +00001808 StoredVal = CoerceAvailableValueToLoadType(StoredVal, L->getType(),
1809 L, *TD);
1810 if (StoredVal == 0)
1811 return false;
1812
David Greenebf7f78e2010-01-05 01:27:17 +00001813 DEBUG(dbgs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
Chris Lattnera52fce42009-10-21 04:11:19 +00001814 << '\n' << *L << "\n\n\n");
1815 }
1816 else
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001817 return false;
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001818 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001819
Chris Lattnerb51deb92008-12-05 21:04:20 +00001820 // Remove it!
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001821 L->replaceAllUsesWith(StoredVal);
Duncan Sands1df98592010-02-16 11:11:14 +00001822 if (StoredVal->getType()->isPointerTy())
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001823 MD->invalidateCachedPointerInfo(StoredVal);
Chris Lattner4756ecb2011-04-28 16:36:48 +00001824 markInstructionForDeletion(L);
Dan Gohmanfe601042010-06-22 15:08:57 +00001825 ++NumGVNLoad;
Chris Lattnerb51deb92008-12-05 21:04:20 +00001826 return true;
1827 }
1828
1829 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001830 Value *AvailableVal = DepLI;
1831
1832 // The loads are of a must-aliased pointer, but they may not actually have
1833 // the same type. See if we know how to reuse the previously loaded value
1834 // (depending on its type).
Chris Lattnera52fce42009-10-21 04:11:19 +00001835 if (DepLI->getType() != L->getType()) {
Duncan Sands88c3df72010-11-12 21:10:24 +00001836 if (TD) {
Chris Lattner1f821512011-04-26 01:21:15 +00001837 AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(),
1838 L, *TD);
Chris Lattnera52fce42009-10-21 04:11:19 +00001839 if (AvailableVal == 0)
1840 return false;
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001841
David Greenebf7f78e2010-01-05 01:27:17 +00001842 DEBUG(dbgs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
Chris Lattnera52fce42009-10-21 04:11:19 +00001843 << "\n" << *L << "\n\n\n");
1844 }
1845 else
1846 return false;
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001847 }
1848
Chris Lattnerb51deb92008-12-05 21:04:20 +00001849 // Remove it!
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001850 L->replaceAllUsesWith(AvailableVal);
Duncan Sands1df98592010-02-16 11:11:14 +00001851 if (DepLI->getType()->isPointerTy())
Chris Lattnerbc99be12008-12-09 22:06:23 +00001852 MD->invalidateCachedPointerInfo(DepLI);
Chris Lattner4756ecb2011-04-28 16:36:48 +00001853 markInstructionForDeletion(L);
Dan Gohmanfe601042010-06-22 15:08:57 +00001854 ++NumGVNLoad;
Chris Lattnerb51deb92008-12-05 21:04:20 +00001855 return true;
1856 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001857
Chris Lattner237a8282008-11-30 01:39:32 +00001858 // If this load really doesn't depend on anything, then we must be loading an
1859 // undef value. This can happen when loading for a fresh allocation with no
1860 // intervening stores, for example.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001861 if (isa<AllocaInst>(DepInst) || isMalloc(DepInst)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001862 L->replaceAllUsesWith(UndefValue::get(L->getType()));
Chris Lattner4756ecb2011-04-28 16:36:48 +00001863 markInstructionForDeletion(L);
Dan Gohmanfe601042010-06-22 15:08:57 +00001864 ++NumGVNLoad;
Chris Lattnerb51deb92008-12-05 21:04:20 +00001865 return true;
Eli Friedmanb6c36e42008-02-12 12:08:14 +00001866 }
Owen Andersonb62f7922009-10-28 07:05:35 +00001867
Owen Anderson9ff5a232009-12-02 07:35:19 +00001868 // If this load occurs either right after a lifetime begin,
Owen Andersonb62f7922009-10-28 07:05:35 +00001869 // then the loaded value is undefined.
Chris Lattner4756ecb2011-04-28 16:36:48 +00001870 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(DepInst)) {
Owen Anderson9ff5a232009-12-02 07:35:19 +00001871 if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
Owen Andersonb62f7922009-10-28 07:05:35 +00001872 L->replaceAllUsesWith(UndefValue::get(L->getType()));
Chris Lattner4756ecb2011-04-28 16:36:48 +00001873 markInstructionForDeletion(L);
Dan Gohmanfe601042010-06-22 15:08:57 +00001874 ++NumGVNLoad;
Owen Andersonb62f7922009-10-28 07:05:35 +00001875 return true;
1876 }
1877 }
Eli Friedmanb6c36e42008-02-12 12:08:14 +00001878
Chris Lattnerb51deb92008-12-05 21:04:20 +00001879 return false;
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001880}
1881
Owen Anderson7a75d612011-01-04 19:13:25 +00001882// findLeader - In order to find a leader for a given value number at a
Owen Anderson68c26392010-11-19 22:48:40 +00001883// specific basic block, we first obtain the list of all Values for that number,
1884// and then scan the list to find one whose block dominates the block in
1885// question. This is fast because dominator tree queries consist of only
1886// a few comparisons of DFS numbers.
Owen Anderson7a75d612011-01-04 19:13:25 +00001887Value *GVN::findLeader(BasicBlock *BB, uint32_t num) {
Owen Andersonb1602ab2011-01-04 19:29:46 +00001888 LeaderTableEntry Vals = LeaderTable[num];
Owen Andersonf0568382010-12-21 23:54:34 +00001889 if (!Vals.Val) return 0;
Owen Andersona04a0642010-11-18 18:32:40 +00001890
Owen Andersonf0568382010-12-21 23:54:34 +00001891 Value *Val = 0;
1892 if (DT->dominates(Vals.BB, BB)) {
1893 Val = Vals.Val;
1894 if (isa<Constant>(Val)) return Val;
1895 }
1896
Owen Anderson7a75d612011-01-04 19:13:25 +00001897 LeaderTableEntry* Next = Vals.Next;
Owen Andersona04a0642010-11-18 18:32:40 +00001898 while (Next) {
Owen Andersonf0568382010-12-21 23:54:34 +00001899 if (DT->dominates(Next->BB, BB)) {
1900 if (isa<Constant>(Next->Val)) return Next->Val;
1901 if (!Val) Val = Next->Val;
1902 }
Owen Andersona04a0642010-11-18 18:32:40 +00001903
Owen Andersonf0568382010-12-21 23:54:34 +00001904 Next = Next->Next;
Owen Anderson6fafe842008-06-20 01:15:47 +00001905 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001906
Owen Andersonf0568382010-12-21 23:54:34 +00001907 return Val;
Owen Anderson6fafe842008-06-20 01:15:47 +00001908}
1909
Duncan Sands02b5e722011-10-05 14:28:49 +00001910/// replaceAllDominatedUsesWith - Replace all uses of 'From' with 'To' if the
1911/// use is dominated by the given basic block. Returns the number of uses that
1912/// were replaced.
1913unsigned GVN::replaceAllDominatedUsesWith(Value *From, Value *To,
1914 BasicBlock *Root) {
1915 unsigned Count = 0;
1916 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
1917 UI != UE; ) {
Duncan Sands8c160542012-02-08 14:10:53 +00001918 Use &U = (UI++).getUse();
1919 if (DT->dominates(Root, cast<Instruction>(U.getUser())->getParent())) {
1920 U.set(To);
Duncan Sands02b5e722011-10-05 14:28:49 +00001921 ++Count;
1922 }
1923 }
1924 return Count;
1925}
1926
1927/// propagateEquality - The given values are known to be equal in every block
1928/// dominated by 'Root'. Exploit this, for example by replacing 'LHS' with
1929/// 'RHS' everywhere in the scope. Returns whether a change was made.
1930bool GVN::propagateEquality(Value *LHS, Value *RHS, BasicBlock *Root) {
1931 if (LHS == RHS) return false;
1932 assert(LHS->getType() == RHS->getType() && "Equal but types differ!");
1933
1934 // Don't try to propagate equalities between constants.
1935 if (isa<Constant>(LHS) && isa<Constant>(RHS))
1936 return false;
1937
1938 // Make sure that any constants are on the right-hand side. In general the
1939 // best results are obtained by placing the longest lived value on the RHS.
1940 if (isa<Constant>(LHS))
1941 std::swap(LHS, RHS);
1942
1943 // If neither term is constant then bail out. This is not for correctness,
1944 // it's just that the non-constant case is much less useful: it occurs just
1945 // as often as the constant case but handling it hardly ever results in an
1946 // improvement.
1947 if (!isa<Constant>(RHS))
1948 return false;
1949
1950 // If value numbering later deduces that an instruction in the scope is equal
1951 // to 'LHS' then ensure it will be turned into 'RHS'.
1952 addToLeaderTable(VN.lookup_or_add(LHS), RHS, Root);
1953
Duncan Sands1673b152011-10-15 11:13:42 +00001954 // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope. As
1955 // LHS always has at least one use that is not dominated by Root, this will
1956 // never do anything if LHS has only one use.
1957 bool Changed = false;
1958 if (!LHS->hasOneUse()) {
1959 unsigned NumReplacements = replaceAllDominatedUsesWith(LHS, RHS, Root);
1960 Changed |= NumReplacements > 0;
1961 NumGVNEqProp += NumReplacements;
1962 }
Duncan Sands02b5e722011-10-05 14:28:49 +00001963
1964 // Now try to deduce additional equalities from this one. For example, if the
1965 // known equality was "(A != B)" == "false" then it follows that A and B are
1966 // equal in the scope. Only boolean equalities with an explicit true or false
1967 // RHS are currently supported.
1968 if (!RHS->getType()->isIntegerTy(1))
1969 // Not a boolean equality - bail out.
1970 return Changed;
1971 ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
1972 if (!CI)
1973 // RHS neither 'true' nor 'false' - bail out.
1974 return Changed;
1975 // Whether RHS equals 'true'. Otherwise it equals 'false'.
1976 bool isKnownTrue = CI->isAllOnesValue();
1977 bool isKnownFalse = !isKnownTrue;
1978
1979 // If "A && B" is known true then both A and B are known true. If "A || B"
1980 // is known false then both A and B are known false.
1981 Value *A, *B;
1982 if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) ||
1983 (isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) {
1984 Changed |= propagateEquality(A, RHS, Root);
1985 Changed |= propagateEquality(B, RHS, Root);
1986 return Changed;
1987 }
1988
1989 // If we are propagating an equality like "(A == B)" == "true" then also
1990 // propagate the equality A == B.
1991 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(LHS)) {
1992 // Only equality comparisons are supported.
1993 if ((isKnownTrue && Cmp->getPredicate() == CmpInst::ICMP_EQ) ||
1994 (isKnownFalse && Cmp->getPredicate() == CmpInst::ICMP_NE)) {
1995 Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
1996 Changed |= propagateEquality(Op0, Op1, Root);
1997 }
1998 return Changed;
1999 }
2000
2001 return Changed;
2002}
Owen Anderson255dafc2008-12-15 02:03:00 +00002003
Duncan Sands3f329cb2011-10-07 08:29:06 +00002004/// isOnlyReachableViaThisEdge - There is an edge from 'Src' to 'Dst'. Return
2005/// true if every path from the entry block to 'Dst' passes via this edge. In
2006/// particular 'Dst' must not be reachable via another edge from 'Src'.
2007static bool isOnlyReachableViaThisEdge(BasicBlock *Src, BasicBlock *Dst,
2008 DominatorTree *DT) {
Duncan Sands33756f92012-02-05 18:25:50 +00002009 // While in theory it is interesting to consider the case in which Dst has
2010 // more than one predecessor, because Dst might be part of a loop which is
2011 // only reachable from Src, in practice it is pointless since at the time
2012 // GVN runs all such loops have preheaders, which means that Dst will have
2013 // been changed to have only one predecessor, namely Src.
Duncan Sandsc4fd4482012-02-05 19:43:37 +00002014 BasicBlock *Pred = Dst->getSinglePredecessor();
2015 assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
Duncan Sands33756f92012-02-05 18:25:50 +00002016 (void)Src;
Duncan Sandsc4fd4482012-02-05 19:43:37 +00002017 return Pred != 0;
Duncan Sands3f329cb2011-10-07 08:29:06 +00002018}
2019
Owen Anderson36057c72007-08-14 18:16:29 +00002020/// processInstruction - When calculating availability, handle an instruction
Owen Anderson1ad2cb72007-07-24 17:55:58 +00002021/// by inserting it into the appropriate sets
Chris Lattnerf07054d2011-04-28 16:18:52 +00002022bool GVN::processInstruction(Instruction *I) {
Devang Patelbe905e22010-02-11 00:20:49 +00002023 // Ignore dbg info intrinsics.
2024 if (isa<DbgInfoIntrinsic>(I))
2025 return false;
2026
Duncan Sands88c3df72010-11-12 21:10:24 +00002027 // If the instruction can be easily simplified then do so now in preference
2028 // to value numbering it. Value numbering often exposes redundancies, for
2029 // example if it determines that %y is equal to %x then the instruction
2030 // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
Chad Rosier618c1db2011-12-01 03:08:23 +00002031 if (Value *V = SimplifyInstruction(I, TD, TLI, DT)) {
Duncan Sands88c3df72010-11-12 21:10:24 +00002032 I->replaceAllUsesWith(V);
2033 if (MD && V->getType()->isPointerTy())
2034 MD->invalidateCachedPointerInfo(V);
Chris Lattner4756ecb2011-04-28 16:36:48 +00002035 markInstructionForDeletion(I);
Duncan Sands02b5e722011-10-05 14:28:49 +00002036 ++NumGVNSimpl;
Duncan Sands88c3df72010-11-12 21:10:24 +00002037 return true;
2038 }
2039
Chris Lattnerb2412a82009-09-21 02:42:51 +00002040 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf07054d2011-04-28 16:18:52 +00002041 if (processLoad(LI))
2042 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002043
Chris Lattnerf07054d2011-04-28 16:18:52 +00002044 unsigned Num = VN.lookup_or_add(LI);
2045 addToLeaderTable(Num, LI, LI->getParent());
2046 return false;
Owen Andersonb2303722008-06-18 21:41:49 +00002047 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002048
Duncan Sands02b5e722011-10-05 14:28:49 +00002049 // For conditional branches, we can perform simple conditional propagation on
Owen Andersonf0568382010-12-21 23:54:34 +00002050 // the condition value itself.
2051 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
Owen Andersonf0568382010-12-21 23:54:34 +00002052 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
2053 return false;
Duncan Sands02b5e722011-10-05 14:28:49 +00002054
Owen Andersonf0568382010-12-21 23:54:34 +00002055 Value *BranchCond = BI->getCondition();
Duncan Sands02b5e722011-10-05 14:28:49 +00002056
Owen Andersonf0568382010-12-21 23:54:34 +00002057 BasicBlock *TrueSucc = BI->getSuccessor(0);
2058 BasicBlock *FalseSucc = BI->getSuccessor(1);
Duncan Sands452c58f2011-10-05 14:17:01 +00002059 BasicBlock *Parent = BI->getParent();
Duncan Sands3f329cb2011-10-07 08:29:06 +00002060 bool Changed = false;
Duncan Sands452c58f2011-10-05 14:17:01 +00002061
Duncan Sands3f329cb2011-10-07 08:29:06 +00002062 if (isOnlyReachableViaThisEdge(Parent, TrueSucc, DT))
2063 Changed |= propagateEquality(BranchCond,
Duncan Sands02b5e722011-10-05 14:28:49 +00002064 ConstantInt::getTrue(TrueSucc->getContext()),
Duncan Sands3f329cb2011-10-07 08:29:06 +00002065 TrueSucc);
2066
2067 if (isOnlyReachableViaThisEdge(Parent, FalseSucc, DT))
2068 Changed |= propagateEquality(BranchCond,
2069 ConstantInt::getFalse(FalseSucc->getContext()),
2070 FalseSucc);
2071
2072 return Changed;
Owen Andersonf0568382010-12-21 23:54:34 +00002073 }
Duncan Sands3f329cb2011-10-07 08:29:06 +00002074
2075 // For switches, propagate the case values into the case destinations.
2076 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
2077 Value *SwitchCond = SI->getCondition();
2078 BasicBlock *Parent = SI->getParent();
2079 bool Changed = false;
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00002080 for (unsigned i = 0, e = SI->getNumCases(); i != e; ++i) {
2081 BasicBlock *Dst = SI->getCaseSuccessor(i);
Duncan Sands3f329cb2011-10-07 08:29:06 +00002082 if (isOnlyReachableViaThisEdge(Parent, Dst, DT))
2083 Changed |= propagateEquality(SwitchCond, SI->getCaseValue(i), Dst);
2084 }
2085 return Changed;
2086 }
2087
Owen Anderson2cf75372011-01-04 22:15:21 +00002088 // Instructions with void type don't return a value, so there's
2089 // no point in trying to find redudancies in them.
2090 if (I->getType()->isVoidTy()) return false;
2091
Owen Andersonc2146a62011-01-04 18:54:18 +00002092 uint32_t NextNum = VN.getNextUnusedValueNumber();
2093 unsigned Num = VN.lookup_or_add(I);
2094
Owen Andersone5ffa902008-04-07 09:59:07 +00002095 // Allocations are always uniquely numbered, so we can save time and memory
Daniel Dunbara279bc32009-09-20 02:20:51 +00002096 // by fast failing them.
Chris Lattner459f4f82010-12-19 20:24:28 +00002097 if (isa<AllocaInst>(I) || isa<TerminatorInst>(I) || isa<PHINode>(I)) {
Owen Anderson7a75d612011-01-04 19:13:25 +00002098 addToLeaderTable(Num, I, I->getParent());
Owen Andersone5ffa902008-04-07 09:59:07 +00002099 return false;
Owen Andersonb2303722008-06-18 21:41:49 +00002100 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002101
Owen Anderson0ae33ef2008-07-03 17:44:33 +00002102 // If the number we were assigned was a brand new VN, then we don't
2103 // need to do a lookup to see if the number already exists
2104 // somewhere in the domtree: it can't!
Chris Lattner459f4f82010-12-19 20:24:28 +00002105 if (Num == NextNum) {
Owen Anderson7a75d612011-01-04 19:13:25 +00002106 addToLeaderTable(Num, I, I->getParent());
Chris Lattner459f4f82010-12-19 20:24:28 +00002107 return false;
2108 }
2109
Owen Anderson255dafc2008-12-15 02:03:00 +00002110 // Perform fast-path value-number based elimination of values inherited from
2111 // dominators.
Owen Anderson7a75d612011-01-04 19:13:25 +00002112 Value *repl = findLeader(I->getParent(), Num);
Chris Lattner459f4f82010-12-19 20:24:28 +00002113 if (repl == 0) {
2114 // Failure, just remember this instance for future use.
Owen Anderson7a75d612011-01-04 19:13:25 +00002115 addToLeaderTable(Num, I, I->getParent());
Chris Lattner459f4f82010-12-19 20:24:28 +00002116 return false;
Owen Anderson1ad2cb72007-07-24 17:55:58 +00002117 }
Chris Lattner459f4f82010-12-19 20:24:28 +00002118
2119 // Remove it!
Chris Lattner459f4f82010-12-19 20:24:28 +00002120 I->replaceAllUsesWith(repl);
2121 if (MD && repl->getType()->isPointerTy())
2122 MD->invalidateCachedPointerInfo(repl);
Chris Lattner4756ecb2011-04-28 16:36:48 +00002123 markInstructionForDeletion(I);
Chris Lattner459f4f82010-12-19 20:24:28 +00002124 return true;
Owen Anderson1ad2cb72007-07-24 17:55:58 +00002125}
2126
Bill Wendling30788b82008-12-22 22:32:22 +00002127/// runOnFunction - This is the main transformation entry point for a function.
Owen Anderson3e75a422007-08-14 18:04:11 +00002128bool GVN::runOnFunction(Function& F) {
Dan Gohman4ec01b22009-11-14 02:27:51 +00002129 if (!NoLoads)
2130 MD = &getAnalysis<MemoryDependenceAnalysis>();
Chris Lattner663e4412008-12-01 00:40:32 +00002131 DT = &getAnalysis<DominatorTree>();
Duncan Sands88c3df72010-11-12 21:10:24 +00002132 TD = getAnalysisIfAvailable<TargetData>();
Chad Rosier618c1db2011-12-01 03:08:23 +00002133 TLI = &getAnalysis<TargetLibraryInfo>();
Owen Andersona472c4a2008-05-12 20:15:55 +00002134 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
Chris Lattner663e4412008-12-01 00:40:32 +00002135 VN.setMemDep(MD);
2136 VN.setDomTree(DT);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002137
Chris Lattnerb2412a82009-09-21 02:42:51 +00002138 bool Changed = false;
2139 bool ShouldContinue = true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002140
Owen Anderson5d0af032008-07-16 17:52:31 +00002141 // Merge unconditional branches, allowing PRE to catch more
2142 // optimization opportunities.
2143 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
Chris Lattnerb5b79972011-01-11 08:13:40 +00002144 BasicBlock *BB = FI++;
2145
Owen Andersonb31b06d2008-07-17 00:01:40 +00002146 bool removedBlock = MergeBlockIntoPredecessor(BB, this);
Dan Gohmanfe601042010-06-22 15:08:57 +00002147 if (removedBlock) ++NumGVNBlocks;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002148
Chris Lattnerb2412a82009-09-21 02:42:51 +00002149 Changed |= removedBlock;
Owen Anderson5d0af032008-07-16 17:52:31 +00002150 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002151
Chris Lattnerae199312008-12-09 19:21:47 +00002152 unsigned Iteration = 0;
Chris Lattnerb2412a82009-09-21 02:42:51 +00002153 while (ShouldContinue) {
David Greenebf7f78e2010-01-05 01:27:17 +00002154 DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
Chris Lattnerb2412a82009-09-21 02:42:51 +00002155 ShouldContinue = iterateOnFunction(F);
Bob Wilson484d4a32010-02-16 19:51:59 +00002156 if (splitCriticalEdges())
2157 ShouldContinue = true;
Chris Lattnerb2412a82009-09-21 02:42:51 +00002158 Changed |= ShouldContinue;
Chris Lattnerae199312008-12-09 19:21:47 +00002159 ++Iteration;
Owen Anderson3e75a422007-08-14 18:04:11 +00002160 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002161
Owen Andersone98c54c2008-07-18 18:03:38 +00002162 if (EnablePRE) {
Owen Anderson0c7f91c2008-09-03 23:06:07 +00002163 bool PREChanged = true;
2164 while (PREChanged) {
2165 PREChanged = performPRE(F);
Chris Lattnerb2412a82009-09-21 02:42:51 +00002166 Changed |= PREChanged;
Owen Anderson0c7f91c2008-09-03 23:06:07 +00002167 }
Owen Andersone98c54c2008-07-18 18:03:38 +00002168 }
Chris Lattnerae199312008-12-09 19:21:47 +00002169 // FIXME: Should perform GVN again after PRE does something. PRE can move
2170 // computations into blocks where they become fully redundant. Note that
2171 // we can't do this until PRE's critical edge splitting updates memdep.
2172 // Actually, when this happens, we should just fully integrate PRE into GVN.
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +00002173
2174 cleanupGlobalSets();
2175
Chris Lattnerb2412a82009-09-21 02:42:51 +00002176 return Changed;
Owen Anderson3e75a422007-08-14 18:04:11 +00002177}
2178
2179
Chris Lattnerb2412a82009-09-21 02:42:51 +00002180bool GVN::processBlock(BasicBlock *BB) {
Chris Lattnerf07054d2011-04-28 16:18:52 +00002181 // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function
2182 // (and incrementing BI before processing an instruction).
2183 assert(InstrsToErase.empty() &&
2184 "We expect InstrsToErase to be empty across iterations");
Chris Lattnerb2412a82009-09-21 02:42:51 +00002185 bool ChangedFunction = false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002186
Owen Andersonaf4240a2008-06-12 19:25:32 +00002187 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
2188 BI != BE;) {
Chris Lattnerf07054d2011-04-28 16:18:52 +00002189 ChangedFunction |= processInstruction(BI);
2190 if (InstrsToErase.empty()) {
Owen Andersonaf4240a2008-06-12 19:25:32 +00002191 ++BI;
2192 continue;
2193 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002194
Owen Andersonaf4240a2008-06-12 19:25:32 +00002195 // If we need some instructions deleted, do it now.
Chris Lattnerf07054d2011-04-28 16:18:52 +00002196 NumGVNInstr += InstrsToErase.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002197
Owen Andersonaf4240a2008-06-12 19:25:32 +00002198 // Avoid iterator invalidation.
2199 bool AtStart = BI == BB->begin();
2200 if (!AtStart)
2201 --BI;
2202
Chris Lattnerf07054d2011-04-28 16:18:52 +00002203 for (SmallVector<Instruction*, 4>::iterator I = InstrsToErase.begin(),
2204 E = InstrsToErase.end(); I != E; ++I) {
David Greenebf7f78e2010-01-05 01:27:17 +00002205 DEBUG(dbgs() << "GVN removed: " << **I << '\n');
Dan Gohman4ec01b22009-11-14 02:27:51 +00002206 if (MD) MD->removeInstruction(*I);
Owen Andersonaf4240a2008-06-12 19:25:32 +00002207 (*I)->eraseFromParent();
Bill Wendlingec40d502008-12-22 21:57:30 +00002208 DEBUG(verifyRemoved(*I));
Chris Lattner663e4412008-12-01 00:40:32 +00002209 }
Chris Lattnerf07054d2011-04-28 16:18:52 +00002210 InstrsToErase.clear();
Owen Andersonaf4240a2008-06-12 19:25:32 +00002211
2212 if (AtStart)
2213 BI = BB->begin();
2214 else
2215 ++BI;
Owen Andersonaf4240a2008-06-12 19:25:32 +00002216 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002217
Chris Lattnerb2412a82009-09-21 02:42:51 +00002218 return ChangedFunction;
Owen Andersonaf4240a2008-06-12 19:25:32 +00002219}
2220
Owen Andersonb2303722008-06-18 21:41:49 +00002221/// performPRE - Perform a purely local form of PRE that looks for diamond
2222/// control flow patterns and attempts to perform simple PRE at the join point.
Chris Lattnerfb6e7012009-10-31 22:11:15 +00002223bool GVN::performPRE(Function &F) {
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002224 bool Changed = false;
Chris Lattner09713792008-12-01 07:29:03 +00002225 DenseMap<BasicBlock*, Value*> predMap;
Owen Andersonb2303722008-06-18 21:41:49 +00002226 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
2227 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
Chris Lattnerb2412a82009-09-21 02:42:51 +00002228 BasicBlock *CurrentBlock = *DI;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002229
Owen Andersonb2303722008-06-18 21:41:49 +00002230 // Nothing to PRE in the entry block.
2231 if (CurrentBlock == &F.getEntryBlock()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002232
Bill Wendling795cf5e2011-08-17 21:32:02 +00002233 // Don't perform PRE on a landing pad.
2234 if (CurrentBlock->isLandingPad()) continue;
2235
Owen Andersonb2303722008-06-18 21:41:49 +00002236 for (BasicBlock::iterator BI = CurrentBlock->begin(),
2237 BE = CurrentBlock->end(); BI != BE; ) {
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002238 Instruction *CurInst = BI++;
Duncan Sands7af1c782009-05-06 06:49:50 +00002239
Victor Hernandez7b929da2009-10-23 21:09:37 +00002240 if (isa<AllocaInst>(CurInst) ||
Victor Hernandez83d63912009-09-18 22:35:49 +00002241 isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
Devang Patel9674d152009-10-14 17:29:00 +00002242 CurInst->getType()->isVoidTy() ||
Duncan Sands7af1c782009-05-06 06:49:50 +00002243 CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
John Criswell090c0a22009-03-10 15:04:53 +00002244 isa<DbgInfoIntrinsic>(CurInst))
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002245 continue;
Owen Anderson5015b342010-08-07 00:20:35 +00002246
2247 // We don't currently value number ANY inline asm calls.
2248 if (CallInst *CallI = dyn_cast<CallInst>(CurInst))
2249 if (CallI->isInlineAsm())
2250 continue;
Duncan Sands7af1c782009-05-06 06:49:50 +00002251
Chris Lattnerb2412a82009-09-21 02:42:51 +00002252 uint32_t ValNo = VN.lookup(CurInst);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002253
Owen Andersonb2303722008-06-18 21:41:49 +00002254 // Look for the predecessors for PRE opportunities. We're
2255 // only trying to solve the basic diamond case, where
2256 // a value is computed in the successor and one predecessor,
2257 // but not the other. We also explicitly disallow cases
2258 // where the successor is its own predecessor, because they're
2259 // more complicated to get right.
Chris Lattnerb2412a82009-09-21 02:42:51 +00002260 unsigned NumWith = 0;
2261 unsigned NumWithout = 0;
2262 BasicBlock *PREPred = 0;
Chris Lattner09713792008-12-01 07:29:03 +00002263 predMap.clear();
2264
Owen Andersonb2303722008-06-18 21:41:49 +00002265 for (pred_iterator PI = pred_begin(CurrentBlock),
2266 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
Gabor Greif08149852010-07-09 14:36:49 +00002267 BasicBlock *P = *PI;
Owen Andersonb2303722008-06-18 21:41:49 +00002268 // We're not interested in PRE where the block is its
Bob Wilsone7b635f2010-02-03 00:33:21 +00002269 // own predecessor, or in blocks with predecessors
Owen Anderson6fafe842008-06-20 01:15:47 +00002270 // that are not reachable.
Gabor Greif08149852010-07-09 14:36:49 +00002271 if (P == CurrentBlock) {
Chris Lattnerb2412a82009-09-21 02:42:51 +00002272 NumWithout = 2;
Owen Anderson6fafe842008-06-20 01:15:47 +00002273 break;
Owen Andersona04a0642010-11-18 18:32:40 +00002274 } else if (!DT->dominates(&F.getEntryBlock(), P)) {
Chris Lattnerb2412a82009-09-21 02:42:51 +00002275 NumWithout = 2;
Owen Anderson6fafe842008-06-20 01:15:47 +00002276 break;
2277 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002278
Owen Anderson7a75d612011-01-04 19:13:25 +00002279 Value* predV = findLeader(P, ValNo);
Owen Andersona04a0642010-11-18 18:32:40 +00002280 if (predV == 0) {
Gabor Greif08149852010-07-09 14:36:49 +00002281 PREPred = P;
Dan Gohmanfe601042010-06-22 15:08:57 +00002282 ++NumWithout;
Owen Andersona04a0642010-11-18 18:32:40 +00002283 } else if (predV == CurInst) {
Chris Lattnerb2412a82009-09-21 02:42:51 +00002284 NumWithout = 2;
Owen Andersonb2303722008-06-18 21:41:49 +00002285 } else {
Owen Andersona04a0642010-11-18 18:32:40 +00002286 predMap[P] = predV;
Dan Gohmanfe601042010-06-22 15:08:57 +00002287 ++NumWith;
Owen Andersonb2303722008-06-18 21:41:49 +00002288 }
2289 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002290
Owen Andersonb2303722008-06-18 21:41:49 +00002291 // Don't do PRE when it might increase code size, i.e. when
2292 // we would need to insert instructions in more than one pred.
Chris Lattnerb2412a82009-09-21 02:42:51 +00002293 if (NumWithout != 1 || NumWith == 0)
Owen Andersonb2303722008-06-18 21:41:49 +00002294 continue;
Chris Lattnerfb6e7012009-10-31 22:11:15 +00002295
2296 // Don't do PRE across indirect branch.
2297 if (isa<IndirectBrInst>(PREPred->getTerminator()))
2298 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002299
Owen Anderson5c274ee2008-06-19 19:54:19 +00002300 // We can't do PRE safely on a critical edge, so instead we schedule
2301 // the edge to be split and perform the PRE the next time we iterate
2302 // on the function.
Bob Wilsonae23daf2010-02-16 21:06:42 +00002303 unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
Chris Lattnerb2412a82009-09-21 02:42:51 +00002304 if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
2305 toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
Owen Anderson5c274ee2008-06-19 19:54:19 +00002306 continue;
2307 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002308
Bob Wilsone7b635f2010-02-03 00:33:21 +00002309 // Instantiate the expression in the predecessor that lacked it.
Owen Andersonb2303722008-06-18 21:41:49 +00002310 // Because we are going top-down through the block, all value numbers
2311 // will be available in the predecessor by the time we need them. Any
Bob Wilsone7b635f2010-02-03 00:33:21 +00002312 // that weren't originally present will have been instantiated earlier
Owen Andersonb2303722008-06-18 21:41:49 +00002313 // in this loop.
Nick Lewycky67760642009-09-27 07:38:41 +00002314 Instruction *PREInstr = CurInst->clone();
Owen Andersonb2303722008-06-18 21:41:49 +00002315 bool success = true;
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002316 for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
2317 Value *Op = PREInstr->getOperand(i);
2318 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
2319 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002320
Owen Anderson7a75d612011-01-04 19:13:25 +00002321 if (Value *V = findLeader(PREPred, VN.lookup(Op))) {
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002322 PREInstr->setOperand(i, V);
2323 } else {
2324 success = false;
2325 break;
Owen Andersonc45996b2008-07-11 20:05:13 +00002326 }
Owen Andersonb2303722008-06-18 21:41:49 +00002327 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002328
Owen Andersonb2303722008-06-18 21:41:49 +00002329 // Fail out if we encounter an operand that is not available in
Daniel Dunbara279bc32009-09-20 02:20:51 +00002330 // the PRE predecessor. This is typically because of loads which
Owen Andersonb2303722008-06-18 21:41:49 +00002331 // are not value numbered precisely.
2332 if (!success) {
2333 delete PREInstr;
Bill Wendling70ded192008-12-22 22:14:07 +00002334 DEBUG(verifyRemoved(PREInstr));
Owen Andersonb2303722008-06-18 21:41:49 +00002335 continue;
2336 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002337
Owen Andersonb2303722008-06-18 21:41:49 +00002338 PREInstr->insertBefore(PREPred->getTerminator());
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002339 PREInstr->setName(CurInst->getName() + ".pre");
Devang Patelde985682011-05-17 20:00:02 +00002340 PREInstr->setDebugLoc(CurInst->getDebugLoc());
Owen Anderson6fafe842008-06-20 01:15:47 +00002341 predMap[PREPred] = PREInstr;
Chris Lattnerb2412a82009-09-21 02:42:51 +00002342 VN.add(PREInstr, ValNo);
Dan Gohmanfe601042010-06-22 15:08:57 +00002343 ++NumGVNPRE;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002344
Owen Andersonb2303722008-06-18 21:41:49 +00002345 // Update the availability map to include the new instruction.
Owen Anderson7a75d612011-01-04 19:13:25 +00002346 addToLeaderTable(ValNo, PREInstr, PREPred);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002347
Owen Andersonb2303722008-06-18 21:41:49 +00002348 // Create a PHI to make the value available in this block.
Jay Foadd8b4fb42011-03-30 11:19:20 +00002349 pred_iterator PB = pred_begin(CurrentBlock), PE = pred_end(CurrentBlock);
Jay Foad3ecfc862011-03-30 11:28:46 +00002350 PHINode* Phi = PHINode::Create(CurInst->getType(), std::distance(PB, PE),
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002351 CurInst->getName() + ".pre-phi",
Owen Andersonb2303722008-06-18 21:41:49 +00002352 CurrentBlock->begin());
Jay Foadd8b4fb42011-03-30 11:19:20 +00002353 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif1d3ae022010-07-09 14:48:08 +00002354 BasicBlock *P = *PI;
2355 Phi->addIncoming(predMap[P], P);
2356 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002357
Chris Lattnerb2412a82009-09-21 02:42:51 +00002358 VN.add(Phi, ValNo);
Owen Anderson7a75d612011-01-04 19:13:25 +00002359 addToLeaderTable(ValNo, Phi, CurrentBlock);
Devang Patel0f18d972011-05-04 23:58:50 +00002360 Phi->setDebugLoc(CurInst->getDebugLoc());
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002361 CurInst->replaceAllUsesWith(Phi);
Owen Anderson392249f2011-01-03 23:51:43 +00002362 if (Phi->getType()->isPointerTy()) {
2363 // Because we have added a PHI-use of the pointer value, it has now
2364 // "escaped" from alias analysis' perspective. We need to inform
2365 // AA of this.
Jay Foadc1371202011-06-20 14:18:48 +00002366 for (unsigned ii = 0, ee = Phi->getNumIncomingValues(); ii != ee;
2367 ++ii) {
2368 unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
2369 VN.getAliasAnalysis()->addEscapingUse(Phi->getOperandUse(jj));
2370 }
Owen Anderson392249f2011-01-03 23:51:43 +00002371
2372 if (MD)
2373 MD->invalidateCachedPointerInfo(Phi);
2374 }
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002375 VN.erase(CurInst);
Owen Anderson7a75d612011-01-04 19:13:25 +00002376 removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002377
David Greenebf7f78e2010-01-05 01:27:17 +00002378 DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
Dan Gohman4ec01b22009-11-14 02:27:51 +00002379 if (MD) MD->removeInstruction(CurInst);
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002380 CurInst->eraseFromParent();
Bill Wendlingec40d502008-12-22 21:57:30 +00002381 DEBUG(verifyRemoved(CurInst));
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002382 Changed = true;
Owen Andersonb2303722008-06-18 21:41:49 +00002383 }
2384 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002385
Bob Wilson484d4a32010-02-16 19:51:59 +00002386 if (splitCriticalEdges())
2387 Changed = true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002388
Bob Wilson484d4a32010-02-16 19:51:59 +00002389 return Changed;
2390}
2391
2392/// splitCriticalEdges - Split critical edges found during the previous
2393/// iteration that may enable further optimization.
2394bool GVN::splitCriticalEdges() {
2395 if (toSplit.empty())
2396 return false;
2397 do {
2398 std::pair<TerminatorInst*, unsigned> Edge = toSplit.pop_back_val();
2399 SplitCriticalEdge(Edge.first, Edge.second, this);
2400 } while (!toSplit.empty());
Evan Cheng19d417c2010-03-01 22:23:12 +00002401 if (MD) MD->invalidateCachedPredecessors();
Bob Wilson484d4a32010-02-16 19:51:59 +00002402 return true;
Owen Andersonb2303722008-06-18 21:41:49 +00002403}
2404
Bill Wendling30788b82008-12-22 22:32:22 +00002405/// iterateOnFunction - Executes one iteration of GVN
Owen Anderson3e75a422007-08-14 18:04:11 +00002406bool GVN::iterateOnFunction(Function &F) {
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +00002407 cleanupGlobalSets();
Owen Andersona04a0642010-11-18 18:32:40 +00002408
Owen Anderson1ad2cb72007-07-24 17:55:58 +00002409 // Top-down walk of the dominator tree
Chris Lattnerb2412a82009-09-21 02:42:51 +00002410 bool Changed = false;
Owen Andersonc34d1122008-12-15 03:52:17 +00002411#if 0
2412 // Needed for value numbering with phi construction to work.
Owen Anderson255dafc2008-12-15 02:03:00 +00002413 ReversePostOrderTraversal<Function*> RPOT(&F);
2414 for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
2415 RE = RPOT.end(); RI != RE; ++RI)
Chris Lattnerb2412a82009-09-21 02:42:51 +00002416 Changed |= processBlock(*RI);
Owen Andersonc34d1122008-12-15 03:52:17 +00002417#else
2418 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
2419 DE = df_end(DT->getRootNode()); DI != DE; ++DI)
Chris Lattnerb2412a82009-09-21 02:42:51 +00002420 Changed |= processBlock(DI->getBlock());
Owen Andersonc34d1122008-12-15 03:52:17 +00002421#endif
2422
Chris Lattnerb2412a82009-09-21 02:42:51 +00002423 return Changed;
Owen Anderson1ad2cb72007-07-24 17:55:58 +00002424}
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +00002425
2426void GVN::cleanupGlobalSets() {
2427 VN.clear();
Owen Andersonb1602ab2011-01-04 19:29:46 +00002428 LeaderTable.clear();
Owen Andersona04a0642010-11-18 18:32:40 +00002429 TableAllocator.Reset();
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +00002430}
Bill Wendling246dbbb2008-12-22 21:36:08 +00002431
2432/// verifyRemoved - Verify that the specified instruction does not occur in our
2433/// internal data structures.
Bill Wendling6d463f22008-12-22 22:28:56 +00002434void GVN::verifyRemoved(const Instruction *Inst) const {
2435 VN.verifyRemoved(Inst);
Bill Wendling70ded192008-12-22 22:14:07 +00002436
Bill Wendling6d463f22008-12-22 22:28:56 +00002437 // Walk through the value number scope to make sure the instruction isn't
2438 // ferreted away in it.
Owen Anderson7a75d612011-01-04 19:13:25 +00002439 for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator
Owen Andersonb1602ab2011-01-04 19:29:46 +00002440 I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) {
Owen Anderson7a75d612011-01-04 19:13:25 +00002441 const LeaderTableEntry *Node = &I->second;
Owen Andersonf0568382010-12-21 23:54:34 +00002442 assert(Node->Val != Inst && "Inst still in value numbering scope!");
Owen Andersona04a0642010-11-18 18:32:40 +00002443
Owen Andersonf0568382010-12-21 23:54:34 +00002444 while (Node->Next) {
2445 Node = Node->Next;
2446 assert(Node->Val != Inst && "Inst still in value numbering scope!");
Bill Wendling70ded192008-12-22 22:14:07 +00002447 }
2448 }
Bill Wendling246dbbb2008-12-22 21:36:08 +00002449}