blob: 996996dc55d9e9241850abf30c7f2e8192277b10 [file] [log] [blame]
Chris Lattnerd2a653a2008-12-05 07:49:08 +00001//===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
Owen Andersonab6ec2e2007-07-24 17:55:58 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Andersonab6ec2e2007-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 Criswell073e4d12009-03-10 15:04:53 +000013// Note that this pass does the value numbering itself; it does not use the
Matthijs Kooijman5afc2742008-06-05 07:55:49 +000014// ValueNumbering analysis passes.
15//
Owen Andersonab6ec2e2007-07-24 17:55:58 +000016//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "gvn"
Owen Andersonab6ec2e2007-07-24 17:55:58 +000019#include "llvm/Transforms/Scalar.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000020#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/DepthFirstIterator.h"
22#include "llvm/ADT/Hashing.h"
23#include "llvm/ADT/SmallPtrSet.h"
24#include "llvm/ADT/Statistic.h"
Owen Anderson09b83ba2007-10-18 19:39:33 +000025#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner778cb922009-12-06 05:29:56 +000026#include "llvm/Analysis/ConstantFolding.h"
27#include "llvm/Analysis/Dominators.h"
Duncan Sands246b71c2010-11-12 21:10:24 +000028#include "llvm/Analysis/InstructionSimplify.h"
Dan Gohman826bdf82010-05-28 16:19:17 +000029#include "llvm/Analysis/Loads.h"
Victor Hernandezf390e042009-10-27 20:05:49 +000030#include "llvm/Analysis/MemoryBuiltins.h"
Owen Andersonab6ec2e2007-07-24 17:55:58 +000031#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Chris Lattner972e6d82009-12-09 01:59:31 +000032#include "llvm/Analysis/PHITransAddr.h"
Chris Lattnere28618d2010-11-30 22:25:26 +000033#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbf0aa922011-01-02 22:09:33 +000034#include "llvm/Assembly/Writer.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/DataLayout.h"
36#include "llvm/IR/GlobalVariable.h"
37#include "llvm/IR/IRBuilder.h"
38#include "llvm/IR/IntrinsicInst.h"
39#include "llvm/IR/LLVMContext.h"
40#include "llvm/IR/Metadata.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000041#include "llvm/Support/Allocator.h"
42#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/Debug.h"
44#include "llvm/Support/PatternMatch.h"
Chad Rosierc24b86f2011-12-01 03:08:23 +000045#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattnere28618d2010-11-30 22:25:26 +000046#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnere28618d2010-11-30 22:25:26 +000047#include "llvm/Transforms/Utils/SSAUpdater.h"
Shuxin Yang1d8d7e42013-05-09 18:34:27 +000048#include <vector>
Owen Andersonab6ec2e2007-07-24 17:55:58 +000049using namespace llvm;
Duncan Sandsf4f47cc2011-10-05 14:28:49 +000050using namespace PatternMatch;
Owen Andersonab6ec2e2007-07-24 17:55:58 +000051
Bill Wendling3c793442008-12-22 22:14:07 +000052STATISTIC(NumGVNInstr, "Number of instructions deleted");
53STATISTIC(NumGVNLoad, "Number of loads deleted");
54STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
Owen Anderson53d546e2008-07-15 16:28:06 +000055STATISTIC(NumGVNBlocks, "Number of blocks merged");
Duncan Sandsf4f47cc2011-10-05 14:28:49 +000056STATISTIC(NumGVNSimpl, "Number of instructions simplified");
57STATISTIC(NumGVNEqProp, "Number of equalities propagated");
Bill Wendling3c793442008-12-22 22:14:07 +000058STATISTIC(NumPRELoad, "Number of loads PRE'd");
Chris Lattner168be762008-03-22 04:13:49 +000059
Evan Cheng9598f932008-06-20 01:01:07 +000060static cl::opt<bool> EnablePRE("enable-pre",
Owen Andersonaddbe3e2008-07-17 19:41:00 +000061 cl::init(true), cl::Hidden);
Dan Gohmana8f8a852009-06-15 18:30:15 +000062static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
Owen Andersone780d662008-06-19 19:57:25 +000063
Mon P Wang6120cfb2012-04-27 18:09:28 +000064// Maximum allowed recursion depth.
David Blaikie84e4b392012-04-27 19:30:32 +000065static cl::opt<uint32_t>
Mon P Wang6120cfb2012-04-27 18:09:28 +000066MaxRecurseDepth("max-recurse-depth", cl::Hidden, cl::init(1000), cl::ZeroOrMore,
67 cl::desc("Max recurse depth (default = 1000)"));
68
Owen Andersonab6ec2e2007-07-24 17:55:58 +000069//===----------------------------------------------------------------------===//
70// ValueTable Class
71//===----------------------------------------------------------------------===//
72
73/// This class holds the mapping between values and value numbers. It is used
74/// as an efficient mechanism to determine the expression-wise equivalence of
75/// two values.
76namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +000077 struct Expression {
Owen Anderson3a33d0c2011-01-03 19:00:11 +000078 uint32_t opcode;
Chris Lattner229907c2011-07-18 04:54:35 +000079 Type *type;
Owen Andersonab6ec2e2007-07-24 17:55:58 +000080 SmallVector<uint32_t, 4> varargs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000081
Chris Lattner45e393f2011-04-28 18:08:21 +000082 Expression(uint32_t o = ~2U) : opcode(o) { }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000083
Owen Andersonab6ec2e2007-07-24 17:55:58 +000084 bool operator==(const Expression &other) const {
85 if (opcode != other.opcode)
86 return false;
Chris Lattner45e393f2011-04-28 18:08:21 +000087 if (opcode == ~0U || opcode == ~1U)
Owen Andersonab6ec2e2007-07-24 17:55:58 +000088 return true;
Chris Lattner45e393f2011-04-28 18:08:21 +000089 if (type != other.type)
Owen Andersonab6ec2e2007-07-24 17:55:58 +000090 return false;
Chris Lattner45e393f2011-04-28 18:08:21 +000091 if (varargs != other.varargs)
Benjamin Kramer43493c02010-12-21 21:30:19 +000092 return false;
93 return true;
Owen Andersonab6ec2e2007-07-24 17:55:58 +000094 }
Chandler Carruthe134d1a2012-03-05 11:29:54 +000095
96 friend hash_code hash_value(const Expression &Value) {
Chandler Carruthe134d1a2012-03-05 11:29:54 +000097 return hash_combine(Value.opcode, Value.type,
98 hash_combine_range(Value.varargs.begin(),
99 Value.varargs.end()));
100 }
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000101 };
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000102
Chris Lattner2dd09db2009-09-02 06:11:42 +0000103 class ValueTable {
Chris Lattner45e393f2011-04-28 18:08:21 +0000104 DenseMap<Value*, uint32_t> valueNumbering;
105 DenseMap<Expression, uint32_t> expressionNumbering;
106 AliasAnalysis *AA;
107 MemoryDependenceAnalysis *MD;
108 DominatorTree *DT;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000109
Chris Lattner45e393f2011-04-28 18:08:21 +0000110 uint32_t nextValueNumber;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000111
Chris Lattner45e393f2011-04-28 18:08:21 +0000112 Expression create_expression(Instruction* I);
Duncan Sands27f45952012-02-27 08:14:30 +0000113 Expression create_cmp_expression(unsigned Opcode,
114 CmpInst::Predicate Predicate,
115 Value *LHS, Value *RHS);
Lang Hames29cd98f2011-07-08 01:50:54 +0000116 Expression create_extractvalue_expression(ExtractValueInst* EI);
Chris Lattner45e393f2011-04-28 18:08:21 +0000117 uint32_t lookup_or_add_call(CallInst* C);
118 public:
119 ValueTable() : nextValueNumber(1) { }
120 uint32_t lookup_or_add(Value *V);
121 uint32_t lookup(Value *V) const;
Duncan Sands27f45952012-02-27 08:14:30 +0000122 uint32_t lookup_or_add_cmp(unsigned Opcode, CmpInst::Predicate Pred,
123 Value *LHS, Value *RHS);
Chris Lattner45e393f2011-04-28 18:08:21 +0000124 void add(Value *V, uint32_t num);
125 void clear();
126 void erase(Value *v);
127 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
128 AliasAnalysis *getAliasAnalysis() const { return AA; }
129 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
130 void setDomTree(DominatorTree* D) { DT = D; }
131 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
132 void verifyRemoved(const Value *) const;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000133 };
134}
135
136namespace llvm {
Chris Lattner0625bd62007-09-17 18:34:04 +0000137template <> struct DenseMapInfo<Expression> {
Owen Anderson9699a6e2007-08-02 18:16:06 +0000138 static inline Expression getEmptyKey() {
Owen Anderson3a33d0c2011-01-03 19:00:11 +0000139 return ~0U;
Owen Anderson9699a6e2007-08-02 18:16:06 +0000140 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000141
Owen Anderson9699a6e2007-08-02 18:16:06 +0000142 static inline Expression getTombstoneKey() {
Owen Anderson3a33d0c2011-01-03 19:00:11 +0000143 return ~1U;
Owen Anderson9699a6e2007-08-02 18:16:06 +0000144 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000145
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000146 static unsigned getHashValue(const Expression e) {
Chandler Carruthe134d1a2012-03-05 11:29:54 +0000147 using llvm::hash_value;
148 return static_cast<unsigned>(hash_value(e));
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000149 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000150 static bool isEqual(const Expression &LHS, const Expression &RHS) {
151 return LHS == RHS;
152 }
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000153};
Chris Lattner45d040b2009-12-15 07:26:43 +0000154
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000155}
156
157//===----------------------------------------------------------------------===//
158// ValueTable Internal Functions
159//===----------------------------------------------------------------------===//
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000160
Owen Anderson3a33d0c2011-01-03 19:00:11 +0000161Expression ValueTable::create_expression(Instruction *I) {
162 Expression e;
163 e.type = I->getType();
164 e.opcode = I->getOpcode();
165 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
166 OI != OE; ++OI)
167 e.varargs.push_back(lookup_or_add(*OI));
Duncan Sands926d1012012-02-24 15:16:31 +0000168 if (I->isCommutative()) {
169 // Ensure that commutative instructions that only differ by a permutation
170 // of their operands get the same value number by sorting the operand value
171 // numbers. Since all commutative instructions have two operands it is more
172 // efficient to sort by hand rather than using, say, std::sort.
173 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
174 if (e.varargs[0] > e.varargs[1])
175 std::swap(e.varargs[0], e.varargs[1]);
176 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000177
Lang Hames29cd98f2011-07-08 01:50:54 +0000178 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
Duncan Sands926d1012012-02-24 15:16:31 +0000179 // Sort the operand value numbers so x<y and y>x get the same value number.
180 CmpInst::Predicate Predicate = C->getPredicate();
181 if (e.varargs[0] > e.varargs[1]) {
182 std::swap(e.varargs[0], e.varargs[1]);
183 Predicate = CmpInst::getSwappedPredicate(Predicate);
184 }
185 e.opcode = (C->getOpcode() << 8) | Predicate;
Owen Anderson3a33d0c2011-01-03 19:00:11 +0000186 } else if (InsertValueInst *E = dyn_cast<InsertValueInst>(I)) {
187 for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
188 II != IE; ++II)
189 e.varargs.push_back(*II);
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000190 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000191
Owen Anderson168ad692009-10-19 22:14:22 +0000192 return e;
193}
194
Duncan Sands27f45952012-02-27 08:14:30 +0000195Expression ValueTable::create_cmp_expression(unsigned Opcode,
196 CmpInst::Predicate Predicate,
197 Value *LHS, Value *RHS) {
198 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
199 "Not a comparison!");
200 Expression e;
201 e.type = CmpInst::makeCmpResultType(LHS->getType());
202 e.varargs.push_back(lookup_or_add(LHS));
203 e.varargs.push_back(lookup_or_add(RHS));
204
205 // Sort the operand value numbers so x<y and y>x get the same value number.
206 if (e.varargs[0] > e.varargs[1]) {
207 std::swap(e.varargs[0], e.varargs[1]);
208 Predicate = CmpInst::getSwappedPredicate(Predicate);
209 }
210 e.opcode = (Opcode << 8) | Predicate;
211 return e;
212}
213
Lang Hames29cd98f2011-07-08 01:50:54 +0000214Expression ValueTable::create_extractvalue_expression(ExtractValueInst *EI) {
215 assert(EI != 0 && "Not an ExtractValueInst?");
216 Expression e;
217 e.type = EI->getType();
218 e.opcode = 0;
219
220 IntrinsicInst *I = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
221 if (I != 0 && EI->getNumIndices() == 1 && *EI->idx_begin() == 0 ) {
222 // EI might be an extract from one of our recognised intrinsics. If it
223 // is we'll synthesize a semantically equivalent expression instead on
224 // an extract value expression.
225 switch (I->getIntrinsicID()) {
Lang Hames266dab72011-07-09 00:25:11 +0000226 case Intrinsic::sadd_with_overflow:
Lang Hames29cd98f2011-07-08 01:50:54 +0000227 case Intrinsic::uadd_with_overflow:
228 e.opcode = Instruction::Add;
229 break;
Lang Hames266dab72011-07-09 00:25:11 +0000230 case Intrinsic::ssub_with_overflow:
Lang Hames29cd98f2011-07-08 01:50:54 +0000231 case Intrinsic::usub_with_overflow:
232 e.opcode = Instruction::Sub;
233 break;
Lang Hames266dab72011-07-09 00:25:11 +0000234 case Intrinsic::smul_with_overflow:
Lang Hames29cd98f2011-07-08 01:50:54 +0000235 case Intrinsic::umul_with_overflow:
236 e.opcode = Instruction::Mul;
237 break;
238 default:
239 break;
240 }
241
242 if (e.opcode != 0) {
243 // Intrinsic recognized. Grab its args to finish building the expression.
244 assert(I->getNumArgOperands() == 2 &&
245 "Expect two args for recognised intrinsics.");
246 e.varargs.push_back(lookup_or_add(I->getArgOperand(0)));
247 e.varargs.push_back(lookup_or_add(I->getArgOperand(1)));
248 return e;
249 }
250 }
251
252 // Not a recognised intrinsic. Fall back to producing an extract value
253 // expression.
254 e.opcode = EI->getOpcode();
255 for (Instruction::op_iterator OI = EI->op_begin(), OE = EI->op_end();
256 OI != OE; ++OI)
257 e.varargs.push_back(lookup_or_add(*OI));
258
259 for (ExtractValueInst::idx_iterator II = EI->idx_begin(), IE = EI->idx_end();
260 II != IE; ++II)
261 e.varargs.push_back(*II);
262
263 return e;
264}
265
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000266//===----------------------------------------------------------------------===//
267// ValueTable External Functions
268//===----------------------------------------------------------------------===//
269
Owen Anderson6a903bc2008-06-18 21:41:49 +0000270/// add - Insert a value into the table with a specified value number.
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000271void ValueTable::add(Value *V, uint32_t num) {
Owen Anderson6a903bc2008-06-18 21:41:49 +0000272 valueNumbering.insert(std::make_pair(V, num));
273}
274
Nick Lewycky12d825d2012-09-09 23:41:11 +0000275uint32_t ValueTable::lookup_or_add_call(CallInst *C) {
Owen Anderson168ad692009-10-19 22:14:22 +0000276 if (AA->doesNotAccessMemory(C)) {
277 Expression exp = create_expression(C);
Nick Lewycky12d825d2012-09-09 23:41:11 +0000278 uint32_t &e = expressionNumbering[exp];
Owen Anderson168ad692009-10-19 22:14:22 +0000279 if (!e) e = nextValueNumber++;
280 valueNumbering[C] = e;
281 return e;
282 } else if (AA->onlyReadsMemory(C)) {
283 Expression exp = create_expression(C);
Nick Lewycky12d825d2012-09-09 23:41:11 +0000284 uint32_t &e = expressionNumbering[exp];
Owen Anderson168ad692009-10-19 22:14:22 +0000285 if (!e) {
286 e = nextValueNumber++;
287 valueNumbering[C] = e;
288 return e;
289 }
Dan Gohman81132462009-11-14 02:27:51 +0000290 if (!MD) {
291 e = nextValueNumber++;
292 valueNumbering[C] = e;
293 return e;
294 }
Owen Anderson168ad692009-10-19 22:14:22 +0000295
296 MemDepResult local_dep = MD->getDependency(C);
297
298 if (!local_dep.isDef() && !local_dep.isNonLocal()) {
299 valueNumbering[C] = nextValueNumber;
300 return nextValueNumber++;
301 }
302
303 if (local_dep.isDef()) {
304 CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
305
Gabor Greiff628ecd2010-06-30 09:17:53 +0000306 if (local_cdep->getNumArgOperands() != C->getNumArgOperands()) {
Owen Anderson168ad692009-10-19 22:14:22 +0000307 valueNumbering[C] = nextValueNumber;
308 return nextValueNumber++;
309 }
310
Gabor Greif2d958d42010-06-24 10:17:17 +0000311 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
312 uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
313 uint32_t cd_vn = lookup_or_add(local_cdep->getArgOperand(i));
Owen Anderson168ad692009-10-19 22:14:22 +0000314 if (c_vn != cd_vn) {
315 valueNumbering[C] = nextValueNumber;
316 return nextValueNumber++;
317 }
318 }
319
320 uint32_t v = lookup_or_add(local_cdep);
321 valueNumbering[C] = v;
322 return v;
323 }
324
325 // Non-local case.
326 const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
327 MD->getNonLocalCallDependency(CallSite(C));
Eli Friedman7d58bc72011-06-15 00:47:34 +0000328 // FIXME: Move the checking logic to MemDep!
Owen Anderson168ad692009-10-19 22:14:22 +0000329 CallInst* cdep = 0;
330
331 // Check to see if we have a single dominating call instruction that is
332 // identical to C.
333 for (unsigned i = 0, e = deps.size(); i != e; ++i) {
Chris Lattner0c315472009-12-09 07:08:01 +0000334 const NonLocalDepEntry *I = &deps[i];
Chris Lattner0c315472009-12-09 07:08:01 +0000335 if (I->getResult().isNonLocal())
Owen Anderson168ad692009-10-19 22:14:22 +0000336 continue;
337
Eli Friedman7d58bc72011-06-15 00:47:34 +0000338 // We don't handle non-definitions. If we already have a call, reject
Owen Anderson168ad692009-10-19 22:14:22 +0000339 // instruction dependencies.
Eli Friedman7d58bc72011-06-15 00:47:34 +0000340 if (!I->getResult().isDef() || cdep != 0) {
Owen Anderson168ad692009-10-19 22:14:22 +0000341 cdep = 0;
342 break;
343 }
344
Chris Lattner0c315472009-12-09 07:08:01 +0000345 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst());
Owen Anderson168ad692009-10-19 22:14:22 +0000346 // FIXME: All duplicated with non-local case.
Chris Lattner0c315472009-12-09 07:08:01 +0000347 if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){
Owen Anderson168ad692009-10-19 22:14:22 +0000348 cdep = NonLocalDepCall;
349 continue;
350 }
351
352 cdep = 0;
353 break;
354 }
355
356 if (!cdep) {
357 valueNumbering[C] = nextValueNumber;
358 return nextValueNumber++;
359 }
360
Gabor Greiff628ecd2010-06-30 09:17:53 +0000361 if (cdep->getNumArgOperands() != C->getNumArgOperands()) {
Owen Anderson168ad692009-10-19 22:14:22 +0000362 valueNumbering[C] = nextValueNumber;
363 return nextValueNumber++;
364 }
Gabor Greif2d958d42010-06-24 10:17:17 +0000365 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
366 uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
367 uint32_t cd_vn = lookup_or_add(cdep->getArgOperand(i));
Owen Anderson168ad692009-10-19 22:14:22 +0000368 if (c_vn != cd_vn) {
369 valueNumbering[C] = nextValueNumber;
370 return nextValueNumber++;
371 }
372 }
373
374 uint32_t v = lookup_or_add(cdep);
375 valueNumbering[C] = v;
376 return v;
377
378 } else {
379 valueNumbering[C] = nextValueNumber;
380 return nextValueNumber++;
381 }
382}
383
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000384/// lookup_or_add - Returns the value number for the specified value, assigning
385/// it a new number if it did not have one before.
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000386uint32_t ValueTable::lookup_or_add(Value *V) {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000387 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
388 if (VI != valueNumbering.end())
389 return VI->second;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000390
Owen Anderson168ad692009-10-19 22:14:22 +0000391 if (!isa<Instruction>(V)) {
Owen Anderson1059b5b2009-10-19 21:14:57 +0000392 valueNumbering[V] = nextValueNumber;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000393 return nextValueNumber++;
394 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000395
Owen Anderson168ad692009-10-19 22:14:22 +0000396 Instruction* I = cast<Instruction>(V);
397 Expression exp;
398 switch (I->getOpcode()) {
399 case Instruction::Call:
400 return lookup_or_add_call(cast<CallInst>(I));
401 case Instruction::Add:
402 case Instruction::FAdd:
403 case Instruction::Sub:
404 case Instruction::FSub:
405 case Instruction::Mul:
406 case Instruction::FMul:
407 case Instruction::UDiv:
408 case Instruction::SDiv:
409 case Instruction::FDiv:
410 case Instruction::URem:
411 case Instruction::SRem:
412 case Instruction::FRem:
413 case Instruction::Shl:
414 case Instruction::LShr:
415 case Instruction::AShr:
416 case Instruction::And:
Nick Lewycky12d825d2012-09-09 23:41:11 +0000417 case Instruction::Or:
Owen Anderson168ad692009-10-19 22:14:22 +0000418 case Instruction::Xor:
Owen Anderson168ad692009-10-19 22:14:22 +0000419 case Instruction::ICmp:
420 case Instruction::FCmp:
Owen Anderson168ad692009-10-19 22:14:22 +0000421 case Instruction::Trunc:
422 case Instruction::ZExt:
423 case Instruction::SExt:
424 case Instruction::FPToUI:
425 case Instruction::FPToSI:
426 case Instruction::UIToFP:
427 case Instruction::SIToFP:
428 case Instruction::FPTrunc:
429 case Instruction::FPExt:
430 case Instruction::PtrToInt:
431 case Instruction::IntToPtr:
432 case Instruction::BitCast:
Owen Anderson168ad692009-10-19 22:14:22 +0000433 case Instruction::Select:
Owen Anderson168ad692009-10-19 22:14:22 +0000434 case Instruction::ExtractElement:
Owen Anderson168ad692009-10-19 22:14:22 +0000435 case Instruction::InsertElement:
Owen Anderson168ad692009-10-19 22:14:22 +0000436 case Instruction::ShuffleVector:
Owen Anderson168ad692009-10-19 22:14:22 +0000437 case Instruction::InsertValue:
Owen Anderson168ad692009-10-19 22:14:22 +0000438 case Instruction::GetElementPtr:
Owen Anderson3a33d0c2011-01-03 19:00:11 +0000439 exp = create_expression(I);
Owen Anderson168ad692009-10-19 22:14:22 +0000440 break;
Lang Hames29cd98f2011-07-08 01:50:54 +0000441 case Instruction::ExtractValue:
442 exp = create_extractvalue_expression(cast<ExtractValueInst>(I));
443 break;
Owen Anderson168ad692009-10-19 22:14:22 +0000444 default:
445 valueNumbering[V] = nextValueNumber;
446 return nextValueNumber++;
447 }
448
449 uint32_t& e = expressionNumbering[exp];
450 if (!e) e = nextValueNumber++;
451 valueNumbering[V] = e;
452 return e;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000453}
454
455/// lookup - Returns the value number of the specified value. Fails if
456/// the value has not yet been numbered.
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000457uint32_t ValueTable::lookup(Value *V) const {
Jeffrey Yasskinb40d3f72009-11-10 01:02:17 +0000458 DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
Chris Lattner2876a642008-03-21 21:14:38 +0000459 assert(VI != valueNumbering.end() && "Value not numbered?");
460 return VI->second;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000461}
462
Duncan Sands27f45952012-02-27 08:14:30 +0000463/// lookup_or_add_cmp - Returns the value number of the given comparison,
464/// assigning it a new number if it did not have one before. Useful when
465/// we deduced the result of a comparison, but don't immediately have an
466/// instruction realizing that comparison to hand.
467uint32_t ValueTable::lookup_or_add_cmp(unsigned Opcode,
468 CmpInst::Predicate Predicate,
469 Value *LHS, Value *RHS) {
470 Expression exp = create_cmp_expression(Opcode, Predicate, LHS, RHS);
471 uint32_t& e = expressionNumbering[exp];
472 if (!e) e = nextValueNumber++;
473 return e;
474}
475
Chris Lattner45e393f2011-04-28 18:08:21 +0000476/// clear - Remove all entries from the ValueTable.
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000477void ValueTable::clear() {
478 valueNumbering.clear();
479 expressionNumbering.clear();
480 nextValueNumber = 1;
481}
482
Chris Lattner45e393f2011-04-28 18:08:21 +0000483/// erase - Remove a value from the value numbering.
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000484void ValueTable::erase(Value *V) {
Owen Anderson10ffa862007-07-31 23:27:13 +0000485 valueNumbering.erase(V);
486}
487
Bill Wendling6b18a392008-12-22 21:36:08 +0000488/// verifyRemoved - Verify that the value is removed from all internal data
489/// structures.
490void ValueTable::verifyRemoved(const Value *V) const {
Jeffrey Yasskinb40d3f72009-11-10 01:02:17 +0000491 for (DenseMap<Value*, uint32_t>::const_iterator
Bill Wendling6b18a392008-12-22 21:36:08 +0000492 I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
493 assert(I->first != V && "Inst still occurs in value numbering map!");
494 }
495}
496
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000497//===----------------------------------------------------------------------===//
Bill Wendling456e8852008-12-22 22:32:22 +0000498// GVN Pass
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000499//===----------------------------------------------------------------------===//
500
501namespace {
Shuxin Yang637b9be2013-05-03 19:17:26 +0000502 class GVN;
503 struct AvailableValueInBlock {
504 /// BB - The basic block in question.
505 BasicBlock *BB;
506 enum ValType {
507 SimpleVal, // A simple offsetted value that is accessed.
508 LoadVal, // A value produced by a load.
509 MemIntrin // A memory intrinsic which is loaded from.
510 };
511
512 /// V - The value that is live out of the block.
513 PointerIntPair<Value *, 2, ValType> Val;
514
515 /// Offset - The byte offset in Val that is interesting for the load query.
516 unsigned Offset;
517
518 static AvailableValueInBlock get(BasicBlock *BB, Value *V,
519 unsigned Offset = 0) {
520 AvailableValueInBlock Res;
521 Res.BB = BB;
522 Res.Val.setPointer(V);
523 Res.Val.setInt(SimpleVal);
524 Res.Offset = Offset;
525 return Res;
526 }
527
528 static AvailableValueInBlock getMI(BasicBlock *BB, MemIntrinsic *MI,
529 unsigned Offset = 0) {
530 AvailableValueInBlock Res;
531 Res.BB = BB;
532 Res.Val.setPointer(MI);
533 Res.Val.setInt(MemIntrin);
534 Res.Offset = Offset;
535 return Res;
536 }
537
538 static AvailableValueInBlock getLoad(BasicBlock *BB, LoadInst *LI,
539 unsigned Offset = 0) {
540 AvailableValueInBlock Res;
541 Res.BB = BB;
542 Res.Val.setPointer(LI);
543 Res.Val.setInt(LoadVal);
544 Res.Offset = Offset;
545 return Res;
546 }
547
548 bool isSimpleValue() const { return Val.getInt() == SimpleVal; }
549 bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; }
550 bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; }
551
552 Value *getSimpleValue() const {
553 assert(isSimpleValue() && "Wrong accessor");
554 return Val.getPointer();
555 }
556
557 LoadInst *getCoercedLoadValue() const {
558 assert(isCoercedLoadValue() && "Wrong accessor");
559 return cast<LoadInst>(Val.getPointer());
560 }
561
562 MemIntrinsic *getMemIntrinValue() const {
563 assert(isMemIntrinValue() && "Wrong accessor");
564 return cast<MemIntrinsic>(Val.getPointer());
565 }
566
567 /// MaterializeAdjustedValue - Emit code into this block to adjust the value
568 /// defined here to the specified type. This handles various coercion cases.
569 Value *MaterializeAdjustedValue(Type *LoadTy, GVN &gvn) const;
570 };
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000571
Chris Lattner2dd09db2009-09-02 06:11:42 +0000572 class GVN : public FunctionPass {
Dan Gohman81132462009-11-14 02:27:51 +0000573 bool NoLoads;
Chris Lattner8541ede2008-12-01 00:40:32 +0000574 MemoryDependenceAnalysis *MD;
575 DominatorTree *DT;
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000576 const DataLayout *TD;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000577 const TargetLibraryInfo *TLI;
578
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000579 ValueTable VN;
Nadav Rotem465834c2012-07-24 10:51:42 +0000580
Owen Andersone39cb572011-01-04 19:29:46 +0000581 /// LeaderTable - A mapping from value numbers to lists of Value*'s that
Owen Andersonc7c3bc62011-01-04 19:13:25 +0000582 /// have that value number. Use findLeader to query it.
583 struct LeaderTableEntry {
Owen Anderson5ab8d4b2010-12-21 23:54:34 +0000584 Value *Val;
Rafael Espindola64e7b5702012-08-10 15:55:25 +0000585 const BasicBlock *BB;
Owen Andersonc7c3bc62011-01-04 19:13:25 +0000586 LeaderTableEntry *Next;
Owen Anderson5ab8d4b2010-12-21 23:54:34 +0000587 };
Owen Andersone39cb572011-01-04 19:29:46 +0000588 DenseMap<uint32_t, LeaderTableEntry> LeaderTable;
Owen Andersonc21c1002010-11-18 18:32:40 +0000589 BumpPtrAllocator TableAllocator;
Nadav Rotem465834c2012-07-24 10:51:42 +0000590
Chris Lattner6cec6ab2011-04-28 16:18:52 +0000591 SmallVector<Instruction*, 8> InstrsToErase;
Shuxin Yang637b9be2013-05-03 19:17:26 +0000592
593 typedef SmallVector<NonLocalDepResult, 64> LoadDepVect;
594 typedef SmallVector<AvailableValueInBlock, 64> AvailValInBlkVect;
595 typedef SmallVector<BasicBlock*, 64> UnavailBlkVect;
596
Chris Lattnerf81f7892011-04-28 16:36:48 +0000597 public:
598 static char ID; // Pass identification, replacement for typeid
599 explicit GVN(bool noloads = false)
600 : FunctionPass(ID), NoLoads(noloads), MD(0) {
601 initializeGVNPass(*PassRegistry::getPassRegistry());
602 }
603
604 bool runOnFunction(Function &F);
Nadav Rotem465834c2012-07-24 10:51:42 +0000605
Chris Lattnerf81f7892011-04-28 16:36:48 +0000606 /// markInstructionForDeletion - This removes the specified instruction from
607 /// our various maps and marks it for deletion.
608 void markInstructionForDeletion(Instruction *I) {
609 VN.erase(I);
610 InstrsToErase.push_back(I);
611 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000612
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000613 const DataLayout *getDataLayout() const { return TD; }
Chris Lattnerf81f7892011-04-28 16:36:48 +0000614 DominatorTree &getDominatorTree() const { return *DT; }
615 AliasAnalysis *getAliasAnalysis() const { return VN.getAliasAnalysis(); }
Chris Lattner45e393f2011-04-28 18:08:21 +0000616 MemoryDependenceAnalysis &getMemDep() const { return *MD; }
Chris Lattnerf81f7892011-04-28 16:36:48 +0000617 private:
Owen Andersone39cb572011-01-04 19:29:46 +0000618 /// addToLeaderTable - Push a new Value to the LeaderTable onto the list for
Owen Andersonea326db2010-11-19 22:48:40 +0000619 /// its value number.
Rafael Espindola64e7b5702012-08-10 15:55:25 +0000620 void addToLeaderTable(uint32_t N, Value *V, const BasicBlock *BB) {
Chris Lattner17776012011-04-28 18:15:47 +0000621 LeaderTableEntry &Curr = LeaderTable[N];
Owen Anderson5ab8d4b2010-12-21 23:54:34 +0000622 if (!Curr.Val) {
623 Curr.Val = V;
624 Curr.BB = BB;
Owen Andersonc21c1002010-11-18 18:32:40 +0000625 return;
626 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000627
Chris Lattner17776012011-04-28 18:15:47 +0000628 LeaderTableEntry *Node = TableAllocator.Allocate<LeaderTableEntry>();
Owen Anderson5ab8d4b2010-12-21 23:54:34 +0000629 Node->Val = V;
630 Node->BB = BB;
631 Node->Next = Curr.Next;
632 Curr.Next = Node;
Owen Andersonc21c1002010-11-18 18:32:40 +0000633 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000634
Owen Andersone39cb572011-01-04 19:29:46 +0000635 /// removeFromLeaderTable - Scan the list of values corresponding to a given
Duncan Sands4df5e962012-05-22 14:17:53 +0000636 /// value number, and remove the given instruction if encountered.
637 void removeFromLeaderTable(uint32_t N, Instruction *I, BasicBlock *BB) {
Owen Andersonc7c3bc62011-01-04 19:13:25 +0000638 LeaderTableEntry* Prev = 0;
Owen Andersone39cb572011-01-04 19:29:46 +0000639 LeaderTableEntry* Curr = &LeaderTable[N];
Owen Andersonc21c1002010-11-18 18:32:40 +0000640
Duncan Sands4df5e962012-05-22 14:17:53 +0000641 while (Curr->Val != I || Curr->BB != BB) {
Owen Andersonc21c1002010-11-18 18:32:40 +0000642 Prev = Curr;
Owen Anderson5ab8d4b2010-12-21 23:54:34 +0000643 Curr = Curr->Next;
Owen Andersonc21c1002010-11-18 18:32:40 +0000644 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000645
Owen Andersonc21c1002010-11-18 18:32:40 +0000646 if (Prev) {
Owen Anderson5ab8d4b2010-12-21 23:54:34 +0000647 Prev->Next = Curr->Next;
Owen Andersonc21c1002010-11-18 18:32:40 +0000648 } else {
Owen Anderson5ab8d4b2010-12-21 23:54:34 +0000649 if (!Curr->Next) {
650 Curr->Val = 0;
651 Curr->BB = 0;
Owen Andersonc21c1002010-11-18 18:32:40 +0000652 } else {
Owen Andersonc7c3bc62011-01-04 19:13:25 +0000653 LeaderTableEntry* Next = Curr->Next;
Owen Anderson5ab8d4b2010-12-21 23:54:34 +0000654 Curr->Val = Next->Val;
655 Curr->BB = Next->BB;
Owen Anderson83546f22011-01-04 19:10:54 +0000656 Curr->Next = Next->Next;
Owen Andersonc21c1002010-11-18 18:32:40 +0000657 }
658 }
659 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000660
Bob Wilson92cdb6e2010-02-16 19:51:59 +0000661 // List of critical edges to be split between iterations.
662 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
663
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000664 // This transformation requires dominator postdominator info
665 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000666 AU.addRequired<DominatorTree>();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000667 AU.addRequired<TargetLibraryInfo>();
Dan Gohman81132462009-11-14 02:27:51 +0000668 if (!NoLoads)
669 AU.addRequired<MemoryDependenceAnalysis>();
Owen Anderson09b83ba2007-10-18 19:39:33 +0000670 AU.addRequired<AliasAnalysis>();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000671
Owen Anderson54e02192008-06-23 17:49:45 +0000672 AU.addPreserved<DominatorTree>();
Owen Anderson09b83ba2007-10-18 19:39:33 +0000673 AU.addPreserved<AliasAnalysis>();
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000674 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000675
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000676
Shuxin Yang637b9be2013-05-03 19:17:26 +0000677 // Helper fuctions of redundant load elimination
Chris Lattner6cec6ab2011-04-28 16:18:52 +0000678 bool processLoad(LoadInst *L);
Chris Lattner6cec6ab2011-04-28 16:18:52 +0000679 bool processNonLocalLoad(LoadInst *L);
Shuxin Yang637b9be2013-05-03 19:17:26 +0000680 void AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps,
681 AvailValInBlkVect &ValuesPerBlock,
682 UnavailBlkVect &UnavailableBlocks);
683 bool PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock,
684 UnavailBlkVect &UnavailableBlocks);
685
686 // Other helper routines
687 bool processInstruction(Instruction *I);
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000688 bool processBlock(BasicBlock *BB);
Chris Lattner6cec6ab2011-04-28 16:18:52 +0000689 void dump(DenseMap<uint32_t, Value*> &d);
Owen Anderson676070d2007-08-14 18:04:11 +0000690 bool iterateOnFunction(Function &F);
Chris Lattner6cec6ab2011-04-28 16:18:52 +0000691 bool performPRE(Function &F);
Rafael Espindola64e7b5702012-08-10 15:55:25 +0000692 Value *findLeader(const BasicBlock *BB, uint32_t num);
Nuno Lopese3127f32008-10-10 16:25:50 +0000693 void cleanupGlobalSets();
Bill Wendling6b18a392008-12-22 21:36:08 +0000694 void verifyRemoved(const Instruction *I) const;
Bob Wilson92cdb6e2010-02-16 19:51:59 +0000695 bool splitCriticalEdges();
Shuxin Yang1d8d7e42013-05-09 18:34:27 +0000696 BasicBlock *splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ);
Duncan Sandsf4f47cc2011-10-05 14:28:49 +0000697 unsigned replaceAllDominatedUsesWith(Value *From, Value *To,
Rafael Espindolacc80cde2012-08-16 15:09:43 +0000698 const BasicBlockEdge &Root);
699 bool propagateEquality(Value *LHS, Value *RHS, const BasicBlockEdge &Root);
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000700 };
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000701
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000702 char GVN::ID = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000703}
704
705// createGVNPass - The public interface to this file...
Bob Wilson11361662010-02-28 05:34:05 +0000706FunctionPass *llvm::createGVNPass(bool NoLoads) {
707 return new GVN(NoLoads);
Dan Gohman81132462009-11-14 02:27:51 +0000708}
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000709
Owen Anderson8ac477f2010-10-12 19:48:12 +0000710INITIALIZE_PASS_BEGIN(GVN, "gvn", "Global Value Numbering", false, false)
711INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
712INITIALIZE_PASS_DEPENDENCY(DominatorTree)
Chad Rosierc24b86f2011-12-01 03:08:23 +0000713INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000714INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
715INITIALIZE_PASS_END(GVN, "gvn", "Global Value Numbering", false, false)
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000716
Manman Ren49d684e2012-09-12 05:06:18 +0000717#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Owen Anderson6a903bc2008-06-18 21:41:49 +0000718void GVN::dump(DenseMap<uint32_t, Value*>& d) {
Dan Gohman57e80862009-12-18 03:25:51 +0000719 errs() << "{\n";
Owen Anderson6a903bc2008-06-18 21:41:49 +0000720 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
Owen Anderson5e5599b2007-07-25 19:57:03 +0000721 E = d.end(); I != E; ++I) {
Dan Gohman57e80862009-12-18 03:25:51 +0000722 errs() << I->first << "\n";
Owen Anderson5e5599b2007-07-25 19:57:03 +0000723 I->second->dump();
724 }
Dan Gohman57e80862009-12-18 03:25:51 +0000725 errs() << "}\n";
Owen Anderson5e5599b2007-07-25 19:57:03 +0000726}
Manman Renc3366cc2012-09-06 19:55:56 +0000727#endif
Owen Anderson5e5599b2007-07-25 19:57:03 +0000728
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000729/// IsValueFullyAvailableInBlock - Return true if we can prove that the value
730/// we're analyzing is fully available in the specified block. As we go, keep
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000731/// track of which blocks we know are fully alive in FullyAvailableBlocks. This
732/// map is actually a tri-state map with the following values:
733/// 0) we know the block *is not* fully available.
734/// 1) we know the block *is* fully available.
735/// 2) we do not know whether the block is fully available or not, but we are
736/// currently speculating that it will be.
737/// 3) we are speculating for this block and have used that to speculate for
738/// other blocks.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000739static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
Mon P Wang6120cfb2012-04-27 18:09:28 +0000740 DenseMap<BasicBlock*, char> &FullyAvailableBlocks,
741 uint32_t RecurseDepth) {
742 if (RecurseDepth > MaxRecurseDepth)
743 return false;
744
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000745 // Optimistically assume that the block is fully available and check to see
746 // if we already know about this block in one lookup.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000747 std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000748 FullyAvailableBlocks.insert(std::make_pair(BB, 2));
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000749
750 // If the entry already existed for this block, return the precomputed value.
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000751 if (!IV.second) {
752 // If this is a speculative "available" value, mark it as being used for
753 // speculation of other blocks.
754 if (IV.first->second == 2)
755 IV.first->second = 3;
756 return IV.first->second != 0;
757 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000758
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000759 // Otherwise, see if it is fully available in all predecessors.
760 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000761
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000762 // If this block has no predecessors, it isn't live-in here.
763 if (PI == PE)
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000764 goto SpeculationFailure;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000765
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000766 for (; PI != PE; ++PI)
767 // If the value isn't fully available in one of our predecessors, then it
768 // isn't fully available in this block either. Undo our previous
769 // optimistic assumption and bail out.
Mon P Wang6120cfb2012-04-27 18:09:28 +0000770 if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks,RecurseDepth+1))
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000771 goto SpeculationFailure;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000772
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000773 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000774
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000775// SpeculationFailure - If we get here, we found out that this is not, after
776// all, a fully-available block. We have a problem if we speculated on this and
777// used the speculation to mark other blocks as available.
778SpeculationFailure:
779 char &BBVal = FullyAvailableBlocks[BB];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000780
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000781 // If we didn't speculate on this, just return with it set to false.
782 if (BBVal == 2) {
783 BBVal = 0;
784 return false;
785 }
786
787 // If we did speculate on this value, we could have blocks set to 1 that are
788 // incorrect. Walk the (transitive) successors of this block and mark them as
789 // 0 if set to one.
790 SmallVector<BasicBlock*, 32> BBWorklist;
791 BBWorklist.push_back(BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000792
Dan Gohman28943872010-01-05 16:27:25 +0000793 do {
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000794 BasicBlock *Entry = BBWorklist.pop_back_val();
795 // Note that this sets blocks to 0 (unavailable) if they happen to not
796 // already be in FullyAvailableBlocks. This is safe.
797 char &EntryVal = FullyAvailableBlocks[Entry];
798 if (EntryVal == 0) continue; // Already unavailable.
799
800 // Mark as unavailable.
801 EntryVal = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000802
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000803 for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I)
804 BBWorklist.push_back(*I);
Dan Gohman28943872010-01-05 16:27:25 +0000805 } while (!BBWorklist.empty());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000806
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000807 return false;
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000808}
809
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000810
Chris Lattner9045f232009-09-21 17:24:04 +0000811/// CanCoerceMustAliasedValueToLoad - Return true if
812/// CoerceAvailableValueToLoadType will succeed.
813static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
Chris Lattner229907c2011-07-18 04:54:35 +0000814 Type *LoadTy,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000815 const DataLayout &TD) {
Chris Lattner9045f232009-09-21 17:24:04 +0000816 // If the loaded or stored value is an first class array or struct, don't try
817 // to transform them. We need to be able to bitcast to integer.
Duncan Sands19d0b472010-02-16 11:11:14 +0000818 if (LoadTy->isStructTy() || LoadTy->isArrayTy() ||
819 StoredVal->getType()->isStructTy() ||
820 StoredVal->getType()->isArrayTy())
Chris Lattner9045f232009-09-21 17:24:04 +0000821 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000822
Chris Lattner9045f232009-09-21 17:24:04 +0000823 // The store has to be at least as big as the load.
824 if (TD.getTypeSizeInBits(StoredVal->getType()) <
825 TD.getTypeSizeInBits(LoadTy))
826 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000827
Chris Lattner9045f232009-09-21 17:24:04 +0000828 return true;
829}
Nadav Rotem465834c2012-07-24 10:51:42 +0000830
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000831/// CoerceAvailableValueToLoadType - If we saw a store of a value to memory, and
832/// then a load from a must-aliased pointer of a different type, try to coerce
833/// the stored value. LoadedTy is the type of the load we want to replace and
834/// InsertPt is the place to insert new instructions.
835///
836/// If we can't do it, return null.
Nadav Rotem465834c2012-07-24 10:51:42 +0000837static Value *CoerceAvailableValueToLoadType(Value *StoredVal,
Chris Lattner229907c2011-07-18 04:54:35 +0000838 Type *LoadedTy,
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000839 Instruction *InsertPt,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000840 const DataLayout &TD) {
Chris Lattner9045f232009-09-21 17:24:04 +0000841 if (!CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, TD))
842 return 0;
Nadav Rotem465834c2012-07-24 10:51:42 +0000843
Chris Lattner827a2702011-04-28 07:29:08 +0000844 // If this is already the right type, just return it.
Chris Lattner229907c2011-07-18 04:54:35 +0000845 Type *StoredValTy = StoredVal->getType();
Nadav Rotem465834c2012-07-24 10:51:42 +0000846
Jakub Staszak7470fb02011-09-02 14:57:37 +0000847 uint64_t StoreSize = TD.getTypeSizeInBits(StoredValTy);
848 uint64_t LoadSize = TD.getTypeSizeInBits(LoadedTy);
Nadav Rotem465834c2012-07-24 10:51:42 +0000849
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000850 // If the store and reload are the same size, we can always reuse it.
851 if (StoreSize == LoadSize) {
Chris Lattner6f83d062011-04-26 01:21:15 +0000852 // Pointer to Pointer -> use bitcast.
Hal Finkel69b07a22012-10-24 21:22:30 +0000853 if (StoredValTy->getScalarType()->isPointerTy() &&
854 LoadedTy->getScalarType()->isPointerTy())
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000855 return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
Nadav Rotem465834c2012-07-24 10:51:42 +0000856
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000857 // Convert source pointers to integers, which can be bitcast.
Hal Finkel69b07a22012-10-24 21:22:30 +0000858 if (StoredValTy->getScalarType()->isPointerTy()) {
Duncan Sands5bdd9dd2012-10-29 17:31:46 +0000859 StoredValTy = TD.getIntPtrType(StoredValTy);
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000860 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
861 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000862
Chris Lattner229907c2011-07-18 04:54:35 +0000863 Type *TypeToCastTo = LoadedTy;
Hal Finkel69b07a22012-10-24 21:22:30 +0000864 if (TypeToCastTo->getScalarType()->isPointerTy())
Duncan Sandsa17bb142012-11-02 07:49:32 +0000865 TypeToCastTo = TD.getIntPtrType(TypeToCastTo);
Nadav Rotem465834c2012-07-24 10:51:42 +0000866
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000867 if (StoredValTy != TypeToCastTo)
868 StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
Nadav Rotem465834c2012-07-24 10:51:42 +0000869
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000870 // Cast to pointer if the load needs a pointer type.
Hal Finkel69b07a22012-10-24 21:22:30 +0000871 if (LoadedTy->getScalarType()->isPointerTy())
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000872 StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
Nadav Rotem465834c2012-07-24 10:51:42 +0000873
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000874 return StoredVal;
875 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000876
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000877 // If the loaded value is smaller than the available value, then we can
878 // extract out a piece from it. If the available value is too small, then we
879 // can't do anything.
Chris Lattner9045f232009-09-21 17:24:04 +0000880 assert(StoreSize >= LoadSize && "CanCoerceMustAliasedValueToLoad fail");
Nadav Rotem465834c2012-07-24 10:51:42 +0000881
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000882 // Convert source pointers to integers, which can be manipulated.
Hal Finkel69b07a22012-10-24 21:22:30 +0000883 if (StoredValTy->getScalarType()->isPointerTy()) {
Duncan Sands5bdd9dd2012-10-29 17:31:46 +0000884 StoredValTy = TD.getIntPtrType(StoredValTy);
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000885 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
886 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000887
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000888 // Convert vectors and fp to integer, which can be manipulated.
Duncan Sands19d0b472010-02-16 11:11:14 +0000889 if (!StoredValTy->isIntegerTy()) {
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000890 StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
891 StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
892 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000893
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000894 // If this is a big-endian system, we need to shift the value down to the low
895 // bits so that a truncate will work.
896 if (TD.isBigEndian()) {
897 Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
898 StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
899 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000900
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000901 // Truncate the integer to the right size now.
Chris Lattner229907c2011-07-18 04:54:35 +0000902 Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000903 StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
Nadav Rotem465834c2012-07-24 10:51:42 +0000904
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000905 if (LoadedTy == NewIntTy)
906 return StoredVal;
Nadav Rotem465834c2012-07-24 10:51:42 +0000907
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000908 // If the result is a pointer, inttoptr.
Hal Finkel69b07a22012-10-24 21:22:30 +0000909 if (LoadedTy->getScalarType()->isPointerTy())
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000910 return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
Nadav Rotem465834c2012-07-24 10:51:42 +0000911
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000912 // Otherwise, bitcast.
913 return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
914}
915
Chris Lattner42376062009-12-06 01:57:02 +0000916/// AnalyzeLoadFromClobberingWrite - This function is called when we have a
917/// memdep query of a load that ends up being a clobbering memory write (store,
918/// memset, memcpy, memmove). This means that the write *may* provide bits used
919/// by the load but we can't be sure because the pointers don't mustalias.
920///
921/// Check this case to see if there is anything more we can do before we give
922/// up. This returns -1 if we have to give up, or a byte number in the stored
923/// value of the piece that feeds the load.
Chris Lattner229907c2011-07-18 04:54:35 +0000924static int AnalyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr,
Chris Lattner0def8612009-12-09 07:34:10 +0000925 Value *WritePtr,
Chris Lattner42376062009-12-06 01:57:02 +0000926 uint64_t WriteSizeInBits,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000927 const DataLayout &TD) {
Chad Rosier6a0baa82012-01-30 22:44:13 +0000928 // If the loaded or stored value is a first class array or struct, don't try
Chris Lattner9045f232009-09-21 17:24:04 +0000929 // to transform them. We need to be able to bitcast to integer.
Duncan Sands19d0b472010-02-16 11:11:14 +0000930 if (LoadTy->isStructTy() || LoadTy->isArrayTy())
Chris Lattner9045f232009-09-21 17:24:04 +0000931 return -1;
Nadav Rotem465834c2012-07-24 10:51:42 +0000932
Chris Lattnerd28f9082009-09-21 06:24:16 +0000933 int64_t StoreOffset = 0, LoadOffset = 0;
Dan Gohman20a2ae92013-01-31 02:00:45 +0000934 Value *StoreBase = GetPointerBaseWithConstantOffset(WritePtr,StoreOffset,&TD);
935 Value *LoadBase = GetPointerBaseWithConstantOffset(LoadPtr, LoadOffset, &TD);
Chris Lattnerd28f9082009-09-21 06:24:16 +0000936 if (StoreBase != LoadBase)
937 return -1;
Nadav Rotem465834c2012-07-24 10:51:42 +0000938
Chris Lattnerd28f9082009-09-21 06:24:16 +0000939 // If the load and store are to the exact same address, they should have been
940 // a must alias. AA must have gotten confused.
Chris Lattner05638042010-03-25 05:58:19 +0000941 // FIXME: Study to see if/when this happens. One case is forwarding a memset
942 // to a load from the base of the memset.
Chris Lattnerd28f9082009-09-21 06:24:16 +0000943#if 0
Chris Lattner05638042010-03-25 05:58:19 +0000944 if (LoadOffset == StoreOffset) {
David Greene2e6efc42010-01-05 01:27:17 +0000945 dbgs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
Chris Lattnerd28f9082009-09-21 06:24:16 +0000946 << "Base = " << *StoreBase << "\n"
Chris Lattner42376062009-12-06 01:57:02 +0000947 << "Store Ptr = " << *WritePtr << "\n"
948 << "Store Offs = " << StoreOffset << "\n"
Chris Lattner3ddf8042009-12-10 00:04:46 +0000949 << "Load Ptr = " << *LoadPtr << "\n";
Chris Lattner946b58d2009-12-09 02:41:54 +0000950 abort();
Chris Lattnerd28f9082009-09-21 06:24:16 +0000951 }
Chris Lattner05638042010-03-25 05:58:19 +0000952#endif
Nadav Rotem465834c2012-07-24 10:51:42 +0000953
Chris Lattnerd28f9082009-09-21 06:24:16 +0000954 // If the load and store don't overlap at all, the store doesn't provide
955 // anything to the load. In this case, they really don't alias at all, AA
956 // must have gotten confused.
Chris Lattner0def8612009-12-09 07:34:10 +0000957 uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy);
Nadav Rotem465834c2012-07-24 10:51:42 +0000958
Chris Lattner42376062009-12-06 01:57:02 +0000959 if ((WriteSizeInBits & 7) | (LoadSize & 7))
Chris Lattnerd28f9082009-09-21 06:24:16 +0000960 return -1;
Chris Lattner42376062009-12-06 01:57:02 +0000961 uint64_t StoreSize = WriteSizeInBits >> 3; // Convert to bytes.
Chris Lattnerd28f9082009-09-21 06:24:16 +0000962 LoadSize >>= 3;
Nadav Rotem465834c2012-07-24 10:51:42 +0000963
964
Chris Lattnerd28f9082009-09-21 06:24:16 +0000965 bool isAAFailure = false;
Chris Lattner05638042010-03-25 05:58:19 +0000966 if (StoreOffset < LoadOffset)
Chris Lattnerd28f9082009-09-21 06:24:16 +0000967 isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
Chris Lattner05638042010-03-25 05:58:19 +0000968 else
Chris Lattnerd28f9082009-09-21 06:24:16 +0000969 isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
Chris Lattner05638042010-03-25 05:58:19 +0000970
Chris Lattnerd28f9082009-09-21 06:24:16 +0000971 if (isAAFailure) {
972#if 0
David Greene2e6efc42010-01-05 01:27:17 +0000973 dbgs() << "STORE LOAD DEP WITH COMMON BASE:\n"
Chris Lattnerd28f9082009-09-21 06:24:16 +0000974 << "Base = " << *StoreBase << "\n"
Chris Lattner42376062009-12-06 01:57:02 +0000975 << "Store Ptr = " << *WritePtr << "\n"
976 << "Store Offs = " << StoreOffset << "\n"
Chris Lattner3ddf8042009-12-10 00:04:46 +0000977 << "Load Ptr = " << *LoadPtr << "\n";
Chris Lattner946b58d2009-12-09 02:41:54 +0000978 abort();
Chris Lattnerd28f9082009-09-21 06:24:16 +0000979#endif
980 return -1;
981 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000982
Chris Lattnerd28f9082009-09-21 06:24:16 +0000983 // If the Load isn't completely contained within the stored bits, we don't
984 // have all the bits to feed it. We could do something crazy in the future
985 // (issue a smaller load then merge the bits in) but this seems unlikely to be
986 // valuable.
987 if (StoreOffset > LoadOffset ||
988 StoreOffset+StoreSize < LoadOffset+LoadSize)
989 return -1;
Nadav Rotem465834c2012-07-24 10:51:42 +0000990
Chris Lattnerd28f9082009-09-21 06:24:16 +0000991 // Okay, we can do this transformation. Return the number of bytes into the
992 // store that the load is.
993 return LoadOffset-StoreOffset;
Nadav Rotem465834c2012-07-24 10:51:42 +0000994}
Chris Lattnerd28f9082009-09-21 06:24:16 +0000995
Chris Lattner42376062009-12-06 01:57:02 +0000996/// AnalyzeLoadFromClobberingStore - This function is called when we have a
997/// memdep query of a load that ends up being a clobbering store.
Chris Lattner229907c2011-07-18 04:54:35 +0000998static int AnalyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr,
Chris Lattner07df9ef2009-12-09 07:37:07 +0000999 StoreInst *DepSI,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001000 const DataLayout &TD) {
Chris Lattner42376062009-12-06 01:57:02 +00001001 // Cannot handle reading from store of first-class aggregate yet.
Dan Gohmand2099112010-11-10 19:03:33 +00001002 if (DepSI->getValueOperand()->getType()->isStructTy() ||
1003 DepSI->getValueOperand()->getType()->isArrayTy())
Chris Lattner42376062009-12-06 01:57:02 +00001004 return -1;
1005
1006 Value *StorePtr = DepSI->getPointerOperand();
Dan Gohmand2099112010-11-10 19:03:33 +00001007 uint64_t StoreSize =TD.getTypeSizeInBits(DepSI->getValueOperand()->getType());
Chris Lattner07df9ef2009-12-09 07:37:07 +00001008 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
Chris Lattner0def8612009-12-09 07:34:10 +00001009 StorePtr, StoreSize, TD);
Chris Lattner42376062009-12-06 01:57:02 +00001010}
1011
Chris Lattner6f83d062011-04-26 01:21:15 +00001012/// AnalyzeLoadFromClobberingLoad - This function is called when we have a
1013/// memdep query of a load that ends up being clobbered by another load. See if
1014/// the other load can feed into the second load.
Chris Lattner229907c2011-07-18 04:54:35 +00001015static int AnalyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001016 LoadInst *DepLI, const DataLayout &TD){
Chris Lattner6f83d062011-04-26 01:21:15 +00001017 // Cannot handle reading from store of first-class aggregate yet.
1018 if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy())
1019 return -1;
Nadav Rotem465834c2012-07-24 10:51:42 +00001020
Chris Lattner6f83d062011-04-26 01:21:15 +00001021 Value *DepPtr = DepLI->getPointerOperand();
1022 uint64_t DepSize = TD.getTypeSizeInBits(DepLI->getType());
Chris Lattner827a2702011-04-28 07:29:08 +00001023 int R = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, TD);
1024 if (R != -1) return R;
Nadav Rotem465834c2012-07-24 10:51:42 +00001025
Chris Lattner827a2702011-04-28 07:29:08 +00001026 // If we have a load/load clobber an DepLI can be widened to cover this load,
1027 // then we should widen it!
1028 int64_t LoadOffs = 0;
1029 const Value *LoadBase =
Dan Gohman20a2ae92013-01-31 02:00:45 +00001030 GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, &TD);
Chris Lattner827a2702011-04-28 07:29:08 +00001031 unsigned LoadSize = TD.getTypeStoreSize(LoadTy);
Nadav Rotem465834c2012-07-24 10:51:42 +00001032
Chris Lattner827a2702011-04-28 07:29:08 +00001033 unsigned Size = MemoryDependenceAnalysis::
1034 getLoadLoadClobberFullWidthSize(LoadBase, LoadOffs, LoadSize, DepLI, TD);
1035 if (Size == 0) return -1;
Nadav Rotem465834c2012-07-24 10:51:42 +00001036
Chris Lattner827a2702011-04-28 07:29:08 +00001037 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size*8, TD);
Chris Lattner6f83d062011-04-26 01:21:15 +00001038}
1039
1040
1041
Chris Lattner229907c2011-07-18 04:54:35 +00001042static int AnalyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr,
Chris Lattner07df9ef2009-12-09 07:37:07 +00001043 MemIntrinsic *MI,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001044 const DataLayout &TD) {
Chris Lattner42376062009-12-06 01:57:02 +00001045 // If the mem operation is a non-constant size, we can't handle it.
1046 ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength());
1047 if (SizeCst == 0) return -1;
1048 uint64_t MemSizeInBits = SizeCst->getZExtValue()*8;
Chris Lattner778cb922009-12-06 05:29:56 +00001049
1050 // If this is memset, we just need to see if the offset is valid in the size
1051 // of the memset..
Chris Lattner42376062009-12-06 01:57:02 +00001052 if (MI->getIntrinsicID() == Intrinsic::memset)
Chris Lattner07df9ef2009-12-09 07:37:07 +00001053 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
1054 MemSizeInBits, TD);
Nadav Rotem465834c2012-07-24 10:51:42 +00001055
Chris Lattner778cb922009-12-06 05:29:56 +00001056 // If we have a memcpy/memmove, the only case we can handle is if this is a
1057 // copy from constant memory. In that case, we can read directly from the
1058 // constant memory.
1059 MemTransferInst *MTI = cast<MemTransferInst>(MI);
Nadav Rotem465834c2012-07-24 10:51:42 +00001060
Chris Lattner778cb922009-12-06 05:29:56 +00001061 Constant *Src = dyn_cast<Constant>(MTI->getSource());
1062 if (Src == 0) return -1;
Nadav Rotem465834c2012-07-24 10:51:42 +00001063
Dan Gohman0f124e12011-01-24 18:53:32 +00001064 GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Src, &TD));
Chris Lattner778cb922009-12-06 05:29:56 +00001065 if (GV == 0 || !GV->isConstant()) return -1;
Nadav Rotem465834c2012-07-24 10:51:42 +00001066
Chris Lattner778cb922009-12-06 05:29:56 +00001067 // See if the access is within the bounds of the transfer.
Chris Lattner07df9ef2009-12-09 07:37:07 +00001068 int Offset = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
1069 MI->getDest(), MemSizeInBits, TD);
Chris Lattner778cb922009-12-06 05:29:56 +00001070 if (Offset == -1)
1071 return Offset;
Nadav Rotem465834c2012-07-24 10:51:42 +00001072
Chris Lattner778cb922009-12-06 05:29:56 +00001073 // Otherwise, see if we can constant fold a load from the constant with the
1074 // offset applied as appropriate.
1075 Src = ConstantExpr::getBitCast(Src,
1076 llvm::Type::getInt8PtrTy(Src->getContext()));
Nadav Rotem465834c2012-07-24 10:51:42 +00001077 Constant *OffsetCst =
Chris Lattner778cb922009-12-06 05:29:56 +00001078 ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
Jay Foaded8db7d2011-07-21 14:31:17 +00001079 Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
Chris Lattner07df9ef2009-12-09 07:37:07 +00001080 Src = ConstantExpr::getBitCast(Src, PointerType::getUnqual(LoadTy));
Chris Lattner778cb922009-12-06 05:29:56 +00001081 if (ConstantFoldLoadFromConstPtr(Src, &TD))
1082 return Offset;
Chris Lattner42376062009-12-06 01:57:02 +00001083 return -1;
1084}
Nadav Rotem465834c2012-07-24 10:51:42 +00001085
Chris Lattnerd28f9082009-09-21 06:24:16 +00001086
1087/// GetStoreValueForLoad - This function is called when we have a
1088/// memdep query of a load that ends up being a clobbering store. This means
Chris Lattner827a2702011-04-28 07:29:08 +00001089/// that the store provides bits used by the load but we the pointers don't
1090/// mustalias. Check this case to see if there is anything more we can do
1091/// before we give up.
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001092static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
Chris Lattner229907c2011-07-18 04:54:35 +00001093 Type *LoadTy,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001094 Instruction *InsertPt, const DataLayout &TD){
Chris Lattnerd28f9082009-09-21 06:24:16 +00001095 LLVMContext &Ctx = SrcVal->getType()->getContext();
Nadav Rotem465834c2012-07-24 10:51:42 +00001096
Chris Lattner5a62d6e2010-05-08 20:01:44 +00001097 uint64_t StoreSize = (TD.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
1098 uint64_t LoadSize = (TD.getTypeSizeInBits(LoadTy) + 7) / 8;
Nadav Rotem465834c2012-07-24 10:51:42 +00001099
Chris Lattnerf8ba1252009-12-09 18:13:28 +00001100 IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
Nadav Rotem465834c2012-07-24 10:51:42 +00001101
Chris Lattnerd28f9082009-09-21 06:24:16 +00001102 // Compute which bits of the stored value are being used by the load. Convert
1103 // to an integer type to start with.
Hal Finkel69b07a22012-10-24 21:22:30 +00001104 if (SrcVal->getType()->getScalarType()->isPointerTy())
Micah Villmow12d91272012-10-24 15:52:52 +00001105 SrcVal = Builder.CreatePtrToInt(SrcVal,
Duncan Sands5bdd9dd2012-10-29 17:31:46 +00001106 TD.getIntPtrType(SrcVal->getType()));
Duncan Sands19d0b472010-02-16 11:11:14 +00001107 if (!SrcVal->getType()->isIntegerTy())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001108 SrcVal = Builder.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize*8));
Nadav Rotem465834c2012-07-24 10:51:42 +00001109
Chris Lattnerd28f9082009-09-21 06:24:16 +00001110 // Shift the bits to the least significant depending on endianness.
1111 unsigned ShiftAmt;
Chris Lattner42376062009-12-06 01:57:02 +00001112 if (TD.isLittleEndian())
Chris Lattnerd28f9082009-09-21 06:24:16 +00001113 ShiftAmt = Offset*8;
Chris Lattner42376062009-12-06 01:57:02 +00001114 else
Chris Lattner24705382009-09-21 17:55:47 +00001115 ShiftAmt = (StoreSize-LoadSize-Offset)*8;
Nadav Rotem465834c2012-07-24 10:51:42 +00001116
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001117 if (ShiftAmt)
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001118 SrcVal = Builder.CreateLShr(SrcVal, ShiftAmt);
Nadav Rotem465834c2012-07-24 10:51:42 +00001119
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001120 if (LoadSize != StoreSize)
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001121 SrcVal = Builder.CreateTrunc(SrcVal, IntegerType::get(Ctx, LoadSize*8));
Nadav Rotem465834c2012-07-24 10:51:42 +00001122
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001123 return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, TD);
Chris Lattnerd28f9082009-09-21 06:24:16 +00001124}
1125
Chad Rosier41003f82012-01-30 21:13:22 +00001126/// GetLoadValueForLoad - This function is called when we have a
Chris Lattner827a2702011-04-28 07:29:08 +00001127/// memdep query of a load that ends up being a clobbering load. This means
1128/// that the load *may* provide bits used by the load but we can't be sure
1129/// because the pointers don't mustalias. Check this case to see if there is
1130/// anything more we can do before we give up.
1131static Value *GetLoadValueForLoad(LoadInst *SrcVal, unsigned Offset,
Chris Lattner229907c2011-07-18 04:54:35 +00001132 Type *LoadTy, Instruction *InsertPt,
Chris Lattnerf81f7892011-04-28 16:36:48 +00001133 GVN &gvn) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001134 const DataLayout &TD = *gvn.getDataLayout();
Chris Lattner827a2702011-04-28 07:29:08 +00001135 // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to
1136 // widen SrcVal out to a larger load.
1137 unsigned SrcValSize = TD.getTypeStoreSize(SrcVal->getType());
1138 unsigned LoadSize = TD.getTypeStoreSize(LoadTy);
1139 if (Offset+LoadSize > SrcValSize) {
Eli Friedman9a468152011-08-17 22:22:24 +00001140 assert(SrcVal->isSimple() && "Cannot widen volatile/atomic load!");
1141 assert(SrcVal->getType()->isIntegerTy() && "Can't widen non-integer load");
Chris Lattner827a2702011-04-28 07:29:08 +00001142 // If we have a load/load clobber an DepLI can be widened to cover this
1143 // load, then we should widen it to the next power of 2 size big enough!
1144 unsigned NewLoadSize = Offset+LoadSize;
1145 if (!isPowerOf2_32(NewLoadSize))
1146 NewLoadSize = NextPowerOf2(NewLoadSize);
1147
1148 Value *PtrVal = SrcVal->getPointerOperand();
Nadav Rotem465834c2012-07-24 10:51:42 +00001149
Chris Lattner17776012011-04-28 18:15:47 +00001150 // Insert the new load after the old load. This ensures that subsequent
1151 // memdep queries will find the new load. We can't easily remove the old
1152 // load completely because it is already in the value numbering table.
1153 IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal));
Nadav Rotem465834c2012-07-24 10:51:42 +00001154 Type *DestPTy =
Chris Lattner827a2702011-04-28 07:29:08 +00001155 IntegerType::get(LoadTy->getContext(), NewLoadSize*8);
Nadav Rotem465834c2012-07-24 10:51:42 +00001156 DestPTy = PointerType::get(DestPTy,
Chris Lattner827a2702011-04-28 07:29:08 +00001157 cast<PointerType>(PtrVal->getType())->getAddressSpace());
Devang Patelffb798c2011-05-04 23:58:50 +00001158 Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc());
Chris Lattner827a2702011-04-28 07:29:08 +00001159 PtrVal = Builder.CreateBitCast(PtrVal, DestPTy);
1160 LoadInst *NewLoad = Builder.CreateLoad(PtrVal);
1161 NewLoad->takeName(SrcVal);
1162 NewLoad->setAlignment(SrcVal->getAlignment());
Devang Patelffb798c2011-05-04 23:58:50 +00001163
Chris Lattner827a2702011-04-28 07:29:08 +00001164 DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n");
1165 DEBUG(dbgs() << "TO: " << *NewLoad << "\n");
Nadav Rotem465834c2012-07-24 10:51:42 +00001166
Chris Lattner827a2702011-04-28 07:29:08 +00001167 // Replace uses of the original load with the wider load. On a big endian
1168 // system, we need to shift down to get the relevant bits.
1169 Value *RV = NewLoad;
1170 if (TD.isBigEndian())
1171 RV = Builder.CreateLShr(RV,
1172 NewLoadSize*8-SrcVal->getType()->getPrimitiveSizeInBits());
1173 RV = Builder.CreateTrunc(RV, SrcVal->getType());
1174 SrcVal->replaceAllUsesWith(RV);
Nadav Rotem465834c2012-07-24 10:51:42 +00001175
Chris Lattnera5452c02011-04-28 20:02:57 +00001176 // We would like to use gvn.markInstructionForDeletion here, but we can't
1177 // because the load is already memoized into the leader map table that GVN
1178 // tracks. It is potentially possible to remove the load from the table,
1179 // but then there all of the operations based on it would need to be
1180 // rehashed. Just leave the dead load around.
Chris Lattner45e393f2011-04-28 18:08:21 +00001181 gvn.getMemDep().removeInstruction(SrcVal);
Chris Lattner827a2702011-04-28 07:29:08 +00001182 SrcVal = NewLoad;
1183 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001184
Chris Lattner827a2702011-04-28 07:29:08 +00001185 return GetStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, TD);
1186}
1187
1188
Chris Lattner42376062009-12-06 01:57:02 +00001189/// GetMemInstValueForLoad - This function is called when we have a
1190/// memdep query of a load that ends up being a clobbering mem intrinsic.
1191static Value *GetMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
Chris Lattner229907c2011-07-18 04:54:35 +00001192 Type *LoadTy, Instruction *InsertPt,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001193 const DataLayout &TD){
Chris Lattner42376062009-12-06 01:57:02 +00001194 LLVMContext &Ctx = LoadTy->getContext();
1195 uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy)/8;
1196
1197 IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
Nadav Rotem465834c2012-07-24 10:51:42 +00001198
Chris Lattner42376062009-12-06 01:57:02 +00001199 // We know that this method is only called when the mem transfer fully
1200 // provides the bits for the load.
1201 if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) {
1202 // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
1203 // independently of what the offset is.
1204 Value *Val = MSI->getValue();
1205 if (LoadSize != 1)
1206 Val = Builder.CreateZExt(Val, IntegerType::get(Ctx, LoadSize*8));
Nadav Rotem465834c2012-07-24 10:51:42 +00001207
Chris Lattner42376062009-12-06 01:57:02 +00001208 Value *OneElt = Val;
Nadav Rotem465834c2012-07-24 10:51:42 +00001209
Chris Lattner42376062009-12-06 01:57:02 +00001210 // Splat the value out to the right number of bits.
1211 for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize; ) {
1212 // If we can double the number of bytes set, do it.
1213 if (NumBytesSet*2 <= LoadSize) {
1214 Value *ShVal = Builder.CreateShl(Val, NumBytesSet*8);
1215 Val = Builder.CreateOr(Val, ShVal);
1216 NumBytesSet <<= 1;
1217 continue;
1218 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001219
Chris Lattner42376062009-12-06 01:57:02 +00001220 // Otherwise insert one byte at a time.
1221 Value *ShVal = Builder.CreateShl(Val, 1*8);
1222 Val = Builder.CreateOr(OneElt, ShVal);
1223 ++NumBytesSet;
1224 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001225
Chris Lattner42376062009-12-06 01:57:02 +00001226 return CoerceAvailableValueToLoadType(Val, LoadTy, InsertPt, TD);
1227 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001228
Chris Lattner778cb922009-12-06 05:29:56 +00001229 // Otherwise, this is a memcpy/memmove from a constant global.
1230 MemTransferInst *MTI = cast<MemTransferInst>(SrcInst);
1231 Constant *Src = cast<Constant>(MTI->getSource());
1232
1233 // Otherwise, see if we can constant fold a load from the constant with the
1234 // offset applied as appropriate.
1235 Src = ConstantExpr::getBitCast(Src,
1236 llvm::Type::getInt8PtrTy(Src->getContext()));
Nadav Rotem465834c2012-07-24 10:51:42 +00001237 Constant *OffsetCst =
Chris Lattner778cb922009-12-06 05:29:56 +00001238 ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
Jay Foaded8db7d2011-07-21 14:31:17 +00001239 Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
Chris Lattner778cb922009-12-06 05:29:56 +00001240 Src = ConstantExpr::getBitCast(Src, PointerType::getUnqual(LoadTy));
1241 return ConstantFoldLoadFromConstPtr(Src, &TD);
Chris Lattner42376062009-12-06 01:57:02 +00001242}
1243
Dan Gohmanb29cda92010-04-15 17:08:50 +00001244
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001245/// ConstructSSAForLoadSet - Given a set of loads specified by ValuesPerBlock,
1246/// construct SSA form, allowing us to eliminate LI. This returns the value
1247/// that should be used at LI's definition site.
Nadav Rotem465834c2012-07-24 10:51:42 +00001248static Value *ConstructSSAForLoadSet(LoadInst *LI,
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001249 SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
Chris Lattnerf81f7892011-04-28 16:36:48 +00001250 GVN &gvn) {
Chris Lattnerbf200182009-12-21 23:15:48 +00001251 // Check for the fully redundant, dominating load case. In this case, we can
1252 // just use the dominating value directly.
Nadav Rotem465834c2012-07-24 10:51:42 +00001253 if (ValuesPerBlock.size() == 1 &&
Chris Lattnerf81f7892011-04-28 16:36:48 +00001254 gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
1255 LI->getParent()))
1256 return ValuesPerBlock[0].MaterializeAdjustedValue(LI->getType(), gvn);
Chris Lattnerbf200182009-12-21 23:15:48 +00001257
1258 // Otherwise, we have to construct SSA form.
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001259 SmallVector<PHINode*, 8> NewPHIs;
1260 SSAUpdater SSAUpdate(&NewPHIs);
Duncan Sands67781492010-09-02 08:14:03 +00001261 SSAUpdate.Initialize(LI->getType(), LI->getName());
Nadav Rotem465834c2012-07-24 10:51:42 +00001262
Chris Lattner229907c2011-07-18 04:54:35 +00001263 Type *LoadTy = LI->getType();
Nadav Rotem465834c2012-07-24 10:51:42 +00001264
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001265 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
Chris Lattner93236ba2009-12-06 04:54:31 +00001266 const AvailableValueInBlock &AV = ValuesPerBlock[i];
1267 BasicBlock *BB = AV.BB;
Nadav Rotem465834c2012-07-24 10:51:42 +00001268
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001269 if (SSAUpdate.HasValueForBlock(BB))
1270 continue;
Chris Lattner93236ba2009-12-06 04:54:31 +00001271
Chris Lattnerf81f7892011-04-28 16:36:48 +00001272 SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LoadTy, gvn));
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001273 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001274
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001275 // Perform PHI construction.
1276 Value *V = SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
Nadav Rotem465834c2012-07-24 10:51:42 +00001277
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001278 // If new PHI nodes were created, notify alias analysis.
Hal Finkel69b07a22012-10-24 21:22:30 +00001279 if (V->getType()->getScalarType()->isPointerTy()) {
Chris Lattnerf81f7892011-04-28 16:36:48 +00001280 AliasAnalysis *AA = gvn.getAliasAnalysis();
Nadav Rotem465834c2012-07-24 10:51:42 +00001281
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001282 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
1283 AA->copyValue(LI, NewPHIs[i]);
Nadav Rotem465834c2012-07-24 10:51:42 +00001284
Owen Andersond62d3722011-01-03 23:51:43 +00001285 // Now that we've copied information to the new PHIs, scan through
1286 // them again and inform alias analysis that we've added potentially
1287 // escaping uses to any values that are operands to these PHIs.
1288 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i) {
1289 PHINode *P = NewPHIs[i];
Jay Foad372ad642011-06-20 14:18:48 +00001290 for (unsigned ii = 0, ee = P->getNumIncomingValues(); ii != ee; ++ii) {
1291 unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
1292 AA->addEscapingUse(P->getOperandUse(jj));
1293 }
Owen Andersond62d3722011-01-03 23:51:43 +00001294 }
Chris Lattnerf81f7892011-04-28 16:36:48 +00001295 }
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001296
1297 return V;
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001298}
1299
Shuxin Yang637b9be2013-05-03 19:17:26 +00001300Value *AvailableValueInBlock::MaterializeAdjustedValue(Type *LoadTy, GVN &gvn) const {
1301 Value *Res;
1302 if (isSimpleValue()) {
1303 Res = getSimpleValue();
1304 if (Res->getType() != LoadTy) {
1305 const DataLayout *TD = gvn.getDataLayout();
1306 assert(TD && "Need target data to handle type mismatch case");
1307 Res = GetStoreValueForLoad(Res, Offset, LoadTy, BB->getTerminator(),
1308 *TD);
1309
1310 DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset << " "
1311 << *getSimpleValue() << '\n'
1312 << *Res << '\n' << "\n\n\n");
1313 }
1314 } else if (isCoercedLoadValue()) {
1315 LoadInst *Load = getCoercedLoadValue();
1316 if (Load->getType() == LoadTy && Offset == 0) {
1317 Res = Load;
1318 } else {
1319 Res = GetLoadValueForLoad(Load, Offset, LoadTy, BB->getTerminator(),
1320 gvn);
1321
1322 DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset << " "
1323 << *getCoercedLoadValue() << '\n'
1324 << *Res << '\n' << "\n\n\n");
1325 }
1326 } else {
1327 const DataLayout *TD = gvn.getDataLayout();
1328 assert(TD && "Need target data to handle type mismatch case");
1329 Res = GetMemInstValueForLoad(getMemIntrinValue(), Offset,
1330 LoadTy, BB->getTerminator(), *TD);
1331 DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
1332 << " " << *getMemIntrinValue() << '\n'
1333 << *Res << '\n' << "\n\n\n");
1334 }
1335 return Res;
1336}
1337
Gabor Greifce6dd882010-04-09 10:57:00 +00001338static bool isLifetimeStart(const Instruction *Inst) {
1339 if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
Owen Andersonb9878ee2009-12-02 07:35:19 +00001340 return II->getIntrinsicID() == Intrinsic::lifetime_start;
Chris Lattnerc4680252009-12-02 06:44:58 +00001341 return false;
1342}
1343
Shuxin Yang637b9be2013-05-03 19:17:26 +00001344void GVN::AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps,
1345 AvailValInBlkVect &ValuesPerBlock,
1346 UnavailBlkVect &UnavailableBlocks) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001347
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001348 // Filter out useless results (non-locals, etc). Keep track of the blocks
1349 // where we have a value available in repl, also keep track of whether we see
1350 // dependencies that produce an unknown value for the load (such as a call
1351 // that could potentially clobber the load).
Shuxin Yang637b9be2013-05-03 19:17:26 +00001352 unsigned NumDeps = Deps.size();
Bill Wendling8a333122012-01-31 06:57:53 +00001353 for (unsigned i = 0, e = NumDeps; i != e; ++i) {
Chris Lattner0c315472009-12-09 07:08:01 +00001354 BasicBlock *DepBB = Deps[i].getBB();
1355 MemDepResult DepInfo = Deps[i].getResult();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001356
Eli Friedmanc1702c82011-10-13 22:14:57 +00001357 if (!DepInfo.isDef() && !DepInfo.isClobber()) {
Eli Friedman7d58bc72011-06-15 00:47:34 +00001358 UnavailableBlocks.push_back(DepBB);
1359 continue;
1360 }
1361
Chris Lattner0e3d6332008-12-05 21:04:20 +00001362 if (DepInfo.isClobber()) {
Chris Lattnerca5f9cb2009-12-09 18:21:46 +00001363 // The address being loaded in this non-local block may not be the same as
1364 // the pointer operand of the load if PHI translation occurs. Make sure
1365 // to consider the right address.
1366 Value *Address = Deps[i].getAddress();
Nadav Rotem465834c2012-07-24 10:51:42 +00001367
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001368 // If the dependence is to a store that writes to a superset of the bits
1369 // read by the load, we can extract the bits we need for the load from the
1370 // stored value.
1371 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
Chris Lattnerca5f9cb2009-12-09 18:21:46 +00001372 if (TD && Address) {
1373 int Offset = AnalyzeLoadFromClobberingStore(LI->getType(), Address,
Chris Lattner07df9ef2009-12-09 07:37:07 +00001374 DepSI, *TD);
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001375 if (Offset != -1) {
1376 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
Dan Gohmand2099112010-11-10 19:03:33 +00001377 DepSI->getValueOperand(),
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001378 Offset));
1379 continue;
1380 }
1381 }
1382 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001383
Chris Lattner6f83d062011-04-26 01:21:15 +00001384 // Check to see if we have something like this:
1385 // load i32* P
1386 // load i8* (P+1)
1387 // if we have this, replace the later with an extraction from the former.
1388 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInfo.getInst())) {
1389 // If this is a clobber and L is the first instruction in its block, then
1390 // we have the first instruction in the entry block.
1391 if (DepLI != LI && Address && TD) {
1392 int Offset = AnalyzeLoadFromClobberingLoad(LI->getType(),
1393 LI->getPointerOperand(),
1394 DepLI, *TD);
Nadav Rotem465834c2012-07-24 10:51:42 +00001395
Chris Lattner6f83d062011-04-26 01:21:15 +00001396 if (Offset != -1) {
Chris Lattner827a2702011-04-28 07:29:08 +00001397 ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB,DepLI,
1398 Offset));
Chris Lattner6f83d062011-04-26 01:21:15 +00001399 continue;
1400 }
1401 }
1402 }
Chris Lattner42376062009-12-06 01:57:02 +00001403
Chris Lattner42376062009-12-06 01:57:02 +00001404 // If the clobbering value is a memset/memcpy/memmove, see if we can
1405 // forward a value on from it.
Chris Lattner93236ba2009-12-06 04:54:31 +00001406 if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInfo.getInst())) {
Chris Lattnerca5f9cb2009-12-09 18:21:46 +00001407 if (TD && Address) {
1408 int Offset = AnalyzeLoadFromClobberingMemInst(LI->getType(), Address,
Chris Lattner07df9ef2009-12-09 07:37:07 +00001409 DepMI, *TD);
Chris Lattner93236ba2009-12-06 04:54:31 +00001410 if (Offset != -1) {
1411 ValuesPerBlock.push_back(AvailableValueInBlock::getMI(DepBB, DepMI,
1412 Offset));
1413 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00001414 }
Chris Lattner42376062009-12-06 01:57:02 +00001415 }
1416 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001417
Chris Lattner0e3d6332008-12-05 21:04:20 +00001418 UnavailableBlocks.push_back(DepBB);
1419 continue;
1420 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001421
Eli Friedmanc1702c82011-10-13 22:14:57 +00001422 // DepInfo.isDef() here
Eli Friedman7d58bc72011-06-15 00:47:34 +00001423
Chris Lattner0e3d6332008-12-05 21:04:20 +00001424 Instruction *DepInst = DepInfo.getInst();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001425
Chris Lattner0e3d6332008-12-05 21:04:20 +00001426 // Loading the allocation -> undef.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001427 if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI) ||
Owen Andersonb9878ee2009-12-02 07:35:19 +00001428 // Loading immediately after lifetime begin -> undef.
1429 isLifetimeStart(DepInst)) {
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001430 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1431 UndefValue::get(LI->getType())));
Chris Lattner7e61daf2008-12-01 01:15:42 +00001432 continue;
1433 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001434
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001435 if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001436 // Reject loads and stores that are to the same address but are of
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001437 // different types if we have to.
Dan Gohmand2099112010-11-10 19:03:33 +00001438 if (S->getValueOperand()->getType() != LI->getType()) {
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001439 // If the stored value is larger or equal to the loaded value, we can
1440 // reuse it.
Dan Gohmand2099112010-11-10 19:03:33 +00001441 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(S->getValueOperand(),
Chris Lattner9045f232009-09-21 17:24:04 +00001442 LI->getType(), *TD)) {
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001443 UnavailableBlocks.push_back(DepBB);
1444 continue;
1445 }
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001446 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001447
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001448 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
Dan Gohmand2099112010-11-10 19:03:33 +00001449 S->getValueOperand()));
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001450 continue;
1451 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001452
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001453 if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001454 // If the types mismatch and we can't handle it, reject reuse of the load.
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001455 if (LD->getType() != LI->getType()) {
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001456 // If the stored value is larger or equal to the loaded value, we can
1457 // reuse it.
Chris Lattner9045f232009-09-21 17:24:04 +00001458 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(LD, LI->getType(),*TD)){
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001459 UnavailableBlocks.push_back(DepBB);
1460 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00001461 }
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001462 }
Chris Lattner827a2702011-04-28 07:29:08 +00001463 ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB, LD));
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001464 continue;
Owen Anderson5e5599b2007-07-25 19:57:03 +00001465 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001466
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001467 UnavailableBlocks.push_back(DepBB);
Chris Lattner2876a642008-03-21 21:14:38 +00001468 }
Shuxin Yang637b9be2013-05-03 19:17:26 +00001469}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001470
Shuxin Yang637b9be2013-05-03 19:17:26 +00001471bool GVN::PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock,
1472 UnavailBlkVect &UnavailableBlocks) {
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001473 // Okay, we have *some* definitions of the value. This means that the value
1474 // is available in some of our (transitive) predecessors. Lets think about
1475 // doing PRE of this load. This will involve inserting a new load into the
1476 // predecessor when it's not available. We could do this in general, but
1477 // prefer to not increase code size. As such, we only do this when we know
1478 // that we only have to insert *one* load (which means we're basically moving
1479 // the load, not inserting a new one).
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001480
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001481 SmallPtrSet<BasicBlock *, 4> Blockers;
1482 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1483 Blockers.insert(UnavailableBlocks[i]);
1484
Bill Wendling8bbcbed2011-08-17 21:32:02 +00001485 // Let's find the first basic block with more than one predecessor. Walk
1486 // backwards through predecessors if needed.
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001487 BasicBlock *LoadBB = LI->getParent();
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001488 BasicBlock *TmpBB = LoadBB;
1489
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001490 while (TmpBB->getSinglePredecessor()) {
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001491 TmpBB = TmpBB->getSinglePredecessor();
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001492 if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1493 return false;
1494 if (Blockers.count(TmpBB))
1495 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001496
Owen Andersonb590a922010-09-25 05:26:18 +00001497 // If any of these blocks has more than one successor (i.e. if the edge we
Nadav Rotem465834c2012-07-24 10:51:42 +00001498 // just traversed was critical), then there are other paths through this
1499 // block along which the load may not be anticipated. Hoisting the load
Owen Andersonb590a922010-09-25 05:26:18 +00001500 // above this block would be adding the load to execution paths along
1501 // which it was not previously executed.
Dale Johannesen81b64632009-06-17 20:48:23 +00001502 if (TmpBB->getTerminator()->getNumSuccessors() != 1)
Owen Andersonb590a922010-09-25 05:26:18 +00001503 return false;
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001504 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001505
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001506 assert(TmpBB);
1507 LoadBB = TmpBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001508
Bob Wilsond517b522010-02-01 21:17:14 +00001509 // Check to see how many predecessors have the loaded value fully
1510 // available.
1511 DenseMap<BasicBlock*, Value*> PredLoads;
Chris Lattnerd2a653a2008-12-05 07:49:08 +00001512 DenseMap<BasicBlock*, char> FullyAvailableBlocks;
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001513 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001514 FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001515 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1516 FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1517
Shuxin Yang1d8d7e42013-05-09 18:34:27 +00001518 SmallVector<BasicBlock *, 4> CriticalEdgePred;
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001519 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1520 PI != E; ++PI) {
Bob Wilsond517b522010-02-01 21:17:14 +00001521 BasicBlock *Pred = *PI;
Mon P Wang6120cfb2012-04-27 18:09:28 +00001522 if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks, 0)) {
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001523 continue;
Bob Wilsond517b522010-02-01 21:17:14 +00001524 }
1525 PredLoads[Pred] = 0;
Bob Wilson92cdb6e2010-02-16 19:51:59 +00001526
Bob Wilsond517b522010-02-01 21:17:14 +00001527 if (Pred->getTerminator()->getNumSuccessors() != 1) {
Bob Wilson92cdb6e2010-02-16 19:51:59 +00001528 if (isa<IndirectBrInst>(Pred->getTerminator())) {
1529 DEBUG(dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
1530 << Pred->getName() << "': " << *LI << '\n');
1531 return false;
1532 }
Bill Wendling8bbcbed2011-08-17 21:32:02 +00001533
1534 if (LoadBB->isLandingPad()) {
1535 DEBUG(dbgs()
1536 << "COULD NOT PRE LOAD BECAUSE OF LANDING PAD CRITICAL EDGE '"
1537 << Pred->getName() << "': " << *LI << '\n');
1538 return false;
1539 }
1540
Shuxin Yang1d8d7e42013-05-09 18:34:27 +00001541 CriticalEdgePred.push_back(Pred);
Bob Wilsond517b522010-02-01 21:17:14 +00001542 }
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001543 }
Bill Wendling8bbcbed2011-08-17 21:32:02 +00001544
Bob Wilsond517b522010-02-01 21:17:14 +00001545 // Decide whether PRE is profitable for this load.
1546 unsigned NumUnavailablePreds = PredLoads.size();
1547 assert(NumUnavailablePreds != 0 &&
Shuxin Yang1d8d7e42013-05-09 18:34:27 +00001548 "Fully available value should already be eliminated!");
Nadav Rotem465834c2012-07-24 10:51:42 +00001549
Owen Anderson13a642d2010-10-01 20:02:55 +00001550 // If this load is unavailable in multiple predecessors, reject it.
1551 // FIXME: If we could restructure the CFG, we could make a common pred with
1552 // all the preds that don't have an available LI and insert a new load into
1553 // that one block.
1554 if (NumUnavailablePreds != 1)
Bob Wilsond517b522010-02-01 21:17:14 +00001555 return false;
Bob Wilsond517b522010-02-01 21:17:14 +00001556
Shuxin Yang1d8d7e42013-05-09 18:34:27 +00001557 // Split critical edges, and update the unavailable predecessors accordingly.
1558 for (SmallVector<BasicBlock *, 4>::iterator I = CriticalEdgePred.begin(),
1559 E = CriticalEdgePred.end(); I != E; I++) {
1560 BasicBlock *OrigPred = *I;
1561 BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB);
1562 PredLoads.erase(OrigPred);
1563 PredLoads[NewPred] = 0;
1564 DEBUG(dbgs() << "Split critical edge " << OrigPred->getName() << "->"
1565 << LoadBB->getName() << '\n');
1566 }
1567
Bob Wilsond517b522010-02-01 21:17:14 +00001568 // Check if the load can safely be moved to all the unavailable predecessors.
1569 bool CanDoPRE = true;
Chris Lattner44da5bd2009-11-28 15:39:14 +00001570 SmallVector<Instruction*, 8> NewInsts;
Bob Wilsond517b522010-02-01 21:17:14 +00001571 for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1572 E = PredLoads.end(); I != E; ++I) {
1573 BasicBlock *UnavailablePred = I->first;
1574
1575 // Do PHI translation to get its value in the predecessor if necessary. The
1576 // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
1577
1578 // If all preds have a single successor, then we know it is safe to insert
1579 // the load on the pred (?!?), so we can insert code to materialize the
1580 // pointer if it is not available.
Dan Gohmand2099112010-11-10 19:03:33 +00001581 PHITransAddr Address(LI->getPointerOperand(), TD);
Bob Wilsond517b522010-02-01 21:17:14 +00001582 Value *LoadPtr = 0;
Shuxin Yangaf2c3dd2013-05-02 21:14:31 +00001583 LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred,
1584 *DT, NewInsts);
Bob Wilsond517b522010-02-01 21:17:14 +00001585
1586 // If we couldn't find or insert a computation of this phi translated value,
1587 // we fail PRE.
1588 if (LoadPtr == 0) {
1589 DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
Dan Gohmand2099112010-11-10 19:03:33 +00001590 << *LI->getPointerOperand() << "\n");
Bob Wilsond517b522010-02-01 21:17:14 +00001591 CanDoPRE = false;
1592 break;
1593 }
1594
Bob Wilsond517b522010-02-01 21:17:14 +00001595 I->second = LoadPtr;
Chris Lattner972e6d82009-12-09 01:59:31 +00001596 }
1597
Bob Wilsond517b522010-02-01 21:17:14 +00001598 if (!CanDoPRE) {
Chris Lattner193ce7c2011-01-11 08:19:16 +00001599 while (!NewInsts.empty()) {
1600 Instruction *I = NewInsts.pop_back_val();
1601 if (MD) MD->removeInstruction(I);
1602 I->eraseFromParent();
1603 }
Shuxin Yang1d8d7e42013-05-09 18:34:27 +00001604 // HINT:Don't revert the edge-splitting as following transformation may
1605 // also need to split these critial edges.
1606 return !CriticalEdgePred.empty();
Chris Lattner32140312009-11-28 16:08:18 +00001607 }
Dale Johannesen81b64632009-06-17 20:48:23 +00001608
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001609 // Okay, we can eliminate this load by inserting a reload in the predecessor
1610 // and using PHI construction to get the value in the other predecessors, do
1611 // it.
David Greene2e6efc42010-01-05 01:27:17 +00001612 DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
Chris Lattner32140312009-11-28 16:08:18 +00001613 DEBUG(if (!NewInsts.empty())
David Greene2e6efc42010-01-05 01:27:17 +00001614 dbgs() << "INSERTED " << NewInsts.size() << " INSTS: "
Chris Lattner32140312009-11-28 16:08:18 +00001615 << *NewInsts.back() << '\n');
Nadav Rotem465834c2012-07-24 10:51:42 +00001616
Bob Wilsond517b522010-02-01 21:17:14 +00001617 // Assign value numbers to the new instructions.
1618 for (unsigned i = 0, e = NewInsts.size(); i != e; ++i) {
Nadav Rotem465834c2012-07-24 10:51:42 +00001619 // FIXME: We really _ought_ to insert these value numbers into their
Bob Wilsond517b522010-02-01 21:17:14 +00001620 // parent's availability map. However, in doing so, we risk getting into
1621 // ordering issues. If a block hasn't been processed yet, we would be
1622 // marking a value as AVAIL-IN, which isn't what we intend.
1623 VN.lookup_or_add(NewInsts[i]);
1624 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001625
Bob Wilsond517b522010-02-01 21:17:14 +00001626 for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1627 E = PredLoads.end(); I != E; ++I) {
1628 BasicBlock *UnavailablePred = I->first;
1629 Value *LoadPtr = I->second;
1630
Dan Gohman4467aa52010-12-15 23:53:55 +00001631 Instruction *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1632 LI->getAlignment(),
1633 UnavailablePred->getTerminator());
1634
1635 // Transfer the old load's TBAA tag to the new load.
1636 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa))
1637 NewLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
Bob Wilsond517b522010-02-01 21:17:14 +00001638
Devang Patelc5933f22011-05-17 19:43:38 +00001639 // Transfer DebugLoc.
1640 NewLoad->setDebugLoc(LI->getDebugLoc());
1641
Bob Wilsond517b522010-02-01 21:17:14 +00001642 // Add the newly created load.
1643 ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,
1644 NewLoad));
Bob Wilson923261b2010-02-23 05:55:00 +00001645 MD->invalidateCachedPointerInfo(LoadPtr);
1646 DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
Bob Wilsond517b522010-02-01 21:17:14 +00001647 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001648
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001649 // Perform PHI construction.
Chris Lattnerf81f7892011-04-28 16:36:48 +00001650 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001651 LI->replaceAllUsesWith(V);
1652 if (isa<PHINode>(V))
1653 V->takeName(LI);
Hal Finkel69b07a22012-10-24 21:22:30 +00001654 if (V->getType()->getScalarType()->isPointerTy())
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001655 MD->invalidateCachedPointerInfo(V);
Chris Lattnerf81f7892011-04-28 16:36:48 +00001656 markInstructionForDeletion(LI);
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001657 ++NumPRELoad;
Owen Anderson5e5599b2007-07-25 19:57:03 +00001658 return true;
1659}
1660
Shuxin Yang637b9be2013-05-03 19:17:26 +00001661/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
1662/// non-local by performing PHI construction.
1663bool GVN::processNonLocalLoad(LoadInst *LI) {
1664 // Step 1: Find the non-local dependencies of the load.
1665 LoadDepVect Deps;
1666 AliasAnalysis::Location Loc = VN.getAliasAnalysis()->getLocation(LI);
1667 MD->getNonLocalPointerDependency(Loc, true, LI->getParent(), Deps);
1668
1669 // If we had to process more than one hundred blocks to find the
1670 // dependencies, this load isn't worth worrying about. Optimizing
1671 // it will be too expensive.
1672 unsigned NumDeps = Deps.size();
1673 if (NumDeps > 100)
1674 return false;
1675
1676 // If we had a phi translation failure, we'll have a single entry which is a
1677 // clobber in the current block. Reject this early.
1678 if (NumDeps == 1 &&
1679 !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
1680 DEBUG(
1681 dbgs() << "GVN: non-local load ";
1682 WriteAsOperand(dbgs(), LI);
1683 dbgs() << " has unknown dependencies\n";
1684 );
1685 return false;
1686 }
1687
1688 // Step 2: Analyze the availability of the load
1689 AvailValInBlkVect ValuesPerBlock;
1690 UnavailBlkVect UnavailableBlocks;
1691 AnalyzeLoadAvailability(LI, Deps, ValuesPerBlock, UnavailableBlocks);
1692
1693 // If we have no predecessors that produce a known value for this load, exit
1694 // early.
1695 if (ValuesPerBlock.empty())
1696 return false;
1697
1698 // Step 3: Eliminate fully redundancy.
1699 //
1700 // If all of the instructions we depend on produce a known value for this
1701 // load, then it is fully redundant and we can use PHI insertion to compute
1702 // its value. Insert PHIs and remove the fully redundant value now.
1703 if (UnavailableBlocks.empty()) {
1704 DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
1705
1706 // Perform PHI construction.
1707 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1708 LI->replaceAllUsesWith(V);
1709
1710 if (isa<PHINode>(V))
1711 V->takeName(LI);
1712 if (V->getType()->getScalarType()->isPointerTy())
1713 MD->invalidateCachedPointerInfo(V);
1714 markInstructionForDeletion(LI);
1715 ++NumGVNLoad;
1716 return true;
1717 }
1718
1719 // Step 4: Eliminate partial redundancy.
1720 if (!EnablePRE || !EnableLoadPRE)
1721 return false;
1722
1723 return PerformLoadPRE(LI, ValuesPerBlock, UnavailableBlocks);
1724}
1725
1726
Dan Gohman00253592013-03-12 16:22:56 +00001727static void patchReplacementInstruction(Instruction *I, Value *Repl) {
Rafael Espindola47d988c2012-06-04 22:44:21 +00001728 // Patch the replacement so that it is not more restrictive than the value
1729 // being replaced.
1730 BinaryOperator *Op = dyn_cast<BinaryOperator>(I);
1731 BinaryOperator *ReplOp = dyn_cast<BinaryOperator>(Repl);
1732 if (Op && ReplOp && isa<OverflowingBinaryOperator>(Op) &&
1733 isa<OverflowingBinaryOperator>(ReplOp)) {
1734 if (ReplOp->hasNoSignedWrap() && !Op->hasNoSignedWrap())
1735 ReplOp->setHasNoSignedWrap(false);
1736 if (ReplOp->hasNoUnsignedWrap() && !Op->hasNoUnsignedWrap())
1737 ReplOp->setHasNoUnsignedWrap(false);
1738 }
1739 if (Instruction *ReplInst = dyn_cast<Instruction>(Repl)) {
1740 SmallVector<std::pair<unsigned, MDNode*>, 4> Metadata;
1741 ReplInst->getAllMetadataOtherThanDebugLoc(Metadata);
1742 for (int i = 0, n = Metadata.size(); i < n; ++i) {
1743 unsigned Kind = Metadata[i].first;
1744 MDNode *IMD = I->getMetadata(Kind);
1745 MDNode *ReplMD = Metadata[i].second;
1746 switch(Kind) {
1747 default:
1748 ReplInst->setMetadata(Kind, NULL); // Remove unknown metadata
1749 break;
1750 case LLVMContext::MD_dbg:
1751 llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
1752 case LLVMContext::MD_tbaa:
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001753 ReplInst->setMetadata(Kind, MDNode::getMostGenericTBAA(IMD, ReplMD));
Rafael Espindola47d988c2012-06-04 22:44:21 +00001754 break;
1755 case LLVMContext::MD_range:
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001756 ReplInst->setMetadata(Kind, MDNode::getMostGenericRange(IMD, ReplMD));
Rafael Espindola47d988c2012-06-04 22:44:21 +00001757 break;
1758 case LLVMContext::MD_prof:
1759 llvm_unreachable("MD_prof in a non terminator instruction");
1760 break;
1761 case LLVMContext::MD_fpmath:
Hal Finkel16ddd4b2012-06-16 20:33:37 +00001762 ReplInst->setMetadata(Kind, MDNode::getMostGenericFPMath(IMD, ReplMD));
Rafael Espindola47d988c2012-06-04 22:44:21 +00001763 break;
1764 }
1765 }
1766 }
1767}
1768
Dan Gohman00253592013-03-12 16:22:56 +00001769static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
1770 patchReplacementInstruction(I, Repl);
Rafael Espindola47d988c2012-06-04 22:44:21 +00001771 I->replaceAllUsesWith(Repl);
1772}
1773
Owen Anderson221a4362007-08-16 22:02:55 +00001774/// processLoad - Attempt to eliminate a load, first by eliminating it
1775/// locally, and then attempting non-local elimination if that fails.
Chris Lattner6cec6ab2011-04-28 16:18:52 +00001776bool GVN::processLoad(LoadInst *L) {
Dan Gohman81132462009-11-14 02:27:51 +00001777 if (!MD)
1778 return false;
1779
Eli Friedman9a468152011-08-17 22:22:24 +00001780 if (!L->isSimple())
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001781 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001782
Chris Lattnerf0d59072011-05-22 07:03:34 +00001783 if (L->use_empty()) {
1784 markInstructionForDeletion(L);
1785 return true;
1786 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001787
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001788 // ... to a pointer that has been loaded from before...
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001789 MemDepResult Dep = MD->getDependency(L);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001790
Chris Lattner6f83d062011-04-26 01:21:15 +00001791 // If we have a clobber and target data is around, see if this is a clobber
1792 // that we can fix up through code synthesis.
1793 if (Dep.isClobber() && TD) {
Chris Lattner0a9616d2009-09-21 05:57:11 +00001794 // Check to see if we have something like this:
Chris Lattner1dd48c32009-09-20 19:03:47 +00001795 // store i32 123, i32* %P
1796 // %A = bitcast i32* %P to i8*
1797 // %B = gep i8* %A, i32 1
1798 // %C = load i8* %B
1799 //
1800 // We could do that by recognizing if the clobber instructions are obviously
1801 // a common base + constant offset, and if the previous store (or memset)
1802 // completely covers this load. This sort of thing can happen in bitfield
1803 // access code.
Chris Lattner42376062009-12-06 01:57:02 +00001804 Value *AvailVal = 0;
Chris Lattner6f83d062011-04-26 01:21:15 +00001805 if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst())) {
1806 int Offset = AnalyzeLoadFromClobberingStore(L->getType(),
1807 L->getPointerOperand(),
1808 DepSI, *TD);
1809 if (Offset != -1)
1810 AvailVal = GetStoreValueForLoad(DepSI->getValueOperand(), Offset,
1811 L->getType(), L, *TD);
1812 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001813
Chris Lattner6f83d062011-04-26 01:21:15 +00001814 // Check to see if we have something like this:
1815 // load i32* P
1816 // load i8* (P+1)
1817 // if we have this, replace the later with an extraction from the former.
1818 if (LoadInst *DepLI = dyn_cast<LoadInst>(Dep.getInst())) {
1819 // If this is a clobber and L is the first instruction in its block, then
1820 // we have the first instruction in the entry block.
1821 if (DepLI == L)
1822 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001823
Chris Lattner6f83d062011-04-26 01:21:15 +00001824 int Offset = AnalyzeLoadFromClobberingLoad(L->getType(),
1825 L->getPointerOperand(),
1826 DepLI, *TD);
1827 if (Offset != -1)
Chris Lattnerf81f7892011-04-28 16:36:48 +00001828 AvailVal = GetLoadValueForLoad(DepLI, Offset, L->getType(), L, *this);
Chris Lattner6f83d062011-04-26 01:21:15 +00001829 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001830
Chris Lattner42376062009-12-06 01:57:02 +00001831 // If the clobbering value is a memset/memcpy/memmove, see if we can forward
1832 // a value on from it.
1833 if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(Dep.getInst())) {
Chris Lattner6f83d062011-04-26 01:21:15 +00001834 int Offset = AnalyzeLoadFromClobberingMemInst(L->getType(),
1835 L->getPointerOperand(),
1836 DepMI, *TD);
1837 if (Offset != -1)
1838 AvailVal = GetMemInstValueForLoad(DepMI, Offset, L->getType(), L, *TD);
Chris Lattner42376062009-12-06 01:57:02 +00001839 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001840
Chris Lattner42376062009-12-06 01:57:02 +00001841 if (AvailVal) {
David Greene2e6efc42010-01-05 01:27:17 +00001842 DEBUG(dbgs() << "GVN COERCED INST:\n" << *Dep.getInst() << '\n'
Chris Lattner42376062009-12-06 01:57:02 +00001843 << *AvailVal << '\n' << *L << "\n\n\n");
Nadav Rotem465834c2012-07-24 10:51:42 +00001844
Chris Lattner42376062009-12-06 01:57:02 +00001845 // Replace the load!
1846 L->replaceAllUsesWith(AvailVal);
Hal Finkel69b07a22012-10-24 21:22:30 +00001847 if (AvailVal->getType()->getScalarType()->isPointerTy())
Chris Lattner42376062009-12-06 01:57:02 +00001848 MD->invalidateCachedPointerInfo(AvailVal);
Chris Lattnerf81f7892011-04-28 16:36:48 +00001849 markInstructionForDeletion(L);
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001850 ++NumGVNLoad;
Chris Lattner42376062009-12-06 01:57:02 +00001851 return true;
1852 }
Chris Lattner6f83d062011-04-26 01:21:15 +00001853 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001854
Chris Lattner6f83d062011-04-26 01:21:15 +00001855 // If the value isn't available, don't do anything!
1856 if (Dep.isClobber()) {
Torok Edwin72070282009-05-29 09:46:03 +00001857 DEBUG(
Chris Lattner6f83d062011-04-26 01:21:15 +00001858 // fast print dep, using operator<< on instruction is too slow.
David Greene2e6efc42010-01-05 01:27:17 +00001859 dbgs() << "GVN: load ";
1860 WriteAsOperand(dbgs(), L);
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001861 Instruction *I = Dep.getInst();
David Greene2e6efc42010-01-05 01:27:17 +00001862 dbgs() << " is clobbered by " << *I << '\n';
Torok Edwin72070282009-05-29 09:46:03 +00001863 );
Chris Lattner0e3d6332008-12-05 21:04:20 +00001864 return false;
Torok Edwin72070282009-05-29 09:46:03 +00001865 }
Chris Lattner0e3d6332008-12-05 21:04:20 +00001866
Eli Friedmanc1702c82011-10-13 22:14:57 +00001867 // If it is defined in another block, try harder.
1868 if (Dep.isNonLocal())
1869 return processNonLocalLoad(L);
1870
1871 if (!Dep.isDef()) {
Eli Friedman7d58bc72011-06-15 00:47:34 +00001872 DEBUG(
1873 // fast print dep, using operator<< on instruction is too slow.
1874 dbgs() << "GVN: load ";
1875 WriteAsOperand(dbgs(), L);
1876 dbgs() << " has unknown dependence\n";
1877 );
1878 return false;
1879 }
1880
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001881 Instruction *DepInst = Dep.getInst();
Chris Lattner0e3d6332008-12-05 21:04:20 +00001882 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
Dan Gohmand2099112010-11-10 19:03:33 +00001883 Value *StoredVal = DepSI->getValueOperand();
Nadav Rotem465834c2012-07-24 10:51:42 +00001884
Chris Lattner1dd48c32009-09-20 19:03:47 +00001885 // The store and load are to a must-aliased pointer, but they may not
1886 // actually have the same type. See if we know how to reuse the stored
1887 // value (depending on its type).
Chris Lattner8ed7bef2009-10-21 04:11:19 +00001888 if (StoredVal->getType() != L->getType()) {
Duncan Sands246b71c2010-11-12 21:10:24 +00001889 if (TD) {
Chris Lattner8ed7bef2009-10-21 04:11:19 +00001890 StoredVal = CoerceAvailableValueToLoadType(StoredVal, L->getType(),
1891 L, *TD);
1892 if (StoredVal == 0)
1893 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001894
David Greene2e6efc42010-01-05 01:27:17 +00001895 DEBUG(dbgs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
Chris Lattner8ed7bef2009-10-21 04:11:19 +00001896 << '\n' << *L << "\n\n\n");
1897 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001898 else
Chris Lattner1dd48c32009-09-20 19:03:47 +00001899 return false;
Chris Lattner1dd48c32009-09-20 19:03:47 +00001900 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001901
Chris Lattner0e3d6332008-12-05 21:04:20 +00001902 // Remove it!
Chris Lattner1dd48c32009-09-20 19:03:47 +00001903 L->replaceAllUsesWith(StoredVal);
Hal Finkel69b07a22012-10-24 21:22:30 +00001904 if (StoredVal->getType()->getScalarType()->isPointerTy())
Chris Lattner1dd48c32009-09-20 19:03:47 +00001905 MD->invalidateCachedPointerInfo(StoredVal);
Chris Lattnerf81f7892011-04-28 16:36:48 +00001906 markInstructionForDeletion(L);
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001907 ++NumGVNLoad;
Chris Lattner0e3d6332008-12-05 21:04:20 +00001908 return true;
1909 }
1910
1911 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
Chris Lattner1dd48c32009-09-20 19:03:47 +00001912 Value *AvailableVal = DepLI;
Nadav Rotem465834c2012-07-24 10:51:42 +00001913
Chris Lattner1dd48c32009-09-20 19:03:47 +00001914 // The loads are of a must-aliased pointer, but they may not actually have
1915 // the same type. See if we know how to reuse the previously loaded value
1916 // (depending on its type).
Chris Lattner8ed7bef2009-10-21 04:11:19 +00001917 if (DepLI->getType() != L->getType()) {
Duncan Sands246b71c2010-11-12 21:10:24 +00001918 if (TD) {
Chris Lattner6f83d062011-04-26 01:21:15 +00001919 AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(),
1920 L, *TD);
Chris Lattner8ed7bef2009-10-21 04:11:19 +00001921 if (AvailableVal == 0)
1922 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001923
David Greene2e6efc42010-01-05 01:27:17 +00001924 DEBUG(dbgs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
Chris Lattner8ed7bef2009-10-21 04:11:19 +00001925 << "\n" << *L << "\n\n\n");
1926 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001927 else
Chris Lattner8ed7bef2009-10-21 04:11:19 +00001928 return false;
Chris Lattner1dd48c32009-09-20 19:03:47 +00001929 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001930
Chris Lattner0e3d6332008-12-05 21:04:20 +00001931 // Remove it!
Dan Gohman00253592013-03-12 16:22:56 +00001932 patchAndReplaceAllUsesWith(L, AvailableVal);
Hal Finkel69b07a22012-10-24 21:22:30 +00001933 if (DepLI->getType()->getScalarType()->isPointerTy())
Chris Lattnerfa9f99a2008-12-09 22:06:23 +00001934 MD->invalidateCachedPointerInfo(DepLI);
Chris Lattnerf81f7892011-04-28 16:36:48 +00001935 markInstructionForDeletion(L);
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001936 ++NumGVNLoad;
Chris Lattner0e3d6332008-12-05 21:04:20 +00001937 return true;
1938 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001939
Chris Lattner3ff6d012008-11-30 01:39:32 +00001940 // If this load really doesn't depend on anything, then we must be loading an
1941 // undef value. This can happen when loading for a fresh allocation with no
1942 // intervening stores, for example.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001943 if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00001944 L->replaceAllUsesWith(UndefValue::get(L->getType()));
Chris Lattnerf81f7892011-04-28 16:36:48 +00001945 markInstructionForDeletion(L);
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001946 ++NumGVNLoad;
Chris Lattner0e3d6332008-12-05 21:04:20 +00001947 return true;
Eli Friedman716c10c2008-02-12 12:08:14 +00001948 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001949
Owen Andersonb9878ee2009-12-02 07:35:19 +00001950 // If this load occurs either right after a lifetime begin,
Owen Anderson2b2bd282009-10-28 07:05:35 +00001951 // then the loaded value is undefined.
Chris Lattnerf81f7892011-04-28 16:36:48 +00001952 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(DepInst)) {
Owen Andersonb9878ee2009-12-02 07:35:19 +00001953 if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
Owen Anderson2b2bd282009-10-28 07:05:35 +00001954 L->replaceAllUsesWith(UndefValue::get(L->getType()));
Chris Lattnerf81f7892011-04-28 16:36:48 +00001955 markInstructionForDeletion(L);
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001956 ++NumGVNLoad;
Owen Anderson2b2bd282009-10-28 07:05:35 +00001957 return true;
1958 }
1959 }
Eli Friedman716c10c2008-02-12 12:08:14 +00001960
Chris Lattner0e3d6332008-12-05 21:04:20 +00001961 return false;
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001962}
1963
Nadav Rotem465834c2012-07-24 10:51:42 +00001964// findLeader - In order to find a leader for a given value number at a
Owen Andersonea326db2010-11-19 22:48:40 +00001965// specific basic block, we first obtain the list of all Values for that number,
Nadav Rotem465834c2012-07-24 10:51:42 +00001966// and then scan the list to find one whose block dominates the block in
Owen Andersonea326db2010-11-19 22:48:40 +00001967// question. This is fast because dominator tree queries consist of only
1968// a few comparisons of DFS numbers.
Rafael Espindola64e7b5702012-08-10 15:55:25 +00001969Value *GVN::findLeader(const BasicBlock *BB, uint32_t num) {
Owen Andersone39cb572011-01-04 19:29:46 +00001970 LeaderTableEntry Vals = LeaderTable[num];
Owen Anderson5ab8d4b2010-12-21 23:54:34 +00001971 if (!Vals.Val) return 0;
Nadav Rotem465834c2012-07-24 10:51:42 +00001972
Owen Anderson5ab8d4b2010-12-21 23:54:34 +00001973 Value *Val = 0;
1974 if (DT->dominates(Vals.BB, BB)) {
1975 Val = Vals.Val;
1976 if (isa<Constant>(Val)) return Val;
1977 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001978
Owen Andersonc7c3bc62011-01-04 19:13:25 +00001979 LeaderTableEntry* Next = Vals.Next;
Owen Andersonc21c1002010-11-18 18:32:40 +00001980 while (Next) {
Owen Anderson5ab8d4b2010-12-21 23:54:34 +00001981 if (DT->dominates(Next->BB, BB)) {
1982 if (isa<Constant>(Next->Val)) return Next->Val;
1983 if (!Val) Val = Next->Val;
1984 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001985
Owen Anderson5ab8d4b2010-12-21 23:54:34 +00001986 Next = Next->Next;
Owen Anderson1b3ea962008-06-20 01:15:47 +00001987 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001988
Owen Anderson5ab8d4b2010-12-21 23:54:34 +00001989 return Val;
Owen Anderson1b3ea962008-06-20 01:15:47 +00001990}
1991
Duncan Sandsf4f47cc2011-10-05 14:28:49 +00001992/// replaceAllDominatedUsesWith - Replace all uses of 'From' with 'To' if the
1993/// use is dominated by the given basic block. Returns the number of uses that
1994/// were replaced.
1995unsigned GVN::replaceAllDominatedUsesWith(Value *From, Value *To,
Rafael Espindolacc80cde2012-08-16 15:09:43 +00001996 const BasicBlockEdge &Root) {
Duncan Sandsf4f47cc2011-10-05 14:28:49 +00001997 unsigned Count = 0;
1998 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
1999 UI != UE; ) {
Duncan Sands09203082012-02-08 14:10:53 +00002000 Use &U = (UI++).getUse();
Duncan Sands4d928e72012-03-04 13:25:19 +00002001
Rafael Espindolacc80cde2012-08-16 15:09:43 +00002002 if (DT->dominates(Root, U)) {
Duncan Sands09203082012-02-08 14:10:53 +00002003 U.set(To);
Duncan Sandsf4f47cc2011-10-05 14:28:49 +00002004 ++Count;
2005 }
2006 }
2007 return Count;
2008}
2009
Rafael Espindolacc80cde2012-08-16 15:09:43 +00002010/// isOnlyReachableViaThisEdge - There is an edge from 'Src' to 'Dst'. Return
2011/// true if every path from the entry block to 'Dst' passes via this edge. In
2012/// particular 'Dst' must not be reachable via another edge from 'Src'.
2013static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E,
2014 DominatorTree *DT) {
2015 // While in theory it is interesting to consider the case in which Dst has
2016 // more than one predecessor, because Dst might be part of a loop which is
2017 // only reachable from Src, in practice it is pointless since at the time
2018 // GVN runs all such loops have preheaders, which means that Dst will have
2019 // been changed to have only one predecessor, namely Src.
2020 const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
2021 const BasicBlock *Src = E.getStart();
2022 assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
2023 (void)Src;
2024 return Pred != 0;
2025}
2026
Duncan Sandsf4f47cc2011-10-05 14:28:49 +00002027/// propagateEquality - The given values are known to be equal in every block
2028/// dominated by 'Root'. Exploit this, for example by replacing 'LHS' with
2029/// 'RHS' everywhere in the scope. Returns whether a change was made.
Rafael Espindolacc80cde2012-08-16 15:09:43 +00002030bool GVN::propagateEquality(Value *LHS, Value *RHS,
2031 const BasicBlockEdge &Root) {
Duncan Sandsd12b18f2012-04-06 15:31:09 +00002032 SmallVector<std::pair<Value*, Value*>, 4> Worklist;
2033 Worklist.push_back(std::make_pair(LHS, RHS));
Duncan Sandsf537a6e2011-10-15 11:13:42 +00002034 bool Changed = false;
Rafael Espindolacc80cde2012-08-16 15:09:43 +00002035 // For speed, compute a conservative fast approximation to
2036 // DT->dominates(Root, Root.getEnd());
2037 bool RootDominatesEnd = isOnlyReachableViaThisEdge(Root, DT);
Duncan Sandsf4f47cc2011-10-05 14:28:49 +00002038
Duncan Sandsd12b18f2012-04-06 15:31:09 +00002039 while (!Worklist.empty()) {
2040 std::pair<Value*, Value*> Item = Worklist.pop_back_val();
2041 LHS = Item.first; RHS = Item.second;
Duncan Sandsf4f47cc2011-10-05 14:28:49 +00002042
Duncan Sandsd12b18f2012-04-06 15:31:09 +00002043 if (LHS == RHS) continue;
2044 assert(LHS->getType() == RHS->getType() && "Equality but unequal types!");
Duncan Sandsf4f47cc2011-10-05 14:28:49 +00002045
Duncan Sandsd12b18f2012-04-06 15:31:09 +00002046 // Don't try to propagate equalities between constants.
2047 if (isa<Constant>(LHS) && isa<Constant>(RHS)) continue;
Duncan Sands27f45952012-02-27 08:14:30 +00002048
Duncan Sandsd12b18f2012-04-06 15:31:09 +00002049 // Prefer a constant on the right-hand side, or an Argument if no constants.
2050 if (isa<Constant>(LHS) || (isa<Argument>(LHS) && !isa<Constant>(RHS)))
2051 std::swap(LHS, RHS);
2052 assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) && "Unexpected value!");
Duncan Sands27f45952012-02-27 08:14:30 +00002053
Duncan Sandsd12b18f2012-04-06 15:31:09 +00002054 // If there is no obvious reason to prefer the left-hand side over the right-
2055 // hand side, ensure the longest lived term is on the right-hand side, so the
2056 // shortest lived term will be replaced by the longest lived. This tends to
2057 // expose more simplifications.
2058 uint32_t LVN = VN.lookup_or_add(LHS);
2059 if ((isa<Argument>(LHS) && isa<Argument>(RHS)) ||
2060 (isa<Instruction>(LHS) && isa<Instruction>(RHS))) {
2061 // Move the 'oldest' value to the right-hand side, using the value number as
2062 // a proxy for age.
2063 uint32_t RVN = VN.lookup_or_add(RHS);
2064 if (LVN < RVN) {
2065 std::swap(LHS, RHS);
2066 LVN = RVN;
Duncan Sands9edea842012-02-27 12:11:41 +00002067 }
Duncan Sandsf4f47cc2011-10-05 14:28:49 +00002068 }
Duncan Sands27f45952012-02-27 08:14:30 +00002069
Duncan Sands4df5e962012-05-22 14:17:53 +00002070 // If value numbering later sees that an instruction in the scope is equal
2071 // to 'LHS' then ensure it will be turned into 'RHS'. In order to preserve
2072 // the invariant that instructions only occur in the leader table for their
2073 // own value number (this is used by removeFromLeaderTable), do not do this
2074 // if RHS is an instruction (if an instruction in the scope is morphed into
2075 // LHS then it will be turned into RHS by the next GVN iteration anyway, so
2076 // using the leader table is about compiling faster, not optimizing better).
Rafael Espindolacc80cde2012-08-16 15:09:43 +00002077 // The leader table only tracks basic blocks, not edges. Only add to if we
2078 // have the simple case where the edge dominates the end.
2079 if (RootDominatesEnd && !isa<Instruction>(RHS))
2080 addToLeaderTable(LVN, RHS, Root.getEnd());
Duncan Sandsd12b18f2012-04-06 15:31:09 +00002081
2082 // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope. As
2083 // LHS always has at least one use that is not dominated by Root, this will
2084 // never do anything if LHS has only one use.
2085 if (!LHS->hasOneUse()) {
2086 unsigned NumReplacements = replaceAllDominatedUsesWith(LHS, RHS, Root);
2087 Changed |= NumReplacements > 0;
2088 NumGVNEqProp += NumReplacements;
2089 }
2090
2091 // Now try to deduce additional equalities from this one. For example, if the
2092 // known equality was "(A != B)" == "false" then it follows that A and B are
2093 // equal in the scope. Only boolean equalities with an explicit true or false
2094 // RHS are currently supported.
2095 if (!RHS->getType()->isIntegerTy(1))
2096 // Not a boolean equality - bail out.
2097 continue;
2098 ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
2099 if (!CI)
2100 // RHS neither 'true' nor 'false' - bail out.
2101 continue;
2102 // Whether RHS equals 'true'. Otherwise it equals 'false'.
2103 bool isKnownTrue = CI->isAllOnesValue();
2104 bool isKnownFalse = !isKnownTrue;
2105
2106 // If "A && B" is known true then both A and B are known true. If "A || B"
2107 // is known false then both A and B are known false.
2108 Value *A, *B;
2109 if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) ||
2110 (isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) {
2111 Worklist.push_back(std::make_pair(A, RHS));
2112 Worklist.push_back(std::make_pair(B, RHS));
2113 continue;
2114 }
2115
2116 // If we are propagating an equality like "(A == B)" == "true" then also
2117 // propagate the equality A == B. When propagating a comparison such as
2118 // "(A >= B)" == "true", replace all instances of "A < B" with "false".
2119 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(LHS)) {
2120 Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
2121
2122 // If "A == B" is known true, or "A != B" is known false, then replace
2123 // A with B everywhere in the scope.
2124 if ((isKnownTrue && Cmp->getPredicate() == CmpInst::ICMP_EQ) ||
2125 (isKnownFalse && Cmp->getPredicate() == CmpInst::ICMP_NE))
2126 Worklist.push_back(std::make_pair(Op0, Op1));
2127
2128 // If "A >= B" is known true, replace "A < B" with false everywhere.
2129 CmpInst::Predicate NotPred = Cmp->getInversePredicate();
2130 Constant *NotVal = ConstantInt::get(Cmp->getType(), isKnownFalse);
2131 // Since we don't have the instruction "A < B" immediately to hand, work out
2132 // the value number that it would have and use that to find an appropriate
2133 // instruction (if any).
2134 uint32_t NextNum = VN.getNextUnusedValueNumber();
2135 uint32_t Num = VN.lookup_or_add_cmp(Cmp->getOpcode(), NotPred, Op0, Op1);
2136 // If the number we were assigned was brand new then there is no point in
2137 // looking for an instruction realizing it: there cannot be one!
2138 if (Num < NextNum) {
Rafael Espindolacc80cde2012-08-16 15:09:43 +00002139 Value *NotCmp = findLeader(Root.getEnd(), Num);
Duncan Sandsd12b18f2012-04-06 15:31:09 +00002140 if (NotCmp && isa<Instruction>(NotCmp)) {
2141 unsigned NumReplacements =
2142 replaceAllDominatedUsesWith(NotCmp, NotVal, Root);
2143 Changed |= NumReplacements > 0;
2144 NumGVNEqProp += NumReplacements;
2145 }
2146 }
2147 // Ensure that any instruction in scope that gets the "A < B" value number
2148 // is replaced with false.
Rafael Espindolacc80cde2012-08-16 15:09:43 +00002149 // The leader table only tracks basic blocks, not edges. Only add to if we
2150 // have the simple case where the edge dominates the end.
2151 if (RootDominatesEnd)
2152 addToLeaderTable(Num, NotVal, Root.getEnd());
Duncan Sandsd12b18f2012-04-06 15:31:09 +00002153
2154 continue;
2155 }
Duncan Sandsf4f47cc2011-10-05 14:28:49 +00002156 }
2157
2158 return Changed;
2159}
Owen Andersonbfe133e2008-12-15 02:03:00 +00002160
Owen Anderson398602a2007-08-14 18:16:29 +00002161/// processInstruction - When calculating availability, handle an instruction
Owen Andersonab6ec2e2007-07-24 17:55:58 +00002162/// by inserting it into the appropriate sets
Chris Lattner6cec6ab2011-04-28 16:18:52 +00002163bool GVN::processInstruction(Instruction *I) {
Devang Patel03936a12010-02-11 00:20:49 +00002164 // Ignore dbg info intrinsics.
2165 if (isa<DbgInfoIntrinsic>(I))
2166 return false;
2167
Duncan Sands246b71c2010-11-12 21:10:24 +00002168 // If the instruction can be easily simplified then do so now in preference
2169 // to value numbering it. Value numbering often exposes redundancies, for
2170 // example if it determines that %y is equal to %x then the instruction
2171 // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
Chad Rosierc24b86f2011-12-01 03:08:23 +00002172 if (Value *V = SimplifyInstruction(I, TD, TLI, DT)) {
Duncan Sands246b71c2010-11-12 21:10:24 +00002173 I->replaceAllUsesWith(V);
Hal Finkel69b07a22012-10-24 21:22:30 +00002174 if (MD && V->getType()->getScalarType()->isPointerTy())
Duncan Sands246b71c2010-11-12 21:10:24 +00002175 MD->invalidateCachedPointerInfo(V);
Chris Lattnerf81f7892011-04-28 16:36:48 +00002176 markInstructionForDeletion(I);
Duncan Sandsf4f47cc2011-10-05 14:28:49 +00002177 ++NumGVNSimpl;
Duncan Sands246b71c2010-11-12 21:10:24 +00002178 return true;
2179 }
2180
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002181 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner6cec6ab2011-04-28 16:18:52 +00002182 if (processLoad(LI))
2183 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002184
Chris Lattner6cec6ab2011-04-28 16:18:52 +00002185 unsigned Num = VN.lookup_or_add(LI);
2186 addToLeaderTable(Num, LI, LI->getParent());
2187 return false;
Owen Anderson6a903bc2008-06-18 21:41:49 +00002188 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002189
Duncan Sandsf4f47cc2011-10-05 14:28:49 +00002190 // For conditional branches, we can perform simple conditional propagation on
Owen Anderson5ab8d4b2010-12-21 23:54:34 +00002191 // the condition value itself.
2192 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
Owen Anderson5ab8d4b2010-12-21 23:54:34 +00002193 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
2194 return false;
Duncan Sandsf4f47cc2011-10-05 14:28:49 +00002195
Owen Anderson5ab8d4b2010-12-21 23:54:34 +00002196 Value *BranchCond = BI->getCondition();
Duncan Sandsf4f47cc2011-10-05 14:28:49 +00002197
Owen Anderson5ab8d4b2010-12-21 23:54:34 +00002198 BasicBlock *TrueSucc = BI->getSuccessor(0);
2199 BasicBlock *FalseSucc = BI->getSuccessor(1);
Rafael Espindolacc80cde2012-08-16 15:09:43 +00002200 // Avoid multiple edges early.
2201 if (TrueSucc == FalseSucc)
2202 return false;
2203
Duncan Sandse90dd052011-10-05 14:17:01 +00002204 BasicBlock *Parent = BI->getParent();
Duncan Sandsc52af462011-10-07 08:29:06 +00002205 bool Changed = false;
Duncan Sandse90dd052011-10-05 14:17:01 +00002206
Rafael Espindolacc80cde2012-08-16 15:09:43 +00002207 Value *TrueVal = ConstantInt::getTrue(TrueSucc->getContext());
2208 BasicBlockEdge TrueE(Parent, TrueSucc);
2209 Changed |= propagateEquality(BranchCond, TrueVal, TrueE);
Duncan Sandsc52af462011-10-07 08:29:06 +00002210
Rafael Espindolacc80cde2012-08-16 15:09:43 +00002211 Value *FalseVal = ConstantInt::getFalse(FalseSucc->getContext());
2212 BasicBlockEdge FalseE(Parent, FalseSucc);
2213 Changed |= propagateEquality(BranchCond, FalseVal, FalseE);
Duncan Sandsc52af462011-10-07 08:29:06 +00002214
2215 return Changed;
Owen Anderson5ab8d4b2010-12-21 23:54:34 +00002216 }
Duncan Sandsc52af462011-10-07 08:29:06 +00002217
2218 // For switches, propagate the case values into the case destinations.
2219 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
2220 Value *SwitchCond = SI->getCondition();
2221 BasicBlock *Parent = SI->getParent();
2222 bool Changed = false;
Benjamin Kramerdd62d6b2012-08-24 15:06:28 +00002223
2224 // Remember how many outgoing edges there are to every successor.
2225 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
2226 for (unsigned i = 0, n = SI->getNumSuccessors(); i != n; ++i)
2227 ++SwitchEdges[SI->getSuccessor(i)];
2228
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00002229 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002230 i != e; ++i) {
2231 BasicBlock *Dst = i.getCaseSuccessor();
Benjamin Kramerdd62d6b2012-08-24 15:06:28 +00002232 // If there is only a single edge, propagate the case value into it.
2233 if (SwitchEdges.lookup(Dst) == 1) {
2234 BasicBlockEdge E(Parent, Dst);
Rafael Espindolacc80cde2012-08-16 15:09:43 +00002235 Changed |= propagateEquality(SwitchCond, i.getCaseValue(), E);
Benjamin Kramerdd62d6b2012-08-24 15:06:28 +00002236 }
Duncan Sandsc52af462011-10-07 08:29:06 +00002237 }
2238 return Changed;
2239 }
2240
Owen Anderson7b25ff02011-01-04 22:15:21 +00002241 // Instructions with void type don't return a value, so there's
Duncan Sands1be25a72012-02-27 09:54:35 +00002242 // no point in trying to find redundancies in them.
Owen Anderson7b25ff02011-01-04 22:15:21 +00002243 if (I->getType()->isVoidTy()) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00002244
Owen Anderson41a15502011-01-04 18:54:18 +00002245 uint32_t NextNum = VN.getNextUnusedValueNumber();
2246 unsigned Num = VN.lookup_or_add(I);
2247
Owen Anderson0c1e6342008-04-07 09:59:07 +00002248 // Allocations are always uniquely numbered, so we can save time and memory
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002249 // by fast failing them.
Chris Lattnerb6252a32010-12-19 20:24:28 +00002250 if (isa<AllocaInst>(I) || isa<TerminatorInst>(I) || isa<PHINode>(I)) {
Owen Andersonc7c3bc62011-01-04 19:13:25 +00002251 addToLeaderTable(Num, I, I->getParent());
Owen Anderson0c1e6342008-04-07 09:59:07 +00002252 return false;
Owen Anderson6a903bc2008-06-18 21:41:49 +00002253 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002254
Owen Anderson3ea90a72008-07-03 17:44:33 +00002255 // If the number we were assigned was a brand new VN, then we don't
2256 // need to do a lookup to see if the number already exists
2257 // somewhere in the domtree: it can't!
Duncan Sands1be25a72012-02-27 09:54:35 +00002258 if (Num >= NextNum) {
Owen Andersonc7c3bc62011-01-04 19:13:25 +00002259 addToLeaderTable(Num, I, I->getParent());
Chris Lattnerb6252a32010-12-19 20:24:28 +00002260 return false;
2261 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002262
Owen Andersonbfe133e2008-12-15 02:03:00 +00002263 // Perform fast-path value-number based elimination of values inherited from
2264 // dominators.
Owen Andersonc7c3bc62011-01-04 19:13:25 +00002265 Value *repl = findLeader(I->getParent(), Num);
Chris Lattnerb6252a32010-12-19 20:24:28 +00002266 if (repl == 0) {
2267 // Failure, just remember this instance for future use.
Owen Andersonc7c3bc62011-01-04 19:13:25 +00002268 addToLeaderTable(Num, I, I->getParent());
Chris Lattnerb6252a32010-12-19 20:24:28 +00002269 return false;
Owen Andersonab6ec2e2007-07-24 17:55:58 +00002270 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002271
Chris Lattnerb6252a32010-12-19 20:24:28 +00002272 // Remove it!
Dan Gohman00253592013-03-12 16:22:56 +00002273 patchAndReplaceAllUsesWith(I, repl);
Hal Finkel69b07a22012-10-24 21:22:30 +00002274 if (MD && repl->getType()->getScalarType()->isPointerTy())
Chris Lattnerb6252a32010-12-19 20:24:28 +00002275 MD->invalidateCachedPointerInfo(repl);
Chris Lattnerf81f7892011-04-28 16:36:48 +00002276 markInstructionForDeletion(I);
Chris Lattnerb6252a32010-12-19 20:24:28 +00002277 return true;
Owen Andersonab6ec2e2007-07-24 17:55:58 +00002278}
2279
Bill Wendling456e8852008-12-22 22:32:22 +00002280/// runOnFunction - This is the main transformation entry point for a function.
Owen Anderson676070d2007-08-14 18:04:11 +00002281bool GVN::runOnFunction(Function& F) {
Dan Gohman81132462009-11-14 02:27:51 +00002282 if (!NoLoads)
2283 MD = &getAnalysis<MemoryDependenceAnalysis>();
Chris Lattner8541ede2008-12-01 00:40:32 +00002284 DT = &getAnalysis<DominatorTree>();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002285 TD = getAnalysisIfAvailable<DataLayout>();
Chad Rosierc24b86f2011-12-01 03:08:23 +00002286 TLI = &getAnalysis<TargetLibraryInfo>();
Owen Andersonf7928602008-05-12 20:15:55 +00002287 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
Chris Lattner8541ede2008-12-01 00:40:32 +00002288 VN.setMemDep(MD);
2289 VN.setDomTree(DT);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002290
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002291 bool Changed = false;
2292 bool ShouldContinue = true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002293
Owen Andersonac310962008-07-16 17:52:31 +00002294 // Merge unconditional branches, allowing PRE to catch more
2295 // optimization opportunities.
2296 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
Chris Lattnerf6ae9042011-01-11 08:13:40 +00002297 BasicBlock *BB = FI++;
Nadav Rotem465834c2012-07-24 10:51:42 +00002298
Owen Andersonc0623812008-07-17 00:01:40 +00002299 bool removedBlock = MergeBlockIntoPredecessor(BB, this);
Dan Gohmand2d1ae12010-06-22 15:08:57 +00002300 if (removedBlock) ++NumGVNBlocks;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002301
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002302 Changed |= removedBlock;
Owen Andersonac310962008-07-16 17:52:31 +00002303 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002304
Chris Lattner0a5a8d52008-12-09 19:21:47 +00002305 unsigned Iteration = 0;
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002306 while (ShouldContinue) {
David Greene2e6efc42010-01-05 01:27:17 +00002307 DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002308 ShouldContinue = iterateOnFunction(F);
2309 Changed |= ShouldContinue;
Chris Lattner0a5a8d52008-12-09 19:21:47 +00002310 ++Iteration;
Owen Anderson676070d2007-08-14 18:04:11 +00002311 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002312
Owen Anderson04a6e0b2008-07-18 18:03:38 +00002313 if (EnablePRE) {
Owen Anderson2fbfb702008-09-03 23:06:07 +00002314 bool PREChanged = true;
2315 while (PREChanged) {
2316 PREChanged = performPRE(F);
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002317 Changed |= PREChanged;
Owen Anderson2fbfb702008-09-03 23:06:07 +00002318 }
Owen Anderson04a6e0b2008-07-18 18:03:38 +00002319 }
Shuxin Yang1d8d7e42013-05-09 18:34:27 +00002320
Chris Lattner0a5a8d52008-12-09 19:21:47 +00002321 // FIXME: Should perform GVN again after PRE does something. PRE can move
2322 // computations into blocks where they become fully redundant. Note that
2323 // we can't do this until PRE's critical edge splitting updates memdep.
2324 // Actually, when this happens, we should just fully integrate PRE into GVN.
Nuno Lopese3127f32008-10-10 16:25:50 +00002325
2326 cleanupGlobalSets();
2327
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002328 return Changed;
Owen Anderson676070d2007-08-14 18:04:11 +00002329}
2330
2331
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002332bool GVN::processBlock(BasicBlock *BB) {
Chris Lattner6cec6ab2011-04-28 16:18:52 +00002333 // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function
2334 // (and incrementing BI before processing an instruction).
2335 assert(InstrsToErase.empty() &&
2336 "We expect InstrsToErase to be empty across iterations");
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002337 bool ChangedFunction = false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002338
Owen Andersonaccdca12008-06-12 19:25:32 +00002339 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
2340 BI != BE;) {
Chris Lattner6cec6ab2011-04-28 16:18:52 +00002341 ChangedFunction |= processInstruction(BI);
2342 if (InstrsToErase.empty()) {
Owen Andersonaccdca12008-06-12 19:25:32 +00002343 ++BI;
2344 continue;
2345 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002346
Owen Andersonaccdca12008-06-12 19:25:32 +00002347 // If we need some instructions deleted, do it now.
Chris Lattner6cec6ab2011-04-28 16:18:52 +00002348 NumGVNInstr += InstrsToErase.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002349
Owen Andersonaccdca12008-06-12 19:25:32 +00002350 // Avoid iterator invalidation.
2351 bool AtStart = BI == BB->begin();
2352 if (!AtStart)
2353 --BI;
2354
Chris Lattner6cec6ab2011-04-28 16:18:52 +00002355 for (SmallVector<Instruction*, 4>::iterator I = InstrsToErase.begin(),
2356 E = InstrsToErase.end(); I != E; ++I) {
David Greene2e6efc42010-01-05 01:27:17 +00002357 DEBUG(dbgs() << "GVN removed: " << **I << '\n');
Dan Gohman81132462009-11-14 02:27:51 +00002358 if (MD) MD->removeInstruction(*I);
Bill Wendlingebb6a542008-12-22 21:57:30 +00002359 DEBUG(verifyRemoved(*I));
Dan Gohmanfd41de02013-02-12 18:44:43 +00002360 (*I)->eraseFromParent();
Chris Lattner8541ede2008-12-01 00:40:32 +00002361 }
Chris Lattner6cec6ab2011-04-28 16:18:52 +00002362 InstrsToErase.clear();
Owen Andersonaccdca12008-06-12 19:25:32 +00002363
2364 if (AtStart)
2365 BI = BB->begin();
2366 else
2367 ++BI;
Owen Andersonaccdca12008-06-12 19:25:32 +00002368 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002369
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002370 return ChangedFunction;
Owen Andersonaccdca12008-06-12 19:25:32 +00002371}
2372
Owen Anderson6a903bc2008-06-18 21:41:49 +00002373/// performPRE - Perform a purely local form of PRE that looks for diamond
2374/// control flow patterns and attempts to perform simple PRE at the join point.
Chris Lattnera546dcf2009-10-31 22:11:15 +00002375bool GVN::performPRE(Function &F) {
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00002376 bool Changed = false;
Dan Gohmanf3771602013-02-12 19:49:10 +00002377 SmallVector<std::pair<Value*, BasicBlock*>, 8> predMap;
Owen Anderson6a903bc2008-06-18 21:41:49 +00002378 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
2379 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002380 BasicBlock *CurrentBlock = *DI;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002381
Owen Anderson6a903bc2008-06-18 21:41:49 +00002382 // Nothing to PRE in the entry block.
2383 if (CurrentBlock == &F.getEntryBlock()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002384
Bill Wendling8bbcbed2011-08-17 21:32:02 +00002385 // Don't perform PRE on a landing pad.
2386 if (CurrentBlock->isLandingPad()) continue;
2387
Owen Anderson6a903bc2008-06-18 21:41:49 +00002388 for (BasicBlock::iterator BI = CurrentBlock->begin(),
2389 BE = CurrentBlock->end(); BI != BE; ) {
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00002390 Instruction *CurInst = BI++;
Duncan Sands1efabaa2009-05-06 06:49:50 +00002391
Victor Hernandez8acf2952009-10-23 21:09:37 +00002392 if (isa<AllocaInst>(CurInst) ||
Victor Hernandez5d034492009-09-18 22:35:49 +00002393 isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
Devang Patel92f86192009-10-14 17:29:00 +00002394 CurInst->getType()->isVoidTy() ||
Duncan Sands1efabaa2009-05-06 06:49:50 +00002395 CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
John Criswell073e4d12009-03-10 15:04:53 +00002396 isa<DbgInfoIntrinsic>(CurInst))
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00002397 continue;
Jakob Stoklund Olesen4e550442012-03-29 17:22:39 +00002398
2399 // Don't do PRE on compares. The PHI would prevent CodeGenPrepare from
2400 // sinking the compare again, and it would force the code generator to
2401 // move the i1 from processor flags or predicate registers into a general
2402 // purpose register.
2403 if (isa<CmpInst>(CurInst))
2404 continue;
2405
Owen Anderson03986072010-08-07 00:20:35 +00002406 // We don't currently value number ANY inline asm calls.
2407 if (CallInst *CallI = dyn_cast<CallInst>(CurInst))
2408 if (CallI->isInlineAsm())
2409 continue;
Duncan Sands1efabaa2009-05-06 06:49:50 +00002410
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002411 uint32_t ValNo = VN.lookup(CurInst);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002412
Owen Anderson6a903bc2008-06-18 21:41:49 +00002413 // Look for the predecessors for PRE opportunities. We're
2414 // only trying to solve the basic diamond case, where
2415 // a value is computed in the successor and one predecessor,
2416 // but not the other. We also explicitly disallow cases
2417 // where the successor is its own predecessor, because they're
2418 // more complicated to get right.
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002419 unsigned NumWith = 0;
2420 unsigned NumWithout = 0;
2421 BasicBlock *PREPred = 0;
Chris Lattnerf00aae42008-12-01 07:29:03 +00002422 predMap.clear();
2423
Owen Anderson6a903bc2008-06-18 21:41:49 +00002424 for (pred_iterator PI = pred_begin(CurrentBlock),
2425 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
Gabor Greifb0d56ff2010-07-09 14:36:49 +00002426 BasicBlock *P = *PI;
Owen Anderson6a903bc2008-06-18 21:41:49 +00002427 // We're not interested in PRE where the block is its
Bob Wilson76e8c592010-02-03 00:33:21 +00002428 // own predecessor, or in blocks with predecessors
Owen Anderson1b3ea962008-06-20 01:15:47 +00002429 // that are not reachable.
Gabor Greifb0d56ff2010-07-09 14:36:49 +00002430 if (P == CurrentBlock) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002431 NumWithout = 2;
Owen Anderson1b3ea962008-06-20 01:15:47 +00002432 break;
Dan Gohmanf6066702013-02-12 18:38:36 +00002433 } else if (!DT->isReachableFromEntry(P)) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002434 NumWithout = 2;
Owen Anderson1b3ea962008-06-20 01:15:47 +00002435 break;
2436 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002437
Owen Andersonc7c3bc62011-01-04 19:13:25 +00002438 Value* predV = findLeader(P, ValNo);
Owen Andersonc21c1002010-11-18 18:32:40 +00002439 if (predV == 0) {
Dan Gohmanf3771602013-02-12 19:49:10 +00002440 predMap.push_back(std::make_pair(static_cast<Value *>(0), P));
Gabor Greifb0d56ff2010-07-09 14:36:49 +00002441 PREPred = P;
Dan Gohmand2d1ae12010-06-22 15:08:57 +00002442 ++NumWithout;
Owen Andersonc21c1002010-11-18 18:32:40 +00002443 } else if (predV == CurInst) {
Dan Gohman2001cd82013-02-12 19:05:10 +00002444 /* CurInst dominates this predecessor. */
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002445 NumWithout = 2;
Dan Gohman2001cd82013-02-12 19:05:10 +00002446 break;
Owen Anderson6a903bc2008-06-18 21:41:49 +00002447 } else {
Dan Gohmanf3771602013-02-12 19:49:10 +00002448 predMap.push_back(std::make_pair(predV, P));
Dan Gohmand2d1ae12010-06-22 15:08:57 +00002449 ++NumWith;
Owen Anderson6a903bc2008-06-18 21:41:49 +00002450 }
2451 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002452
Owen Anderson6a903bc2008-06-18 21:41:49 +00002453 // Don't do PRE when it might increase code size, i.e. when
2454 // we would need to insert instructions in more than one pred.
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002455 if (NumWithout != 1 || NumWith == 0)
Owen Anderson6a903bc2008-06-18 21:41:49 +00002456 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00002457
Chris Lattnera546dcf2009-10-31 22:11:15 +00002458 // Don't do PRE across indirect branch.
2459 if (isa<IndirectBrInst>(PREPred->getTerminator()))
2460 continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002461
Owen Andersonfdf9f162008-06-19 19:54:19 +00002462 // We can't do PRE safely on a critical edge, so instead we schedule
2463 // the edge to be split and perform the PRE the next time we iterate
2464 // on the function.
Bob Wilsonaff96b22010-02-16 21:06:42 +00002465 unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002466 if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
2467 toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
Owen Andersonfdf9f162008-06-19 19:54:19 +00002468 continue;
2469 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002470
Bob Wilson76e8c592010-02-03 00:33:21 +00002471 // Instantiate the expression in the predecessor that lacked it.
Owen Anderson6a903bc2008-06-18 21:41:49 +00002472 // Because we are going top-down through the block, all value numbers
2473 // will be available in the predecessor by the time we need them. Any
Bob Wilson76e8c592010-02-03 00:33:21 +00002474 // that weren't originally present will have been instantiated earlier
Owen Anderson6a903bc2008-06-18 21:41:49 +00002475 // in this loop.
Nick Lewycky42fb7452009-09-27 07:38:41 +00002476 Instruction *PREInstr = CurInst->clone();
Owen Anderson6a903bc2008-06-18 21:41:49 +00002477 bool success = true;
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00002478 for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
2479 Value *Op = PREInstr->getOperand(i);
2480 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
2481 continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002482
Owen Andersonc7c3bc62011-01-04 19:13:25 +00002483 if (Value *V = findLeader(PREPred, VN.lookup(Op))) {
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00002484 PREInstr->setOperand(i, V);
2485 } else {
2486 success = false;
2487 break;
Owen Anderson8e462e92008-07-11 20:05:13 +00002488 }
Owen Anderson6a903bc2008-06-18 21:41:49 +00002489 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002490
Owen Anderson6a903bc2008-06-18 21:41:49 +00002491 // Fail out if we encounter an operand that is not available in
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002492 // the PRE predecessor. This is typically because of loads which
Owen Anderson6a903bc2008-06-18 21:41:49 +00002493 // are not value numbered precisely.
2494 if (!success) {
Bill Wendling3c793442008-12-22 22:14:07 +00002495 DEBUG(verifyRemoved(PREInstr));
Dan Gohmanfd41de02013-02-12 18:44:43 +00002496 delete PREInstr;
Owen Anderson6a903bc2008-06-18 21:41:49 +00002497 continue;
2498 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002499
Owen Anderson6a903bc2008-06-18 21:41:49 +00002500 PREInstr->insertBefore(PREPred->getTerminator());
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00002501 PREInstr->setName(CurInst->getName() + ".pre");
Devang Patel341b38c2011-05-17 20:00:02 +00002502 PREInstr->setDebugLoc(CurInst->getDebugLoc());
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002503 VN.add(PREInstr, ValNo);
Dan Gohmand2d1ae12010-06-22 15:08:57 +00002504 ++NumGVNPRE;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002505
Owen Anderson6a903bc2008-06-18 21:41:49 +00002506 // Update the availability map to include the new instruction.
Owen Andersonc7c3bc62011-01-04 19:13:25 +00002507 addToLeaderTable(ValNo, PREInstr, PREPred);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002508
Owen Anderson6a903bc2008-06-18 21:41:49 +00002509 // Create a PHI to make the value available in this block.
Dan Gohmanf3771602013-02-12 19:49:10 +00002510 PHINode* Phi = PHINode::Create(CurInst->getType(), predMap.size(),
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00002511 CurInst->getName() + ".pre-phi",
Owen Anderson6a903bc2008-06-18 21:41:49 +00002512 CurrentBlock->begin());
Dan Gohmanf3771602013-02-12 19:49:10 +00002513 for (unsigned i = 0, e = predMap.size(); i != e; ++i) {
2514 if (Value *V = predMap[i].first)
2515 Phi->addIncoming(V, predMap[i].second);
2516 else
2517 Phi->addIncoming(PREInstr, PREPred);
Gabor Greifd323f5e2010-07-09 14:48:08 +00002518 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002519
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002520 VN.add(Phi, ValNo);
Owen Andersonc7c3bc62011-01-04 19:13:25 +00002521 addToLeaderTable(ValNo, Phi, CurrentBlock);
Devang Patelffb798c2011-05-04 23:58:50 +00002522 Phi->setDebugLoc(CurInst->getDebugLoc());
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00002523 CurInst->replaceAllUsesWith(Phi);
Hal Finkel69b07a22012-10-24 21:22:30 +00002524 if (Phi->getType()->getScalarType()->isPointerTy()) {
Owen Andersond62d3722011-01-03 23:51:43 +00002525 // Because we have added a PHI-use of the pointer value, it has now
2526 // "escaped" from alias analysis' perspective. We need to inform
2527 // AA of this.
Jay Foad372ad642011-06-20 14:18:48 +00002528 for (unsigned ii = 0, ee = Phi->getNumIncomingValues(); ii != ee;
2529 ++ii) {
2530 unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
2531 VN.getAliasAnalysis()->addEscapingUse(Phi->getOperandUse(jj));
2532 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002533
Owen Andersond62d3722011-01-03 23:51:43 +00002534 if (MD)
2535 MD->invalidateCachedPointerInfo(Phi);
2536 }
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00002537 VN.erase(CurInst);
Owen Andersonc7c3bc62011-01-04 19:13:25 +00002538 removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002539
David Greene2e6efc42010-01-05 01:27:17 +00002540 DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
Dan Gohman81132462009-11-14 02:27:51 +00002541 if (MD) MD->removeInstruction(CurInst);
Bill Wendlingebb6a542008-12-22 21:57:30 +00002542 DEBUG(verifyRemoved(CurInst));
Dan Gohmanfd41de02013-02-12 18:44:43 +00002543 CurInst->eraseFromParent();
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00002544 Changed = true;
Owen Anderson6a903bc2008-06-18 21:41:49 +00002545 }
2546 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002547
Bob Wilson92cdb6e2010-02-16 19:51:59 +00002548 if (splitCriticalEdges())
2549 Changed = true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002550
Bob Wilson92cdb6e2010-02-16 19:51:59 +00002551 return Changed;
2552}
2553
Shuxin Yang1d8d7e42013-05-09 18:34:27 +00002554/// Split the critical edge connecting the given two blocks, and return
2555/// the block inserted to the critical edge.
2556BasicBlock *GVN::splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ) {
2557 BasicBlock *BB = SplitCriticalEdge(Pred, Succ, this);
2558 if (MD)
2559 MD->invalidateCachedPredecessors();
2560 return BB;
2561}
2562
Bob Wilson92cdb6e2010-02-16 19:51:59 +00002563/// splitCriticalEdges - Split critical edges found during the previous
2564/// iteration that may enable further optimization.
2565bool GVN::splitCriticalEdges() {
2566 if (toSplit.empty())
2567 return false;
2568 do {
2569 std::pair<TerminatorInst*, unsigned> Edge = toSplit.pop_back_val();
2570 SplitCriticalEdge(Edge.first, Edge.second, this);
2571 } while (!toSplit.empty());
Evan Cheng7263cf8432010-03-01 22:23:12 +00002572 if (MD) MD->invalidateCachedPredecessors();
Bob Wilson92cdb6e2010-02-16 19:51:59 +00002573 return true;
Owen Anderson6a903bc2008-06-18 21:41:49 +00002574}
2575
Bill Wendling456e8852008-12-22 22:32:22 +00002576/// iterateOnFunction - Executes one iteration of GVN
Owen Anderson676070d2007-08-14 18:04:11 +00002577bool GVN::iterateOnFunction(Function &F) {
Nuno Lopese3127f32008-10-10 16:25:50 +00002578 cleanupGlobalSets();
Nadav Rotem465834c2012-07-24 10:51:42 +00002579
Owen Andersonab6ec2e2007-07-24 17:55:58 +00002580 // Top-down walk of the dominator tree
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002581 bool Changed = false;
Owen Anderson03aacba2008-12-15 03:52:17 +00002582#if 0
2583 // Needed for value numbering with phi construction to work.
Owen Andersonbfe133e2008-12-15 02:03:00 +00002584 ReversePostOrderTraversal<Function*> RPOT(&F);
2585 for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
2586 RE = RPOT.end(); RI != RE; ++RI)
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002587 Changed |= processBlock(*RI);
Owen Anderson03aacba2008-12-15 03:52:17 +00002588#else
Shuxin Yang1d8d7e42013-05-09 18:34:27 +00002589 // Save the blocks this function have before transformation begins. GVN may
2590 // split critical edge, and hence may invalidate the RPO/DT iterator.
2591 //
2592 std::vector<BasicBlock *> BBVect;
2593 BBVect.reserve(256);
Owen Anderson03aacba2008-12-15 03:52:17 +00002594 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
2595 DE = df_end(DT->getRootNode()); DI != DE; ++DI)
Shuxin Yang1d8d7e42013-05-09 18:34:27 +00002596 BBVect.push_back(DI->getBlock());
2597
2598 for (std::vector<BasicBlock *>::iterator I = BBVect.begin(), E = BBVect.end();
2599 I != E; I++)
2600 Changed |= processBlock(*I);
Owen Anderson03aacba2008-12-15 03:52:17 +00002601#endif
2602
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002603 return Changed;
Owen Andersonab6ec2e2007-07-24 17:55:58 +00002604}
Nuno Lopese3127f32008-10-10 16:25:50 +00002605
2606void GVN::cleanupGlobalSets() {
2607 VN.clear();
Owen Andersone39cb572011-01-04 19:29:46 +00002608 LeaderTable.clear();
Owen Andersonc21c1002010-11-18 18:32:40 +00002609 TableAllocator.Reset();
Nuno Lopese3127f32008-10-10 16:25:50 +00002610}
Bill Wendling6b18a392008-12-22 21:36:08 +00002611
2612/// verifyRemoved - Verify that the specified instruction does not occur in our
2613/// internal data structures.
Bill Wendlinge7f08e72008-12-22 22:28:56 +00002614void GVN::verifyRemoved(const Instruction *Inst) const {
2615 VN.verifyRemoved(Inst);
Bill Wendling3c793442008-12-22 22:14:07 +00002616
Bill Wendlinge7f08e72008-12-22 22:28:56 +00002617 // Walk through the value number scope to make sure the instruction isn't
2618 // ferreted away in it.
Owen Andersonc7c3bc62011-01-04 19:13:25 +00002619 for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator
Owen Andersone39cb572011-01-04 19:29:46 +00002620 I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) {
Owen Andersonc7c3bc62011-01-04 19:13:25 +00002621 const LeaderTableEntry *Node = &I->second;
Owen Anderson5ab8d4b2010-12-21 23:54:34 +00002622 assert(Node->Val != Inst && "Inst still in value numbering scope!");
Nadav Rotem465834c2012-07-24 10:51:42 +00002623
Owen Anderson5ab8d4b2010-12-21 23:54:34 +00002624 while (Node->Next) {
2625 Node = Node->Next;
2626 assert(Node->Val != Inst && "Inst still in value numbering scope!");
Bill Wendling3c793442008-12-22 22:14:07 +00002627 }
2628 }
Bill Wendling6b18a392008-12-22 21:36:08 +00002629}