blob: bc32b7f44181d68a1a1635272d0e35616562991c [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"
Chandler Carruth16003d02012-03-05 11:29:54 +000039#include "llvm/ADT/Hashing.h"
Chris Lattnered58a6f2010-11-30 22:25:26 +000040#include "llvm/ADT/SmallPtrSet.h"
41#include "llvm/ADT/Statistic.h"
Owen Andersona04a0642010-11-18 18:32:40 +000042#include "llvm/Support/Allocator.h"
Owen Andersonaa0b6342008-06-19 19:57:25 +000043#include "llvm/Support/CommandLine.h"
Chris Lattner9f8a6a72008-03-29 04:36:18 +000044#include "llvm/Support/Debug.h"
Chris Lattnerfaf815b2009-12-06 01:57:02 +000045#include "llvm/Support/IRBuilder.h"
Duncan Sands02b5e722011-10-05 14:28:49 +000046#include "llvm/Support/PatternMatch.h"
Owen Anderson1ad2cb72007-07-24 17:55:58 +000047using namespace llvm;
Duncan Sands02b5e722011-10-05 14:28:49 +000048using namespace PatternMatch;
Owen Anderson1ad2cb72007-07-24 17:55:58 +000049
Bill Wendling70ded192008-12-22 22:14:07 +000050STATISTIC(NumGVNInstr, "Number of instructions deleted");
51STATISTIC(NumGVNLoad, "Number of loads deleted");
52STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
Owen Anderson961edc82008-07-15 16:28:06 +000053STATISTIC(NumGVNBlocks, "Number of blocks merged");
Duncan Sands02b5e722011-10-05 14:28:49 +000054STATISTIC(NumGVNSimpl, "Number of instructions simplified");
55STATISTIC(NumGVNEqProp, "Number of equalities propagated");
Bill Wendling70ded192008-12-22 22:14:07 +000056STATISTIC(NumPRELoad, "Number of loads PRE'd");
Chris Lattnerd27290d2008-03-22 04:13:49 +000057
Evan Cheng88d11c02008-06-20 01:01:07 +000058static cl::opt<bool> EnablePRE("enable-pre",
Owen Andersonc2b856e2008-07-17 19:41:00 +000059 cl::init(true), cl::Hidden);
Dan Gohmanc915c952009-06-15 18:30:15 +000060static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
Owen Andersonaa0b6342008-06-19 19:57:25 +000061
Owen Anderson1ad2cb72007-07-24 17:55:58 +000062//===----------------------------------------------------------------------===//
63// ValueTable Class
64//===----------------------------------------------------------------------===//
65
66/// This class holds the mapping between values and value numbers. It is used
67/// as an efficient mechanism to determine the expression-wise equivalence of
68/// two values.
69namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000070 struct Expression {
Owen Anderson30f4a552011-01-03 19:00:11 +000071 uint32_t opcode;
Chris Lattnerdb125cf2011-07-18 04:54:35 +000072 Type *type;
Owen Anderson1ad2cb72007-07-24 17:55:58 +000073 SmallVector<uint32_t, 4> varargs;
Daniel Dunbara279bc32009-09-20 02:20:51 +000074
Chris Lattnerad3ba6a2011-04-28 18:08:21 +000075 Expression(uint32_t o = ~2U) : opcode(o) { }
Daniel Dunbara279bc32009-09-20 02:20:51 +000076
Owen Anderson1ad2cb72007-07-24 17:55:58 +000077 bool operator==(const Expression &other) const {
78 if (opcode != other.opcode)
79 return false;
Chris Lattnerad3ba6a2011-04-28 18:08:21 +000080 if (opcode == ~0U || opcode == ~1U)
Owen Anderson1ad2cb72007-07-24 17:55:58 +000081 return true;
Chris Lattnerad3ba6a2011-04-28 18:08:21 +000082 if (type != other.type)
Owen Anderson1ad2cb72007-07-24 17:55:58 +000083 return false;
Chris Lattnerad3ba6a2011-04-28 18:08:21 +000084 if (varargs != other.varargs)
Benjamin Krameraad94aa2010-12-21 21:30:19 +000085 return false;
86 return true;
Owen Anderson1ad2cb72007-07-24 17:55:58 +000087 }
Chandler Carruth16003d02012-03-05 11:29:54 +000088
89 friend hash_code hash_value(const Expression &Value) {
90 // Optimize for the common case.
91 if (Value.varargs.empty())
92 return hash_combine(Value.opcode, Value.type);
93
94 return hash_combine(Value.opcode, Value.type,
95 hash_combine_range(Value.varargs.begin(),
96 Value.varargs.end()));
97 }
Owen Anderson1ad2cb72007-07-24 17:55:58 +000098 };
Daniel Dunbara279bc32009-09-20 02:20:51 +000099
Chris Lattner3e8b6632009-09-02 06:11:42 +0000100 class ValueTable {
Chris Lattnerad3ba6a2011-04-28 18:08:21 +0000101 DenseMap<Value*, uint32_t> valueNumbering;
102 DenseMap<Expression, uint32_t> expressionNumbering;
103 AliasAnalysis *AA;
104 MemoryDependenceAnalysis *MD;
105 DominatorTree *DT;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000106
Chris Lattnerad3ba6a2011-04-28 18:08:21 +0000107 uint32_t nextValueNumber;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000108
Chris Lattnerad3ba6a2011-04-28 18:08:21 +0000109 Expression create_expression(Instruction* I);
Duncan Sands669011f2012-02-27 08:14:30 +0000110 Expression create_cmp_expression(unsigned Opcode,
111 CmpInst::Predicate Predicate,
112 Value *LHS, Value *RHS);
Lang Hames1fb09552011-07-08 01:50:54 +0000113 Expression create_extractvalue_expression(ExtractValueInst* EI);
Chris Lattnerad3ba6a2011-04-28 18:08:21 +0000114 uint32_t lookup_or_add_call(CallInst* C);
115 public:
116 ValueTable() : nextValueNumber(1) { }
117 uint32_t lookup_or_add(Value *V);
118 uint32_t lookup(Value *V) const;
Duncan Sands669011f2012-02-27 08:14:30 +0000119 uint32_t lookup_or_add_cmp(unsigned Opcode, CmpInst::Predicate Pred,
120 Value *LHS, Value *RHS);
Chris Lattnerad3ba6a2011-04-28 18:08:21 +0000121 void add(Value *V, uint32_t num);
122 void clear();
123 void erase(Value *v);
124 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
125 AliasAnalysis *getAliasAnalysis() const { return AA; }
126 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
127 void setDomTree(DominatorTree* D) { DT = D; }
128 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
129 void verifyRemoved(const Value *) const;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000130 };
131}
132
133namespace llvm {
Chris Lattner76c1b972007-09-17 18:34:04 +0000134template <> struct DenseMapInfo<Expression> {
Owen Anderson830db6a2007-08-02 18:16:06 +0000135 static inline Expression getEmptyKey() {
Owen Anderson30f4a552011-01-03 19:00:11 +0000136 return ~0U;
Owen Anderson830db6a2007-08-02 18:16:06 +0000137 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000138
Owen Anderson830db6a2007-08-02 18:16:06 +0000139 static inline Expression getTombstoneKey() {
Owen Anderson30f4a552011-01-03 19:00:11 +0000140 return ~1U;
Owen Anderson830db6a2007-08-02 18:16:06 +0000141 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000142
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000143 static unsigned getHashValue(const Expression e) {
Chandler Carruth16003d02012-03-05 11:29:54 +0000144 using llvm::hash_value;
145 return static_cast<unsigned>(hash_value(e));
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000146 }
Chris Lattner76c1b972007-09-17 18:34:04 +0000147 static bool isEqual(const Expression &LHS, const Expression &RHS) {
148 return LHS == RHS;
149 }
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000150};
Chris Lattner4bbf4ee2009-12-15 07:26:43 +0000151
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000152}
153
154//===----------------------------------------------------------------------===//
155// ValueTable Internal Functions
156//===----------------------------------------------------------------------===//
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000157
Owen Anderson30f4a552011-01-03 19:00:11 +0000158Expression ValueTable::create_expression(Instruction *I) {
159 Expression e;
160 e.type = I->getType();
161 e.opcode = I->getOpcode();
162 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
163 OI != OE; ++OI)
164 e.varargs.push_back(lookup_or_add(*OI));
Duncan Sandse170c762012-02-24 15:16:31 +0000165 if (I->isCommutative()) {
166 // Ensure that commutative instructions that only differ by a permutation
167 // of their operands get the same value number by sorting the operand value
168 // numbers. Since all commutative instructions have two operands it is more
169 // efficient to sort by hand rather than using, say, std::sort.
170 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
171 if (e.varargs[0] > e.varargs[1])
172 std::swap(e.varargs[0], e.varargs[1]);
173 }
Owen Anderson30f4a552011-01-03 19:00:11 +0000174
Lang Hames1fb09552011-07-08 01:50:54 +0000175 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
Duncan Sandse170c762012-02-24 15:16:31 +0000176 // Sort the operand value numbers so x<y and y>x get the same value number.
177 CmpInst::Predicate Predicate = C->getPredicate();
178 if (e.varargs[0] > e.varargs[1]) {
179 std::swap(e.varargs[0], e.varargs[1]);
180 Predicate = CmpInst::getSwappedPredicate(Predicate);
181 }
182 e.opcode = (C->getOpcode() << 8) | Predicate;
Owen Anderson30f4a552011-01-03 19:00:11 +0000183 } else if (InsertValueInst *E = dyn_cast<InsertValueInst>(I)) {
184 for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
185 II != IE; ++II)
186 e.varargs.push_back(*II);
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000187 }
Owen Anderson30f4a552011-01-03 19:00:11 +0000188
Owen Andersond41ed4e2009-10-19 22:14:22 +0000189 return e;
190}
191
Duncan Sands669011f2012-02-27 08:14:30 +0000192Expression ValueTable::create_cmp_expression(unsigned Opcode,
193 CmpInst::Predicate Predicate,
194 Value *LHS, Value *RHS) {
195 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
196 "Not a comparison!");
197 Expression e;
198 e.type = CmpInst::makeCmpResultType(LHS->getType());
199 e.varargs.push_back(lookup_or_add(LHS));
200 e.varargs.push_back(lookup_or_add(RHS));
201
202 // Sort the operand value numbers so x<y and y>x get the same value number.
203 if (e.varargs[0] > e.varargs[1]) {
204 std::swap(e.varargs[0], e.varargs[1]);
205 Predicate = CmpInst::getSwappedPredicate(Predicate);
206 }
207 e.opcode = (Opcode << 8) | Predicate;
208 return e;
209}
210
Lang Hames1fb09552011-07-08 01:50:54 +0000211Expression ValueTable::create_extractvalue_expression(ExtractValueInst *EI) {
212 assert(EI != 0 && "Not an ExtractValueInst?");
213 Expression e;
214 e.type = EI->getType();
215 e.opcode = 0;
216
217 IntrinsicInst *I = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
218 if (I != 0 && EI->getNumIndices() == 1 && *EI->idx_begin() == 0 ) {
219 // EI might be an extract from one of our recognised intrinsics. If it
220 // is we'll synthesize a semantically equivalent expression instead on
221 // an extract value expression.
222 switch (I->getIntrinsicID()) {
Lang Hamesbd1828c2011-07-09 00:25:11 +0000223 case Intrinsic::sadd_with_overflow:
Lang Hames1fb09552011-07-08 01:50:54 +0000224 case Intrinsic::uadd_with_overflow:
225 e.opcode = Instruction::Add;
226 break;
Lang Hamesbd1828c2011-07-09 00:25:11 +0000227 case Intrinsic::ssub_with_overflow:
Lang Hames1fb09552011-07-08 01:50:54 +0000228 case Intrinsic::usub_with_overflow:
229 e.opcode = Instruction::Sub;
230 break;
Lang Hamesbd1828c2011-07-09 00:25:11 +0000231 case Intrinsic::smul_with_overflow:
Lang Hames1fb09552011-07-08 01:50:54 +0000232 case Intrinsic::umul_with_overflow:
233 e.opcode = Instruction::Mul;
234 break;
235 default:
236 break;
237 }
238
239 if (e.opcode != 0) {
240 // Intrinsic recognized. Grab its args to finish building the expression.
241 assert(I->getNumArgOperands() == 2 &&
242 "Expect two args for recognised intrinsics.");
243 e.varargs.push_back(lookup_or_add(I->getArgOperand(0)));
244 e.varargs.push_back(lookup_or_add(I->getArgOperand(1)));
245 return e;
246 }
247 }
248
249 // Not a recognised intrinsic. Fall back to producing an extract value
250 // expression.
251 e.opcode = EI->getOpcode();
252 for (Instruction::op_iterator OI = EI->op_begin(), OE = EI->op_end();
253 OI != OE; ++OI)
254 e.varargs.push_back(lookup_or_add(*OI));
255
256 for (ExtractValueInst::idx_iterator II = EI->idx_begin(), IE = EI->idx_end();
257 II != IE; ++II)
258 e.varargs.push_back(*II);
259
260 return e;
261}
262
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000263//===----------------------------------------------------------------------===//
264// ValueTable External Functions
265//===----------------------------------------------------------------------===//
266
Owen Andersonb2303722008-06-18 21:41:49 +0000267/// add - Insert a value into the table with a specified value number.
Chris Lattnerb2412a82009-09-21 02:42:51 +0000268void ValueTable::add(Value *V, uint32_t num) {
Owen Andersonb2303722008-06-18 21:41:49 +0000269 valueNumbering.insert(std::make_pair(V, num));
270}
271
Owen Andersond41ed4e2009-10-19 22:14:22 +0000272uint32_t ValueTable::lookup_or_add_call(CallInst* C) {
273 if (AA->doesNotAccessMemory(C)) {
274 Expression exp = create_expression(C);
275 uint32_t& e = expressionNumbering[exp];
276 if (!e) e = nextValueNumber++;
277 valueNumbering[C] = e;
278 return e;
279 } else if (AA->onlyReadsMemory(C)) {
280 Expression exp = create_expression(C);
281 uint32_t& e = expressionNumbering[exp];
282 if (!e) {
283 e = nextValueNumber++;
284 valueNumbering[C] = e;
285 return e;
286 }
Dan Gohman4ec01b22009-11-14 02:27:51 +0000287 if (!MD) {
288 e = nextValueNumber++;
289 valueNumbering[C] = e;
290 return e;
291 }
Owen Andersond41ed4e2009-10-19 22:14:22 +0000292
293 MemDepResult local_dep = MD->getDependency(C);
294
295 if (!local_dep.isDef() && !local_dep.isNonLocal()) {
296 valueNumbering[C] = nextValueNumber;
297 return nextValueNumber++;
298 }
299
300 if (local_dep.isDef()) {
301 CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
302
Gabor Greif237e1da2010-06-30 09:17:53 +0000303 if (local_cdep->getNumArgOperands() != C->getNumArgOperands()) {
Owen Andersond41ed4e2009-10-19 22:14:22 +0000304 valueNumbering[C] = nextValueNumber;
305 return nextValueNumber++;
306 }
307
Gabor Greifd883a9d2010-06-24 10:17:17 +0000308 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
309 uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
310 uint32_t cd_vn = lookup_or_add(local_cdep->getArgOperand(i));
Owen Andersond41ed4e2009-10-19 22:14:22 +0000311 if (c_vn != cd_vn) {
312 valueNumbering[C] = nextValueNumber;
313 return nextValueNumber++;
314 }
315 }
316
317 uint32_t v = lookup_or_add(local_cdep);
318 valueNumbering[C] = v;
319 return v;
320 }
321
322 // Non-local case.
323 const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
324 MD->getNonLocalCallDependency(CallSite(C));
Eli Friedmana990e072011-06-15 00:47:34 +0000325 // FIXME: Move the checking logic to MemDep!
Owen Andersond41ed4e2009-10-19 22:14:22 +0000326 CallInst* cdep = 0;
327
328 // Check to see if we have a single dominating call instruction that is
329 // identical to C.
330 for (unsigned i = 0, e = deps.size(); i != e; ++i) {
Chris Lattnere18b9712009-12-09 07:08:01 +0000331 const NonLocalDepEntry *I = &deps[i];
Chris Lattnere18b9712009-12-09 07:08:01 +0000332 if (I->getResult().isNonLocal())
Owen Andersond41ed4e2009-10-19 22:14:22 +0000333 continue;
334
Eli Friedmana990e072011-06-15 00:47:34 +0000335 // We don't handle non-definitions. If we already have a call, reject
Owen Andersond41ed4e2009-10-19 22:14:22 +0000336 // instruction dependencies.
Eli Friedmana990e072011-06-15 00:47:34 +0000337 if (!I->getResult().isDef() || cdep != 0) {
Owen Andersond41ed4e2009-10-19 22:14:22 +0000338 cdep = 0;
339 break;
340 }
341
Chris Lattnere18b9712009-12-09 07:08:01 +0000342 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst());
Owen Andersond41ed4e2009-10-19 22:14:22 +0000343 // FIXME: All duplicated with non-local case.
Chris Lattnere18b9712009-12-09 07:08:01 +0000344 if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){
Owen Andersond41ed4e2009-10-19 22:14:22 +0000345 cdep = NonLocalDepCall;
346 continue;
347 }
348
349 cdep = 0;
350 break;
351 }
352
353 if (!cdep) {
354 valueNumbering[C] = nextValueNumber;
355 return nextValueNumber++;
356 }
357
Gabor Greif237e1da2010-06-30 09:17:53 +0000358 if (cdep->getNumArgOperands() != C->getNumArgOperands()) {
Owen Andersond41ed4e2009-10-19 22:14:22 +0000359 valueNumbering[C] = nextValueNumber;
360 return nextValueNumber++;
361 }
Gabor Greifd883a9d2010-06-24 10:17:17 +0000362 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
363 uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
364 uint32_t cd_vn = lookup_or_add(cdep->getArgOperand(i));
Owen Andersond41ed4e2009-10-19 22:14:22 +0000365 if (c_vn != cd_vn) {
366 valueNumbering[C] = nextValueNumber;
367 return nextValueNumber++;
368 }
369 }
370
371 uint32_t v = lookup_or_add(cdep);
372 valueNumbering[C] = v;
373 return v;
374
375 } else {
376 valueNumbering[C] = nextValueNumber;
377 return nextValueNumber++;
378 }
379}
380
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000381/// lookup_or_add - Returns the value number for the specified value, assigning
382/// it a new number if it did not have one before.
Chris Lattnerb2412a82009-09-21 02:42:51 +0000383uint32_t ValueTable::lookup_or_add(Value *V) {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000384 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
385 if (VI != valueNumbering.end())
386 return VI->second;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000387
Owen Andersond41ed4e2009-10-19 22:14:22 +0000388 if (!isa<Instruction>(V)) {
Owen Anderson158d86e2009-10-19 21:14:57 +0000389 valueNumbering[V] = nextValueNumber;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000390 return nextValueNumber++;
391 }
Owen Andersond41ed4e2009-10-19 22:14:22 +0000392
393 Instruction* I = cast<Instruction>(V);
394 Expression exp;
395 switch (I->getOpcode()) {
396 case Instruction::Call:
397 return lookup_or_add_call(cast<CallInst>(I));
398 case Instruction::Add:
399 case Instruction::FAdd:
400 case Instruction::Sub:
401 case Instruction::FSub:
402 case Instruction::Mul:
403 case Instruction::FMul:
404 case Instruction::UDiv:
405 case Instruction::SDiv:
406 case Instruction::FDiv:
407 case Instruction::URem:
408 case Instruction::SRem:
409 case Instruction::FRem:
410 case Instruction::Shl:
411 case Instruction::LShr:
412 case Instruction::AShr:
413 case Instruction::And:
414 case Instruction::Or :
415 case Instruction::Xor:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000416 case Instruction::ICmp:
417 case Instruction::FCmp:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000418 case Instruction::Trunc:
419 case Instruction::ZExt:
420 case Instruction::SExt:
421 case Instruction::FPToUI:
422 case Instruction::FPToSI:
423 case Instruction::UIToFP:
424 case Instruction::SIToFP:
425 case Instruction::FPTrunc:
426 case Instruction::FPExt:
427 case Instruction::PtrToInt:
428 case Instruction::IntToPtr:
429 case Instruction::BitCast:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000430 case Instruction::Select:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000431 case Instruction::ExtractElement:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000432 case Instruction::InsertElement:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000433 case Instruction::ShuffleVector:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000434 case Instruction::InsertValue:
Owen Andersond41ed4e2009-10-19 22:14:22 +0000435 case Instruction::GetElementPtr:
Owen Anderson30f4a552011-01-03 19:00:11 +0000436 exp = create_expression(I);
Owen Andersond41ed4e2009-10-19 22:14:22 +0000437 break;
Lang Hames1fb09552011-07-08 01:50:54 +0000438 case Instruction::ExtractValue:
439 exp = create_extractvalue_expression(cast<ExtractValueInst>(I));
440 break;
Owen Andersond41ed4e2009-10-19 22:14:22 +0000441 default:
442 valueNumbering[V] = nextValueNumber;
443 return nextValueNumber++;
444 }
445
446 uint32_t& e = expressionNumbering[exp];
447 if (!e) e = nextValueNumber++;
448 valueNumbering[V] = e;
449 return e;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000450}
451
452/// lookup - Returns the value number of the specified value. Fails if
453/// the value has not yet been numbered.
Chris Lattnerb2412a82009-09-21 02:42:51 +0000454uint32_t ValueTable::lookup(Value *V) const {
Jeffrey Yasskin81cf4322009-11-10 01:02:17 +0000455 DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
Chris Lattner88365bb2008-03-21 21:14:38 +0000456 assert(VI != valueNumbering.end() && "Value not numbered?");
457 return VI->second;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000458}
459
Duncan Sands669011f2012-02-27 08:14:30 +0000460/// lookup_or_add_cmp - Returns the value number of the given comparison,
461/// assigning it a new number if it did not have one before. Useful when
462/// we deduced the result of a comparison, but don't immediately have an
463/// instruction realizing that comparison to hand.
464uint32_t ValueTable::lookup_or_add_cmp(unsigned Opcode,
465 CmpInst::Predicate Predicate,
466 Value *LHS, Value *RHS) {
467 Expression exp = create_cmp_expression(Opcode, Predicate, LHS, RHS);
468 uint32_t& e = expressionNumbering[exp];
469 if (!e) e = nextValueNumber++;
470 return e;
471}
472
Chris Lattnerad3ba6a2011-04-28 18:08:21 +0000473/// clear - Remove all entries from the ValueTable.
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000474void ValueTable::clear() {
475 valueNumbering.clear();
476 expressionNumbering.clear();
477 nextValueNumber = 1;
478}
479
Chris Lattnerad3ba6a2011-04-28 18:08:21 +0000480/// erase - Remove a value from the value numbering.
Chris Lattnerb2412a82009-09-21 02:42:51 +0000481void ValueTable::erase(Value *V) {
Owen Andersonbf7d0bc2007-07-31 23:27:13 +0000482 valueNumbering.erase(V);
483}
484
Bill Wendling246dbbb2008-12-22 21:36:08 +0000485/// verifyRemoved - Verify that the value is removed from all internal data
486/// structures.
487void ValueTable::verifyRemoved(const Value *V) const {
Jeffrey Yasskin81cf4322009-11-10 01:02:17 +0000488 for (DenseMap<Value*, uint32_t>::const_iterator
Bill Wendling246dbbb2008-12-22 21:36:08 +0000489 I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
490 assert(I->first != V && "Inst still occurs in value numbering map!");
491 }
492}
493
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000494//===----------------------------------------------------------------------===//
Bill Wendling30788b82008-12-22 22:32:22 +0000495// GVN Pass
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000496//===----------------------------------------------------------------------===//
497
498namespace {
499
Chris Lattner3e8b6632009-09-02 06:11:42 +0000500 class GVN : public FunctionPass {
Dan Gohman4ec01b22009-11-14 02:27:51 +0000501 bool NoLoads;
Chris Lattner663e4412008-12-01 00:40:32 +0000502 MemoryDependenceAnalysis *MD;
503 DominatorTree *DT;
Chris Lattner4756ecb2011-04-28 16:36:48 +0000504 const TargetData *TD;
Chad Rosier618c1db2011-12-01 03:08:23 +0000505 const TargetLibraryInfo *TLI;
506
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000507 ValueTable VN;
Owen Andersona04a0642010-11-18 18:32:40 +0000508
Owen Andersonb1602ab2011-01-04 19:29:46 +0000509 /// LeaderTable - A mapping from value numbers to lists of Value*'s that
Owen Anderson7a75d612011-01-04 19:13:25 +0000510 /// have that value number. Use findLeader to query it.
511 struct LeaderTableEntry {
Owen Andersonf0568382010-12-21 23:54:34 +0000512 Value *Val;
513 BasicBlock *BB;
Owen Anderson7a75d612011-01-04 19:13:25 +0000514 LeaderTableEntry *Next;
Owen Andersonf0568382010-12-21 23:54:34 +0000515 };
Owen Andersonb1602ab2011-01-04 19:29:46 +0000516 DenseMap<uint32_t, LeaderTableEntry> LeaderTable;
Owen Andersona04a0642010-11-18 18:32:40 +0000517 BumpPtrAllocator TableAllocator;
Owen Anderson68c26392010-11-19 22:48:40 +0000518
Chris Lattnerf07054d2011-04-28 16:18:52 +0000519 SmallVector<Instruction*, 8> InstrsToErase;
Chris Lattner4756ecb2011-04-28 16:36:48 +0000520 public:
521 static char ID; // Pass identification, replacement for typeid
522 explicit GVN(bool noloads = false)
523 : FunctionPass(ID), NoLoads(noloads), MD(0) {
524 initializeGVNPass(*PassRegistry::getPassRegistry());
525 }
526
527 bool runOnFunction(Function &F);
Chris Lattnerf07054d2011-04-28 16:18:52 +0000528
Chris Lattner4756ecb2011-04-28 16:36:48 +0000529 /// markInstructionForDeletion - This removes the specified instruction from
530 /// our various maps and marks it for deletion.
531 void markInstructionForDeletion(Instruction *I) {
532 VN.erase(I);
533 InstrsToErase.push_back(I);
534 }
535
536 const TargetData *getTargetData() const { return TD; }
537 DominatorTree &getDominatorTree() const { return *DT; }
538 AliasAnalysis *getAliasAnalysis() const { return VN.getAliasAnalysis(); }
Chris Lattnerad3ba6a2011-04-28 18:08:21 +0000539 MemoryDependenceAnalysis &getMemDep() const { return *MD; }
Chris Lattner4756ecb2011-04-28 16:36:48 +0000540 private:
Owen Andersonb1602ab2011-01-04 19:29:46 +0000541 /// addToLeaderTable - Push a new Value to the LeaderTable onto the list for
Owen Anderson68c26392010-11-19 22:48:40 +0000542 /// its value number.
Owen Anderson7a75d612011-01-04 19:13:25 +0000543 void addToLeaderTable(uint32_t N, Value *V, BasicBlock *BB) {
Chris Lattner0a9e3d62011-04-28 18:15:47 +0000544 LeaderTableEntry &Curr = LeaderTable[N];
Owen Andersonf0568382010-12-21 23:54:34 +0000545 if (!Curr.Val) {
546 Curr.Val = V;
547 Curr.BB = BB;
Owen Andersona04a0642010-11-18 18:32:40 +0000548 return;
549 }
550
Chris Lattner0a9e3d62011-04-28 18:15:47 +0000551 LeaderTableEntry *Node = TableAllocator.Allocate<LeaderTableEntry>();
Owen Andersonf0568382010-12-21 23:54:34 +0000552 Node->Val = V;
553 Node->BB = BB;
554 Node->Next = Curr.Next;
555 Curr.Next = Node;
Owen Andersona04a0642010-11-18 18:32:40 +0000556 }
557
Owen Andersonb1602ab2011-01-04 19:29:46 +0000558 /// removeFromLeaderTable - Scan the list of values corresponding to a given
559 /// value number, and remove the given value if encountered.
Owen Anderson7a75d612011-01-04 19:13:25 +0000560 void removeFromLeaderTable(uint32_t N, Value *V, BasicBlock *BB) {
561 LeaderTableEntry* Prev = 0;
Owen Andersonb1602ab2011-01-04 19:29:46 +0000562 LeaderTableEntry* Curr = &LeaderTable[N];
Owen Andersona04a0642010-11-18 18:32:40 +0000563
Owen Andersonf0568382010-12-21 23:54:34 +0000564 while (Curr->Val != V || Curr->BB != BB) {
Owen Andersona04a0642010-11-18 18:32:40 +0000565 Prev = Curr;
Owen Andersonf0568382010-12-21 23:54:34 +0000566 Curr = Curr->Next;
Owen Andersona04a0642010-11-18 18:32:40 +0000567 }
568
569 if (Prev) {
Owen Andersonf0568382010-12-21 23:54:34 +0000570 Prev->Next = Curr->Next;
Owen Andersona04a0642010-11-18 18:32:40 +0000571 } else {
Owen Andersonf0568382010-12-21 23:54:34 +0000572 if (!Curr->Next) {
573 Curr->Val = 0;
574 Curr->BB = 0;
Owen Andersona04a0642010-11-18 18:32:40 +0000575 } else {
Owen Anderson7a75d612011-01-04 19:13:25 +0000576 LeaderTableEntry* Next = Curr->Next;
Owen Andersonf0568382010-12-21 23:54:34 +0000577 Curr->Val = Next->Val;
578 Curr->BB = Next->BB;
Owen Anderson680ac4f2011-01-04 19:10:54 +0000579 Curr->Next = Next->Next;
Owen Andersona04a0642010-11-18 18:32:40 +0000580 }
581 }
582 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000583
Bob Wilson484d4a32010-02-16 19:51:59 +0000584 // List of critical edges to be split between iterations.
585 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
586
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000587 // This transformation requires dominator postdominator info
588 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000589 AU.addRequired<DominatorTree>();
Chad Rosier618c1db2011-12-01 03:08:23 +0000590 AU.addRequired<TargetLibraryInfo>();
Dan Gohman4ec01b22009-11-14 02:27:51 +0000591 if (!NoLoads)
592 AU.addRequired<MemoryDependenceAnalysis>();
Owen Andersonb388ca92007-10-18 19:39:33 +0000593 AU.addRequired<AliasAnalysis>();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000594
Owen Andersonb70a5712008-06-23 17:49:45 +0000595 AU.addPreserved<DominatorTree>();
Owen Andersonb388ca92007-10-18 19:39:33 +0000596 AU.addPreserved<AliasAnalysis>();
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000597 }
Chris Lattner4756ecb2011-04-28 16:36:48 +0000598
Daniel Dunbara279bc32009-09-20 02:20:51 +0000599
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000600 // Helper fuctions
601 // FIXME: eliminate or document these better
Chris Lattnerf07054d2011-04-28 16:18:52 +0000602 bool processLoad(LoadInst *L);
603 bool processInstruction(Instruction *I);
604 bool processNonLocalLoad(LoadInst *L);
Chris Lattnerb2412a82009-09-21 02:42:51 +0000605 bool processBlock(BasicBlock *BB);
Chris Lattnerf07054d2011-04-28 16:18:52 +0000606 void dump(DenseMap<uint32_t, Value*> &d);
Owen Anderson3e75a422007-08-14 18:04:11 +0000607 bool iterateOnFunction(Function &F);
Chris Lattnerf07054d2011-04-28 16:18:52 +0000608 bool performPRE(Function &F);
Owen Anderson7a75d612011-01-04 19:13:25 +0000609 Value *findLeader(BasicBlock *BB, uint32_t num);
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +0000610 void cleanupGlobalSets();
Bill Wendling246dbbb2008-12-22 21:36:08 +0000611 void verifyRemoved(const Instruction *I) const;
Bob Wilson484d4a32010-02-16 19:51:59 +0000612 bool splitCriticalEdges();
Duncan Sands02b5e722011-10-05 14:28:49 +0000613 unsigned replaceAllDominatedUsesWith(Value *From, Value *To,
614 BasicBlock *Root);
615 bool propagateEquality(Value *LHS, Value *RHS, BasicBlock *Root);
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000616 };
Daniel Dunbara279bc32009-09-20 02:20:51 +0000617
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000618 char GVN::ID = 0;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000619}
620
621// createGVNPass - The public interface to this file...
Bob Wilsonb29d7d22010-02-28 05:34:05 +0000622FunctionPass *llvm::createGVNPass(bool NoLoads) {
623 return new GVN(NoLoads);
Dan Gohman4ec01b22009-11-14 02:27:51 +0000624}
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000625
Owen Anderson2ab36d32010-10-12 19:48:12 +0000626INITIALIZE_PASS_BEGIN(GVN, "gvn", "Global Value Numbering", false, false)
627INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
628INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Chad Rosier618c1db2011-12-01 03:08:23 +0000629INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000630INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
631INITIALIZE_PASS_END(GVN, "gvn", "Global Value Numbering", false, false)
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000632
Owen Andersonb2303722008-06-18 21:41:49 +0000633void GVN::dump(DenseMap<uint32_t, Value*>& d) {
Dan Gohmanad12b262009-12-18 03:25:51 +0000634 errs() << "{\n";
Owen Andersonb2303722008-06-18 21:41:49 +0000635 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
Owen Anderson0cd32032007-07-25 19:57:03 +0000636 E = d.end(); I != E; ++I) {
Dan Gohmanad12b262009-12-18 03:25:51 +0000637 errs() << I->first << "\n";
Owen Anderson0cd32032007-07-25 19:57:03 +0000638 I->second->dump();
639 }
Dan Gohmanad12b262009-12-18 03:25:51 +0000640 errs() << "}\n";
Owen Anderson0cd32032007-07-25 19:57:03 +0000641}
642
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000643/// IsValueFullyAvailableInBlock - Return true if we can prove that the value
644/// we're analyzing is fully available in the specified block. As we go, keep
Chris Lattner72bc70d2008-12-05 07:49:08 +0000645/// track of which blocks we know are fully alive in FullyAvailableBlocks. This
646/// map is actually a tri-state map with the following values:
647/// 0) we know the block *is not* fully available.
648/// 1) we know the block *is* fully available.
649/// 2) we do not know whether the block is fully available or not, but we are
650/// currently speculating that it will be.
651/// 3) we are speculating for this block and have used that to speculate for
652/// other blocks.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000653static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
Chris Lattner72bc70d2008-12-05 07:49:08 +0000654 DenseMap<BasicBlock*, char> &FullyAvailableBlocks) {
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000655 // Optimistically assume that the block is fully available and check to see
656 // if we already know about this block in one lookup.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000657 std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
Chris Lattner72bc70d2008-12-05 07:49:08 +0000658 FullyAvailableBlocks.insert(std::make_pair(BB, 2));
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000659
660 // If the entry already existed for this block, return the precomputed value.
Chris Lattner72bc70d2008-12-05 07:49:08 +0000661 if (!IV.second) {
662 // If this is a speculative "available" value, mark it as being used for
663 // speculation of other blocks.
664 if (IV.first->second == 2)
665 IV.first->second = 3;
666 return IV.first->second != 0;
667 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000668
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000669 // Otherwise, see if it is fully available in all predecessors.
670 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000671
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000672 // If this block has no predecessors, it isn't live-in here.
673 if (PI == PE)
Chris Lattner72bc70d2008-12-05 07:49:08 +0000674 goto SpeculationFailure;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000675
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000676 for (; PI != PE; ++PI)
677 // If the value isn't fully available in one of our predecessors, then it
678 // isn't fully available in this block either. Undo our previous
679 // optimistic assumption and bail out.
680 if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
Chris Lattner72bc70d2008-12-05 07:49:08 +0000681 goto SpeculationFailure;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000682
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000683 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000684
Chris Lattner72bc70d2008-12-05 07:49:08 +0000685// SpeculationFailure - If we get here, we found out that this is not, after
686// all, a fully-available block. We have a problem if we speculated on this and
687// used the speculation to mark other blocks as available.
688SpeculationFailure:
689 char &BBVal = FullyAvailableBlocks[BB];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000690
Chris Lattner72bc70d2008-12-05 07:49:08 +0000691 // If we didn't speculate on this, just return with it set to false.
692 if (BBVal == 2) {
693 BBVal = 0;
694 return false;
695 }
696
697 // If we did speculate on this value, we could have blocks set to 1 that are
698 // incorrect. Walk the (transitive) successors of this block and mark them as
699 // 0 if set to one.
700 SmallVector<BasicBlock*, 32> BBWorklist;
701 BBWorklist.push_back(BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000702
Dan Gohman321a8132010-01-05 16:27:25 +0000703 do {
Chris Lattner72bc70d2008-12-05 07:49:08 +0000704 BasicBlock *Entry = BBWorklist.pop_back_val();
705 // Note that this sets blocks to 0 (unavailable) if they happen to not
706 // already be in FullyAvailableBlocks. This is safe.
707 char &EntryVal = FullyAvailableBlocks[Entry];
708 if (EntryVal == 0) continue; // Already unavailable.
709
710 // Mark as unavailable.
711 EntryVal = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000712
Chris Lattner72bc70d2008-12-05 07:49:08 +0000713 for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I)
714 BBWorklist.push_back(*I);
Dan Gohman321a8132010-01-05 16:27:25 +0000715 } while (!BBWorklist.empty());
Daniel Dunbara279bc32009-09-20 02:20:51 +0000716
Chris Lattner72bc70d2008-12-05 07:49:08 +0000717 return false;
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000718}
719
Chris Lattner771a5422009-09-20 20:09:34 +0000720
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000721/// CanCoerceMustAliasedValueToLoad - Return true if
722/// CoerceAvailableValueToLoadType will succeed.
723static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000724 Type *LoadTy,
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000725 const TargetData &TD) {
726 // If the loaded or stored value is an first class array or struct, don't try
727 // to transform them. We need to be able to bitcast to integer.
Duncan Sands1df98592010-02-16 11:11:14 +0000728 if (LoadTy->isStructTy() || LoadTy->isArrayTy() ||
729 StoredVal->getType()->isStructTy() ||
730 StoredVal->getType()->isArrayTy())
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000731 return false;
732
733 // The store has to be at least as big as the load.
734 if (TD.getTypeSizeInBits(StoredVal->getType()) <
735 TD.getTypeSizeInBits(LoadTy))
736 return false;
737
738 return true;
739}
740
741
Chris Lattner771a5422009-09-20 20:09:34 +0000742/// CoerceAvailableValueToLoadType - If we saw a store of a value to memory, and
743/// then a load from a must-aliased pointer of a different type, try to coerce
744/// the stored value. LoadedTy is the type of the load we want to replace and
745/// InsertPt is the place to insert new instructions.
746///
747/// If we can't do it, return null.
748static Value *CoerceAvailableValueToLoadType(Value *StoredVal,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000749 Type *LoadedTy,
Chris Lattner771a5422009-09-20 20:09:34 +0000750 Instruction *InsertPt,
751 const TargetData &TD) {
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000752 if (!CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, TD))
753 return 0;
754
Chris Lattner4034e142011-04-28 07:29:08 +0000755 // If this is already the right type, just return it.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000756 Type *StoredValTy = StoredVal->getType();
Chris Lattner771a5422009-09-20 20:09:34 +0000757
Jakub Staszak8cec7592011-09-02 14:57:37 +0000758 uint64_t StoreSize = TD.getTypeSizeInBits(StoredValTy);
759 uint64_t LoadSize = TD.getTypeSizeInBits(LoadedTy);
Chris Lattner771a5422009-09-20 20:09:34 +0000760
761 // If the store and reload are the same size, we can always reuse it.
762 if (StoreSize == LoadSize) {
Chris Lattner1f821512011-04-26 01:21:15 +0000763 // Pointer to Pointer -> use bitcast.
764 if (StoredValTy->isPointerTy() && LoadedTy->isPointerTy())
Chris Lattner771a5422009-09-20 20:09:34 +0000765 return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
Chris Lattner771a5422009-09-20 20:09:34 +0000766
767 // Convert source pointers to integers, which can be bitcast.
Duncan Sands1df98592010-02-16 11:11:14 +0000768 if (StoredValTy->isPointerTy()) {
Chris Lattner771a5422009-09-20 20:09:34 +0000769 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
770 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
771 }
772
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000773 Type *TypeToCastTo = LoadedTy;
Duncan Sands1df98592010-02-16 11:11:14 +0000774 if (TypeToCastTo->isPointerTy())
Chris Lattner771a5422009-09-20 20:09:34 +0000775 TypeToCastTo = TD.getIntPtrType(StoredValTy->getContext());
776
777 if (StoredValTy != TypeToCastTo)
778 StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
779
780 // Cast to pointer if the load needs a pointer type.
Duncan Sands1df98592010-02-16 11:11:14 +0000781 if (LoadedTy->isPointerTy())
Chris Lattner771a5422009-09-20 20:09:34 +0000782 StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
783
784 return StoredVal;
785 }
786
787 // If the loaded value is smaller than the available value, then we can
788 // extract out a piece from it. If the available value is too small, then we
789 // can't do anything.
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000790 assert(StoreSize >= LoadSize && "CanCoerceMustAliasedValueToLoad fail");
Chris Lattner771a5422009-09-20 20:09:34 +0000791
792 // Convert source pointers to integers, which can be manipulated.
Duncan Sands1df98592010-02-16 11:11:14 +0000793 if (StoredValTy->isPointerTy()) {
Chris Lattner771a5422009-09-20 20:09:34 +0000794 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
795 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
796 }
797
798 // Convert vectors and fp to integer, which can be manipulated.
Duncan Sands1df98592010-02-16 11:11:14 +0000799 if (!StoredValTy->isIntegerTy()) {
Chris Lattner771a5422009-09-20 20:09:34 +0000800 StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
801 StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
802 }
803
804 // If this is a big-endian system, we need to shift the value down to the low
805 // bits so that a truncate will work.
806 if (TD.isBigEndian()) {
807 Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
808 StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
809 }
810
811 // Truncate the integer to the right size now.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000812 Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
Chris Lattner771a5422009-09-20 20:09:34 +0000813 StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
814
815 if (LoadedTy == NewIntTy)
816 return StoredVal;
817
818 // If the result is a pointer, inttoptr.
Duncan Sands1df98592010-02-16 11:11:14 +0000819 if (LoadedTy->isPointerTy())
Chris Lattner771a5422009-09-20 20:09:34 +0000820 return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
821
822 // Otherwise, bitcast.
823 return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
824}
825
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000826/// AnalyzeLoadFromClobberingWrite - This function is called when we have a
827/// memdep query of a load that ends up being a clobbering memory write (store,
828/// memset, memcpy, memmove). This means that the write *may* provide bits used
829/// by the load but we can't be sure because the pointers don't mustalias.
830///
831/// Check this case to see if there is anything more we can do before we give
832/// up. This returns -1 if we have to give up, or a byte number in the stored
833/// value of the piece that feeds the load.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000834static int AnalyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr,
Chris Lattner03f17da2009-12-09 07:34:10 +0000835 Value *WritePtr,
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000836 uint64_t WriteSizeInBits,
Chris Lattner4fbd14e2009-09-21 06:48:08 +0000837 const TargetData &TD) {
Chad Rosier0cf6b992012-01-30 22:44:13 +0000838 // If the loaded or stored value is a first class array or struct, don't try
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000839 // to transform them. We need to be able to bitcast to integer.
Duncan Sands1df98592010-02-16 11:11:14 +0000840 if (LoadTy->isStructTy() || LoadTy->isArrayTy())
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000841 return -1;
842
Chris Lattnerca749402009-09-21 06:24:16 +0000843 int64_t StoreOffset = 0, LoadOffset = 0;
Chris Lattnered58a6f2010-11-30 22:25:26 +0000844 Value *StoreBase = GetPointerBaseWithConstantOffset(WritePtr, StoreOffset,TD);
845 Value *LoadBase = GetPointerBaseWithConstantOffset(LoadPtr, LoadOffset, TD);
Chris Lattnerca749402009-09-21 06:24:16 +0000846 if (StoreBase != LoadBase)
847 return -1;
848
849 // If the load and store are to the exact same address, they should have been
850 // a must alias. AA must have gotten confused.
Chris Lattner219d7742010-03-25 05:58:19 +0000851 // FIXME: Study to see if/when this happens. One case is forwarding a memset
852 // to a load from the base of the memset.
Chris Lattnerca749402009-09-21 06:24:16 +0000853#if 0
Chris Lattner219d7742010-03-25 05:58:19 +0000854 if (LoadOffset == StoreOffset) {
David Greenebf7f78e2010-01-05 01:27:17 +0000855 dbgs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
Chris Lattnerca749402009-09-21 06:24:16 +0000856 << "Base = " << *StoreBase << "\n"
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000857 << "Store Ptr = " << *WritePtr << "\n"
858 << "Store Offs = " << StoreOffset << "\n"
Chris Lattnerb6760b42009-12-10 00:04:46 +0000859 << "Load Ptr = " << *LoadPtr << "\n";
Chris Lattnerb3f927f2009-12-09 02:41:54 +0000860 abort();
Chris Lattnerca749402009-09-21 06:24:16 +0000861 }
Chris Lattner219d7742010-03-25 05:58:19 +0000862#endif
Chris Lattnerca749402009-09-21 06:24:16 +0000863
864 // If the load and store don't overlap at all, the store doesn't provide
865 // anything to the load. In this case, they really don't alias at all, AA
866 // must have gotten confused.
Chris Lattner03f17da2009-12-09 07:34:10 +0000867 uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy);
Chris Lattnerca749402009-09-21 06:24:16 +0000868
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000869 if ((WriteSizeInBits & 7) | (LoadSize & 7))
Chris Lattnerca749402009-09-21 06:24:16 +0000870 return -1;
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000871 uint64_t StoreSize = WriteSizeInBits >> 3; // Convert to bytes.
Chris Lattnerca749402009-09-21 06:24:16 +0000872 LoadSize >>= 3;
873
874
875 bool isAAFailure = false;
Chris Lattner219d7742010-03-25 05:58:19 +0000876 if (StoreOffset < LoadOffset)
Chris Lattnerca749402009-09-21 06:24:16 +0000877 isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
Chris Lattner219d7742010-03-25 05:58:19 +0000878 else
Chris Lattnerca749402009-09-21 06:24:16 +0000879 isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
Chris Lattner219d7742010-03-25 05:58:19 +0000880
Chris Lattnerca749402009-09-21 06:24:16 +0000881 if (isAAFailure) {
882#if 0
David Greenebf7f78e2010-01-05 01:27:17 +0000883 dbgs() << "STORE LOAD DEP WITH COMMON BASE:\n"
Chris Lattnerca749402009-09-21 06:24:16 +0000884 << "Base = " << *StoreBase << "\n"
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000885 << "Store Ptr = " << *WritePtr << "\n"
886 << "Store Offs = " << StoreOffset << "\n"
Chris Lattnerb6760b42009-12-10 00:04:46 +0000887 << "Load Ptr = " << *LoadPtr << "\n";
Chris Lattnerb3f927f2009-12-09 02:41:54 +0000888 abort();
Chris Lattnerca749402009-09-21 06:24:16 +0000889#endif
890 return -1;
891 }
892
893 // If the Load isn't completely contained within the stored bits, we don't
894 // have all the bits to feed it. We could do something crazy in the future
895 // (issue a smaller load then merge the bits in) but this seems unlikely to be
896 // valuable.
897 if (StoreOffset > LoadOffset ||
898 StoreOffset+StoreSize < LoadOffset+LoadSize)
899 return -1;
900
901 // Okay, we can do this transformation. Return the number of bytes into the
902 // store that the load is.
903 return LoadOffset-StoreOffset;
904}
905
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000906/// AnalyzeLoadFromClobberingStore - This function is called when we have a
907/// memdep query of a load that ends up being a clobbering store.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000908static int AnalyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr,
Chris Lattner4ca70fe2009-12-09 07:37:07 +0000909 StoreInst *DepSI,
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000910 const TargetData &TD) {
911 // Cannot handle reading from store of first-class aggregate yet.
Dan Gohman3355c4e2010-11-10 19:03:33 +0000912 if (DepSI->getValueOperand()->getType()->isStructTy() ||
913 DepSI->getValueOperand()->getType()->isArrayTy())
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000914 return -1;
915
916 Value *StorePtr = DepSI->getPointerOperand();
Dan Gohman3355c4e2010-11-10 19:03:33 +0000917 uint64_t StoreSize =TD.getTypeSizeInBits(DepSI->getValueOperand()->getType());
Chris Lattner4ca70fe2009-12-09 07:37:07 +0000918 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
Chris Lattner03f17da2009-12-09 07:34:10 +0000919 StorePtr, StoreSize, TD);
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000920}
921
Chris Lattner1f821512011-04-26 01:21:15 +0000922/// AnalyzeLoadFromClobberingLoad - This function is called when we have a
923/// memdep query of a load that ends up being clobbered by another load. See if
924/// the other load can feed into the second load.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000925static int AnalyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr,
Chris Lattner1f821512011-04-26 01:21:15 +0000926 LoadInst *DepLI, const TargetData &TD){
927 // Cannot handle reading from store of first-class aggregate yet.
928 if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy())
929 return -1;
930
931 Value *DepPtr = DepLI->getPointerOperand();
932 uint64_t DepSize = TD.getTypeSizeInBits(DepLI->getType());
Chris Lattner4034e142011-04-28 07:29:08 +0000933 int R = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, TD);
934 if (R != -1) return R;
935
936 // If we have a load/load clobber an DepLI can be widened to cover this load,
937 // then we should widen it!
938 int64_t LoadOffs = 0;
939 const Value *LoadBase =
940 GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, TD);
941 unsigned LoadSize = TD.getTypeStoreSize(LoadTy);
942
943 unsigned Size = MemoryDependenceAnalysis::
944 getLoadLoadClobberFullWidthSize(LoadBase, LoadOffs, LoadSize, DepLI, TD);
945 if (Size == 0) return -1;
946
947 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size*8, TD);
Chris Lattner1f821512011-04-26 01:21:15 +0000948}
949
950
951
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000952static int AnalyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr,
Chris Lattner4ca70fe2009-12-09 07:37:07 +0000953 MemIntrinsic *MI,
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000954 const TargetData &TD) {
955 // If the mem operation is a non-constant size, we can't handle it.
956 ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength());
957 if (SizeCst == 0) return -1;
958 uint64_t MemSizeInBits = SizeCst->getZExtValue()*8;
Chris Lattnerbc9a28d2009-12-06 05:29:56 +0000959
960 // If this is memset, we just need to see if the offset is valid in the size
961 // of the memset..
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000962 if (MI->getIntrinsicID() == Intrinsic::memset)
Chris Lattner4ca70fe2009-12-09 07:37:07 +0000963 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
964 MemSizeInBits, TD);
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000965
Chris Lattnerbc9a28d2009-12-06 05:29:56 +0000966 // If we have a memcpy/memmove, the only case we can handle is if this is a
967 // copy from constant memory. In that case, we can read directly from the
968 // constant memory.
969 MemTransferInst *MTI = cast<MemTransferInst>(MI);
970
971 Constant *Src = dyn_cast<Constant>(MTI->getSource());
972 if (Src == 0) return -1;
973
Dan Gohmanbd1801b2011-01-24 18:53:32 +0000974 GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Src, &TD));
Chris Lattnerbc9a28d2009-12-06 05:29:56 +0000975 if (GV == 0 || !GV->isConstant()) return -1;
976
977 // See if the access is within the bounds of the transfer.
Chris Lattner4ca70fe2009-12-09 07:37:07 +0000978 int Offset = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
979 MI->getDest(), MemSizeInBits, TD);
Chris Lattnerbc9a28d2009-12-06 05:29:56 +0000980 if (Offset == -1)
981 return Offset;
982
983 // Otherwise, see if we can constant fold a load from the constant with the
984 // offset applied as appropriate.
985 Src = ConstantExpr::getBitCast(Src,
986 llvm::Type::getInt8PtrTy(Src->getContext()));
987 Constant *OffsetCst =
988 ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
Jay Foaddab3d292011-07-21 14:31:17 +0000989 Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
Chris Lattner4ca70fe2009-12-09 07:37:07 +0000990 Src = ConstantExpr::getBitCast(Src, PointerType::getUnqual(LoadTy));
Chris Lattnerbc9a28d2009-12-06 05:29:56 +0000991 if (ConstantFoldLoadFromConstPtr(Src, &TD))
992 return Offset;
Chris Lattnerfaf815b2009-12-06 01:57:02 +0000993 return -1;
994}
995
Chris Lattnerca749402009-09-21 06:24:16 +0000996
997/// GetStoreValueForLoad - This function is called when we have a
998/// memdep query of a load that ends up being a clobbering store. This means
Chris Lattner4034e142011-04-28 07:29:08 +0000999/// that the store provides bits used by the load but we the pointers don't
1000/// mustalias. Check this case to see if there is anything more we can do
1001/// before we give up.
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001002static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001003 Type *LoadTy,
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001004 Instruction *InsertPt, const TargetData &TD){
Chris Lattnerca749402009-09-21 06:24:16 +00001005 LLVMContext &Ctx = SrcVal->getType()->getContext();
1006
Chris Lattner7944c212010-05-08 20:01:44 +00001007 uint64_t StoreSize = (TD.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
1008 uint64_t LoadSize = (TD.getTypeSizeInBits(LoadTy) + 7) / 8;
Chris Lattnerca749402009-09-21 06:24:16 +00001009
Chris Lattnerb2c6ae82009-12-09 18:13:28 +00001010 IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
Chris Lattnerca749402009-09-21 06:24:16 +00001011
1012 // Compute which bits of the stored value are being used by the load. Convert
1013 // to an integer type to start with.
Duncan Sands1df98592010-02-16 11:11:14 +00001014 if (SrcVal->getType()->isPointerTy())
Benjamin Kramera9390a42011-09-27 20:39:19 +00001015 SrcVal = Builder.CreatePtrToInt(SrcVal, TD.getIntPtrType(Ctx));
Duncan Sands1df98592010-02-16 11:11:14 +00001016 if (!SrcVal->getType()->isIntegerTy())
Benjamin Kramera9390a42011-09-27 20:39:19 +00001017 SrcVal = Builder.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize*8));
Chris Lattnerca749402009-09-21 06:24:16 +00001018
1019 // Shift the bits to the least significant depending on endianness.
1020 unsigned ShiftAmt;
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001021 if (TD.isLittleEndian())
Chris Lattnerca749402009-09-21 06:24:16 +00001022 ShiftAmt = Offset*8;
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001023 else
Chris Lattner19ad7842009-09-21 17:55:47 +00001024 ShiftAmt = (StoreSize-LoadSize-Offset)*8;
Chris Lattnerca749402009-09-21 06:24:16 +00001025
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001026 if (ShiftAmt)
Benjamin Kramera9390a42011-09-27 20:39:19 +00001027 SrcVal = Builder.CreateLShr(SrcVal, ShiftAmt);
Chris Lattnerca749402009-09-21 06:24:16 +00001028
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001029 if (LoadSize != StoreSize)
Benjamin Kramera9390a42011-09-27 20:39:19 +00001030 SrcVal = Builder.CreateTrunc(SrcVal, IntegerType::get(Ctx, LoadSize*8));
Chris Lattnerca749402009-09-21 06:24:16 +00001031
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001032 return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, TD);
Chris Lattnerca749402009-09-21 06:24:16 +00001033}
1034
Chad Rosier431985a2012-01-30 21:13:22 +00001035/// GetLoadValueForLoad - This function is called when we have a
Chris Lattner4034e142011-04-28 07:29:08 +00001036/// memdep query of a load that ends up being a clobbering load. This means
1037/// that the load *may* provide bits used by the load but we can't be sure
1038/// because the pointers don't mustalias. Check this case to see if there is
1039/// anything more we can do before we give up.
1040static Value *GetLoadValueForLoad(LoadInst *SrcVal, unsigned Offset,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001041 Type *LoadTy, Instruction *InsertPt,
Chris Lattner4756ecb2011-04-28 16:36:48 +00001042 GVN &gvn) {
1043 const TargetData &TD = *gvn.getTargetData();
Chris Lattner4034e142011-04-28 07:29:08 +00001044 // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to
1045 // widen SrcVal out to a larger load.
1046 unsigned SrcValSize = TD.getTypeStoreSize(SrcVal->getType());
1047 unsigned LoadSize = TD.getTypeStoreSize(LoadTy);
1048 if (Offset+LoadSize > SrcValSize) {
Eli Friedman56efe242011-08-17 22:22:24 +00001049 assert(SrcVal->isSimple() && "Cannot widen volatile/atomic load!");
1050 assert(SrcVal->getType()->isIntegerTy() && "Can't widen non-integer load");
Chris Lattner4034e142011-04-28 07:29:08 +00001051 // If we have a load/load clobber an DepLI can be widened to cover this
1052 // load, then we should widen it to the next power of 2 size big enough!
1053 unsigned NewLoadSize = Offset+LoadSize;
1054 if (!isPowerOf2_32(NewLoadSize))
1055 NewLoadSize = NextPowerOf2(NewLoadSize);
1056
1057 Value *PtrVal = SrcVal->getPointerOperand();
1058
Chris Lattner0a9e3d62011-04-28 18:15:47 +00001059 // Insert the new load after the old load. This ensures that subsequent
1060 // memdep queries will find the new load. We can't easily remove the old
1061 // load completely because it is already in the value numbering table.
1062 IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001063 Type *DestPTy =
Chris Lattner4034e142011-04-28 07:29:08 +00001064 IntegerType::get(LoadTy->getContext(), NewLoadSize*8);
1065 DestPTy = PointerType::get(DestPTy,
1066 cast<PointerType>(PtrVal->getType())->getAddressSpace());
Devang Patel0f18d972011-05-04 23:58:50 +00001067 Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc());
Chris Lattner4034e142011-04-28 07:29:08 +00001068 PtrVal = Builder.CreateBitCast(PtrVal, DestPTy);
1069 LoadInst *NewLoad = Builder.CreateLoad(PtrVal);
1070 NewLoad->takeName(SrcVal);
1071 NewLoad->setAlignment(SrcVal->getAlignment());
Devang Patel0f18d972011-05-04 23:58:50 +00001072
Chris Lattner4034e142011-04-28 07:29:08 +00001073 DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n");
1074 DEBUG(dbgs() << "TO: " << *NewLoad << "\n");
1075
1076 // Replace uses of the original load with the wider load. On a big endian
1077 // system, we need to shift down to get the relevant bits.
1078 Value *RV = NewLoad;
1079 if (TD.isBigEndian())
1080 RV = Builder.CreateLShr(RV,
1081 NewLoadSize*8-SrcVal->getType()->getPrimitiveSizeInBits());
1082 RV = Builder.CreateTrunc(RV, SrcVal->getType());
1083 SrcVal->replaceAllUsesWith(RV);
Chris Lattner1e4f44b2011-04-28 20:02:57 +00001084
1085 // We would like to use gvn.markInstructionForDeletion here, but we can't
1086 // because the load is already memoized into the leader map table that GVN
1087 // tracks. It is potentially possible to remove the load from the table,
1088 // but then there all of the operations based on it would need to be
1089 // rehashed. Just leave the dead load around.
Chris Lattnerad3ba6a2011-04-28 18:08:21 +00001090 gvn.getMemDep().removeInstruction(SrcVal);
Chris Lattner4034e142011-04-28 07:29:08 +00001091 SrcVal = NewLoad;
1092 }
1093
1094 return GetStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, TD);
1095}
1096
1097
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001098/// GetMemInstValueForLoad - This function is called when we have a
1099/// memdep query of a load that ends up being a clobbering mem intrinsic.
1100static Value *GetMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001101 Type *LoadTy, Instruction *InsertPt,
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001102 const TargetData &TD){
1103 LLVMContext &Ctx = LoadTy->getContext();
1104 uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy)/8;
1105
1106 IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
1107
1108 // We know that this method is only called when the mem transfer fully
1109 // provides the bits for the load.
1110 if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) {
1111 // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
1112 // independently of what the offset is.
1113 Value *Val = MSI->getValue();
1114 if (LoadSize != 1)
1115 Val = Builder.CreateZExt(Val, IntegerType::get(Ctx, LoadSize*8));
1116
1117 Value *OneElt = Val;
1118
1119 // Splat the value out to the right number of bits.
1120 for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize; ) {
1121 // If we can double the number of bytes set, do it.
1122 if (NumBytesSet*2 <= LoadSize) {
1123 Value *ShVal = Builder.CreateShl(Val, NumBytesSet*8);
1124 Val = Builder.CreateOr(Val, ShVal);
1125 NumBytesSet <<= 1;
1126 continue;
1127 }
1128
1129 // Otherwise insert one byte at a time.
1130 Value *ShVal = Builder.CreateShl(Val, 1*8);
1131 Val = Builder.CreateOr(OneElt, ShVal);
1132 ++NumBytesSet;
1133 }
1134
1135 return CoerceAvailableValueToLoadType(Val, LoadTy, InsertPt, TD);
1136 }
Chris Lattnerbc9a28d2009-12-06 05:29:56 +00001137
1138 // Otherwise, this is a memcpy/memmove from a constant global.
1139 MemTransferInst *MTI = cast<MemTransferInst>(SrcInst);
1140 Constant *Src = cast<Constant>(MTI->getSource());
1141
1142 // Otherwise, see if we can constant fold a load from the constant with the
1143 // offset applied as appropriate.
1144 Src = ConstantExpr::getBitCast(Src,
1145 llvm::Type::getInt8PtrTy(Src->getContext()));
1146 Constant *OffsetCst =
1147 ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
Jay Foaddab3d292011-07-21 14:31:17 +00001148 Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
Chris Lattnerbc9a28d2009-12-06 05:29:56 +00001149 Src = ConstantExpr::getBitCast(Src, PointerType::getUnqual(LoadTy));
1150 return ConstantFoldLoadFromConstPtr(Src, &TD);
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001151}
1152
Dan Gohmanb3579832010-04-15 17:08:50 +00001153namespace {
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001154
Chris Lattner87913512009-09-21 06:30:24 +00001155struct AvailableValueInBlock {
1156 /// BB - The basic block in question.
1157 BasicBlock *BB;
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001158 enum ValType {
1159 SimpleVal, // A simple offsetted value that is accessed.
Chris Lattner4034e142011-04-28 07:29:08 +00001160 LoadVal, // A value produced by a load.
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001161 MemIntrin // A memory intrinsic which is loaded from.
1162 };
1163
Chris Lattner87913512009-09-21 06:30:24 +00001164 /// V - The value that is live out of the block.
Chris Lattner4034e142011-04-28 07:29:08 +00001165 PointerIntPair<Value *, 2, ValType> Val;
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001166
1167 /// Offset - The byte offset in Val that is interesting for the load query.
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001168 unsigned Offset;
Chris Lattner87913512009-09-21 06:30:24 +00001169
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001170 static AvailableValueInBlock get(BasicBlock *BB, Value *V,
1171 unsigned Offset = 0) {
Chris Lattner87913512009-09-21 06:30:24 +00001172 AvailableValueInBlock Res;
1173 Res.BB = BB;
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001174 Res.Val.setPointer(V);
1175 Res.Val.setInt(SimpleVal);
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001176 Res.Offset = Offset;
Chris Lattner87913512009-09-21 06:30:24 +00001177 return Res;
1178 }
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001179
1180 static AvailableValueInBlock getMI(BasicBlock *BB, MemIntrinsic *MI,
1181 unsigned Offset = 0) {
1182 AvailableValueInBlock Res;
1183 Res.BB = BB;
1184 Res.Val.setPointer(MI);
1185 Res.Val.setInt(MemIntrin);
1186 Res.Offset = Offset;
1187 return Res;
1188 }
1189
Chris Lattner4034e142011-04-28 07:29:08 +00001190 static AvailableValueInBlock getLoad(BasicBlock *BB, LoadInst *LI,
1191 unsigned Offset = 0) {
1192 AvailableValueInBlock Res;
1193 Res.BB = BB;
1194 Res.Val.setPointer(LI);
1195 Res.Val.setInt(LoadVal);
1196 Res.Offset = Offset;
1197 return Res;
1198 }
1199
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001200 bool isSimpleValue() const { return Val.getInt() == SimpleVal; }
Chris Lattner4034e142011-04-28 07:29:08 +00001201 bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; }
1202 bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; }
1203
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001204 Value *getSimpleValue() const {
1205 assert(isSimpleValue() && "Wrong accessor");
1206 return Val.getPointer();
1207 }
1208
Chris Lattner4034e142011-04-28 07:29:08 +00001209 LoadInst *getCoercedLoadValue() const {
1210 assert(isCoercedLoadValue() && "Wrong accessor");
1211 return cast<LoadInst>(Val.getPointer());
1212 }
1213
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001214 MemIntrinsic *getMemIntrinValue() const {
Chris Lattner4034e142011-04-28 07:29:08 +00001215 assert(isMemIntrinValue() && "Wrong accessor");
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001216 return cast<MemIntrinsic>(Val.getPointer());
1217 }
Chris Lattner5362c542009-12-21 23:04:33 +00001218
1219 /// MaterializeAdjustedValue - Emit code into this block to adjust the value
1220 /// defined here to the specified type. This handles various coercion cases.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001221 Value *MaterializeAdjustedValue(Type *LoadTy, GVN &gvn) const {
Chris Lattner5362c542009-12-21 23:04:33 +00001222 Value *Res;
1223 if (isSimpleValue()) {
1224 Res = getSimpleValue();
1225 if (Res->getType() != LoadTy) {
Chris Lattner4756ecb2011-04-28 16:36:48 +00001226 const TargetData *TD = gvn.getTargetData();
Chris Lattner5362c542009-12-21 23:04:33 +00001227 assert(TD && "Need target data to handle type mismatch case");
1228 Res = GetStoreValueForLoad(Res, Offset, LoadTy, BB->getTerminator(),
1229 *TD);
1230
Chris Lattner4034e142011-04-28 07:29:08 +00001231 DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset << " "
Chris Lattner5362c542009-12-21 23:04:33 +00001232 << *getSimpleValue() << '\n'
1233 << *Res << '\n' << "\n\n\n");
1234 }
Chris Lattner4034e142011-04-28 07:29:08 +00001235 } else if (isCoercedLoadValue()) {
1236 LoadInst *Load = getCoercedLoadValue();
1237 if (Load->getType() == LoadTy && Offset == 0) {
1238 Res = Load;
1239 } else {
Chris Lattner4034e142011-04-28 07:29:08 +00001240 Res = GetLoadValueForLoad(Load, Offset, LoadTy, BB->getTerminator(),
Chris Lattner4756ecb2011-04-28 16:36:48 +00001241 gvn);
Chris Lattner4034e142011-04-28 07:29:08 +00001242
1243 DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset << " "
1244 << *getCoercedLoadValue() << '\n'
1245 << *Res << '\n' << "\n\n\n");
1246 }
Chris Lattner5362c542009-12-21 23:04:33 +00001247 } else {
Chris Lattner4756ecb2011-04-28 16:36:48 +00001248 const TargetData *TD = gvn.getTargetData();
1249 assert(TD && "Need target data to handle type mismatch case");
Chris Lattner5362c542009-12-21 23:04:33 +00001250 Res = GetMemInstValueForLoad(getMemIntrinValue(), Offset,
1251 LoadTy, BB->getTerminator(), *TD);
Chris Lattner4034e142011-04-28 07:29:08 +00001252 DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
Chris Lattner5362c542009-12-21 23:04:33 +00001253 << " " << *getMemIntrinValue() << '\n'
1254 << *Res << '\n' << "\n\n\n");
1255 }
1256 return Res;
1257 }
Chris Lattner87913512009-09-21 06:30:24 +00001258};
1259
Chris Lattner4034e142011-04-28 07:29:08 +00001260} // end anonymous namespace
Dan Gohmanb3579832010-04-15 17:08:50 +00001261
Chris Lattnera09fbf02009-10-10 23:50:30 +00001262/// ConstructSSAForLoadSet - Given a set of loads specified by ValuesPerBlock,
1263/// construct SSA form, allowing us to eliminate LI. This returns the value
1264/// that should be used at LI's definition site.
1265static Value *ConstructSSAForLoadSet(LoadInst *LI,
1266 SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
Chris Lattner4756ecb2011-04-28 16:36:48 +00001267 GVN &gvn) {
Chris Lattnerd2191e52009-12-21 23:15:48 +00001268 // Check for the fully redundant, dominating load case. In this case, we can
1269 // just use the dominating value directly.
1270 if (ValuesPerBlock.size() == 1 &&
Chris Lattner4756ecb2011-04-28 16:36:48 +00001271 gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
1272 LI->getParent()))
1273 return ValuesPerBlock[0].MaterializeAdjustedValue(LI->getType(), gvn);
Chris Lattnerd2191e52009-12-21 23:15:48 +00001274
1275 // Otherwise, we have to construct SSA form.
Chris Lattnera09fbf02009-10-10 23:50:30 +00001276 SmallVector<PHINode*, 8> NewPHIs;
1277 SSAUpdater SSAUpdate(&NewPHIs);
Duncan Sandsfc6e29d2010-09-02 08:14:03 +00001278 SSAUpdate.Initialize(LI->getType(), LI->getName());
Chris Lattnera09fbf02009-10-10 23:50:30 +00001279
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001280 Type *LoadTy = LI->getType();
Chris Lattnera09fbf02009-10-10 23:50:30 +00001281
Chris Lattner771a5422009-09-20 20:09:34 +00001282 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001283 const AvailableValueInBlock &AV = ValuesPerBlock[i];
1284 BasicBlock *BB = AV.BB;
Chris Lattner771a5422009-09-20 20:09:34 +00001285
Chris Lattnera09fbf02009-10-10 23:50:30 +00001286 if (SSAUpdate.HasValueForBlock(BB))
1287 continue;
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001288
Chris Lattner4756ecb2011-04-28 16:36:48 +00001289 SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LoadTy, gvn));
Chris Lattner771a5422009-09-20 20:09:34 +00001290 }
Chris Lattnera09fbf02009-10-10 23:50:30 +00001291
1292 // Perform PHI construction.
1293 Value *V = SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
1294
1295 // If new PHI nodes were created, notify alias analysis.
Chris Lattner4756ecb2011-04-28 16:36:48 +00001296 if (V->getType()->isPointerTy()) {
1297 AliasAnalysis *AA = gvn.getAliasAnalysis();
1298
Chris Lattnera09fbf02009-10-10 23:50:30 +00001299 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
1300 AA->copyValue(LI, NewPHIs[i]);
Owen Anderson392249f2011-01-03 23:51:43 +00001301
1302 // Now that we've copied information to the new PHIs, scan through
1303 // them again and inform alias analysis that we've added potentially
1304 // escaping uses to any values that are operands to these PHIs.
1305 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i) {
1306 PHINode *P = NewPHIs[i];
Jay Foadc1371202011-06-20 14:18:48 +00001307 for (unsigned ii = 0, ee = P->getNumIncomingValues(); ii != ee; ++ii) {
1308 unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
1309 AA->addEscapingUse(P->getOperandUse(jj));
1310 }
Owen Anderson392249f2011-01-03 23:51:43 +00001311 }
Chris Lattner4756ecb2011-04-28 16:36:48 +00001312 }
Chris Lattnera09fbf02009-10-10 23:50:30 +00001313
1314 return V;
Chris Lattner771a5422009-09-20 20:09:34 +00001315}
1316
Gabor Greifea3eec92010-04-09 10:57:00 +00001317static bool isLifetimeStart(const Instruction *Inst) {
1318 if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
Owen Anderson9ff5a232009-12-02 07:35:19 +00001319 return II->getIntrinsicID() == Intrinsic::lifetime_start;
Chris Lattner720e7902009-12-02 06:44:58 +00001320 return false;
1321}
1322
Owen Anderson62bc33c2007-08-16 22:02:55 +00001323/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
1324/// non-local by performing PHI construction.
Chris Lattnerf07054d2011-04-28 16:18:52 +00001325bool GVN::processNonLocalLoad(LoadInst *LI) {
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001326 // Find the non-local dependencies of the load.
Chris Lattner0ee443d2009-12-22 04:25:02 +00001327 SmallVector<NonLocalDepResult, 64> Deps;
Dan Gohman6d8eb152010-11-11 21:50:19 +00001328 AliasAnalysis::Location Loc = VN.getAliasAnalysis()->getLocation(LI);
1329 MD->getNonLocalPointerDependency(Loc, true, LI->getParent(), Deps);
David Greenebf7f78e2010-01-05 01:27:17 +00001330 //DEBUG(dbgs() << "INVESTIGATING NONLOCAL LOAD: "
Dan Gohman2a298992009-07-31 20:24:18 +00001331 // << Deps.size() << *LI << '\n');
Daniel Dunbara279bc32009-09-20 02:20:51 +00001332
Owen Anderson516eb1c2008-08-26 22:07:42 +00001333 // If we had to process more than one hundred blocks to find the
1334 // dependencies, this load isn't worth worrying about. Optimizing
1335 // it will be too expensive.
Bill Wendling5d8ab0f2012-01-31 06:57:53 +00001336 unsigned NumDeps = Deps.size();
1337 if (NumDeps > 100)
Owen Anderson516eb1c2008-08-26 22:07:42 +00001338 return false;
Chris Lattner5f4f84b2008-12-18 00:51:32 +00001339
1340 // If we had a phi translation failure, we'll have a single entry which is a
1341 // clobber in the current block. Reject this early.
Bill Wendling5d8ab0f2012-01-31 06:57:53 +00001342 if (NumDeps == 1 &&
1343 !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
Torok Edwin4306b1a2009-06-17 18:48:18 +00001344 DEBUG(
David Greenebf7f78e2010-01-05 01:27:17 +00001345 dbgs() << "GVN: non-local load ";
1346 WriteAsOperand(dbgs(), LI);
Eli Friedmana990e072011-06-15 00:47:34 +00001347 dbgs() << " has unknown dependencies\n";
Torok Edwin4306b1a2009-06-17 18:48:18 +00001348 );
Chris Lattner5f4f84b2008-12-18 00:51:32 +00001349 return false;
Torok Edwin4306b1a2009-06-17 18:48:18 +00001350 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001351
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001352 // Filter out useless results (non-locals, etc). Keep track of the blocks
1353 // where we have a value available in repl, also keep track of whether we see
1354 // dependencies that produce an unknown value for the load (such as a call
1355 // that could potentially clobber the load).
Bill Wendlingb319f122012-01-31 07:04:52 +00001356 SmallVector<AvailableValueInBlock, 64> ValuesPerBlock;
1357 SmallVector<BasicBlock*, 64> UnavailableBlocks;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001358
Bill Wendling5d8ab0f2012-01-31 06:57:53 +00001359 for (unsigned i = 0, e = NumDeps; i != e; ++i) {
Chris Lattnere18b9712009-12-09 07:08:01 +00001360 BasicBlock *DepBB = Deps[i].getBB();
1361 MemDepResult DepInfo = Deps[i].getResult();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001362
Eli Friedmanb4141422011-10-13 22:14:57 +00001363 if (!DepInfo.isDef() && !DepInfo.isClobber()) {
Eli Friedmana990e072011-06-15 00:47:34 +00001364 UnavailableBlocks.push_back(DepBB);
1365 continue;
1366 }
1367
Chris Lattnerb51deb92008-12-05 21:04:20 +00001368 if (DepInfo.isClobber()) {
Chris Lattneraf064ae2009-12-09 18:21:46 +00001369 // The address being loaded in this non-local block may not be the same as
1370 // the pointer operand of the load if PHI translation occurs. Make sure
1371 // to consider the right address.
1372 Value *Address = Deps[i].getAddress();
1373
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001374 // If the dependence is to a store that writes to a superset of the bits
1375 // read by the load, we can extract the bits we need for the load from the
1376 // stored value.
1377 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
Chris Lattneraf064ae2009-12-09 18:21:46 +00001378 if (TD && Address) {
1379 int Offset = AnalyzeLoadFromClobberingStore(LI->getType(), Address,
Chris Lattner4ca70fe2009-12-09 07:37:07 +00001380 DepSI, *TD);
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001381 if (Offset != -1) {
1382 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
Dan Gohman3355c4e2010-11-10 19:03:33 +00001383 DepSI->getValueOperand(),
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001384 Offset));
1385 continue;
1386 }
1387 }
1388 }
Chris Lattner1f821512011-04-26 01:21:15 +00001389
1390 // Check to see if we have something like this:
1391 // load i32* P
1392 // load i8* (P+1)
1393 // if we have this, replace the later with an extraction from the former.
1394 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInfo.getInst())) {
1395 // If this is a clobber and L is the first instruction in its block, then
1396 // we have the first instruction in the entry block.
1397 if (DepLI != LI && Address && TD) {
1398 int Offset = AnalyzeLoadFromClobberingLoad(LI->getType(),
1399 LI->getPointerOperand(),
1400 DepLI, *TD);
1401
1402 if (Offset != -1) {
Chris Lattner4034e142011-04-28 07:29:08 +00001403 ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB,DepLI,
1404 Offset));
Chris Lattner1f821512011-04-26 01:21:15 +00001405 continue;
1406 }
1407 }
1408 }
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001409
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001410 // If the clobbering value is a memset/memcpy/memmove, see if we can
1411 // forward a value on from it.
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001412 if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInfo.getInst())) {
Chris Lattneraf064ae2009-12-09 18:21:46 +00001413 if (TD && Address) {
1414 int Offset = AnalyzeLoadFromClobberingMemInst(LI->getType(), Address,
Chris Lattner4ca70fe2009-12-09 07:37:07 +00001415 DepMI, *TD);
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001416 if (Offset != -1) {
1417 ValuesPerBlock.push_back(AvailableValueInBlock::getMI(DepBB, DepMI,
1418 Offset));
1419 continue;
1420 }
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001421 }
1422 }
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001423
Chris Lattnerb51deb92008-12-05 21:04:20 +00001424 UnavailableBlocks.push_back(DepBB);
1425 continue;
1426 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001427
Eli Friedmanb4141422011-10-13 22:14:57 +00001428 // DepInfo.isDef() here
Eli Friedmana990e072011-06-15 00:47:34 +00001429
Chris Lattnerb51deb92008-12-05 21:04:20 +00001430 Instruction *DepInst = DepInfo.getInst();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001431
Chris Lattnerb51deb92008-12-05 21:04:20 +00001432 // Loading the allocation -> undef.
Chris Lattner720e7902009-12-02 06:44:58 +00001433 if (isa<AllocaInst>(DepInst) || isMalloc(DepInst) ||
Owen Anderson9ff5a232009-12-02 07:35:19 +00001434 // Loading immediately after lifetime begin -> undef.
1435 isLifetimeStart(DepInst)) {
Chris Lattner87913512009-09-21 06:30:24 +00001436 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1437 UndefValue::get(LI->getType())));
Chris Lattnerbf145d62008-12-01 01:15:42 +00001438 continue;
1439 }
Owen Andersonb62f7922009-10-28 07:05:35 +00001440
Chris Lattner87913512009-09-21 06:30:24 +00001441 if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00001442 // Reject loads and stores that are to the same address but are of
Chris Lattner771a5422009-09-20 20:09:34 +00001443 // different types if we have to.
Dan Gohman3355c4e2010-11-10 19:03:33 +00001444 if (S->getValueOperand()->getType() != LI->getType()) {
Chris Lattner771a5422009-09-20 20:09:34 +00001445 // If the stored value is larger or equal to the loaded value, we can
1446 // reuse it.
Dan Gohman3355c4e2010-11-10 19:03:33 +00001447 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(S->getValueOperand(),
Chris Lattner8b2bc3d2009-09-21 17:24:04 +00001448 LI->getType(), *TD)) {
Chris Lattner771a5422009-09-20 20:09:34 +00001449 UnavailableBlocks.push_back(DepBB);
1450 continue;
1451 }
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001452 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001453
Chris Lattner87913512009-09-21 06:30:24 +00001454 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
Dan Gohman3355c4e2010-11-10 19:03:33 +00001455 S->getValueOperand()));
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001456 continue;
1457 }
1458
1459 if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
Chris Lattner771a5422009-09-20 20:09:34 +00001460 // If the types mismatch and we can't handle it, reject reuse of the load.
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001461 if (LD->getType() != LI->getType()) {
Chris Lattner771a5422009-09-20 20:09:34 +00001462 // If the stored value is larger or equal to the loaded value, we can
1463 // reuse it.
Chris Lattner8b2bc3d2009-09-21 17:24:04 +00001464 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(LD, LI->getType(),*TD)){
Chris Lattner771a5422009-09-20 20:09:34 +00001465 UnavailableBlocks.push_back(DepBB);
1466 continue;
1467 }
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001468 }
Chris Lattner4034e142011-04-28 07:29:08 +00001469 ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB, LD));
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001470 continue;
Owen Anderson0cd32032007-07-25 19:57:03 +00001471 }
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001472
1473 UnavailableBlocks.push_back(DepBB);
1474 continue;
Chris Lattner88365bb2008-03-21 21:14:38 +00001475 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001476
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001477 // If we have no predecessors that produce a known value for this load, exit
1478 // early.
1479 if (ValuesPerBlock.empty()) return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001480
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001481 // If all of the instructions we depend on produce a known value for this
1482 // load, then it is fully redundant and we can use PHI insertion to compute
1483 // its value. Insert PHIs and remove the fully redundant value now.
1484 if (UnavailableBlocks.empty()) {
David Greenebf7f78e2010-01-05 01:27:17 +00001485 DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
Chris Lattner771a5422009-09-20 20:09:34 +00001486
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001487 // Perform PHI construction.
Chris Lattner4756ecb2011-04-28 16:36:48 +00001488 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
Chris Lattner771a5422009-09-20 20:09:34 +00001489 LI->replaceAllUsesWith(V);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001490
Chris Lattner771a5422009-09-20 20:09:34 +00001491 if (isa<PHINode>(V))
1492 V->takeName(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001493 if (V->getType()->isPointerTy())
Chris Lattner771a5422009-09-20 20:09:34 +00001494 MD->invalidateCachedPointerInfo(V);
Chris Lattner4756ecb2011-04-28 16:36:48 +00001495 markInstructionForDeletion(LI);
Dan Gohmanfe601042010-06-22 15:08:57 +00001496 ++NumGVNLoad;
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001497 return true;
1498 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001499
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001500 if (!EnablePRE || !EnableLoadPRE)
1501 return false;
1502
1503 // Okay, we have *some* definitions of the value. This means that the value
1504 // is available in some of our (transitive) predecessors. Lets think about
1505 // doing PRE of this load. This will involve inserting a new load into the
1506 // predecessor when it's not available. We could do this in general, but
1507 // prefer to not increase code size. As such, we only do this when we know
1508 // that we only have to insert *one* load (which means we're basically moving
1509 // the load, not inserting a new one).
Daniel Dunbara279bc32009-09-20 02:20:51 +00001510
Owen Anderson88554df2009-05-31 09:03:40 +00001511 SmallPtrSet<BasicBlock *, 4> Blockers;
1512 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1513 Blockers.insert(UnavailableBlocks[i]);
1514
Bill Wendling795cf5e2011-08-17 21:32:02 +00001515 // Let's find the first basic block with more than one predecessor. Walk
1516 // backwards through predecessors if needed.
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001517 BasicBlock *LoadBB = LI->getParent();
Owen Anderson88554df2009-05-31 09:03:40 +00001518 BasicBlock *TmpBB = LoadBB;
1519
1520 bool isSinglePred = false;
Dale Johannesen42c3f552009-06-17 20:48:23 +00001521 bool allSingleSucc = true;
Owen Anderson88554df2009-05-31 09:03:40 +00001522 while (TmpBB->getSinglePredecessor()) {
1523 isSinglePred = true;
1524 TmpBB = TmpBB->getSinglePredecessor();
Owen Anderson88554df2009-05-31 09:03:40 +00001525 if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1526 return false;
1527 if (Blockers.count(TmpBB))
1528 return false;
Owen Andersonb0ba0f42010-09-25 05:26:18 +00001529
1530 // If any of these blocks has more than one successor (i.e. if the edge we
1531 // just traversed was critical), then there are other paths through this
1532 // block along which the load may not be anticipated. Hoisting the load
1533 // above this block would be adding the load to execution paths along
1534 // which it was not previously executed.
Dale Johannesen42c3f552009-06-17 20:48:23 +00001535 if (TmpBB->getTerminator()->getNumSuccessors() != 1)
Owen Andersonb0ba0f42010-09-25 05:26:18 +00001536 return false;
Owen Anderson88554df2009-05-31 09:03:40 +00001537 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001538
Owen Anderson88554df2009-05-31 09:03:40 +00001539 assert(TmpBB);
1540 LoadBB = TmpBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001541
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001542 // FIXME: It is extremely unclear what this loop is doing, other than
1543 // artificially restricting loadpre.
Owen Anderson88554df2009-05-31 09:03:40 +00001544 if (isSinglePred) {
1545 bool isHot = false;
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001546 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
1547 const AvailableValueInBlock &AV = ValuesPerBlock[i];
1548 if (AV.isSimpleValue())
Daniel Dunbara279bc32009-09-20 02:20:51 +00001549 // "Hot" Instruction is in some loop (because it dominates its dep.
1550 // instruction).
Chris Lattnercb9cbc42009-12-06 04:54:31 +00001551 if (Instruction *I = dyn_cast<Instruction>(AV.getSimpleValue()))
1552 if (DT->dominates(LI, I)) {
1553 isHot = true;
1554 break;
1555 }
1556 }
Owen Anderson88554df2009-05-31 09:03:40 +00001557
1558 // We are interested only in "hot" instructions. We don't want to do any
1559 // mis-optimizations here.
1560 if (!isHot)
1561 return false;
1562 }
1563
Bob Wilson6cad4172010-02-01 21:17:14 +00001564 // Check to see how many predecessors have the loaded value fully
1565 // available.
1566 DenseMap<BasicBlock*, Value*> PredLoads;
Chris Lattner72bc70d2008-12-05 07:49:08 +00001567 DenseMap<BasicBlock*, char> FullyAvailableBlocks;
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001568 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
Chris Lattner87913512009-09-21 06:30:24 +00001569 FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001570 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1571 FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1572
Bob Wilson34414a62010-05-04 20:03:21 +00001573 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> NeedToSplit;
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001574 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1575 PI != E; ++PI) {
Bob Wilson6cad4172010-02-01 21:17:14 +00001576 BasicBlock *Pred = *PI;
1577 if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks)) {
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001578 continue;
Bob Wilson6cad4172010-02-01 21:17:14 +00001579 }
1580 PredLoads[Pred] = 0;
Bob Wilson484d4a32010-02-16 19:51:59 +00001581
Bob Wilson6cad4172010-02-01 21:17:14 +00001582 if (Pred->getTerminator()->getNumSuccessors() != 1) {
Bob Wilson484d4a32010-02-16 19:51:59 +00001583 if (isa<IndirectBrInst>(Pred->getTerminator())) {
1584 DEBUG(dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
1585 << Pred->getName() << "': " << *LI << '\n');
1586 return false;
1587 }
Bill Wendling795cf5e2011-08-17 21:32:02 +00001588
1589 if (LoadBB->isLandingPad()) {
1590 DEBUG(dbgs()
1591 << "COULD NOT PRE LOAD BECAUSE OF LANDING PAD CRITICAL EDGE '"
1592 << Pred->getName() << "': " << *LI << '\n');
1593 return false;
1594 }
1595
Bob Wilsonae23daf2010-02-16 21:06:42 +00001596 unsigned SuccNum = GetSuccessorNumber(Pred, LoadBB);
Bob Wilson34414a62010-05-04 20:03:21 +00001597 NeedToSplit.push_back(std::make_pair(Pred->getTerminator(), SuccNum));
Bob Wilson6cad4172010-02-01 21:17:14 +00001598 }
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001599 }
Bill Wendling795cf5e2011-08-17 21:32:02 +00001600
Bob Wilson34414a62010-05-04 20:03:21 +00001601 if (!NeedToSplit.empty()) {
Bob Wilsonbc786532010-05-05 20:44:15 +00001602 toSplit.append(NeedToSplit.begin(), NeedToSplit.end());
Bob Wilson70704972010-03-01 23:37:32 +00001603 return false;
Bob Wilson34414a62010-05-04 20:03:21 +00001604 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001605
Bob Wilson6cad4172010-02-01 21:17:14 +00001606 // Decide whether PRE is profitable for this load.
1607 unsigned NumUnavailablePreds = PredLoads.size();
1608 assert(NumUnavailablePreds != 0 &&
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001609 "Fully available value should be eliminated above!");
Owen Anderson7267e142010-10-01 20:02:55 +00001610
1611 // If this load is unavailable in multiple predecessors, reject it.
1612 // FIXME: If we could restructure the CFG, we could make a common pred with
1613 // all the preds that don't have an available LI and insert a new load into
1614 // that one block.
1615 if (NumUnavailablePreds != 1)
Bob Wilson6cad4172010-02-01 21:17:14 +00001616 return false;
Bob Wilson6cad4172010-02-01 21:17:14 +00001617
1618 // Check if the load can safely be moved to all the unavailable predecessors.
1619 bool CanDoPRE = true;
Chris Lattnerdd696052009-11-28 15:39:14 +00001620 SmallVector<Instruction*, 8> NewInsts;
Bob Wilson6cad4172010-02-01 21:17:14 +00001621 for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1622 E = PredLoads.end(); I != E; ++I) {
1623 BasicBlock *UnavailablePred = I->first;
1624
1625 // Do PHI translation to get its value in the predecessor if necessary. The
1626 // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
1627
1628 // If all preds have a single successor, then we know it is safe to insert
1629 // the load on the pred (?!?), so we can insert code to materialize the
1630 // pointer if it is not available.
Dan Gohman3355c4e2010-11-10 19:03:33 +00001631 PHITransAddr Address(LI->getPointerOperand(), TD);
Bob Wilson6cad4172010-02-01 21:17:14 +00001632 Value *LoadPtr = 0;
1633 if (allSingleSucc) {
1634 LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred,
1635 *DT, NewInsts);
1636 } else {
Daniel Dunbar6d8f2ca2010-02-24 08:48:04 +00001637 Address.PHITranslateValue(LoadBB, UnavailablePred, DT);
Bob Wilson6cad4172010-02-01 21:17:14 +00001638 LoadPtr = Address.getAddr();
Bob Wilson6cad4172010-02-01 21:17:14 +00001639 }
1640
1641 // If we couldn't find or insert a computation of this phi translated value,
1642 // we fail PRE.
1643 if (LoadPtr == 0) {
1644 DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
Dan Gohman3355c4e2010-11-10 19:03:33 +00001645 << *LI->getPointerOperand() << "\n");
Bob Wilson6cad4172010-02-01 21:17:14 +00001646 CanDoPRE = false;
1647 break;
1648 }
1649
1650 // Make sure it is valid to move this load here. We have to watch out for:
1651 // @1 = getelementptr (i8* p, ...
1652 // test p and branch if == 0
1653 // load @1
Owen Andersonb1602ab2011-01-04 19:29:46 +00001654 // It is valid to have the getelementptr before the test, even if p can
1655 // be 0, as getelementptr only does address arithmetic.
Bob Wilson6cad4172010-02-01 21:17:14 +00001656 // If we are not pushing the value through any multiple-successor blocks
1657 // we do not have this case. Otherwise, check that the load is safe to
1658 // put anywhere; this can be improved, but should be conservatively safe.
1659 if (!allSingleSucc &&
1660 // FIXME: REEVALUTE THIS.
1661 !isSafeToLoadUnconditionally(LoadPtr,
1662 UnavailablePred->getTerminator(),
1663 LI->getAlignment(), TD)) {
1664 CanDoPRE = false;
1665 break;
1666 }
1667
1668 I->second = LoadPtr;
Chris Lattner05e15f82009-12-09 01:59:31 +00001669 }
1670
Bob Wilson6cad4172010-02-01 21:17:14 +00001671 if (!CanDoPRE) {
Chris Lattner3077ca92011-01-11 08:19:16 +00001672 while (!NewInsts.empty()) {
1673 Instruction *I = NewInsts.pop_back_val();
1674 if (MD) MD->removeInstruction(I);
1675 I->eraseFromParent();
1676 }
Dale Johannesen42c3f552009-06-17 20:48:23 +00001677 return false;
Chris Lattner0c264b12009-11-28 16:08:18 +00001678 }
Dale Johannesen42c3f552009-06-17 20:48:23 +00001679
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001680 // Okay, we can eliminate this load by inserting a reload in the predecessor
1681 // and using PHI construction to get the value in the other predecessors, do
1682 // it.
David Greenebf7f78e2010-01-05 01:27:17 +00001683 DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
Chris Lattner0c264b12009-11-28 16:08:18 +00001684 DEBUG(if (!NewInsts.empty())
David Greenebf7f78e2010-01-05 01:27:17 +00001685 dbgs() << "INSERTED " << NewInsts.size() << " INSTS: "
Chris Lattner0c264b12009-11-28 16:08:18 +00001686 << *NewInsts.back() << '\n');
1687
Bob Wilson6cad4172010-02-01 21:17:14 +00001688 // Assign value numbers to the new instructions.
1689 for (unsigned i = 0, e = NewInsts.size(); i != e; ++i) {
1690 // FIXME: We really _ought_ to insert these value numbers into their
1691 // parent's availability map. However, in doing so, we risk getting into
1692 // ordering issues. If a block hasn't been processed yet, we would be
1693 // marking a value as AVAIL-IN, which isn't what we intend.
1694 VN.lookup_or_add(NewInsts[i]);
1695 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001696
Bob Wilson6cad4172010-02-01 21:17:14 +00001697 for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1698 E = PredLoads.end(); I != E; ++I) {
1699 BasicBlock *UnavailablePred = I->first;
1700 Value *LoadPtr = I->second;
1701
Dan Gohmanf4177aa2010-12-15 23:53:55 +00001702 Instruction *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1703 LI->getAlignment(),
1704 UnavailablePred->getTerminator());
1705
1706 // Transfer the old load's TBAA tag to the new load.
1707 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa))
1708 NewLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
Bob Wilson6cad4172010-02-01 21:17:14 +00001709
Devang Pateld9b49962011-05-17 19:43:38 +00001710 // Transfer DebugLoc.
1711 NewLoad->setDebugLoc(LI->getDebugLoc());
1712
Bob Wilson6cad4172010-02-01 21:17:14 +00001713 // Add the newly created load.
1714 ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,
1715 NewLoad));
Bob Wilson188f4282010-02-23 05:55:00 +00001716 MD->invalidateCachedPointerInfo(LoadPtr);
1717 DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
Bob Wilson6cad4172010-02-01 21:17:14 +00001718 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001719
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001720 // Perform PHI construction.
Chris Lattner4756ecb2011-04-28 16:36:48 +00001721 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
Chris Lattner771a5422009-09-20 20:09:34 +00001722 LI->replaceAllUsesWith(V);
1723 if (isa<PHINode>(V))
1724 V->takeName(LI);
Duncan Sands1df98592010-02-16 11:11:14 +00001725 if (V->getType()->isPointerTy())
Chris Lattner771a5422009-09-20 20:09:34 +00001726 MD->invalidateCachedPointerInfo(V);
Chris Lattner4756ecb2011-04-28 16:36:48 +00001727 markInstructionForDeletion(LI);
Dan Gohmanfe601042010-06-22 15:08:57 +00001728 ++NumPRELoad;
Owen Anderson0cd32032007-07-25 19:57:03 +00001729 return true;
1730}
1731
Owen Anderson62bc33c2007-08-16 22:02:55 +00001732/// processLoad - Attempt to eliminate a load, first by eliminating it
1733/// locally, and then attempting non-local elimination if that fails.
Chris Lattnerf07054d2011-04-28 16:18:52 +00001734bool GVN::processLoad(LoadInst *L) {
Dan Gohman4ec01b22009-11-14 02:27:51 +00001735 if (!MD)
1736 return false;
1737
Eli Friedman56efe242011-08-17 22:22:24 +00001738 if (!L->isSimple())
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001739 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001740
Chris Lattner9e7bc052011-05-22 07:03:34 +00001741 if (L->use_empty()) {
1742 markInstructionForDeletion(L);
1743 return true;
1744 }
1745
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001746 // ... to a pointer that has been loaded from before...
Chris Lattnerb2412a82009-09-21 02:42:51 +00001747 MemDepResult Dep = MD->getDependency(L);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001748
Chris Lattner1f821512011-04-26 01:21:15 +00001749 // If we have a clobber and target data is around, see if this is a clobber
1750 // that we can fix up through code synthesis.
1751 if (Dep.isClobber() && TD) {
Chris Lattnereed919b2009-09-21 05:57:11 +00001752 // Check to see if we have something like this:
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001753 // store i32 123, i32* %P
1754 // %A = bitcast i32* %P to i8*
1755 // %B = gep i8* %A, i32 1
1756 // %C = load i8* %B
1757 //
1758 // We could do that by recognizing if the clobber instructions are obviously
1759 // a common base + constant offset, and if the previous store (or memset)
1760 // completely covers this load. This sort of thing can happen in bitfield
1761 // access code.
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001762 Value *AvailVal = 0;
Chris Lattner1f821512011-04-26 01:21:15 +00001763 if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst())) {
1764 int Offset = AnalyzeLoadFromClobberingStore(L->getType(),
1765 L->getPointerOperand(),
1766 DepSI, *TD);
1767 if (Offset != -1)
1768 AvailVal = GetStoreValueForLoad(DepSI->getValueOperand(), Offset,
1769 L->getType(), L, *TD);
1770 }
1771
1772 // Check to see if we have something like this:
1773 // load i32* P
1774 // load i8* (P+1)
1775 // if we have this, replace the later with an extraction from the former.
1776 if (LoadInst *DepLI = dyn_cast<LoadInst>(Dep.getInst())) {
1777 // If this is a clobber and L is the first instruction in its block, then
1778 // we have the first instruction in the entry block.
1779 if (DepLI == L)
1780 return false;
1781
1782 int Offset = AnalyzeLoadFromClobberingLoad(L->getType(),
1783 L->getPointerOperand(),
1784 DepLI, *TD);
1785 if (Offset != -1)
Chris Lattner4756ecb2011-04-28 16:36:48 +00001786 AvailVal = GetLoadValueForLoad(DepLI, Offset, L->getType(), L, *this);
Chris Lattner1f821512011-04-26 01:21:15 +00001787 }
Chris Lattnereed919b2009-09-21 05:57:11 +00001788
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001789 // If the clobbering value is a memset/memcpy/memmove, see if we can forward
1790 // a value on from it.
1791 if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(Dep.getInst())) {
Chris Lattner1f821512011-04-26 01:21:15 +00001792 int Offset = AnalyzeLoadFromClobberingMemInst(L->getType(),
1793 L->getPointerOperand(),
1794 DepMI, *TD);
1795 if (Offset != -1)
1796 AvailVal = GetMemInstValueForLoad(DepMI, Offset, L->getType(), L, *TD);
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001797 }
1798
1799 if (AvailVal) {
David Greenebf7f78e2010-01-05 01:27:17 +00001800 DEBUG(dbgs() << "GVN COERCED INST:\n" << *Dep.getInst() << '\n'
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001801 << *AvailVal << '\n' << *L << "\n\n\n");
1802
1803 // Replace the load!
1804 L->replaceAllUsesWith(AvailVal);
Duncan Sands1df98592010-02-16 11:11:14 +00001805 if (AvailVal->getType()->isPointerTy())
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001806 MD->invalidateCachedPointerInfo(AvailVal);
Chris Lattner4756ecb2011-04-28 16:36:48 +00001807 markInstructionForDeletion(L);
Dan Gohmanfe601042010-06-22 15:08:57 +00001808 ++NumGVNLoad;
Chris Lattnerfaf815b2009-12-06 01:57:02 +00001809 return true;
1810 }
Chris Lattner1f821512011-04-26 01:21:15 +00001811 }
1812
1813 // If the value isn't available, don't do anything!
1814 if (Dep.isClobber()) {
Torok Edwin3f3c6d42009-05-29 09:46:03 +00001815 DEBUG(
Chris Lattner1f821512011-04-26 01:21:15 +00001816 // fast print dep, using operator<< on instruction is too slow.
David Greenebf7f78e2010-01-05 01:27:17 +00001817 dbgs() << "GVN: load ";
1818 WriteAsOperand(dbgs(), L);
Chris Lattnerb2412a82009-09-21 02:42:51 +00001819 Instruction *I = Dep.getInst();
David Greenebf7f78e2010-01-05 01:27:17 +00001820 dbgs() << " is clobbered by " << *I << '\n';
Torok Edwin3f3c6d42009-05-29 09:46:03 +00001821 );
Chris Lattnerb51deb92008-12-05 21:04:20 +00001822 return false;
Torok Edwin3f3c6d42009-05-29 09:46:03 +00001823 }
Chris Lattnerb51deb92008-12-05 21:04:20 +00001824
Eli Friedmanb4141422011-10-13 22:14:57 +00001825 // If it is defined in another block, try harder.
1826 if (Dep.isNonLocal())
1827 return processNonLocalLoad(L);
1828
1829 if (!Dep.isDef()) {
Eli Friedmana990e072011-06-15 00:47:34 +00001830 DEBUG(
1831 // fast print dep, using operator<< on instruction is too slow.
1832 dbgs() << "GVN: load ";
1833 WriteAsOperand(dbgs(), L);
1834 dbgs() << " has unknown dependence\n";
1835 );
1836 return false;
1837 }
1838
Chris Lattnerb2412a82009-09-21 02:42:51 +00001839 Instruction *DepInst = Dep.getInst();
Chris Lattnerb51deb92008-12-05 21:04:20 +00001840 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
Dan Gohman3355c4e2010-11-10 19:03:33 +00001841 Value *StoredVal = DepSI->getValueOperand();
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001842
1843 // The store and load are to a must-aliased pointer, but they may not
1844 // actually have the same type. See if we know how to reuse the stored
1845 // value (depending on its type).
Chris Lattnera52fce42009-10-21 04:11:19 +00001846 if (StoredVal->getType() != L->getType()) {
Duncan Sands88c3df72010-11-12 21:10:24 +00001847 if (TD) {
Chris Lattnera52fce42009-10-21 04:11:19 +00001848 StoredVal = CoerceAvailableValueToLoadType(StoredVal, L->getType(),
1849 L, *TD);
1850 if (StoredVal == 0)
1851 return false;
1852
David Greenebf7f78e2010-01-05 01:27:17 +00001853 DEBUG(dbgs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
Chris Lattnera52fce42009-10-21 04:11:19 +00001854 << '\n' << *L << "\n\n\n");
1855 }
1856 else
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001857 return false;
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001858 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001859
Chris Lattnerb51deb92008-12-05 21:04:20 +00001860 // Remove it!
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001861 L->replaceAllUsesWith(StoredVal);
Duncan Sands1df98592010-02-16 11:11:14 +00001862 if (StoredVal->getType()->isPointerTy())
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001863 MD->invalidateCachedPointerInfo(StoredVal);
Chris Lattner4756ecb2011-04-28 16:36:48 +00001864 markInstructionForDeletion(L);
Dan Gohmanfe601042010-06-22 15:08:57 +00001865 ++NumGVNLoad;
Chris Lattnerb51deb92008-12-05 21:04:20 +00001866 return true;
1867 }
1868
1869 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001870 Value *AvailableVal = DepLI;
1871
1872 // The loads are of a must-aliased pointer, but they may not actually have
1873 // the same type. See if we know how to reuse the previously loaded value
1874 // (depending on its type).
Chris Lattnera52fce42009-10-21 04:11:19 +00001875 if (DepLI->getType() != L->getType()) {
Duncan Sands88c3df72010-11-12 21:10:24 +00001876 if (TD) {
Chris Lattner1f821512011-04-26 01:21:15 +00001877 AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(),
1878 L, *TD);
Chris Lattnera52fce42009-10-21 04:11:19 +00001879 if (AvailableVal == 0)
1880 return false;
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001881
David Greenebf7f78e2010-01-05 01:27:17 +00001882 DEBUG(dbgs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
Chris Lattnera52fce42009-10-21 04:11:19 +00001883 << "\n" << *L << "\n\n\n");
1884 }
1885 else
1886 return false;
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001887 }
1888
Chris Lattnerb51deb92008-12-05 21:04:20 +00001889 // Remove it!
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001890 L->replaceAllUsesWith(AvailableVal);
Duncan Sands1df98592010-02-16 11:11:14 +00001891 if (DepLI->getType()->isPointerTy())
Chris Lattnerbc99be12008-12-09 22:06:23 +00001892 MD->invalidateCachedPointerInfo(DepLI);
Chris Lattner4756ecb2011-04-28 16:36:48 +00001893 markInstructionForDeletion(L);
Dan Gohmanfe601042010-06-22 15:08:57 +00001894 ++NumGVNLoad;
Chris Lattnerb51deb92008-12-05 21:04:20 +00001895 return true;
1896 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001897
Chris Lattner237a8282008-11-30 01:39:32 +00001898 // If this load really doesn't depend on anything, then we must be loading an
1899 // undef value. This can happen when loading for a fresh allocation with no
1900 // intervening stores, for example.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001901 if (isa<AllocaInst>(DepInst) || isMalloc(DepInst)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001902 L->replaceAllUsesWith(UndefValue::get(L->getType()));
Chris Lattner4756ecb2011-04-28 16:36:48 +00001903 markInstructionForDeletion(L);
Dan Gohmanfe601042010-06-22 15:08:57 +00001904 ++NumGVNLoad;
Chris Lattnerb51deb92008-12-05 21:04:20 +00001905 return true;
Eli Friedmanb6c36e42008-02-12 12:08:14 +00001906 }
Owen Andersonb62f7922009-10-28 07:05:35 +00001907
Owen Anderson9ff5a232009-12-02 07:35:19 +00001908 // If this load occurs either right after a lifetime begin,
Owen Andersonb62f7922009-10-28 07:05:35 +00001909 // then the loaded value is undefined.
Chris Lattner4756ecb2011-04-28 16:36:48 +00001910 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(DepInst)) {
Owen Anderson9ff5a232009-12-02 07:35:19 +00001911 if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
Owen Andersonb62f7922009-10-28 07:05:35 +00001912 L->replaceAllUsesWith(UndefValue::get(L->getType()));
Chris Lattner4756ecb2011-04-28 16:36:48 +00001913 markInstructionForDeletion(L);
Dan Gohmanfe601042010-06-22 15:08:57 +00001914 ++NumGVNLoad;
Owen Andersonb62f7922009-10-28 07:05:35 +00001915 return true;
1916 }
1917 }
Eli Friedmanb6c36e42008-02-12 12:08:14 +00001918
Chris Lattnerb51deb92008-12-05 21:04:20 +00001919 return false;
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001920}
1921
Owen Anderson7a75d612011-01-04 19:13:25 +00001922// findLeader - In order to find a leader for a given value number at a
Owen Anderson68c26392010-11-19 22:48:40 +00001923// specific basic block, we first obtain the list of all Values for that number,
1924// and then scan the list to find one whose block dominates the block in
1925// question. This is fast because dominator tree queries consist of only
1926// a few comparisons of DFS numbers.
Owen Anderson7a75d612011-01-04 19:13:25 +00001927Value *GVN::findLeader(BasicBlock *BB, uint32_t num) {
Owen Andersonb1602ab2011-01-04 19:29:46 +00001928 LeaderTableEntry Vals = LeaderTable[num];
Owen Andersonf0568382010-12-21 23:54:34 +00001929 if (!Vals.Val) return 0;
Owen Andersona04a0642010-11-18 18:32:40 +00001930
Owen Andersonf0568382010-12-21 23:54:34 +00001931 Value *Val = 0;
1932 if (DT->dominates(Vals.BB, BB)) {
1933 Val = Vals.Val;
1934 if (isa<Constant>(Val)) return Val;
1935 }
1936
Owen Anderson7a75d612011-01-04 19:13:25 +00001937 LeaderTableEntry* Next = Vals.Next;
Owen Andersona04a0642010-11-18 18:32:40 +00001938 while (Next) {
Owen Andersonf0568382010-12-21 23:54:34 +00001939 if (DT->dominates(Next->BB, BB)) {
1940 if (isa<Constant>(Next->Val)) return Next->Val;
1941 if (!Val) Val = Next->Val;
1942 }
Owen Andersona04a0642010-11-18 18:32:40 +00001943
Owen Andersonf0568382010-12-21 23:54:34 +00001944 Next = Next->Next;
Owen Anderson6fafe842008-06-20 01:15:47 +00001945 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001946
Owen Andersonf0568382010-12-21 23:54:34 +00001947 return Val;
Owen Anderson6fafe842008-06-20 01:15:47 +00001948}
1949
Duncan Sands02b5e722011-10-05 14:28:49 +00001950/// replaceAllDominatedUsesWith - Replace all uses of 'From' with 'To' if the
1951/// use is dominated by the given basic block. Returns the number of uses that
1952/// were replaced.
1953unsigned GVN::replaceAllDominatedUsesWith(Value *From, Value *To,
1954 BasicBlock *Root) {
1955 unsigned Count = 0;
1956 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
1957 UI != UE; ) {
Duncan Sands8c160542012-02-08 14:10:53 +00001958 Use &U = (UI++).getUse();
Duncan Sands190e5a32012-03-04 13:25:19 +00001959
1960 // If From occurs as a phi node operand then the use implicitly lives in the
1961 // corresponding incoming block. Otherwise it is the block containing the
1962 // user that must be dominated by Root.
1963 BasicBlock *UsingBlock;
1964 if (PHINode *PN = dyn_cast<PHINode>(U.getUser()))
1965 UsingBlock = PN->getIncomingBlock(U);
1966 else
1967 UsingBlock = cast<Instruction>(U.getUser())->getParent();
1968
1969 if (DT->dominates(Root, UsingBlock)) {
Duncan Sands8c160542012-02-08 14:10:53 +00001970 U.set(To);
Duncan Sands02b5e722011-10-05 14:28:49 +00001971 ++Count;
1972 }
1973 }
1974 return Count;
1975}
1976
1977/// propagateEquality - The given values are known to be equal in every block
1978/// dominated by 'Root'. Exploit this, for example by replacing 'LHS' with
1979/// 'RHS' everywhere in the scope. Returns whether a change was made.
1980bool GVN::propagateEquality(Value *LHS, Value *RHS, BasicBlock *Root) {
1981 if (LHS == RHS) return false;
1982 assert(LHS->getType() == RHS->getType() && "Equal but types differ!");
1983
1984 // Don't try to propagate equalities between constants.
1985 if (isa<Constant>(LHS) && isa<Constant>(RHS))
1986 return false;
1987
Duncan Sands2b4f4912012-02-29 11:12:03 +00001988 // Prefer a constant on the right-hand side, or an Argument if no constants.
1989 if (isa<Constant>(LHS) || (isa<Argument>(LHS) && !isa<Constant>(RHS)))
Duncan Sands02b5e722011-10-05 14:28:49 +00001990 std::swap(LHS, RHS);
Duncan Sands2b4f4912012-02-29 11:12:03 +00001991 assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) && "Unexpected value!");
Duncan Sands02b5e722011-10-05 14:28:49 +00001992
Duncan Sands2b4f4912012-02-29 11:12:03 +00001993 // If there is no obvious reason to prefer the left-hand side over the right-
1994 // hand side, ensure the longest lived term is on the right-hand side, so the
1995 // shortest lived term will be replaced by the longest lived. This tends to
1996 // expose more simplifications.
1997 uint32_t LVN = VN.lookup_or_add(LHS);
1998 if ((isa<Argument>(LHS) && isa<Argument>(RHS)) ||
1999 (isa<Instruction>(LHS) && isa<Instruction>(RHS))) {
2000 // Move the 'oldest' value to the right-hand side, using the value number as
2001 // a proxy for age.
2002 uint32_t RVN = VN.lookup_or_add(RHS);
2003 if (LVN < RVN) {
2004 std::swap(LHS, RHS);
2005 LVN = RVN;
2006 }
2007 }
Duncan Sands02b5e722011-10-05 14:28:49 +00002008
2009 // If value numbering later deduces that an instruction in the scope is equal
2010 // to 'LHS' then ensure it will be turned into 'RHS'.
Duncan Sands2b4f4912012-02-29 11:12:03 +00002011 addToLeaderTable(LVN, RHS, Root);
Duncan Sands02b5e722011-10-05 14:28:49 +00002012
Duncan Sands1673b152011-10-15 11:13:42 +00002013 // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope. As
2014 // LHS always has at least one use that is not dominated by Root, this will
2015 // never do anything if LHS has only one use.
2016 bool Changed = false;
2017 if (!LHS->hasOneUse()) {
2018 unsigned NumReplacements = replaceAllDominatedUsesWith(LHS, RHS, Root);
2019 Changed |= NumReplacements > 0;
2020 NumGVNEqProp += NumReplacements;
2021 }
Duncan Sands02b5e722011-10-05 14:28:49 +00002022
2023 // Now try to deduce additional equalities from this one. For example, if the
2024 // known equality was "(A != B)" == "false" then it follows that A and B are
2025 // equal in the scope. Only boolean equalities with an explicit true or false
2026 // RHS are currently supported.
2027 if (!RHS->getType()->isIntegerTy(1))
2028 // Not a boolean equality - bail out.
2029 return Changed;
2030 ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
2031 if (!CI)
2032 // RHS neither 'true' nor 'false' - bail out.
2033 return Changed;
2034 // Whether RHS equals 'true'. Otherwise it equals 'false'.
2035 bool isKnownTrue = CI->isAllOnesValue();
2036 bool isKnownFalse = !isKnownTrue;
2037
2038 // If "A && B" is known true then both A and B are known true. If "A || B"
2039 // is known false then both A and B are known false.
2040 Value *A, *B;
2041 if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) ||
2042 (isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) {
2043 Changed |= propagateEquality(A, RHS, Root);
2044 Changed |= propagateEquality(B, RHS, Root);
2045 return Changed;
2046 }
2047
2048 // If we are propagating an equality like "(A == B)" == "true" then also
Duncan Sands669011f2012-02-27 08:14:30 +00002049 // propagate the equality A == B. When propagating a comparison such as
2050 // "(A >= B)" == "true", replace all instances of "A < B" with "false".
Duncan Sands02b5e722011-10-05 14:28:49 +00002051 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(LHS)) {
Duncan Sands669011f2012-02-27 08:14:30 +00002052 Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
2053
2054 // If "A == B" is known true, or "A != B" is known false, then replace
2055 // A with B everywhere in the scope.
Duncan Sands02b5e722011-10-05 14:28:49 +00002056 if ((isKnownTrue && Cmp->getPredicate() == CmpInst::ICMP_EQ) ||
Duncan Sands669011f2012-02-27 08:14:30 +00002057 (isKnownFalse && Cmp->getPredicate() == CmpInst::ICMP_NE))
Duncan Sands02b5e722011-10-05 14:28:49 +00002058 Changed |= propagateEquality(Op0, Op1, Root);
Duncan Sands669011f2012-02-27 08:14:30 +00002059
2060 // If "A >= B" is known true, replace "A < B" with false everywhere.
2061 CmpInst::Predicate NotPred = Cmp->getInversePredicate();
2062 Constant *NotVal = ConstantInt::get(Cmp->getType(), isKnownFalse);
2063 // Since we don't have the instruction "A < B" immediately to hand, work out
2064 // the value number that it would have and use that to find an appropriate
2065 // instruction (if any).
Duncan Sands768ada62012-02-27 12:11:41 +00002066 uint32_t NextNum = VN.getNextUnusedValueNumber();
2067 uint32_t Num = VN.lookup_or_add_cmp(Cmp->getOpcode(), NotPred, Op0, Op1);
2068 // If the number we were assigned was brand new then there is no point in
2069 // looking for an instruction realizing it: there cannot be one!
2070 if (Num < NextNum) {
2071 Value *NotCmp = findLeader(Root, Num);
2072 if (NotCmp && isa<Instruction>(NotCmp)) {
2073 unsigned NumReplacements =
2074 replaceAllDominatedUsesWith(NotCmp, NotVal, Root);
2075 Changed |= NumReplacements > 0;
2076 NumGVNEqProp += NumReplacements;
2077 }
Duncan Sands02b5e722011-10-05 14:28:49 +00002078 }
Duncan Sands669011f2012-02-27 08:14:30 +00002079 // Ensure that any instruction in scope that gets the "A < B" value number
2080 // is replaced with false.
2081 addToLeaderTable(Num, NotVal, Root);
2082
Duncan Sands02b5e722011-10-05 14:28:49 +00002083 return Changed;
2084 }
2085
2086 return Changed;
2087}
Owen Anderson255dafc2008-12-15 02:03:00 +00002088
Duncan Sands3f329cb2011-10-07 08:29:06 +00002089/// isOnlyReachableViaThisEdge - There is an edge from 'Src' to 'Dst'. Return
2090/// true if every path from the entry block to 'Dst' passes via this edge. In
2091/// particular 'Dst' must not be reachable via another edge from 'Src'.
2092static bool isOnlyReachableViaThisEdge(BasicBlock *Src, BasicBlock *Dst,
2093 DominatorTree *DT) {
Duncan Sands33756f92012-02-05 18:25:50 +00002094 // While in theory it is interesting to consider the case in which Dst has
2095 // more than one predecessor, because Dst might be part of a loop which is
2096 // only reachable from Src, in practice it is pointless since at the time
2097 // GVN runs all such loops have preheaders, which means that Dst will have
2098 // been changed to have only one predecessor, namely Src.
Duncan Sandsc4fd4482012-02-05 19:43:37 +00002099 BasicBlock *Pred = Dst->getSinglePredecessor();
2100 assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
Duncan Sands33756f92012-02-05 18:25:50 +00002101 (void)Src;
Duncan Sandsc4fd4482012-02-05 19:43:37 +00002102 return Pred != 0;
Duncan Sands3f329cb2011-10-07 08:29:06 +00002103}
2104
Owen Anderson36057c72007-08-14 18:16:29 +00002105/// processInstruction - When calculating availability, handle an instruction
Owen Anderson1ad2cb72007-07-24 17:55:58 +00002106/// by inserting it into the appropriate sets
Chris Lattnerf07054d2011-04-28 16:18:52 +00002107bool GVN::processInstruction(Instruction *I) {
Devang Patelbe905e22010-02-11 00:20:49 +00002108 // Ignore dbg info intrinsics.
2109 if (isa<DbgInfoIntrinsic>(I))
2110 return false;
2111
Duncan Sands88c3df72010-11-12 21:10:24 +00002112 // If the instruction can be easily simplified then do so now in preference
2113 // to value numbering it. Value numbering often exposes redundancies, for
2114 // example if it determines that %y is equal to %x then the instruction
2115 // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
Chad Rosier618c1db2011-12-01 03:08:23 +00002116 if (Value *V = SimplifyInstruction(I, TD, TLI, DT)) {
Duncan Sands88c3df72010-11-12 21:10:24 +00002117 I->replaceAllUsesWith(V);
2118 if (MD && V->getType()->isPointerTy())
2119 MD->invalidateCachedPointerInfo(V);
Chris Lattner4756ecb2011-04-28 16:36:48 +00002120 markInstructionForDeletion(I);
Duncan Sands02b5e722011-10-05 14:28:49 +00002121 ++NumGVNSimpl;
Duncan Sands88c3df72010-11-12 21:10:24 +00002122 return true;
2123 }
2124
Chris Lattnerb2412a82009-09-21 02:42:51 +00002125 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf07054d2011-04-28 16:18:52 +00002126 if (processLoad(LI))
2127 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002128
Chris Lattnerf07054d2011-04-28 16:18:52 +00002129 unsigned Num = VN.lookup_or_add(LI);
2130 addToLeaderTable(Num, LI, LI->getParent());
2131 return false;
Owen Andersonb2303722008-06-18 21:41:49 +00002132 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002133
Duncan Sands02b5e722011-10-05 14:28:49 +00002134 // For conditional branches, we can perform simple conditional propagation on
Owen Andersonf0568382010-12-21 23:54:34 +00002135 // the condition value itself.
2136 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
Owen Andersonf0568382010-12-21 23:54:34 +00002137 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
2138 return false;
Duncan Sands02b5e722011-10-05 14:28:49 +00002139
Owen Andersonf0568382010-12-21 23:54:34 +00002140 Value *BranchCond = BI->getCondition();
Duncan Sands02b5e722011-10-05 14:28:49 +00002141
Owen Andersonf0568382010-12-21 23:54:34 +00002142 BasicBlock *TrueSucc = BI->getSuccessor(0);
2143 BasicBlock *FalseSucc = BI->getSuccessor(1);
Duncan Sands452c58f2011-10-05 14:17:01 +00002144 BasicBlock *Parent = BI->getParent();
Duncan Sands3f329cb2011-10-07 08:29:06 +00002145 bool Changed = false;
Duncan Sands452c58f2011-10-05 14:17:01 +00002146
Duncan Sands3f329cb2011-10-07 08:29:06 +00002147 if (isOnlyReachableViaThisEdge(Parent, TrueSucc, DT))
2148 Changed |= propagateEquality(BranchCond,
Duncan Sands02b5e722011-10-05 14:28:49 +00002149 ConstantInt::getTrue(TrueSucc->getContext()),
Duncan Sands3f329cb2011-10-07 08:29:06 +00002150 TrueSucc);
2151
2152 if (isOnlyReachableViaThisEdge(Parent, FalseSucc, DT))
2153 Changed |= propagateEquality(BranchCond,
2154 ConstantInt::getFalse(FalseSucc->getContext()),
2155 FalseSucc);
2156
2157 return Changed;
Owen Andersonf0568382010-12-21 23:54:34 +00002158 }
Duncan Sands3f329cb2011-10-07 08:29:06 +00002159
2160 // For switches, propagate the case values into the case destinations.
2161 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
2162 Value *SwitchCond = SI->getCondition();
2163 BasicBlock *Parent = SI->getParent();
2164 bool Changed = false;
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00002165 for (unsigned i = 0, e = SI->getNumCases(); i != e; ++i) {
2166 BasicBlock *Dst = SI->getCaseSuccessor(i);
Duncan Sands3f329cb2011-10-07 08:29:06 +00002167 if (isOnlyReachableViaThisEdge(Parent, Dst, DT))
2168 Changed |= propagateEquality(SwitchCond, SI->getCaseValue(i), Dst);
2169 }
2170 return Changed;
2171 }
2172
Owen Anderson2cf75372011-01-04 22:15:21 +00002173 // Instructions with void type don't return a value, so there's
Duncan Sands5583e302012-02-27 09:54:35 +00002174 // no point in trying to find redundancies in them.
Owen Anderson2cf75372011-01-04 22:15:21 +00002175 if (I->getType()->isVoidTy()) return false;
2176
Owen Andersonc2146a62011-01-04 18:54:18 +00002177 uint32_t NextNum = VN.getNextUnusedValueNumber();
2178 unsigned Num = VN.lookup_or_add(I);
2179
Owen Andersone5ffa902008-04-07 09:59:07 +00002180 // Allocations are always uniquely numbered, so we can save time and memory
Daniel Dunbara279bc32009-09-20 02:20:51 +00002181 // by fast failing them.
Chris Lattner459f4f82010-12-19 20:24:28 +00002182 if (isa<AllocaInst>(I) || isa<TerminatorInst>(I) || isa<PHINode>(I)) {
Owen Anderson7a75d612011-01-04 19:13:25 +00002183 addToLeaderTable(Num, I, I->getParent());
Owen Andersone5ffa902008-04-07 09:59:07 +00002184 return false;
Owen Andersonb2303722008-06-18 21:41:49 +00002185 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002186
Owen Anderson0ae33ef2008-07-03 17:44:33 +00002187 // If the number we were assigned was a brand new VN, then we don't
2188 // need to do a lookup to see if the number already exists
2189 // somewhere in the domtree: it can't!
Duncan Sands5583e302012-02-27 09:54:35 +00002190 if (Num >= NextNum) {
Owen Anderson7a75d612011-01-04 19:13:25 +00002191 addToLeaderTable(Num, I, I->getParent());
Chris Lattner459f4f82010-12-19 20:24:28 +00002192 return false;
2193 }
2194
Owen Anderson255dafc2008-12-15 02:03:00 +00002195 // Perform fast-path value-number based elimination of values inherited from
2196 // dominators.
Owen Anderson7a75d612011-01-04 19:13:25 +00002197 Value *repl = findLeader(I->getParent(), Num);
Chris Lattner459f4f82010-12-19 20:24:28 +00002198 if (repl == 0) {
2199 // Failure, just remember this instance for future use.
Owen Anderson7a75d612011-01-04 19:13:25 +00002200 addToLeaderTable(Num, I, I->getParent());
Chris Lattner459f4f82010-12-19 20:24:28 +00002201 return false;
Owen Anderson1ad2cb72007-07-24 17:55:58 +00002202 }
Chris Lattner459f4f82010-12-19 20:24:28 +00002203
2204 // Remove it!
Chris Lattner459f4f82010-12-19 20:24:28 +00002205 I->replaceAllUsesWith(repl);
2206 if (MD && repl->getType()->isPointerTy())
2207 MD->invalidateCachedPointerInfo(repl);
Chris Lattner4756ecb2011-04-28 16:36:48 +00002208 markInstructionForDeletion(I);
Chris Lattner459f4f82010-12-19 20:24:28 +00002209 return true;
Owen Anderson1ad2cb72007-07-24 17:55:58 +00002210}
2211
Bill Wendling30788b82008-12-22 22:32:22 +00002212/// runOnFunction - This is the main transformation entry point for a function.
Owen Anderson3e75a422007-08-14 18:04:11 +00002213bool GVN::runOnFunction(Function& F) {
Dan Gohman4ec01b22009-11-14 02:27:51 +00002214 if (!NoLoads)
2215 MD = &getAnalysis<MemoryDependenceAnalysis>();
Chris Lattner663e4412008-12-01 00:40:32 +00002216 DT = &getAnalysis<DominatorTree>();
Duncan Sands88c3df72010-11-12 21:10:24 +00002217 TD = getAnalysisIfAvailable<TargetData>();
Chad Rosier618c1db2011-12-01 03:08:23 +00002218 TLI = &getAnalysis<TargetLibraryInfo>();
Owen Andersona472c4a2008-05-12 20:15:55 +00002219 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
Chris Lattner663e4412008-12-01 00:40:32 +00002220 VN.setMemDep(MD);
2221 VN.setDomTree(DT);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002222
Chris Lattnerb2412a82009-09-21 02:42:51 +00002223 bool Changed = false;
2224 bool ShouldContinue = true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002225
Owen Anderson5d0af032008-07-16 17:52:31 +00002226 // Merge unconditional branches, allowing PRE to catch more
2227 // optimization opportunities.
2228 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
Chris Lattnerb5b79972011-01-11 08:13:40 +00002229 BasicBlock *BB = FI++;
2230
Owen Andersonb31b06d2008-07-17 00:01:40 +00002231 bool removedBlock = MergeBlockIntoPredecessor(BB, this);
Dan Gohmanfe601042010-06-22 15:08:57 +00002232 if (removedBlock) ++NumGVNBlocks;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002233
Chris Lattnerb2412a82009-09-21 02:42:51 +00002234 Changed |= removedBlock;
Owen Anderson5d0af032008-07-16 17:52:31 +00002235 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002236
Chris Lattnerae199312008-12-09 19:21:47 +00002237 unsigned Iteration = 0;
Chris Lattnerb2412a82009-09-21 02:42:51 +00002238 while (ShouldContinue) {
David Greenebf7f78e2010-01-05 01:27:17 +00002239 DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
Chris Lattnerb2412a82009-09-21 02:42:51 +00002240 ShouldContinue = iterateOnFunction(F);
Bob Wilson484d4a32010-02-16 19:51:59 +00002241 if (splitCriticalEdges())
2242 ShouldContinue = true;
Chris Lattnerb2412a82009-09-21 02:42:51 +00002243 Changed |= ShouldContinue;
Chris Lattnerae199312008-12-09 19:21:47 +00002244 ++Iteration;
Owen Anderson3e75a422007-08-14 18:04:11 +00002245 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002246
Owen Andersone98c54c2008-07-18 18:03:38 +00002247 if (EnablePRE) {
Owen Anderson0c7f91c2008-09-03 23:06:07 +00002248 bool PREChanged = true;
2249 while (PREChanged) {
2250 PREChanged = performPRE(F);
Chris Lattnerb2412a82009-09-21 02:42:51 +00002251 Changed |= PREChanged;
Owen Anderson0c7f91c2008-09-03 23:06:07 +00002252 }
Owen Andersone98c54c2008-07-18 18:03:38 +00002253 }
Chris Lattnerae199312008-12-09 19:21:47 +00002254 // FIXME: Should perform GVN again after PRE does something. PRE can move
2255 // computations into blocks where they become fully redundant. Note that
2256 // we can't do this until PRE's critical edge splitting updates memdep.
2257 // Actually, when this happens, we should just fully integrate PRE into GVN.
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +00002258
2259 cleanupGlobalSets();
2260
Chris Lattnerb2412a82009-09-21 02:42:51 +00002261 return Changed;
Owen Anderson3e75a422007-08-14 18:04:11 +00002262}
2263
2264
Chris Lattnerb2412a82009-09-21 02:42:51 +00002265bool GVN::processBlock(BasicBlock *BB) {
Chris Lattnerf07054d2011-04-28 16:18:52 +00002266 // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function
2267 // (and incrementing BI before processing an instruction).
2268 assert(InstrsToErase.empty() &&
2269 "We expect InstrsToErase to be empty across iterations");
Chris Lattnerb2412a82009-09-21 02:42:51 +00002270 bool ChangedFunction = false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002271
Owen Andersonaf4240a2008-06-12 19:25:32 +00002272 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
2273 BI != BE;) {
Chris Lattnerf07054d2011-04-28 16:18:52 +00002274 ChangedFunction |= processInstruction(BI);
2275 if (InstrsToErase.empty()) {
Owen Andersonaf4240a2008-06-12 19:25:32 +00002276 ++BI;
2277 continue;
2278 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002279
Owen Andersonaf4240a2008-06-12 19:25:32 +00002280 // If we need some instructions deleted, do it now.
Chris Lattnerf07054d2011-04-28 16:18:52 +00002281 NumGVNInstr += InstrsToErase.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00002282
Owen Andersonaf4240a2008-06-12 19:25:32 +00002283 // Avoid iterator invalidation.
2284 bool AtStart = BI == BB->begin();
2285 if (!AtStart)
2286 --BI;
2287
Chris Lattnerf07054d2011-04-28 16:18:52 +00002288 for (SmallVector<Instruction*, 4>::iterator I = InstrsToErase.begin(),
2289 E = InstrsToErase.end(); I != E; ++I) {
David Greenebf7f78e2010-01-05 01:27:17 +00002290 DEBUG(dbgs() << "GVN removed: " << **I << '\n');
Dan Gohman4ec01b22009-11-14 02:27:51 +00002291 if (MD) MD->removeInstruction(*I);
Owen Andersonaf4240a2008-06-12 19:25:32 +00002292 (*I)->eraseFromParent();
Bill Wendlingec40d502008-12-22 21:57:30 +00002293 DEBUG(verifyRemoved(*I));
Chris Lattner663e4412008-12-01 00:40:32 +00002294 }
Chris Lattnerf07054d2011-04-28 16:18:52 +00002295 InstrsToErase.clear();
Owen Andersonaf4240a2008-06-12 19:25:32 +00002296
2297 if (AtStart)
2298 BI = BB->begin();
2299 else
2300 ++BI;
Owen Andersonaf4240a2008-06-12 19:25:32 +00002301 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002302
Chris Lattnerb2412a82009-09-21 02:42:51 +00002303 return ChangedFunction;
Owen Andersonaf4240a2008-06-12 19:25:32 +00002304}
2305
Owen Andersonb2303722008-06-18 21:41:49 +00002306/// performPRE - Perform a purely local form of PRE that looks for diamond
2307/// control flow patterns and attempts to perform simple PRE at the join point.
Chris Lattnerfb6e7012009-10-31 22:11:15 +00002308bool GVN::performPRE(Function &F) {
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002309 bool Changed = false;
Chris Lattner09713792008-12-01 07:29:03 +00002310 DenseMap<BasicBlock*, Value*> predMap;
Owen Andersonb2303722008-06-18 21:41:49 +00002311 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
2312 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
Chris Lattnerb2412a82009-09-21 02:42:51 +00002313 BasicBlock *CurrentBlock = *DI;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002314
Owen Andersonb2303722008-06-18 21:41:49 +00002315 // Nothing to PRE in the entry block.
2316 if (CurrentBlock == &F.getEntryBlock()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002317
Bill Wendling795cf5e2011-08-17 21:32:02 +00002318 // Don't perform PRE on a landing pad.
2319 if (CurrentBlock->isLandingPad()) continue;
2320
Owen Andersonb2303722008-06-18 21:41:49 +00002321 for (BasicBlock::iterator BI = CurrentBlock->begin(),
2322 BE = CurrentBlock->end(); BI != BE; ) {
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002323 Instruction *CurInst = BI++;
Duncan Sands7af1c782009-05-06 06:49:50 +00002324
Victor Hernandez7b929da2009-10-23 21:09:37 +00002325 if (isa<AllocaInst>(CurInst) ||
Victor Hernandez83d63912009-09-18 22:35:49 +00002326 isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
Devang Patel9674d152009-10-14 17:29:00 +00002327 CurInst->getType()->isVoidTy() ||
Duncan Sands7af1c782009-05-06 06:49:50 +00002328 CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
John Criswell090c0a22009-03-10 15:04:53 +00002329 isa<DbgInfoIntrinsic>(CurInst))
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002330 continue;
Owen Anderson5015b342010-08-07 00:20:35 +00002331
2332 // We don't currently value number ANY inline asm calls.
2333 if (CallInst *CallI = dyn_cast<CallInst>(CurInst))
2334 if (CallI->isInlineAsm())
2335 continue;
Duncan Sands7af1c782009-05-06 06:49:50 +00002336
Chris Lattnerb2412a82009-09-21 02:42:51 +00002337 uint32_t ValNo = VN.lookup(CurInst);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002338
Owen Andersonb2303722008-06-18 21:41:49 +00002339 // Look for the predecessors for PRE opportunities. We're
2340 // only trying to solve the basic diamond case, where
2341 // a value is computed in the successor and one predecessor,
2342 // but not the other. We also explicitly disallow cases
2343 // where the successor is its own predecessor, because they're
2344 // more complicated to get right.
Chris Lattnerb2412a82009-09-21 02:42:51 +00002345 unsigned NumWith = 0;
2346 unsigned NumWithout = 0;
2347 BasicBlock *PREPred = 0;
Chris Lattner09713792008-12-01 07:29:03 +00002348 predMap.clear();
2349
Owen Andersonb2303722008-06-18 21:41:49 +00002350 for (pred_iterator PI = pred_begin(CurrentBlock),
2351 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
Gabor Greif08149852010-07-09 14:36:49 +00002352 BasicBlock *P = *PI;
Owen Andersonb2303722008-06-18 21:41:49 +00002353 // We're not interested in PRE where the block is its
Bob Wilsone7b635f2010-02-03 00:33:21 +00002354 // own predecessor, or in blocks with predecessors
Owen Anderson6fafe842008-06-20 01:15:47 +00002355 // that are not reachable.
Gabor Greif08149852010-07-09 14:36:49 +00002356 if (P == CurrentBlock) {
Chris Lattnerb2412a82009-09-21 02:42:51 +00002357 NumWithout = 2;
Owen Anderson6fafe842008-06-20 01:15:47 +00002358 break;
Owen Andersona04a0642010-11-18 18:32:40 +00002359 } else if (!DT->dominates(&F.getEntryBlock(), P)) {
Chris Lattnerb2412a82009-09-21 02:42:51 +00002360 NumWithout = 2;
Owen Anderson6fafe842008-06-20 01:15:47 +00002361 break;
2362 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002363
Owen Anderson7a75d612011-01-04 19:13:25 +00002364 Value* predV = findLeader(P, ValNo);
Owen Andersona04a0642010-11-18 18:32:40 +00002365 if (predV == 0) {
Gabor Greif08149852010-07-09 14:36:49 +00002366 PREPred = P;
Dan Gohmanfe601042010-06-22 15:08:57 +00002367 ++NumWithout;
Owen Andersona04a0642010-11-18 18:32:40 +00002368 } else if (predV == CurInst) {
Chris Lattnerb2412a82009-09-21 02:42:51 +00002369 NumWithout = 2;
Owen Andersonb2303722008-06-18 21:41:49 +00002370 } else {
Owen Andersona04a0642010-11-18 18:32:40 +00002371 predMap[P] = predV;
Dan Gohmanfe601042010-06-22 15:08:57 +00002372 ++NumWith;
Owen Andersonb2303722008-06-18 21:41:49 +00002373 }
2374 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002375
Owen Andersonb2303722008-06-18 21:41:49 +00002376 // Don't do PRE when it might increase code size, i.e. when
2377 // we would need to insert instructions in more than one pred.
Chris Lattnerb2412a82009-09-21 02:42:51 +00002378 if (NumWithout != 1 || NumWith == 0)
Owen Andersonb2303722008-06-18 21:41:49 +00002379 continue;
Chris Lattnerfb6e7012009-10-31 22:11:15 +00002380
2381 // Don't do PRE across indirect branch.
2382 if (isa<IndirectBrInst>(PREPred->getTerminator()))
2383 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002384
Owen Anderson5c274ee2008-06-19 19:54:19 +00002385 // We can't do PRE safely on a critical edge, so instead we schedule
2386 // the edge to be split and perform the PRE the next time we iterate
2387 // on the function.
Bob Wilsonae23daf2010-02-16 21:06:42 +00002388 unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
Chris Lattnerb2412a82009-09-21 02:42:51 +00002389 if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
2390 toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
Owen Anderson5c274ee2008-06-19 19:54:19 +00002391 continue;
2392 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002393
Bob Wilsone7b635f2010-02-03 00:33:21 +00002394 // Instantiate the expression in the predecessor that lacked it.
Owen Andersonb2303722008-06-18 21:41:49 +00002395 // Because we are going top-down through the block, all value numbers
2396 // will be available in the predecessor by the time we need them. Any
Bob Wilsone7b635f2010-02-03 00:33:21 +00002397 // that weren't originally present will have been instantiated earlier
Owen Andersonb2303722008-06-18 21:41:49 +00002398 // in this loop.
Nick Lewycky67760642009-09-27 07:38:41 +00002399 Instruction *PREInstr = CurInst->clone();
Owen Andersonb2303722008-06-18 21:41:49 +00002400 bool success = true;
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002401 for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
2402 Value *Op = PREInstr->getOperand(i);
2403 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
2404 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002405
Owen Anderson7a75d612011-01-04 19:13:25 +00002406 if (Value *V = findLeader(PREPred, VN.lookup(Op))) {
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002407 PREInstr->setOperand(i, V);
2408 } else {
2409 success = false;
2410 break;
Owen Andersonc45996b2008-07-11 20:05:13 +00002411 }
Owen Andersonb2303722008-06-18 21:41:49 +00002412 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002413
Owen Andersonb2303722008-06-18 21:41:49 +00002414 // Fail out if we encounter an operand that is not available in
Daniel Dunbara279bc32009-09-20 02:20:51 +00002415 // the PRE predecessor. This is typically because of loads which
Owen Andersonb2303722008-06-18 21:41:49 +00002416 // are not value numbered precisely.
2417 if (!success) {
2418 delete PREInstr;
Bill Wendling70ded192008-12-22 22:14:07 +00002419 DEBUG(verifyRemoved(PREInstr));
Owen Andersonb2303722008-06-18 21:41:49 +00002420 continue;
2421 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002422
Owen Andersonb2303722008-06-18 21:41:49 +00002423 PREInstr->insertBefore(PREPred->getTerminator());
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002424 PREInstr->setName(CurInst->getName() + ".pre");
Devang Patelde985682011-05-17 20:00:02 +00002425 PREInstr->setDebugLoc(CurInst->getDebugLoc());
Owen Anderson6fafe842008-06-20 01:15:47 +00002426 predMap[PREPred] = PREInstr;
Chris Lattnerb2412a82009-09-21 02:42:51 +00002427 VN.add(PREInstr, ValNo);
Dan Gohmanfe601042010-06-22 15:08:57 +00002428 ++NumGVNPRE;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002429
Owen Andersonb2303722008-06-18 21:41:49 +00002430 // Update the availability map to include the new instruction.
Owen Anderson7a75d612011-01-04 19:13:25 +00002431 addToLeaderTable(ValNo, PREInstr, PREPred);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002432
Owen Andersonb2303722008-06-18 21:41:49 +00002433 // Create a PHI to make the value available in this block.
Jay Foadd8b4fb42011-03-30 11:19:20 +00002434 pred_iterator PB = pred_begin(CurrentBlock), PE = pred_end(CurrentBlock);
Jay Foad3ecfc862011-03-30 11:28:46 +00002435 PHINode* Phi = PHINode::Create(CurInst->getType(), std::distance(PB, PE),
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002436 CurInst->getName() + ".pre-phi",
Owen Andersonb2303722008-06-18 21:41:49 +00002437 CurrentBlock->begin());
Jay Foadd8b4fb42011-03-30 11:19:20 +00002438 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif1d3ae022010-07-09 14:48:08 +00002439 BasicBlock *P = *PI;
2440 Phi->addIncoming(predMap[P], P);
2441 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002442
Chris Lattnerb2412a82009-09-21 02:42:51 +00002443 VN.add(Phi, ValNo);
Owen Anderson7a75d612011-01-04 19:13:25 +00002444 addToLeaderTable(ValNo, Phi, CurrentBlock);
Devang Patel0f18d972011-05-04 23:58:50 +00002445 Phi->setDebugLoc(CurInst->getDebugLoc());
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002446 CurInst->replaceAllUsesWith(Phi);
Owen Anderson392249f2011-01-03 23:51:43 +00002447 if (Phi->getType()->isPointerTy()) {
2448 // Because we have added a PHI-use of the pointer value, it has now
2449 // "escaped" from alias analysis' perspective. We need to inform
2450 // AA of this.
Jay Foadc1371202011-06-20 14:18:48 +00002451 for (unsigned ii = 0, ee = Phi->getNumIncomingValues(); ii != ee;
2452 ++ii) {
2453 unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
2454 VN.getAliasAnalysis()->addEscapingUse(Phi->getOperandUse(jj));
2455 }
Owen Anderson392249f2011-01-03 23:51:43 +00002456
2457 if (MD)
2458 MD->invalidateCachedPointerInfo(Phi);
2459 }
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002460 VN.erase(CurInst);
Owen Anderson7a75d612011-01-04 19:13:25 +00002461 removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
Daniel Dunbara279bc32009-09-20 02:20:51 +00002462
David Greenebf7f78e2010-01-05 01:27:17 +00002463 DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
Dan Gohman4ec01b22009-11-14 02:27:51 +00002464 if (MD) MD->removeInstruction(CurInst);
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002465 CurInst->eraseFromParent();
Bill Wendlingec40d502008-12-22 21:57:30 +00002466 DEBUG(verifyRemoved(CurInst));
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00002467 Changed = true;
Owen Andersonb2303722008-06-18 21:41:49 +00002468 }
2469 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00002470
Bob Wilson484d4a32010-02-16 19:51:59 +00002471 if (splitCriticalEdges())
2472 Changed = true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00002473
Bob Wilson484d4a32010-02-16 19:51:59 +00002474 return Changed;
2475}
2476
2477/// splitCriticalEdges - Split critical edges found during the previous
2478/// iteration that may enable further optimization.
2479bool GVN::splitCriticalEdges() {
2480 if (toSplit.empty())
2481 return false;
2482 do {
2483 std::pair<TerminatorInst*, unsigned> Edge = toSplit.pop_back_val();
2484 SplitCriticalEdge(Edge.first, Edge.second, this);
2485 } while (!toSplit.empty());
Evan Cheng19d417c2010-03-01 22:23:12 +00002486 if (MD) MD->invalidateCachedPredecessors();
Bob Wilson484d4a32010-02-16 19:51:59 +00002487 return true;
Owen Andersonb2303722008-06-18 21:41:49 +00002488}
2489
Bill Wendling30788b82008-12-22 22:32:22 +00002490/// iterateOnFunction - Executes one iteration of GVN
Owen Anderson3e75a422007-08-14 18:04:11 +00002491bool GVN::iterateOnFunction(Function &F) {
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +00002492 cleanupGlobalSets();
Owen Andersona04a0642010-11-18 18:32:40 +00002493
Owen Anderson1ad2cb72007-07-24 17:55:58 +00002494 // Top-down walk of the dominator tree
Chris Lattnerb2412a82009-09-21 02:42:51 +00002495 bool Changed = false;
Owen Andersonc34d1122008-12-15 03:52:17 +00002496#if 0
2497 // Needed for value numbering with phi construction to work.
Owen Anderson255dafc2008-12-15 02:03:00 +00002498 ReversePostOrderTraversal<Function*> RPOT(&F);
2499 for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
2500 RE = RPOT.end(); RI != RE; ++RI)
Chris Lattnerb2412a82009-09-21 02:42:51 +00002501 Changed |= processBlock(*RI);
Owen Andersonc34d1122008-12-15 03:52:17 +00002502#else
2503 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
2504 DE = df_end(DT->getRootNode()); DI != DE; ++DI)
Chris Lattnerb2412a82009-09-21 02:42:51 +00002505 Changed |= processBlock(DI->getBlock());
Owen Andersonc34d1122008-12-15 03:52:17 +00002506#endif
2507
Chris Lattnerb2412a82009-09-21 02:42:51 +00002508 return Changed;
Owen Anderson1ad2cb72007-07-24 17:55:58 +00002509}
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +00002510
2511void GVN::cleanupGlobalSets() {
2512 VN.clear();
Owen Andersonb1602ab2011-01-04 19:29:46 +00002513 LeaderTable.clear();
Owen Andersona04a0642010-11-18 18:32:40 +00002514 TableAllocator.Reset();
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +00002515}
Bill Wendling246dbbb2008-12-22 21:36:08 +00002516
2517/// verifyRemoved - Verify that the specified instruction does not occur in our
2518/// internal data structures.
Bill Wendling6d463f22008-12-22 22:28:56 +00002519void GVN::verifyRemoved(const Instruction *Inst) const {
2520 VN.verifyRemoved(Inst);
Bill Wendling70ded192008-12-22 22:14:07 +00002521
Bill Wendling6d463f22008-12-22 22:28:56 +00002522 // Walk through the value number scope to make sure the instruction isn't
2523 // ferreted away in it.
Owen Anderson7a75d612011-01-04 19:13:25 +00002524 for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator
Owen Andersonb1602ab2011-01-04 19:29:46 +00002525 I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) {
Owen Anderson7a75d612011-01-04 19:13:25 +00002526 const LeaderTableEntry *Node = &I->second;
Owen Andersonf0568382010-12-21 23:54:34 +00002527 assert(Node->Val != Inst && "Inst still in value numbering scope!");
Owen Andersona04a0642010-11-18 18:32:40 +00002528
Owen Andersonf0568382010-12-21 23:54:34 +00002529 while (Node->Next) {
2530 Node = Node->Next;
2531 assert(Node->Val != Inst && "Inst still in value numbering scope!");
Bill Wendling70ded192008-12-22 22:14:07 +00002532 }
2533 }
Bill Wendling246dbbb2008-12-22 21:36:08 +00002534}