blob: af26d028676d429d94683644aadcb953a6c591eb [file] [log] [blame]
Owen Anderson85c40642007-07-24 17:55:58 +00001//===- GVN.cpp - Eliminate redundant values and loads ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-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 Anderson85c40642007-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//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "gvn"
Owen Andersonacfa3ad2007-07-26 18:26:51 +000016
Owen Anderson85c40642007-07-24 17:55:58 +000017#include "llvm/Transforms/Scalar.h"
Owen Anderson5d72a422007-07-25 19:57:03 +000018#include "llvm/BasicBlock.h"
Owen Andersonacfa3ad2007-07-26 18:26:51 +000019#include "llvm/Constants.h"
Owen Anderson85c40642007-07-24 17:55:58 +000020#include "llvm/DerivedTypes.h"
Owen Andersonacfa3ad2007-07-26 18:26:51 +000021#include "llvm/Function.h"
Owen Anderson8d272d52008-02-12 21:15:18 +000022#include "llvm/IntrinsicInst.h"
Owen Andersonacfa3ad2007-07-26 18:26:51 +000023#include "llvm/Instructions.h"
Owen Anderson282dd322008-02-18 09:24:53 +000024#include "llvm/ParameterAttributes.h"
Owen Andersonacfa3ad2007-07-26 18:26:51 +000025#include "llvm/Value.h"
Owen Anderson85c40642007-07-24 17:55:58 +000026#include "llvm/ADT/BitVector.h"
27#include "llvm/ADT/DenseMap.h"
28#include "llvm/ADT/DepthFirstIterator.h"
29#include "llvm/ADT/SmallPtrSet.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/Statistic.h"
Owen Anderson5e9366f2007-10-18 19:39:33 +000032#include "llvm/Analysis/Dominators.h"
33#include "llvm/Analysis/AliasAnalysis.h"
Owen Anderson85c40642007-07-24 17:55:58 +000034#include "llvm/Analysis/MemoryDependenceAnalysis.h"
35#include "llvm/Support/CFG.h"
36#include "llvm/Support/Compiler.h"
Owen Anderson29f73562008-02-19 06:35:43 +000037#include "llvm/Target/TargetData.h"
Owen Anderson85c40642007-07-24 17:55:58 +000038using namespace llvm;
39
40//===----------------------------------------------------------------------===//
41// ValueTable Class
42//===----------------------------------------------------------------------===//
43
44/// This class holds the mapping between values and value numbers. It is used
45/// as an efficient mechanism to determine the expression-wise equivalence of
46/// two values.
47namespace {
48 struct VISIBILITY_HIDDEN Expression {
49 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
50 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
51 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
52 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
53 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
54 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
55 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
56 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
57 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
Owen Anderson5e9366f2007-10-18 19:39:33 +000058 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, EMPTY,
Owen Anderson85c40642007-07-24 17:55:58 +000059 TOMBSTONE };
60
61 ExpressionOpcode opcode;
62 const Type* type;
63 uint32_t firstVN;
64 uint32_t secondVN;
65 uint32_t thirdVN;
66 SmallVector<uint32_t, 4> varargs;
Owen Anderson5e9366f2007-10-18 19:39:33 +000067 Value* function;
Owen Anderson85c40642007-07-24 17:55:58 +000068
69 Expression() { }
70 Expression(ExpressionOpcode o) : opcode(o) { }
71
72 bool operator==(const Expression &other) const {
73 if (opcode != other.opcode)
74 return false;
75 else if (opcode == EMPTY || opcode == TOMBSTONE)
76 return true;
77 else if (type != other.type)
78 return false;
Owen Anderson5e9366f2007-10-18 19:39:33 +000079 else if (function != other.function)
80 return false;
Owen Anderson85c40642007-07-24 17:55:58 +000081 else if (firstVN != other.firstVN)
82 return false;
83 else if (secondVN != other.secondVN)
84 return false;
85 else if (thirdVN != other.thirdVN)
86 return false;
87 else {
88 if (varargs.size() != other.varargs.size())
89 return false;
90
91 for (size_t i = 0; i < varargs.size(); ++i)
92 if (varargs[i] != other.varargs[i])
93 return false;
94
95 return true;
96 }
97 }
98
99 bool operator!=(const Expression &other) const {
100 if (opcode != other.opcode)
101 return true;
102 else if (opcode == EMPTY || opcode == TOMBSTONE)
103 return false;
104 else if (type != other.type)
105 return true;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000106 else if (function != other.function)
107 return true;
Owen Anderson85c40642007-07-24 17:55:58 +0000108 else if (firstVN != other.firstVN)
109 return true;
110 else if (secondVN != other.secondVN)
111 return true;
112 else if (thirdVN != other.thirdVN)
113 return true;
114 else {
115 if (varargs.size() != other.varargs.size())
116 return true;
117
118 for (size_t i = 0; i < varargs.size(); ++i)
119 if (varargs[i] != other.varargs[i])
120 return true;
121
122 return false;
123 }
124 }
125 };
126
127 class VISIBILITY_HIDDEN ValueTable {
128 private:
129 DenseMap<Value*, uint32_t> valueNumbering;
130 DenseMap<Expression, uint32_t> expressionNumbering;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000131 AliasAnalysis* AA;
Owen Anderson85c40642007-07-24 17:55:58 +0000132
133 uint32_t nextValueNumber;
134
135 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
136 Expression::ExpressionOpcode getOpcode(CmpInst* C);
137 Expression::ExpressionOpcode getOpcode(CastInst* C);
138 Expression create_expression(BinaryOperator* BO);
139 Expression create_expression(CmpInst* C);
140 Expression create_expression(ShuffleVectorInst* V);
141 Expression create_expression(ExtractElementInst* C);
142 Expression create_expression(InsertElementInst* V);
143 Expression create_expression(SelectInst* V);
144 Expression create_expression(CastInst* C);
145 Expression create_expression(GetElementPtrInst* G);
Owen Anderson5e9366f2007-10-18 19:39:33 +0000146 Expression create_expression(CallInst* C);
Owen Anderson85c40642007-07-24 17:55:58 +0000147 public:
Owen Anderson5e9366f2007-10-18 19:39:33 +0000148 ValueTable() : nextValueNumber(1) { }
Owen Anderson85c40642007-07-24 17:55:58 +0000149 uint32_t lookup_or_add(Value* V);
150 uint32_t lookup(Value* V) const;
151 void add(Value* V, uint32_t num);
152 void clear();
153 void erase(Value* v);
154 unsigned size();
Owen Anderson5e9366f2007-10-18 19:39:33 +0000155 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
Owen Anderson343797c2007-11-26 07:17:19 +0000156 uint32_t hash_operand(Value* v);
Owen Anderson85c40642007-07-24 17:55:58 +0000157 };
158}
159
160namespace llvm {
Chris Lattner92eea072007-09-17 18:34:04 +0000161template <> struct DenseMapInfo<Expression> {
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000162 static inline Expression getEmptyKey() {
163 return Expression(Expression::EMPTY);
164 }
165
166 static inline Expression getTombstoneKey() {
167 return Expression(Expression::TOMBSTONE);
168 }
Owen Anderson85c40642007-07-24 17:55:58 +0000169
170 static unsigned getHashValue(const Expression e) {
171 unsigned hash = e.opcode;
172
173 hash = e.firstVN + hash * 37;
174 hash = e.secondVN + hash * 37;
175 hash = e.thirdVN + hash * 37;
176
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000177 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
178 (unsigned)((uintptr_t)e.type >> 9)) +
179 hash * 37;
Owen Anderson85c40642007-07-24 17:55:58 +0000180
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000181 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
182 E = e.varargs.end(); I != E; ++I)
Owen Anderson85c40642007-07-24 17:55:58 +0000183 hash = *I + hash * 37;
184
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000185 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
186 (unsigned)((uintptr_t)e.function >> 9)) +
187 hash * 37;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000188
Owen Anderson85c40642007-07-24 17:55:58 +0000189 return hash;
190 }
Chris Lattner92eea072007-09-17 18:34:04 +0000191 static bool isEqual(const Expression &LHS, const Expression &RHS) {
192 return LHS == RHS;
193 }
Owen Anderson85c40642007-07-24 17:55:58 +0000194 static bool isPod() { return true; }
195};
196}
197
198//===----------------------------------------------------------------------===//
199// ValueTable Internal Functions
200//===----------------------------------------------------------------------===//
Chris Lattner3d7103e2008-03-21 21:14:38 +0000201Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
Owen Anderson85c40642007-07-24 17:55:58 +0000202 switch(BO->getOpcode()) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000203 default: // THIS SHOULD NEVER HAPPEN
204 assert(0 && "Binary operator with unknown opcode?");
205 case Instruction::Add: return Expression::ADD;
206 case Instruction::Sub: return Expression::SUB;
207 case Instruction::Mul: return Expression::MUL;
208 case Instruction::UDiv: return Expression::UDIV;
209 case Instruction::SDiv: return Expression::SDIV;
210 case Instruction::FDiv: return Expression::FDIV;
211 case Instruction::URem: return Expression::UREM;
212 case Instruction::SRem: return Expression::SREM;
213 case Instruction::FRem: return Expression::FREM;
214 case Instruction::Shl: return Expression::SHL;
215 case Instruction::LShr: return Expression::LSHR;
216 case Instruction::AShr: return Expression::ASHR;
217 case Instruction::And: return Expression::AND;
218 case Instruction::Or: return Expression::OR;
219 case Instruction::Xor: return Expression::XOR;
Owen Anderson85c40642007-07-24 17:55:58 +0000220 }
221}
222
223Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000224 if (isa<ICmpInst>(C)) {
Owen Anderson85c40642007-07-24 17:55:58 +0000225 switch (C->getPredicate()) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000226 default: // THIS SHOULD NEVER HAPPEN
227 assert(0 && "Comparison with unknown predicate?");
228 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ;
229 case ICmpInst::ICMP_NE: return Expression::ICMPNE;
230 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
231 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
232 case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
233 case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
234 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
235 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
236 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
237 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
Owen Anderson85c40642007-07-24 17:55:58 +0000238 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000239 }
240 assert(isa<FCmpInst>(C) && "Unknown compare");
241 switch (C->getPredicate()) {
242 default: // THIS SHOULD NEVER HAPPEN
243 assert(0 && "Comparison with unknown predicate?");
244 case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
245 case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
246 case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
247 case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
248 case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
249 case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
250 case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
251 case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
252 case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
253 case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
254 case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
255 case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
256 case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
257 case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
Owen Anderson85c40642007-07-24 17:55:58 +0000258 }
259}
260
Chris Lattner3d7103e2008-03-21 21:14:38 +0000261Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
Owen Anderson85c40642007-07-24 17:55:58 +0000262 switch(C->getOpcode()) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000263 default: // THIS SHOULD NEVER HAPPEN
264 assert(0 && "Cast operator with unknown opcode?");
265 case Instruction::Trunc: return Expression::TRUNC;
266 case Instruction::ZExt: return Expression::ZEXT;
267 case Instruction::SExt: return Expression::SEXT;
268 case Instruction::FPToUI: return Expression::FPTOUI;
269 case Instruction::FPToSI: return Expression::FPTOSI;
270 case Instruction::UIToFP: return Expression::UITOFP;
271 case Instruction::SIToFP: return Expression::SITOFP;
272 case Instruction::FPTrunc: return Expression::FPTRUNC;
273 case Instruction::FPExt: return Expression::FPEXT;
274 case Instruction::PtrToInt: return Expression::PTRTOINT;
275 case Instruction::IntToPtr: return Expression::INTTOPTR;
276 case Instruction::BitCast: return Expression::BITCAST;
Owen Anderson85c40642007-07-24 17:55:58 +0000277 }
278}
279
Owen Anderson343797c2007-11-26 07:17:19 +0000280uint32_t ValueTable::hash_operand(Value* v) {
281 if (CallInst* CI = dyn_cast<CallInst>(v))
Duncan Sands00b24b52007-12-01 07:51:45 +0000282 if (!AA->doesNotAccessMemory(CI))
Owen Anderson343797c2007-11-26 07:17:19 +0000283 return nextValueNumber++;
284
285 return lookup_or_add(v);
286}
287
Owen Anderson5e9366f2007-10-18 19:39:33 +0000288Expression ValueTable::create_expression(CallInst* C) {
289 Expression e;
290
291 e.type = C->getType();
292 e.firstVN = 0;
293 e.secondVN = 0;
294 e.thirdVN = 0;
295 e.function = C->getCalledFunction();
296 e.opcode = Expression::CALL;
297
298 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
299 I != E; ++I)
Owen Anderson343797c2007-11-26 07:17:19 +0000300 e.varargs.push_back(hash_operand(*I));
Owen Anderson5e9366f2007-10-18 19:39:33 +0000301
302 return e;
303}
304
Owen Anderson85c40642007-07-24 17:55:58 +0000305Expression ValueTable::create_expression(BinaryOperator* BO) {
306 Expression e;
307
Owen Anderson343797c2007-11-26 07:17:19 +0000308 e.firstVN = hash_operand(BO->getOperand(0));
309 e.secondVN = hash_operand(BO->getOperand(1));
Owen Anderson85c40642007-07-24 17:55:58 +0000310 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000311 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000312 e.type = BO->getType();
313 e.opcode = getOpcode(BO);
314
315 return e;
316}
317
318Expression ValueTable::create_expression(CmpInst* C) {
319 Expression e;
320
Owen Anderson343797c2007-11-26 07:17:19 +0000321 e.firstVN = hash_operand(C->getOperand(0));
322 e.secondVN = hash_operand(C->getOperand(1));
Owen Anderson85c40642007-07-24 17:55:58 +0000323 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000324 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000325 e.type = C->getType();
326 e.opcode = getOpcode(C);
327
328 return e;
329}
330
331Expression ValueTable::create_expression(CastInst* C) {
332 Expression e;
333
Owen Anderson343797c2007-11-26 07:17:19 +0000334 e.firstVN = hash_operand(C->getOperand(0));
Owen Anderson85c40642007-07-24 17:55:58 +0000335 e.secondVN = 0;
336 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000337 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000338 e.type = C->getType();
339 e.opcode = getOpcode(C);
340
341 return e;
342}
343
344Expression ValueTable::create_expression(ShuffleVectorInst* S) {
345 Expression e;
346
Owen Anderson343797c2007-11-26 07:17:19 +0000347 e.firstVN = hash_operand(S->getOperand(0));
348 e.secondVN = hash_operand(S->getOperand(1));
349 e.thirdVN = hash_operand(S->getOperand(2));
Owen Anderson5e9366f2007-10-18 19:39:33 +0000350 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000351 e.type = S->getType();
352 e.opcode = Expression::SHUFFLE;
353
354 return e;
355}
356
357Expression ValueTable::create_expression(ExtractElementInst* E) {
358 Expression e;
359
Owen Anderson343797c2007-11-26 07:17:19 +0000360 e.firstVN = hash_operand(E->getOperand(0));
361 e.secondVN = hash_operand(E->getOperand(1));
Owen Anderson85c40642007-07-24 17:55:58 +0000362 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000363 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000364 e.type = E->getType();
365 e.opcode = Expression::EXTRACT;
366
367 return e;
368}
369
370Expression ValueTable::create_expression(InsertElementInst* I) {
371 Expression e;
372
Owen Anderson343797c2007-11-26 07:17:19 +0000373 e.firstVN = hash_operand(I->getOperand(0));
374 e.secondVN = hash_operand(I->getOperand(1));
375 e.thirdVN = hash_operand(I->getOperand(2));
Owen Anderson5e9366f2007-10-18 19:39:33 +0000376 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000377 e.type = I->getType();
378 e.opcode = Expression::INSERT;
379
380 return e;
381}
382
383Expression ValueTable::create_expression(SelectInst* I) {
384 Expression e;
385
Owen Anderson343797c2007-11-26 07:17:19 +0000386 e.firstVN = hash_operand(I->getCondition());
387 e.secondVN = hash_operand(I->getTrueValue());
388 e.thirdVN = hash_operand(I->getFalseValue());
Owen Anderson5e9366f2007-10-18 19:39:33 +0000389 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000390 e.type = I->getType();
391 e.opcode = Expression::SELECT;
392
393 return e;
394}
395
396Expression ValueTable::create_expression(GetElementPtrInst* G) {
397 Expression e;
398
Owen Anderson343797c2007-11-26 07:17:19 +0000399 e.firstVN = hash_operand(G->getPointerOperand());
Owen Anderson85c40642007-07-24 17:55:58 +0000400 e.secondVN = 0;
401 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000402 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000403 e.type = G->getType();
404 e.opcode = Expression::GEP;
405
406 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
407 I != E; ++I)
Owen Anderson343797c2007-11-26 07:17:19 +0000408 e.varargs.push_back(hash_operand(*I));
Owen Anderson85c40642007-07-24 17:55:58 +0000409
410 return e;
411}
412
413//===----------------------------------------------------------------------===//
414// ValueTable External Functions
415//===----------------------------------------------------------------------===//
416
417/// lookup_or_add - Returns the value number for the specified value, assigning
418/// it a new number if it did not have one before.
419uint32_t ValueTable::lookup_or_add(Value* V) {
420 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
421 if (VI != valueNumbering.end())
422 return VI->second;
423
Owen Anderson5e9366f2007-10-18 19:39:33 +0000424 if (CallInst* C = dyn_cast<CallInst>(V)) {
Duncan Sands00b24b52007-12-01 07:51:45 +0000425 if (AA->onlyReadsMemory(C)) { // includes doesNotAccessMemory
Owen Anderson5e9366f2007-10-18 19:39:33 +0000426 Expression e = create_expression(C);
427
428 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
429 if (EI != expressionNumbering.end()) {
430 valueNumbering.insert(std::make_pair(V, EI->second));
431 return EI->second;
432 } else {
433 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
434 valueNumbering.insert(std::make_pair(V, nextValueNumber));
435
436 return nextValueNumber++;
437 }
438 } else {
439 valueNumbering.insert(std::make_pair(V, nextValueNumber));
440 return nextValueNumber++;
441 }
442 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
Owen Anderson85c40642007-07-24 17:55:58 +0000443 Expression e = create_expression(BO);
444
445 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
446 if (EI != expressionNumbering.end()) {
447 valueNumbering.insert(std::make_pair(V, EI->second));
448 return EI->second;
449 } else {
450 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
451 valueNumbering.insert(std::make_pair(V, nextValueNumber));
452
453 return nextValueNumber++;
454 }
455 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
456 Expression e = create_expression(C);
457
458 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
459 if (EI != expressionNumbering.end()) {
460 valueNumbering.insert(std::make_pair(V, EI->second));
461 return EI->second;
462 } else {
463 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
464 valueNumbering.insert(std::make_pair(V, nextValueNumber));
465
466 return nextValueNumber++;
467 }
468 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
469 Expression e = create_expression(U);
470
471 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
472 if (EI != expressionNumbering.end()) {
473 valueNumbering.insert(std::make_pair(V, EI->second));
474 return EI->second;
475 } else {
476 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
477 valueNumbering.insert(std::make_pair(V, nextValueNumber));
478
479 return nextValueNumber++;
480 }
481 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
482 Expression e = create_expression(U);
483
484 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
485 if (EI != expressionNumbering.end()) {
486 valueNumbering.insert(std::make_pair(V, EI->second));
487 return EI->second;
488 } else {
489 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
490 valueNumbering.insert(std::make_pair(V, nextValueNumber));
491
492 return nextValueNumber++;
493 }
494 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
495 Expression e = create_expression(U);
496
497 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
498 if (EI != expressionNumbering.end()) {
499 valueNumbering.insert(std::make_pair(V, EI->second));
500 return EI->second;
501 } else {
502 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
503 valueNumbering.insert(std::make_pair(V, nextValueNumber));
504
505 return nextValueNumber++;
506 }
507 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
508 Expression e = create_expression(U);
509
510 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
511 if (EI != expressionNumbering.end()) {
512 valueNumbering.insert(std::make_pair(V, EI->second));
513 return EI->second;
514 } else {
515 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
516 valueNumbering.insert(std::make_pair(V, nextValueNumber));
517
518 return nextValueNumber++;
519 }
520 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
521 Expression e = create_expression(U);
522
523 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
524 if (EI != expressionNumbering.end()) {
525 valueNumbering.insert(std::make_pair(V, EI->second));
526 return EI->second;
527 } else {
528 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
529 valueNumbering.insert(std::make_pair(V, nextValueNumber));
530
531 return nextValueNumber++;
532 }
533 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
534 Expression e = create_expression(U);
535
536 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
537 if (EI != expressionNumbering.end()) {
538 valueNumbering.insert(std::make_pair(V, EI->second));
539 return EI->second;
540 } else {
541 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
542 valueNumbering.insert(std::make_pair(V, nextValueNumber));
543
544 return nextValueNumber++;
545 }
546 } else {
547 valueNumbering.insert(std::make_pair(V, nextValueNumber));
548 return nextValueNumber++;
549 }
550}
551
552/// lookup - Returns the value number of the specified value. Fails if
553/// the value has not yet been numbered.
554uint32_t ValueTable::lookup(Value* V) const {
555 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
Chris Lattner3d7103e2008-03-21 21:14:38 +0000556 assert(VI != valueNumbering.end() && "Value not numbered?");
557 return VI->second;
Owen Anderson85c40642007-07-24 17:55:58 +0000558}
559
560/// clear - Remove all entries from the ValueTable
561void ValueTable::clear() {
562 valueNumbering.clear();
563 expressionNumbering.clear();
564 nextValueNumber = 1;
565}
566
Owen Anderson5aff8002007-07-31 23:27:13 +0000567/// erase - Remove a value from the value numbering
568void ValueTable::erase(Value* V) {
569 valueNumbering.erase(V);
570}
571
Owen Anderson85c40642007-07-24 17:55:58 +0000572//===----------------------------------------------------------------------===//
573// ValueNumberedSet Class
574//===----------------------------------------------------------------------===//
575namespace {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000576class VISIBILITY_HIDDEN ValueNumberedSet {
Owen Anderson85c40642007-07-24 17:55:58 +0000577 private:
578 SmallPtrSet<Value*, 8> contents;
579 BitVector numbers;
580 public:
581 ValueNumberedSet() { numbers.resize(1); }
582 ValueNumberedSet(const ValueNumberedSet& other) {
583 numbers = other.numbers;
584 contents = other.contents;
585 }
586
587 typedef SmallPtrSet<Value*, 8>::iterator iterator;
588
589 iterator begin() { return contents.begin(); }
590 iterator end() { return contents.end(); }
591
592 bool insert(Value* v) { return contents.insert(v); }
593 void insert(iterator I, iterator E) { contents.insert(I, E); }
594 void erase(Value* v) { contents.erase(v); }
595 unsigned count(Value* v) { return contents.count(v); }
596 size_t size() { return contents.size(); }
597
598 void set(unsigned i) {
599 if (i >= numbers.size())
600 numbers.resize(i+1);
601
602 numbers.set(i);
603 }
604
605 void operator=(const ValueNumberedSet& other) {
606 contents = other.contents;
607 numbers = other.numbers;
608 }
609
610 void reset(unsigned i) {
611 if (i < numbers.size())
612 numbers.reset(i);
613 }
614
615 bool test(unsigned i) {
616 if (i >= numbers.size())
617 return false;
618
619 return numbers.test(i);
620 }
621
622 void clear() {
623 contents.clear();
624 numbers.clear();
625 }
626};
627}
628
629//===----------------------------------------------------------------------===//
630// GVN Pass
631//===----------------------------------------------------------------------===//
632
633namespace {
634
635 class VISIBILITY_HIDDEN GVN : public FunctionPass {
636 bool runOnFunction(Function &F);
637 public:
638 static char ID; // Pass identification, replacement for typeid
639 GVN() : FunctionPass((intptr_t)&ID) { }
640
641 private:
642 ValueTable VN;
643
644 DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
645
Owen Anderson5b299672007-08-07 23:12:31 +0000646 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
647 PhiMapType phiMap;
648
649
Owen Anderson85c40642007-07-24 17:55:58 +0000650 // This transformation requires dominator postdominator info
651 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
652 AU.setPreservesCFG();
653 AU.addRequired<DominatorTree>();
654 AU.addRequired<MemoryDependenceAnalysis>();
Owen Anderson5e9366f2007-10-18 19:39:33 +0000655 AU.addRequired<AliasAnalysis>();
Owen Anderson29f73562008-02-19 06:35:43 +0000656 AU.addRequired<TargetData>();
Owen Anderson5e9366f2007-10-18 19:39:33 +0000657 AU.addPreserved<AliasAnalysis>();
Owen Anderson85c40642007-07-24 17:55:58 +0000658 AU.addPreserved<MemoryDependenceAnalysis>();
Owen Anderson29f73562008-02-19 06:35:43 +0000659 AU.addPreserved<TargetData>();
Owen Anderson85c40642007-07-24 17:55:58 +0000660 }
661
662 // Helper fuctions
663 // FIXME: eliminate or document these better
664 Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
665 void val_insert(ValueNumberedSet& s, Value* v);
666 bool processLoad(LoadInst* L,
Chris Lattner7de20452008-03-21 22:01:16 +0000667 DenseMap<Value*, LoadInst*> &lastLoad,
668 SmallVectorImpl<Instruction*> &toErase);
Chris Lattner248ba4d2008-03-22 00:31:52 +0000669 bool processStore(StoreInst *SI, SmallVectorImpl<Instruction*> &toErase);
Owen Anderson85c40642007-07-24 17:55:58 +0000670 bool processInstruction(Instruction* I,
671 ValueNumberedSet& currAvail,
672 DenseMap<Value*, LoadInst*>& lastSeenLoad,
Chris Lattner7de20452008-03-21 22:01:16 +0000673 SmallVectorImpl<Instruction*> &toErase);
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000674 bool processNonLocalLoad(LoadInst* L,
Chris Lattner7de20452008-03-21 22:01:16 +0000675 SmallVectorImpl<Instruction*> &toErase);
Owen Andersonba958332008-02-19 03:09:45 +0000676 bool processMemCpy(MemCpyInst* M, MemCpyInst* MDep,
Chris Lattner7de20452008-03-21 22:01:16 +0000677 SmallVectorImpl<Instruction*> &toErase);
Owen Andersone41ab4c2008-03-12 07:37:44 +0000678 bool performCallSlotOptzn(MemCpyInst* cpy, CallInst* C,
Chris Lattner7de20452008-03-21 22:01:16 +0000679 SmallVectorImpl<Instruction*> &toErase);
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000680 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
Owen Andersonc6a31b92007-08-02 17:56:05 +0000681 DenseMap<BasicBlock*, Value*> &Phis,
682 bool top_level = false);
Owen Anderson5d72a422007-07-25 19:57:03 +0000683 void dump(DenseMap<BasicBlock*, Value*>& d);
Owen Andersonbe168b32007-08-14 18:04:11 +0000684 bool iterateOnFunction(Function &F);
Owen Andersone02ad522007-08-16 22:51:56 +0000685 Value* CollapsePhi(PHINode* p);
Owen Anderson19625972007-09-16 08:04:16 +0000686 bool isSafeReplacement(PHINode* p, Instruction* inst);
Owen Anderson85c40642007-07-24 17:55:58 +0000687 };
688
689 char GVN::ID = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000690}
691
692// createGVNPass - The public interface to this file...
693FunctionPass *llvm::createGVNPass() { return new GVN(); }
694
695static RegisterPass<GVN> X("gvn",
696 "Global Value Numbering");
697
698STATISTIC(NumGVNInstr, "Number of instructions deleted");
699STATISTIC(NumGVNLoad, "Number of loads deleted");
700
701/// find_leader - Given a set and a value number, return the first
702/// element of the set with that value number, or 0 if no such element
703/// is present
704Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
705 if (!vals.test(v))
706 return 0;
707
708 for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
709 I != E; ++I)
710 if (v == VN.lookup(*I))
711 return *I;
712
713 assert(0 && "No leader found, but present bit is set?");
714 return 0;
715}
716
717/// val_insert - Insert a value into a set only if there is not a value
718/// with the same value number already in the set
719void GVN::val_insert(ValueNumberedSet& s, Value* v) {
720 uint32_t num = VN.lookup(v);
721 if (!s.test(num))
722 s.insert(v);
723}
724
Owen Anderson5d72a422007-07-25 19:57:03 +0000725void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
726 printf("{\n");
727 for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
728 E = d.end(); I != E; ++I) {
729 if (I->second == MemoryDependenceAnalysis::None)
730 printf("None\n");
731 else
732 I->second->dump();
733 }
734 printf("}\n");
735}
736
Owen Andersone02ad522007-08-16 22:51:56 +0000737Value* GVN::CollapsePhi(PHINode* p) {
738 DominatorTree &DT = getAnalysis<DominatorTree>();
739 Value* constVal = p->hasConstantValue();
740
Chris Lattner3d7103e2008-03-21 21:14:38 +0000741 if (!constVal) return 0;
Owen Andersone02ad522007-08-16 22:51:56 +0000742
Chris Lattner3d7103e2008-03-21 21:14:38 +0000743 Instruction* inst = dyn_cast<Instruction>(constVal);
744 if (!inst)
745 return constVal;
746
747 if (DT.dominates(inst, p))
748 if (isSafeReplacement(p, inst))
749 return inst;
Owen Andersone02ad522007-08-16 22:51:56 +0000750 return 0;
751}
Owen Anderson5d72a422007-07-25 19:57:03 +0000752
Owen Anderson19625972007-09-16 08:04:16 +0000753bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
754 if (!isa<PHINode>(inst))
755 return true;
756
757 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
758 UI != E; ++UI)
759 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
760 if (use_phi->getParent() == inst->getParent())
761 return false;
762
763 return true;
764}
765
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000766/// GetValueForBlock - Get the value to use within the specified basic block.
767/// available values are in Phis.
768Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
Chris Lattner3d7103e2008-03-21 21:14:38 +0000769 DenseMap<BasicBlock*, Value*> &Phis,
770 bool top_level) {
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000771
772 // If we have already computed this value, return the previously computed val.
Owen Andersoned7f9932007-08-03 19:59:35 +0000773 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
774 if (V != Phis.end() && !top_level) return V->second;
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000775
Owen Anderson3f75d122007-08-01 22:01:54 +0000776 BasicBlock* singlePred = BB->getSinglePredecessor();
Owen Anderson30463f12007-08-03 11:03:26 +0000777 if (singlePred) {
Owen Andersoned7f9932007-08-03 19:59:35 +0000778 Value *ret = GetValueForBlock(singlePred, orig, Phis);
779 Phis[BB] = ret;
780 return ret;
Owen Anderson30463f12007-08-03 11:03:26 +0000781 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000782
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000783 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
784 // now, then get values to fill in the incoming values for the PHI.
785 PHINode *PN = new PHINode(orig->getType(), orig->getName()+".rle",
786 BB->begin());
787 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
Owen Andersoned7f9932007-08-03 19:59:35 +0000788
789 if (Phis.count(BB) == 0)
790 Phis.insert(std::make_pair(BB, PN));
Owen Anderson48a2c562007-07-30 16:57:08 +0000791
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000792 // Fill in the incoming values for the block.
Owen Anderson9f577412007-07-31 17:43:14 +0000793 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
794 Value* val = GetValueForBlock(*PI, orig, Phis);
Owen Anderson9f577412007-07-31 17:43:14 +0000795 PN->addIncoming(val, *PI);
796 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000797
Nick Lewycky8fba1d02008-02-14 07:11:24 +0000798 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
799 AA.copyValue(orig, PN);
Owen Anderson9f577412007-07-31 17:43:14 +0000800
Owen Andersone0143452007-08-16 22:02:55 +0000801 // Attempt to collapse PHI nodes that are trivially redundant
Owen Andersone02ad522007-08-16 22:51:56 +0000802 Value* v = CollapsePhi(PN);
Chris Lattner3d7103e2008-03-21 21:14:38 +0000803 if (!v) {
804 // Cache our phi construction results
805 phiMap[orig->getPointerOperand()].insert(PN);
806 return PN;
Owen Anderson9f577412007-07-31 17:43:14 +0000807 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000808
809 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
Owen Anderson9f577412007-07-31 17:43:14 +0000810
Chris Lattner3d7103e2008-03-21 21:14:38 +0000811 MD.removeInstruction(PN);
812 PN->replaceAllUsesWith(v);
813
814 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
815 E = Phis.end(); I != E; ++I)
816 if (I->second == PN)
817 I->second = v;
818
819 PN->eraseFromParent();
820
821 Phis[BB] = v;
822 return v;
Owen Anderson5d72a422007-07-25 19:57:03 +0000823}
824
Owen Andersone0143452007-08-16 22:02:55 +0000825/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
826/// non-local by performing PHI construction.
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000827bool GVN::processNonLocalLoad(LoadInst* L,
Chris Lattner7de20452008-03-21 22:01:16 +0000828 SmallVectorImpl<Instruction*> &toErase) {
Owen Anderson5d72a422007-07-25 19:57:03 +0000829 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
830
Owen Andersone0143452007-08-16 22:02:55 +0000831 // Find the non-local dependencies of the load
Owen Anderson5d72a422007-07-25 19:57:03 +0000832 DenseMap<BasicBlock*, Value*> deps;
Owen Anderson3f75d122007-08-01 22:01:54 +0000833 MD.getNonLocalDependency(L, deps);
Owen Anderson5d72a422007-07-25 19:57:03 +0000834
835 DenseMap<BasicBlock*, Value*> repl;
Owen Anderson5b299672007-08-07 23:12:31 +0000836
Owen Andersone0143452007-08-16 22:02:55 +0000837 // Filter out useless results (non-locals, etc)
Owen Anderson5d72a422007-07-25 19:57:03 +0000838 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
Chris Lattner3d7103e2008-03-21 21:14:38 +0000839 I != E; ++I) {
840 if (I->second == MemoryDependenceAnalysis::None)
Owen Anderson5d72a422007-07-25 19:57:03 +0000841 return false;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000842
843 if (I->second == MemoryDependenceAnalysis::NonLocal)
Owen Andersonb484d1f2007-07-30 17:29:24 +0000844 continue;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000845
846 if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
847 if (S->getPointerOperand() != L->getPointerOperand())
Owen Anderson5d72a422007-07-25 19:57:03 +0000848 return false;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000849 repl[I->first] = S->getOperand(0);
Owen Anderson5d72a422007-07-25 19:57:03 +0000850 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000851 if (LD->getPointerOperand() != L->getPointerOperand())
Owen Anderson5d72a422007-07-25 19:57:03 +0000852 return false;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000853 repl[I->first] = LD;
Owen Anderson5d72a422007-07-25 19:57:03 +0000854 } else {
855 return false;
856 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000857 }
Owen Anderson5d72a422007-07-25 19:57:03 +0000858
Owen Andersone0143452007-08-16 22:02:55 +0000859 // Use cached PHI construction information from previous runs
Owen Anderson5b299672007-08-07 23:12:31 +0000860 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
861 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
862 I != E; ++I) {
863 if ((*I)->getParent() == L->getParent()) {
864 MD.removeInstruction(L);
865 L->replaceAllUsesWith(*I);
866 toErase.push_back(L);
867 NumGVNLoad++;
Owen Anderson5b299672007-08-07 23:12:31 +0000868 return true;
Owen Anderson5b299672007-08-07 23:12:31 +0000869 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000870
871 repl.insert(std::make_pair((*I)->getParent(), *I));
Owen Anderson5b299672007-08-07 23:12:31 +0000872 }
873
Owen Andersone0143452007-08-16 22:02:55 +0000874 // Perform PHI construction
Owen Anderson6ce3ae22007-07-25 22:03:06 +0000875 SmallPtrSet<BasicBlock*, 4> visited;
Owen Andersonc6a31b92007-08-02 17:56:05 +0000876 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
Owen Anderson5d72a422007-07-25 19:57:03 +0000877
878 MD.removeInstruction(L);
879 L->replaceAllUsesWith(v);
880 toErase.push_back(L);
Owen Anderson5b299672007-08-07 23:12:31 +0000881 NumGVNLoad++;
Owen Anderson5d72a422007-07-25 19:57:03 +0000882
883 return true;
884}
885
Owen Andersone0143452007-08-16 22:02:55 +0000886/// processLoad - Attempt to eliminate a load, first by eliminating it
887/// locally, and then attempting non-local elimination if that fails.
Chris Lattner7de20452008-03-21 22:01:16 +0000888bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
889 SmallVectorImpl<Instruction*> &toErase) {
Owen Anderson85c40642007-07-24 17:55:58 +0000890 if (L->isVolatile()) {
891 lastLoad[L->getPointerOperand()] = L;
892 return false;
893 }
894
895 Value* pointer = L->getPointerOperand();
896 LoadInst*& last = lastLoad[pointer];
897
898 // ... to a pointer that has been loaded from before...
899 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
Owen Andersoncc8b3a82007-08-14 17:59:48 +0000900 bool removedNonLocal = false;
Owen Anderson935e39b2007-08-09 04:42:44 +0000901 Instruction* dep = MD.getDependency(L);
Owen Anderson5d72a422007-07-25 19:57:03 +0000902 if (dep == MemoryDependenceAnalysis::NonLocal &&
Owen Andersoncc8b3a82007-08-14 17:59:48 +0000903 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
904 removedNonLocal = processNonLocalLoad(L, toErase);
905
906 if (!removedNonLocal)
907 last = L;
908
909 return removedNonLocal;
910 }
911
912
Owen Anderson85c40642007-07-24 17:55:58 +0000913 bool deletedLoad = false;
914
Owen Andersone0143452007-08-16 22:02:55 +0000915 // Walk up the dependency chain until we either find
916 // a dependency we can use, or we can't walk any further
Owen Anderson85c40642007-07-24 17:55:58 +0000917 while (dep != MemoryDependenceAnalysis::None &&
918 dep != MemoryDependenceAnalysis::NonLocal &&
919 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
920 // ... that depends on a store ...
921 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
922 if (S->getPointerOperand() == pointer) {
923 // Remove it!
924 MD.removeInstruction(L);
925
926 L->replaceAllUsesWith(S->getOperand(0));
927 toErase.push_back(L);
928 deletedLoad = true;
929 NumGVNLoad++;
930 }
931
932 // Whether we removed it or not, we can't
933 // go any further
934 break;
935 } else if (!last) {
936 // If we don't depend on a store, and we haven't
937 // been loaded before, bail.
938 break;
939 } else if (dep == last) {
940 // Remove it!
941 MD.removeInstruction(L);
942
943 L->replaceAllUsesWith(last);
944 toErase.push_back(L);
945 deletedLoad = true;
946 NumGVNLoad++;
947
948 break;
949 } else {
Owen Anderson935e39b2007-08-09 04:42:44 +0000950 dep = MD.getDependency(L, dep);
Owen Anderson85c40642007-07-24 17:55:58 +0000951 }
952 }
Eli Friedman350307f2008-02-12 12:08:14 +0000953
954 if (dep != MemoryDependenceAnalysis::None &&
955 dep != MemoryDependenceAnalysis::NonLocal &&
956 isa<AllocationInst>(dep)) {
957 // Check that this load is actually from the
958 // allocation we found
959 Value* v = L->getOperand(0);
960 while (true) {
961 if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
962 v = BC->getOperand(0);
963 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
964 v = GEP->getOperand(0);
965 else
966 break;
967 }
968 if (v == dep) {
969 // If this load depends directly on an allocation, there isn't
970 // anything stored there; therefore, we can optimize this load
971 // to undef.
972 MD.removeInstruction(L);
973
974 L->replaceAllUsesWith(UndefValue::get(L->getType()));
975 toErase.push_back(L);
976 deletedLoad = true;
977 NumGVNLoad++;
978 }
979 }
980
Owen Anderson85c40642007-07-24 17:55:58 +0000981 if (!deletedLoad)
982 last = L;
983
984 return deletedLoad;
985}
986
Chris Lattner248ba4d2008-03-22 00:31:52 +0000987/// isBytewiseValue - If the specified value can be set by repeating the same
988/// byte in memory, return the i8 value that it is represented with. This is
989/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
990/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
991/// byte store (e.g. i16 0x1234), return null.
992static Value *isBytewiseValue(Value *V) {
993 // All byte-wide stores are splatable, even of arbitrary variables.
994 if (V->getType() == Type::Int8Ty) return V;
995
996 // Constant float and double values can be handled as integer values if the
997 // corresponding integer value is "byteable". An important case is 0.0.
998 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
999 if (CFP->getType() == Type::FloatTy)
1000 V = ConstantExpr::getBitCast(CFP, Type::Int32Ty);
1001 if (CFP->getType() == Type::DoubleTy)
1002 V = ConstantExpr::getBitCast(CFP, Type::Int64Ty);
1003 // Don't handle long double formats, which have strange constraints.
1004 }
1005
1006 // We can handle constant integers that are power of two in size and a
1007 // multiple of 8 bits.
1008 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1009 unsigned Width = CI->getBitWidth();
1010 if (isPowerOf2_32(Width) && Width > 8) {
1011 // We can handle this value if the recursive binary decomposition is the
1012 // same at all levels.
1013 APInt Val = CI->getValue();
1014 APInt Val2;
1015 while (Val.getBitWidth() != 8) {
1016 unsigned NextWidth = Val.getBitWidth()/2;
1017 Val2 = Val.lshr(NextWidth);
1018 Val2.trunc(Val.getBitWidth()/2);
1019 Val.trunc(Val.getBitWidth()/2);
1020
1021 // If the top/bottom halves aren't the same, reject it.
1022 if (Val != Val2)
1023 return 0;
1024 }
1025 return ConstantInt::get(Val);
1026 }
1027 }
1028
1029 // Conceptually, we could handle things like:
1030 // %a = zext i8 %X to i16
1031 // %b = shl i16 %a, 8
1032 // %c = or i16 %a, %b
1033 // but until there is an example that actually needs this, it doesn't seem
1034 // worth worrying about.
1035 return 0;
1036}
1037
1038/// IsPointerAtOffset - Return true if Ptr1 is exactly provably equal to Ptr2
1039/// plus the specified constant offset. For example, Ptr1 might be &A[42], and
1040/// Ptr2 might be &A[40] and Offset might be 8.
1041static bool IsPointerAtOffset(Value *Ptr1, Value *Ptr2, uint64_t Offset) {
1042 return false;
1043}
1044
1045
1046/// processStore - When GVN is scanning forward over instructions, we look for
1047/// some other patterns to fold away. In particular, this looks for stores to
1048/// neighboring locations of memory. If it sees enough consequtive ones
1049/// (currently 4) it attempts to merge them together into a memcpy/memset.
1050bool GVN::processStore(StoreInst *SI, SmallVectorImpl<Instruction*> &toErase) {
1051 return false;
1052
1053 if (SI->isVolatile()) return false;
1054
1055 // There are two cases that are interesting for this code to handle: memcpy
1056 // and memset. Right now we only handle memset.
1057
1058 // Ensure that the value being stored is something that can be memset'able a
1059 // byte at a time like "0" or "-1" or any width, as well as things like
1060 // 0xA0A0A0A0 and 0.0.
1061 Value *ByteVal = isBytewiseValue(SI->getOperand(0));
1062 if (!ByteVal)
1063 return false;
1064
1065 TargetData &TD = getAnalysis<TargetData>();
1066 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
1067
1068 // Okay, so we now have a single store that can be splatable. Try to 'grow'
1069 // this store by looking for neighboring stores to the immediate left or right
1070 // of the store we have so far. While we could in theory handle stores in
1071 // this order: A[0], A[2], A[1]
1072 // in practice, right now we only worry about cases where stores are
1073 // consequtive in increasing or decreasing address order.
1074 uint64_t BytesSoFar = TD.getTypeStoreSize(SI->getOperand(0)->getType());
1075 unsigned StartAlign = SI->getAlignment();
1076 Value *StartPtr = SI->getPointerOperand();
1077 SmallVector<StoreInst*, 16> Stores;
1078 Stores.push_back(SI);
1079
1080 BasicBlock::iterator BI = SI; ++BI;
1081 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
1082 if (isa<CallInst>(BI) || isa<InvokeInst>(BI)) {
1083 // If the call is readnone, ignore it, otherwise bail out. We don't even
1084 // allow readonly here because we don't want something like:
1085 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
1086 if (AA.getModRefBehavior(CallSite::get(BI)) ==
1087 AliasAnalysis::DoesNotAccessMemory)
1088 continue;
1089 break;
1090 } else if (isa<VAArgInst>(BI) || isa<LoadInst>(BI))
1091 break;
1092
1093 // If this is a non-store instruction it is fine, ignore it.
1094 StoreInst *NextStore = dyn_cast<StoreInst>(BI);
1095 if (NextStore == 0) continue;
1096
1097 // If this is a store, see if we can merge it in.
1098 if (NextStore->isVolatile()) break;
1099
1100 // Check to see if this stored value is of the same byte-splattable value.
1101 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
1102 break;
1103
1104 Value *ThisPointer = NextStore->getPointerOperand();
1105 unsigned AccessSize = TD.getTypeStoreSize(SI->getOperand(0)->getType());
1106
1107 // If so, check to see if the store is before the current range or after it
1108 // in either case, extend the range, otherwise reject it.
1109 if (IsPointerAtOffset(ThisPointer, StartPtr, BytesSoFar)) {
1110 // Okay, this extends the stored area on the end, just add to the bytes
1111 // so far and remember this store.
1112 BytesSoFar += AccessSize;
1113 Stores.push_back(SI);
1114 continue;
1115 }
1116
1117 if (IsPointerAtOffset(StartPtr, ThisPointer, AccessSize)) {
1118 // Okay, the store is before the current range. Reset our start pointer
1119 // and get new alignment info etc.
1120 BytesSoFar += AccessSize;
1121 Stores.push_back(SI);
1122 StartPtr = ThisPointer;
1123 StartAlign = NextStore->getAlignment();
1124 continue;
1125 }
1126
1127 // Otherwise, this store wasn't contiguous with our current range, bail out.
1128 break;
1129 }
1130
1131 // If we found less than 4 stores to merge, bail out, it isn't worth losing
1132 // type information in llvm IR to do the transformation.
1133 if (Stores.size() < 4)
1134 return false;
1135
1136 // Otherwise, we do want to transform this! But not yet. :)
1137
1138 return false;
1139}
1140
1141
Owen Andersone41ab4c2008-03-12 07:37:44 +00001142/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
1143/// and checks for the possibility of a call slot optimization by having
1144/// the call write its result directly into the destination of the memcpy.
Chris Lattner7de20452008-03-21 22:01:16 +00001145bool GVN::performCallSlotOptzn(MemCpyInst *cpy, CallInst *C,
1146 SmallVectorImpl<Instruction*> &toErase) {
Owen Andersone41ab4c2008-03-12 07:37:44 +00001147 // The general transformation to keep in mind is
1148 //
1149 // call @func(..., src, ...)
1150 // memcpy(dest, src, ...)
1151 //
1152 // ->
1153 //
1154 // memcpy(dest, src, ...)
1155 // call @func(..., dest, ...)
1156 //
1157 // Since moving the memcpy is technically awkward, we additionally check that
1158 // src only holds uninitialized values at the moment of the call, meaning that
1159 // the memcpy can be discarded rather than moved.
Owen Anderson556d0e52008-02-19 03:27:34 +00001160
Owen Anderson364b1eb2008-02-19 07:07:51 +00001161 // Deliberately get the source and destination with bitcasts stripped away,
1162 // because we'll need to do type comparisons based on the underlying type.
Owen Anderson282dd322008-02-18 09:24:53 +00001163 Value* cpyDest = cpy->getDest();
Owen Anderson29f73562008-02-19 06:35:43 +00001164 Value* cpySrc = cpy->getSource();
1165 CallSite CS = CallSite::get(C);
Owen Andersone41ab4c2008-03-12 07:37:44 +00001166
1167 // We need to be able to reason about the size of the memcpy, so we require
1168 // that it be a constant.
1169 ConstantInt* cpyLength = dyn_cast<ConstantInt>(cpy->getLength());
1170 if (!cpyLength)
Owen Anderson282dd322008-02-18 09:24:53 +00001171 return false;
Owen Andersone41ab4c2008-03-12 07:37:44 +00001172
1173 // Require that src be an alloca. This simplifies the reasoning considerably.
1174 AllocaInst* srcAlloca = dyn_cast<AllocaInst>(cpySrc);
1175 if (!srcAlloca)
1176 return false;
1177
1178 // Check that all of src is copied to dest.
1179 TargetData& TD = getAnalysis<TargetData>();
1180
1181 ConstantInt* srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
1182 if (!srcArraySize)
1183 return false;
1184
1185 uint64_t srcSize = TD.getABITypeSize(srcAlloca->getAllocatedType()) *
1186 srcArraySize->getZExtValue();
1187
1188 if (cpyLength->getZExtValue() < srcSize)
1189 return false;
1190
1191 // Check that accessing the first srcSize bytes of dest will not cause a
1192 // trap. Otherwise the transform is invalid since it might cause a trap
1193 // to occur earlier than it otherwise would.
1194 if (AllocaInst* A = dyn_cast<AllocaInst>(cpyDest)) {
1195 // The destination is an alloca. Check it is larger than srcSize.
1196 ConstantInt* destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
1197 if (!destArraySize)
1198 return false;
1199
1200 uint64_t destSize = TD.getABITypeSize(A->getAllocatedType()) *
1201 destArraySize->getZExtValue();
1202
1203 if (destSize < srcSize)
1204 return false;
1205 } else if (Argument* A = dyn_cast<Argument>(cpyDest)) {
1206 // If the destination is an sret parameter then only accesses that are
1207 // outside of the returned struct type can trap.
1208 if (!A->hasStructRetAttr())
1209 return false;
1210
1211 const Type* StructTy = cast<PointerType>(A->getType())->getElementType();
1212 uint64_t destSize = TD.getABITypeSize(StructTy);
1213
1214 if (destSize < srcSize)
1215 return false;
1216 } else {
1217 return false;
1218 }
1219
1220 // Check that src is not accessed except via the call and the memcpy. This
1221 // guarantees that it holds only undefined values when passed in (so the final
1222 // memcpy can be dropped), that it is not read or written between the call and
1223 // the memcpy, and that writing beyond the end of it is undefined.
Owen Andersone41ab4c2008-03-12 07:37:44 +00001224 SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
1225 srcAlloca->use_end());
1226 while (!srcUseList.empty()) {
1227 User* UI = srcUseList.back();
1228 srcUseList.pop_back();
1229
1230 if (isa<GetElementPtrInst>(UI) || isa<BitCastInst>(UI)) {
1231 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
1232 I != E; ++I)
1233 srcUseList.push_back(*I);
1234 } else if (UI != C && UI != cpy) {
1235 return false;
1236 }
1237 }
1238
Owen Anderson05744bd2008-02-25 00:40:41 +00001239 // Since we're changing the parameter to the callsite, we need to make sure
1240 // that what would be the new parameter dominates the callsite.
1241 DominatorTree& DT = getAnalysis<DominatorTree>();
1242 if (Instruction* cpyDestInst = dyn_cast<Instruction>(cpyDest))
1243 if (!DT.dominates(cpyDestInst, C))
1244 return false;
Owen Andersone41ab4c2008-03-12 07:37:44 +00001245
1246 // In addition to knowing that the call does not access src in some
1247 // unexpected manner, for example via a global, which we deduce from
1248 // the use analysis, we also need to know that it does not sneakily
1249 // access dest. We rely on AA to figure this out for us.
Owen Anderson29f73562008-02-19 06:35:43 +00001250 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
Owen Andersone41ab4c2008-03-12 07:37:44 +00001251 if (AA.getModRefInfo(C, cpy->getRawDest(), srcSize) !=
Owen Anderson29f73562008-02-19 06:35:43 +00001252 AliasAnalysis::NoModRef)
1253 return false;
Owen Andersone41ab4c2008-03-12 07:37:44 +00001254
1255 // All the checks have passed, so do the transformation.
1256 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson78a334f2008-03-13 22:07:10 +00001257 if (CS.getArgument(i) == cpySrc) {
1258 if (cpySrc->getType() != cpyDest->getType())
1259 cpyDest = CastInst::createPointerCast(cpyDest, cpySrc->getType(),
1260 cpyDest->getName(), C);
Owen Andersone41ab4c2008-03-12 07:37:44 +00001261 CS.setArgument(i, cpyDest);
Owen Anderson78a334f2008-03-13 22:07:10 +00001262 }
Owen Andersone41ab4c2008-03-12 07:37:44 +00001263
Owen Anderson29f73562008-02-19 06:35:43 +00001264 // Drop any cached information about the call, because we may have changed
1265 // its dependence information by changing its parameter.
Owen Anderson282dd322008-02-18 09:24:53 +00001266 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1267 MD.dropInstruction(C);
Owen Andersone41ab4c2008-03-12 07:37:44 +00001268
Owen Anderson282dd322008-02-18 09:24:53 +00001269 // Remove the memcpy
Owen Andersonff8e2d32008-02-20 08:23:02 +00001270 MD.removeInstruction(cpy);
Owen Anderson282dd322008-02-18 09:24:53 +00001271 toErase.push_back(cpy);
Owen Andersone41ab4c2008-03-12 07:37:44 +00001272
Owen Anderson282dd322008-02-18 09:24:53 +00001273 return true;
1274}
1275
Owen Anderson8d272d52008-02-12 21:15:18 +00001276/// processMemCpy - perform simplication of memcpy's. If we have memcpy A which
1277/// copies X to Y, and memcpy B which copies Y to Z, then we can rewrite B to be
1278/// a memcpy from X to Z (or potentially a memmove, depending on circumstances).
1279/// This allows later passes to remove the first memcpy altogether.
Owen Andersonba958332008-02-19 03:09:45 +00001280bool GVN::processMemCpy(MemCpyInst* M, MemCpyInst* MDep,
Chris Lattner7de20452008-03-21 22:01:16 +00001281 SmallVectorImpl<Instruction*> &toErase) {
Owen Anderson8d272d52008-02-12 21:15:18 +00001282 // We can only transforms memcpy's where the dest of one is the source of the
1283 // other
Owen Anderson8d272d52008-02-12 21:15:18 +00001284 if (M->getSource() != MDep->getDest())
1285 return false;
1286
1287 // Second, the length of the memcpy's must be the same, or the preceeding one
1288 // must be larger than the following one.
1289 ConstantInt* C1 = dyn_cast<ConstantInt>(MDep->getLength());
1290 ConstantInt* C2 = dyn_cast<ConstantInt>(M->getLength());
1291 if (!C1 || !C2)
1292 return false;
1293
Owen Andersonc318b562008-02-26 23:06:17 +00001294 uint64_t DepSize = C1->getValue().getZExtValue();
1295 uint64_t CpySize = C2->getValue().getZExtValue();
Owen Anderson8d272d52008-02-12 21:15:18 +00001296
1297 if (DepSize < CpySize)
1298 return false;
1299
1300 // Finally, we have to make sure that the dest of the second does not
1301 // alias the source of the first
1302 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1303 if (AA.alias(M->getRawDest(), CpySize, MDep->getRawSource(), DepSize) !=
1304 AliasAnalysis::NoAlias)
1305 return false;
1306 else if (AA.alias(M->getRawDest(), CpySize, M->getRawSource(), CpySize) !=
1307 AliasAnalysis::NoAlias)
1308 return false;
1309 else if (AA.alias(MDep->getRawDest(), DepSize, MDep->getRawSource(), DepSize)
1310 != AliasAnalysis::NoAlias)
1311 return false;
1312
1313 // If all checks passed, then we can transform these memcpy's
Owen Andersonba958332008-02-19 03:09:45 +00001314 Function* MemCpyFun = Intrinsic::getDeclaration(
Owen Anderson8d272d52008-02-12 21:15:18 +00001315 M->getParent()->getParent()->getParent(),
Owen Andersonba958332008-02-19 03:09:45 +00001316 M->getIntrinsicID());
Owen Anderson8d272d52008-02-12 21:15:18 +00001317
1318 std::vector<Value*> args;
1319 args.push_back(M->getRawDest());
1320 args.push_back(MDep->getRawSource());
1321 args.push_back(M->getLength());
1322 args.push_back(M->getAlignment());
1323
Owen Andersonba958332008-02-19 03:09:45 +00001324 CallInst* C = new CallInst(MemCpyFun, args.begin(), args.end(), "", M);
Owen Anderson8d272d52008-02-12 21:15:18 +00001325
Owen Andersonba958332008-02-19 03:09:45 +00001326 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
Owen Anderson8d272d52008-02-12 21:15:18 +00001327 if (MD.getDependency(C) == MDep) {
1328 MD.dropInstruction(M);
1329 toErase.push_back(M);
1330 return true;
Owen Anderson8d272d52008-02-12 21:15:18 +00001331 }
Chris Lattner3d7103e2008-03-21 21:14:38 +00001332
1333 MD.removeInstruction(C);
1334 toErase.push_back(C);
1335 return false;
Owen Anderson8d272d52008-02-12 21:15:18 +00001336}
1337
Owen Andersonf631bb62007-08-14 18:16:29 +00001338/// processInstruction - When calculating availability, handle an instruction
Owen Anderson85c40642007-07-24 17:55:58 +00001339/// by inserting it into the appropriate sets
Chris Lattner7de20452008-03-21 22:01:16 +00001340bool GVN::processInstruction(Instruction *I, ValueNumberedSet &currAvail,
1341 DenseMap<Value*, LoadInst*> &lastSeenLoad,
1342 SmallVectorImpl<Instruction*> &toErase) {
1343 if (LoadInst* L = dyn_cast<LoadInst>(I))
Owen Anderson85c40642007-07-24 17:55:58 +00001344 return processLoad(L, lastSeenLoad, toErase);
Chris Lattner7de20452008-03-21 22:01:16 +00001345
Chris Lattner248ba4d2008-03-22 00:31:52 +00001346 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1347 return processStore(SI, toErase);
1348
Chris Lattner7de20452008-03-21 22:01:16 +00001349 if (MemCpyInst* M = dyn_cast<MemCpyInst>(I)) {
Owen Andersonba958332008-02-19 03:09:45 +00001350 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1351
1352 // The are two possible optimizations we can do for memcpy:
1353 // a) memcpy-memcpy xform which exposes redundance for DSE
Owen Andersone41ab4c2008-03-12 07:37:44 +00001354 // b) call-memcpy xform for return slot optimization
Owen Andersonba958332008-02-19 03:09:45 +00001355 Instruction* dep = MD.getDependency(M);
1356 if (dep == MemoryDependenceAnalysis::None ||
1357 dep == MemoryDependenceAnalysis::NonLocal)
1358 return false;
Chris Lattnerfd18dcd2008-02-19 06:53:20 +00001359 if (MemCpyInst *MemCpy = dyn_cast<MemCpyInst>(dep))
1360 return processMemCpy(M, MemCpy, toErase);
Chris Lattner8bc7a0d2008-02-19 06:52:38 +00001361 if (CallInst* C = dyn_cast<CallInst>(dep))
Owen Andersone41ab4c2008-03-12 07:37:44 +00001362 return performCallSlotOptzn(M, C, toErase);
Chris Lattner8bc7a0d2008-02-19 06:52:38 +00001363 return false;
Owen Anderson85c40642007-07-24 17:55:58 +00001364 }
1365
1366 unsigned num = VN.lookup_or_add(I);
1367
Owen Andersone0143452007-08-16 22:02:55 +00001368 // Collapse PHI nodes
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001369 if (PHINode* p = dyn_cast<PHINode>(I)) {
Owen Andersone02ad522007-08-16 22:51:56 +00001370 Value* constVal = CollapsePhi(p);
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001371
1372 if (constVal) {
Owen Andersone02ad522007-08-16 22:51:56 +00001373 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1374 PI != PE; ++PI)
1375 if (PI->second.count(p))
1376 PI->second.erase(p);
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001377
Owen Andersone02ad522007-08-16 22:51:56 +00001378 p->replaceAllUsesWith(constVal);
1379 toErase.push_back(p);
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001380 }
Owen Andersone0143452007-08-16 22:02:55 +00001381 // Perform value-number based elimination
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001382 } else if (currAvail.test(num)) {
Owen Anderson85c40642007-07-24 17:55:58 +00001383 Value* repl = find_leader(currAvail, num);
1384
Owen Anderson8b6f04e2007-11-26 02:26:36 +00001385 if (CallInst* CI = dyn_cast<CallInst>(I)) {
1386 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
Duncan Sands00b24b52007-12-01 07:51:45 +00001387 if (!AA.doesNotAccessMemory(CI)) {
Owen Anderson8b6f04e2007-11-26 02:26:36 +00001388 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
Owen Andersonfb3f6f22007-11-29 18:02:22 +00001389 if (cast<Instruction>(repl)->getParent() != CI->getParent() ||
1390 MD.getDependency(CI) != MD.getDependency(cast<CallInst>(repl))) {
Owen Anderson8b6f04e2007-11-26 02:26:36 +00001391 // There must be an intervening may-alias store, so nothing from
1392 // this point on will be able to be replaced with the preceding call
1393 currAvail.erase(repl);
1394 currAvail.insert(I);
1395
1396 return false;
1397 }
1398 }
1399 }
1400
Owen Andersonc772be72007-12-08 01:37:09 +00001401 // Remove it!
1402 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1403 MD.removeInstruction(I);
1404
Owen Anderson5aff8002007-07-31 23:27:13 +00001405 VN.erase(I);
Owen Anderson85c40642007-07-24 17:55:58 +00001406 I->replaceAllUsesWith(repl);
1407 toErase.push_back(I);
1408 return true;
1409 } else if (!I->isTerminator()) {
1410 currAvail.set(num);
1411 currAvail.insert(I);
1412 }
1413
1414 return false;
1415}
1416
1417// GVN::runOnFunction - This is the main transformation entry point for a
1418// function.
1419//
Owen Andersonbe168b32007-08-14 18:04:11 +00001420bool GVN::runOnFunction(Function& F) {
Owen Anderson5e9366f2007-10-18 19:39:33 +00001421 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1422
Owen Andersonbe168b32007-08-14 18:04:11 +00001423 bool changed = false;
1424 bool shouldContinue = true;
1425
1426 while (shouldContinue) {
1427 shouldContinue = iterateOnFunction(F);
1428 changed |= shouldContinue;
1429 }
1430
1431 return changed;
1432}
1433
1434
1435// GVN::iterateOnFunction - Executes one iteration of GVN
1436bool GVN::iterateOnFunction(Function &F) {
Owen Anderson85c40642007-07-24 17:55:58 +00001437 // Clean out global sets from any previous functions
1438 VN.clear();
1439 availableOut.clear();
Owen Anderson5b299672007-08-07 23:12:31 +00001440 phiMap.clear();
Owen Anderson85c40642007-07-24 17:55:58 +00001441
1442 bool changed_function = false;
1443
1444 DominatorTree &DT = getAnalysis<DominatorTree>();
1445
1446 SmallVector<Instruction*, 4> toErase;
Chris Lattner98054902008-03-21 21:33:23 +00001447 DenseMap<Value*, LoadInst*> lastSeenLoad;
1448
Owen Anderson85c40642007-07-24 17:55:58 +00001449 // Top-down walk of the dominator tree
1450 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1451 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1452
1453 // Get the set to update for this block
1454 ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
Chris Lattner98054902008-03-21 21:33:23 +00001455 lastSeenLoad.clear();
1456
Owen Anderson85c40642007-07-24 17:55:58 +00001457 BasicBlock* BB = DI->getBlock();
1458
1459 // A block inherits AVAIL_OUT from its dominator
1460 if (DI->getIDom() != 0)
1461 currAvail = availableOut[DI->getIDom()->getBlock()];
1462
1463 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
Owen Andersonc0403802007-07-30 21:26:39 +00001464 BI != BE; ) {
Owen Andersonbf8a3eb2007-08-02 18:16:06 +00001465 changed_function |= processInstruction(BI, currAvail,
1466 lastSeenLoad, toErase);
Owen Anderson5d72a422007-07-25 19:57:03 +00001467
1468 NumGVNInstr += toErase.size();
1469
Owen Andersonc0403802007-07-30 21:26:39 +00001470 // Avoid iterator invalidation
1471 ++BI;
Owen Andersonc772be72007-12-08 01:37:09 +00001472
Owen Anderson5d72a422007-07-25 19:57:03 +00001473 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
Chris Lattner3d7103e2008-03-21 21:14:38 +00001474 E = toErase.end(); I != E; ++I)
Owen Anderson5d72a422007-07-25 19:57:03 +00001475 (*I)->eraseFromParent();
Owen Andersonc772be72007-12-08 01:37:09 +00001476
Owen Anderson5d72a422007-07-25 19:57:03 +00001477 toErase.clear();
Owen Anderson85c40642007-07-24 17:55:58 +00001478 }
1479 }
1480
Owen Anderson85c40642007-07-24 17:55:58 +00001481 return changed_function;
1482}