blob: 91f72c4ba65aacaf6fe67112abec4adddaaf7ebc [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 Anderson85c40642007-07-24 17:55:58 +000016#include "llvm/Transforms/Scalar.h"
Owen Anderson5d72a422007-07-25 19:57:03 +000017#include "llvm/BasicBlock.h"
Owen Andersonacfa3ad2007-07-26 18:26:51 +000018#include "llvm/Constants.h"
Owen Anderson85c40642007-07-24 17:55:58 +000019#include "llvm/DerivedTypes.h"
Owen Andersonacfa3ad2007-07-26 18:26:51 +000020#include "llvm/Function.h"
Owen Anderson8d272d52008-02-12 21:15:18 +000021#include "llvm/IntrinsicInst.h"
Owen Andersonacfa3ad2007-07-26 18:26:51 +000022#include "llvm/Instructions.h"
Owen Anderson282dd322008-02-18 09:24:53 +000023#include "llvm/ParameterAttributes.h"
Owen Andersonacfa3ad2007-07-26 18:26:51 +000024#include "llvm/Value.h"
Owen Anderson85c40642007-07-24 17:55:58 +000025#include "llvm/ADT/DenseMap.h"
26#include "llvm/ADT/DepthFirstIterator.h"
27#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/SmallVector.h"
Owen Anderson80033de2008-04-07 17:38:23 +000029#include "llvm/ADT/SparseBitVector.h"
Owen Anderson85c40642007-07-24 17:55:58 +000030#include "llvm/ADT/Statistic.h"
Owen Anderson5e9366f2007-10-18 19:39:33 +000031#include "llvm/Analysis/Dominators.h"
32#include "llvm/Analysis/AliasAnalysis.h"
Owen Anderson85c40642007-07-24 17:55:58 +000033#include "llvm/Analysis/MemoryDependenceAnalysis.h"
34#include "llvm/Support/CFG.h"
Evan Chenge856f8e2008-03-24 05:28:38 +000035#include "llvm/Support/CommandLine.h"
Owen Anderson85c40642007-07-24 17:55:58 +000036#include "llvm/Support/Compiler.h"
Chris Lattner9c5be3c2008-03-29 04:36:18 +000037#include "llvm/Support/Debug.h"
Chris Lattner60b9cb42008-03-22 05:37:16 +000038#include "llvm/Support/GetElementPtrTypeIterator.h"
Owen Anderson29f73562008-02-19 06:35:43 +000039#include "llvm/Target/TargetData.h"
Chris Lattner49650d62008-03-28 06:45:13 +000040#include <list>
Owen Anderson85c40642007-07-24 17:55:58 +000041using namespace llvm;
42
Chris Lattner1be83222008-03-22 04:13:49 +000043STATISTIC(NumGVNInstr, "Number of instructions deleted");
44STATISTIC(NumGVNLoad, "Number of loads deleted");
45STATISTIC(NumMemSetInfer, "Number of memsets inferred");
46
Evan Chenge856f8e2008-03-24 05:28:38 +000047namespace {
48 cl::opt<bool>
49 FormMemSet("form-memset-from-stores",
50 cl::desc("Transform straight-line stores to memsets"),
Chris Lattner9c5be3c2008-03-29 04:36:18 +000051 cl::init(true), cl::Hidden);
Evan Chenge856f8e2008-03-24 05:28:38 +000052}
Chris Lattner1be83222008-03-22 04:13:49 +000053
Owen Anderson85c40642007-07-24 17:55:58 +000054//===----------------------------------------------------------------------===//
55// ValueTable Class
56//===----------------------------------------------------------------------===//
57
58/// This class holds the mapping between values and value numbers. It is used
59/// as an efficient mechanism to determine the expression-wise equivalence of
60/// two values.
61namespace {
62 struct VISIBILITY_HIDDEN Expression {
63 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
64 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
65 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
66 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
67 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
68 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
69 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
70 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
71 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
Owen Anderson5e9366f2007-10-18 19:39:33 +000072 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, EMPTY,
Owen Anderson85c40642007-07-24 17:55:58 +000073 TOMBSTONE };
74
75 ExpressionOpcode opcode;
76 const Type* type;
77 uint32_t firstVN;
78 uint32_t secondVN;
79 uint32_t thirdVN;
80 SmallVector<uint32_t, 4> varargs;
Owen Anderson5e9366f2007-10-18 19:39:33 +000081 Value* function;
Owen Anderson85c40642007-07-24 17:55:58 +000082
83 Expression() { }
84 Expression(ExpressionOpcode o) : opcode(o) { }
85
86 bool operator==(const Expression &other) const {
87 if (opcode != other.opcode)
88 return false;
89 else if (opcode == EMPTY || opcode == TOMBSTONE)
90 return true;
91 else if (type != other.type)
92 return false;
Owen Anderson5e9366f2007-10-18 19:39:33 +000093 else if (function != other.function)
94 return false;
Owen Anderson85c40642007-07-24 17:55:58 +000095 else if (firstVN != other.firstVN)
96 return false;
97 else if (secondVN != other.secondVN)
98 return false;
99 else if (thirdVN != other.thirdVN)
100 return false;
101 else {
102 if (varargs.size() != other.varargs.size())
103 return false;
104
105 for (size_t i = 0; i < varargs.size(); ++i)
106 if (varargs[i] != other.varargs[i])
107 return false;
108
109 return true;
110 }
111 }
112
113 bool operator!=(const Expression &other) const {
114 if (opcode != other.opcode)
115 return true;
116 else if (opcode == EMPTY || opcode == TOMBSTONE)
117 return false;
118 else if (type != other.type)
119 return true;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000120 else if (function != other.function)
121 return true;
Owen Anderson85c40642007-07-24 17:55:58 +0000122 else if (firstVN != other.firstVN)
123 return true;
124 else if (secondVN != other.secondVN)
125 return true;
126 else if (thirdVN != other.thirdVN)
127 return true;
128 else {
129 if (varargs.size() != other.varargs.size())
130 return true;
131
132 for (size_t i = 0; i < varargs.size(); ++i)
133 if (varargs[i] != other.varargs[i])
134 return true;
135
136 return false;
137 }
138 }
139 };
140
141 class VISIBILITY_HIDDEN ValueTable {
142 private:
143 DenseMap<Value*, uint32_t> valueNumbering;
144 DenseMap<Expression, uint32_t> expressionNumbering;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000145 AliasAnalysis* AA;
Owen Anderson85c40642007-07-24 17:55:58 +0000146
147 uint32_t nextValueNumber;
148
149 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
150 Expression::ExpressionOpcode getOpcode(CmpInst* C);
151 Expression::ExpressionOpcode getOpcode(CastInst* C);
152 Expression create_expression(BinaryOperator* BO);
153 Expression create_expression(CmpInst* C);
154 Expression create_expression(ShuffleVectorInst* V);
155 Expression create_expression(ExtractElementInst* C);
156 Expression create_expression(InsertElementInst* V);
157 Expression create_expression(SelectInst* V);
158 Expression create_expression(CastInst* C);
159 Expression create_expression(GetElementPtrInst* G);
Owen Anderson5e9366f2007-10-18 19:39:33 +0000160 Expression create_expression(CallInst* C);
Owen Anderson85c40642007-07-24 17:55:58 +0000161 public:
Owen Anderson5e9366f2007-10-18 19:39:33 +0000162 ValueTable() : nextValueNumber(1) { }
Owen Anderson85c40642007-07-24 17:55:58 +0000163 uint32_t lookup_or_add(Value* V);
164 uint32_t lookup(Value* V) const;
165 void add(Value* V, uint32_t num);
166 void clear();
167 void erase(Value* v);
168 unsigned size();
Owen Anderson5e9366f2007-10-18 19:39:33 +0000169 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
Owen Anderson343797c2007-11-26 07:17:19 +0000170 uint32_t hash_operand(Value* v);
Owen Anderson85c40642007-07-24 17:55:58 +0000171 };
172}
173
174namespace llvm {
Chris Lattner92eea072007-09-17 18:34:04 +0000175template <> struct DenseMapInfo<Expression> {
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000176 static inline Expression getEmptyKey() {
177 return Expression(Expression::EMPTY);
178 }
179
180 static inline Expression getTombstoneKey() {
181 return Expression(Expression::TOMBSTONE);
182 }
Owen Anderson85c40642007-07-24 17:55:58 +0000183
184 static unsigned getHashValue(const Expression e) {
185 unsigned hash = e.opcode;
186
187 hash = e.firstVN + hash * 37;
188 hash = e.secondVN + hash * 37;
189 hash = e.thirdVN + hash * 37;
190
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000191 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
192 (unsigned)((uintptr_t)e.type >> 9)) +
193 hash * 37;
Owen Anderson85c40642007-07-24 17:55:58 +0000194
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000195 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
196 E = e.varargs.end(); I != E; ++I)
Owen Anderson85c40642007-07-24 17:55:58 +0000197 hash = *I + hash * 37;
198
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000199 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
200 (unsigned)((uintptr_t)e.function >> 9)) +
201 hash * 37;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000202
Owen Anderson85c40642007-07-24 17:55:58 +0000203 return hash;
204 }
Chris Lattner92eea072007-09-17 18:34:04 +0000205 static bool isEqual(const Expression &LHS, const Expression &RHS) {
206 return LHS == RHS;
207 }
Owen Anderson85c40642007-07-24 17:55:58 +0000208 static bool isPod() { return true; }
209};
210}
211
212//===----------------------------------------------------------------------===//
213// ValueTable Internal Functions
214//===----------------------------------------------------------------------===//
Chris Lattner3d7103e2008-03-21 21:14:38 +0000215Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
Owen Anderson85c40642007-07-24 17:55:58 +0000216 switch(BO->getOpcode()) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000217 default: // THIS SHOULD NEVER HAPPEN
218 assert(0 && "Binary operator with unknown opcode?");
219 case Instruction::Add: return Expression::ADD;
220 case Instruction::Sub: return Expression::SUB;
221 case Instruction::Mul: return Expression::MUL;
222 case Instruction::UDiv: return Expression::UDIV;
223 case Instruction::SDiv: return Expression::SDIV;
224 case Instruction::FDiv: return Expression::FDIV;
225 case Instruction::URem: return Expression::UREM;
226 case Instruction::SRem: return Expression::SREM;
227 case Instruction::FRem: return Expression::FREM;
228 case Instruction::Shl: return Expression::SHL;
229 case Instruction::LShr: return Expression::LSHR;
230 case Instruction::AShr: return Expression::ASHR;
231 case Instruction::And: return Expression::AND;
232 case Instruction::Or: return Expression::OR;
233 case Instruction::Xor: return Expression::XOR;
Owen Anderson85c40642007-07-24 17:55:58 +0000234 }
235}
236
237Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000238 if (isa<ICmpInst>(C)) {
Owen Anderson85c40642007-07-24 17:55:58 +0000239 switch (C->getPredicate()) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000240 default: // THIS SHOULD NEVER HAPPEN
241 assert(0 && "Comparison with unknown predicate?");
242 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ;
243 case ICmpInst::ICMP_NE: return Expression::ICMPNE;
244 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
245 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
246 case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
247 case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
248 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
249 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
250 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
251 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
Owen Anderson85c40642007-07-24 17:55:58 +0000252 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000253 }
254 assert(isa<FCmpInst>(C) && "Unknown compare");
255 switch (C->getPredicate()) {
256 default: // THIS SHOULD NEVER HAPPEN
257 assert(0 && "Comparison with unknown predicate?");
258 case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
259 case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
260 case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
261 case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
262 case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
263 case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
264 case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
265 case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
266 case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
267 case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
268 case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
269 case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
270 case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
271 case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
Owen Anderson85c40642007-07-24 17:55:58 +0000272 }
273}
274
Chris Lattner3d7103e2008-03-21 21:14:38 +0000275Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
Owen Anderson85c40642007-07-24 17:55:58 +0000276 switch(C->getOpcode()) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000277 default: // THIS SHOULD NEVER HAPPEN
278 assert(0 && "Cast operator with unknown opcode?");
279 case Instruction::Trunc: return Expression::TRUNC;
280 case Instruction::ZExt: return Expression::ZEXT;
281 case Instruction::SExt: return Expression::SEXT;
282 case Instruction::FPToUI: return Expression::FPTOUI;
283 case Instruction::FPToSI: return Expression::FPTOSI;
284 case Instruction::UIToFP: return Expression::UITOFP;
285 case Instruction::SIToFP: return Expression::SITOFP;
286 case Instruction::FPTrunc: return Expression::FPTRUNC;
287 case Instruction::FPExt: return Expression::FPEXT;
288 case Instruction::PtrToInt: return Expression::PTRTOINT;
289 case Instruction::IntToPtr: return Expression::INTTOPTR;
290 case Instruction::BitCast: return Expression::BITCAST;
Owen Anderson85c40642007-07-24 17:55:58 +0000291 }
292}
293
Owen Anderson343797c2007-11-26 07:17:19 +0000294uint32_t ValueTable::hash_operand(Value* v) {
295 if (CallInst* CI = dyn_cast<CallInst>(v))
Duncan Sands00b24b52007-12-01 07:51:45 +0000296 if (!AA->doesNotAccessMemory(CI))
Owen Anderson343797c2007-11-26 07:17:19 +0000297 return nextValueNumber++;
298
299 return lookup_or_add(v);
300}
301
Owen Anderson5e9366f2007-10-18 19:39:33 +0000302Expression ValueTable::create_expression(CallInst* C) {
303 Expression e;
304
305 e.type = C->getType();
306 e.firstVN = 0;
307 e.secondVN = 0;
308 e.thirdVN = 0;
309 e.function = C->getCalledFunction();
310 e.opcode = Expression::CALL;
311
312 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
313 I != E; ++I)
Owen Anderson343797c2007-11-26 07:17:19 +0000314 e.varargs.push_back(hash_operand(*I));
Owen Anderson5e9366f2007-10-18 19:39:33 +0000315
316 return e;
317}
318
Owen Anderson85c40642007-07-24 17:55:58 +0000319Expression ValueTable::create_expression(BinaryOperator* BO) {
320 Expression e;
321
Owen Anderson343797c2007-11-26 07:17:19 +0000322 e.firstVN = hash_operand(BO->getOperand(0));
323 e.secondVN = hash_operand(BO->getOperand(1));
Owen Anderson85c40642007-07-24 17:55:58 +0000324 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000325 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000326 e.type = BO->getType();
327 e.opcode = getOpcode(BO);
328
329 return e;
330}
331
332Expression ValueTable::create_expression(CmpInst* C) {
333 Expression e;
334
Owen Anderson343797c2007-11-26 07:17:19 +0000335 e.firstVN = hash_operand(C->getOperand(0));
336 e.secondVN = hash_operand(C->getOperand(1));
Owen Anderson85c40642007-07-24 17:55:58 +0000337 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000338 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000339 e.type = C->getType();
340 e.opcode = getOpcode(C);
341
342 return e;
343}
344
345Expression ValueTable::create_expression(CastInst* C) {
346 Expression e;
347
Owen Anderson343797c2007-11-26 07:17:19 +0000348 e.firstVN = hash_operand(C->getOperand(0));
Owen Anderson85c40642007-07-24 17:55:58 +0000349 e.secondVN = 0;
350 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000351 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000352 e.type = C->getType();
353 e.opcode = getOpcode(C);
354
355 return e;
356}
357
358Expression ValueTable::create_expression(ShuffleVectorInst* S) {
359 Expression e;
360
Owen Anderson343797c2007-11-26 07:17:19 +0000361 e.firstVN = hash_operand(S->getOperand(0));
362 e.secondVN = hash_operand(S->getOperand(1));
363 e.thirdVN = hash_operand(S->getOperand(2));
Owen Anderson5e9366f2007-10-18 19:39:33 +0000364 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000365 e.type = S->getType();
366 e.opcode = Expression::SHUFFLE;
367
368 return e;
369}
370
371Expression ValueTable::create_expression(ExtractElementInst* E) {
372 Expression e;
373
Owen Anderson343797c2007-11-26 07:17:19 +0000374 e.firstVN = hash_operand(E->getOperand(0));
375 e.secondVN = hash_operand(E->getOperand(1));
Owen Anderson85c40642007-07-24 17:55:58 +0000376 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000377 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000378 e.type = E->getType();
379 e.opcode = Expression::EXTRACT;
380
381 return e;
382}
383
384Expression ValueTable::create_expression(InsertElementInst* I) {
385 Expression e;
386
Owen Anderson343797c2007-11-26 07:17:19 +0000387 e.firstVN = hash_operand(I->getOperand(0));
388 e.secondVN = hash_operand(I->getOperand(1));
389 e.thirdVN = hash_operand(I->getOperand(2));
Owen Anderson5e9366f2007-10-18 19:39:33 +0000390 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000391 e.type = I->getType();
392 e.opcode = Expression::INSERT;
393
394 return e;
395}
396
397Expression ValueTable::create_expression(SelectInst* I) {
398 Expression e;
399
Owen Anderson343797c2007-11-26 07:17:19 +0000400 e.firstVN = hash_operand(I->getCondition());
401 e.secondVN = hash_operand(I->getTrueValue());
402 e.thirdVN = hash_operand(I->getFalseValue());
Owen Anderson5e9366f2007-10-18 19:39:33 +0000403 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000404 e.type = I->getType();
405 e.opcode = Expression::SELECT;
406
407 return e;
408}
409
410Expression ValueTable::create_expression(GetElementPtrInst* G) {
411 Expression e;
412
Owen Anderson343797c2007-11-26 07:17:19 +0000413 e.firstVN = hash_operand(G->getPointerOperand());
Owen Anderson85c40642007-07-24 17:55:58 +0000414 e.secondVN = 0;
415 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000416 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000417 e.type = G->getType();
418 e.opcode = Expression::GEP;
419
420 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
421 I != E; ++I)
Owen Anderson343797c2007-11-26 07:17:19 +0000422 e.varargs.push_back(hash_operand(*I));
Owen Anderson85c40642007-07-24 17:55:58 +0000423
424 return e;
425}
426
427//===----------------------------------------------------------------------===//
428// ValueTable External Functions
429//===----------------------------------------------------------------------===//
430
431/// lookup_or_add - Returns the value number for the specified value, assigning
432/// it a new number if it did not have one before.
433uint32_t ValueTable::lookup_or_add(Value* V) {
434 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
435 if (VI != valueNumbering.end())
436 return VI->second;
437
Owen Anderson5e9366f2007-10-18 19:39:33 +0000438 if (CallInst* C = dyn_cast<CallInst>(V)) {
Duncan Sands00b24b52007-12-01 07:51:45 +0000439 if (AA->onlyReadsMemory(C)) { // includes doesNotAccessMemory
Owen Anderson5e9366f2007-10-18 19:39:33 +0000440 Expression e = create_expression(C);
441
442 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
443 if (EI != expressionNumbering.end()) {
444 valueNumbering.insert(std::make_pair(V, EI->second));
445 return EI->second;
446 } else {
447 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
448 valueNumbering.insert(std::make_pair(V, nextValueNumber));
449
450 return nextValueNumber++;
451 }
452 } else {
453 valueNumbering.insert(std::make_pair(V, nextValueNumber));
454 return nextValueNumber++;
455 }
456 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
Owen Anderson85c40642007-07-24 17:55:58 +0000457 Expression e = create_expression(BO);
458
459 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
460 if (EI != expressionNumbering.end()) {
461 valueNumbering.insert(std::make_pair(V, EI->second));
462 return EI->second;
463 } else {
464 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
465 valueNumbering.insert(std::make_pair(V, nextValueNumber));
466
467 return nextValueNumber++;
468 }
469 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
470 Expression e = create_expression(C);
471
472 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
473 if (EI != expressionNumbering.end()) {
474 valueNumbering.insert(std::make_pair(V, EI->second));
475 return EI->second;
476 } else {
477 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
478 valueNumbering.insert(std::make_pair(V, nextValueNumber));
479
480 return nextValueNumber++;
481 }
482 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
483 Expression e = create_expression(U);
484
485 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
486 if (EI != expressionNumbering.end()) {
487 valueNumbering.insert(std::make_pair(V, EI->second));
488 return EI->second;
489 } else {
490 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
491 valueNumbering.insert(std::make_pair(V, nextValueNumber));
492
493 return nextValueNumber++;
494 }
495 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
496 Expression e = create_expression(U);
497
498 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
499 if (EI != expressionNumbering.end()) {
500 valueNumbering.insert(std::make_pair(V, EI->second));
501 return EI->second;
502 } else {
503 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
504 valueNumbering.insert(std::make_pair(V, nextValueNumber));
505
506 return nextValueNumber++;
507 }
508 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
509 Expression e = create_expression(U);
510
511 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
512 if (EI != expressionNumbering.end()) {
513 valueNumbering.insert(std::make_pair(V, EI->second));
514 return EI->second;
515 } else {
516 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
517 valueNumbering.insert(std::make_pair(V, nextValueNumber));
518
519 return nextValueNumber++;
520 }
521 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
522 Expression e = create_expression(U);
523
524 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
525 if (EI != expressionNumbering.end()) {
526 valueNumbering.insert(std::make_pair(V, EI->second));
527 return EI->second;
528 } else {
529 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
530 valueNumbering.insert(std::make_pair(V, nextValueNumber));
531
532 return nextValueNumber++;
533 }
534 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
535 Expression e = create_expression(U);
536
537 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
538 if (EI != expressionNumbering.end()) {
539 valueNumbering.insert(std::make_pair(V, EI->second));
540 return EI->second;
541 } else {
542 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
543 valueNumbering.insert(std::make_pair(V, nextValueNumber));
544
545 return nextValueNumber++;
546 }
547 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
548 Expression e = create_expression(U);
549
550 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
551 if (EI != expressionNumbering.end()) {
552 valueNumbering.insert(std::make_pair(V, EI->second));
553 return EI->second;
554 } else {
555 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
556 valueNumbering.insert(std::make_pair(V, nextValueNumber));
557
558 return nextValueNumber++;
559 }
560 } else {
561 valueNumbering.insert(std::make_pair(V, nextValueNumber));
562 return nextValueNumber++;
563 }
564}
565
566/// lookup - Returns the value number of the specified value. Fails if
567/// the value has not yet been numbered.
568uint32_t ValueTable::lookup(Value* V) const {
569 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
Chris Lattner3d7103e2008-03-21 21:14:38 +0000570 assert(VI != valueNumbering.end() && "Value not numbered?");
571 return VI->second;
Owen Anderson85c40642007-07-24 17:55:58 +0000572}
573
574/// clear - Remove all entries from the ValueTable
575void ValueTable::clear() {
576 valueNumbering.clear();
577 expressionNumbering.clear();
578 nextValueNumber = 1;
579}
580
Owen Anderson5aff8002007-07-31 23:27:13 +0000581/// erase - Remove a value from the value numbering
582void ValueTable::erase(Value* V) {
583 valueNumbering.erase(V);
584}
585
Owen Anderson85c40642007-07-24 17:55:58 +0000586//===----------------------------------------------------------------------===//
587// ValueNumberedSet Class
588//===----------------------------------------------------------------------===//
589namespace {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000590class VISIBILITY_HIDDEN ValueNumberedSet {
Owen Anderson85c40642007-07-24 17:55:58 +0000591 private:
592 SmallPtrSet<Value*, 8> contents;
Owen Anderson80033de2008-04-07 17:38:23 +0000593 SparseBitVector<64> numbers;
Owen Anderson85c40642007-07-24 17:55:58 +0000594 public:
Owen Anderson80033de2008-04-07 17:38:23 +0000595 ValueNumberedSet() { }
Owen Anderson85c40642007-07-24 17:55:58 +0000596 ValueNumberedSet(const ValueNumberedSet& other) {
597 numbers = other.numbers;
598 contents = other.contents;
599 }
600
601 typedef SmallPtrSet<Value*, 8>::iterator iterator;
602
603 iterator begin() { return contents.begin(); }
604 iterator end() { return contents.end(); }
605
606 bool insert(Value* v) { return contents.insert(v); }
607 void insert(iterator I, iterator E) { contents.insert(I, E); }
608 void erase(Value* v) { contents.erase(v); }
609 unsigned count(Value* v) { return contents.count(v); }
610 size_t size() { return contents.size(); }
611
612 void set(unsigned i) {
Owen Anderson85c40642007-07-24 17:55:58 +0000613 numbers.set(i);
614 }
615
616 void operator=(const ValueNumberedSet& other) {
617 contents = other.contents;
618 numbers = other.numbers;
619 }
620
621 void reset(unsigned i) {
Owen Anderson80033de2008-04-07 17:38:23 +0000622 numbers.reset(i);
Owen Anderson85c40642007-07-24 17:55:58 +0000623 }
624
625 bool test(unsigned i) {
Owen Anderson85c40642007-07-24 17:55:58 +0000626 return numbers.test(i);
627 }
Owen Anderson85c40642007-07-24 17:55:58 +0000628};
629}
630
631//===----------------------------------------------------------------------===//
632// GVN Pass
633//===----------------------------------------------------------------------===//
634
635namespace {
636
637 class VISIBILITY_HIDDEN GVN : public FunctionPass {
638 bool runOnFunction(Function &F);
639 public:
640 static char ID; // Pass identification, replacement for typeid
641 GVN() : FunctionPass((intptr_t)&ID) { }
642
643 private:
644 ValueTable VN;
645
646 DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
647
Owen Anderson5b299672007-08-07 23:12:31 +0000648 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
649 PhiMapType phiMap;
650
651
Owen Anderson85c40642007-07-24 17:55:58 +0000652 // This transformation requires dominator postdominator info
653 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
654 AU.setPreservesCFG();
655 AU.addRequired<DominatorTree>();
656 AU.addRequired<MemoryDependenceAnalysis>();
Owen Anderson5e9366f2007-10-18 19:39:33 +0000657 AU.addRequired<AliasAnalysis>();
Owen Anderson29f73562008-02-19 06:35:43 +0000658 AU.addRequired<TargetData>();
Owen Anderson5e9366f2007-10-18 19:39:33 +0000659 AU.addPreserved<AliasAnalysis>();
Owen Anderson85c40642007-07-24 17:55:58 +0000660 AU.addPreserved<MemoryDependenceAnalysis>();
Owen Anderson29f73562008-02-19 06:35:43 +0000661 AU.addPreserved<TargetData>();
Owen Anderson85c40642007-07-24 17:55:58 +0000662 }
663
664 // Helper fuctions
665 // FIXME: eliminate or document these better
666 Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
667 void val_insert(ValueNumberedSet& s, Value* v);
668 bool processLoad(LoadInst* L,
Chris Lattner7de20452008-03-21 22:01:16 +0000669 DenseMap<Value*, LoadInst*> &lastLoad,
670 SmallVectorImpl<Instruction*> &toErase);
Chris Lattner248ba4d2008-03-22 00:31:52 +0000671 bool processStore(StoreInst *SI, SmallVectorImpl<Instruction*> &toErase);
Owen Anderson85c40642007-07-24 17:55:58 +0000672 bool processInstruction(Instruction* I,
673 ValueNumberedSet& currAvail,
674 DenseMap<Value*, LoadInst*>& lastSeenLoad,
Chris Lattner7de20452008-03-21 22:01:16 +0000675 SmallVectorImpl<Instruction*> &toErase);
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000676 bool processNonLocalLoad(LoadInst* L,
Chris Lattner7de20452008-03-21 22:01:16 +0000677 SmallVectorImpl<Instruction*> &toErase);
Owen Andersonba958332008-02-19 03:09:45 +0000678 bool processMemCpy(MemCpyInst* M, MemCpyInst* MDep,
Chris Lattner7de20452008-03-21 22:01:16 +0000679 SmallVectorImpl<Instruction*> &toErase);
Owen Andersone41ab4c2008-03-12 07:37:44 +0000680 bool performCallSlotOptzn(MemCpyInst* cpy, CallInst* C,
Chris Lattner7de20452008-03-21 22:01:16 +0000681 SmallVectorImpl<Instruction*> &toErase);
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000682 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
Owen Andersonc6a31b92007-08-02 17:56:05 +0000683 DenseMap<BasicBlock*, Value*> &Phis,
684 bool top_level = false);
Owen Anderson5d72a422007-07-25 19:57:03 +0000685 void dump(DenseMap<BasicBlock*, Value*>& d);
Owen Andersonbe168b32007-08-14 18:04:11 +0000686 bool iterateOnFunction(Function &F);
Owen Andersone02ad522007-08-16 22:51:56 +0000687 Value* CollapsePhi(PHINode* p);
Owen Anderson19625972007-09-16 08:04:16 +0000688 bool isSafeReplacement(PHINode* p, Instruction* inst);
Owen Anderson85c40642007-07-24 17:55:58 +0000689 };
690
691 char GVN::ID = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000692}
693
694// createGVNPass - The public interface to this file...
695FunctionPass *llvm::createGVNPass() { return new GVN(); }
696
697static RegisterPass<GVN> X("gvn",
698 "Global Value Numbering");
699
Owen Anderson85c40642007-07-24 17:55:58 +0000700/// find_leader - Given a set and a value number, return the first
701/// element of the set with that value number, or 0 if no such element
702/// is present
703Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
704 if (!vals.test(v))
705 return 0;
706
707 for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
708 I != E; ++I)
709 if (v == VN.lookup(*I))
710 return *I;
711
712 assert(0 && "No leader found, but present bit is set?");
713 return 0;
714}
715
716/// val_insert - Insert a value into a set only if there is not a value
717/// with the same value number already in the set
718void GVN::val_insert(ValueNumberedSet& s, Value* v) {
719 uint32_t num = VN.lookup(v);
720 if (!s.test(num))
721 s.insert(v);
722}
723
Owen Anderson5d72a422007-07-25 19:57:03 +0000724void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
725 printf("{\n");
726 for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
727 E = d.end(); I != E; ++I) {
728 if (I->second == MemoryDependenceAnalysis::None)
729 printf("None\n");
730 else
731 I->second->dump();
732 }
733 printf("}\n");
734}
735
Owen Andersone02ad522007-08-16 22:51:56 +0000736Value* GVN::CollapsePhi(PHINode* p) {
737 DominatorTree &DT = getAnalysis<DominatorTree>();
738 Value* constVal = p->hasConstantValue();
739
Chris Lattner3d7103e2008-03-21 21:14:38 +0000740 if (!constVal) return 0;
Owen Andersone02ad522007-08-16 22:51:56 +0000741
Chris Lattner3d7103e2008-03-21 21:14:38 +0000742 Instruction* inst = dyn_cast<Instruction>(constVal);
743 if (!inst)
744 return constVal;
745
746 if (DT.dominates(inst, p))
747 if (isSafeReplacement(p, inst))
748 return inst;
Owen Andersone02ad522007-08-16 22:51:56 +0000749 return 0;
750}
Owen Anderson5d72a422007-07-25 19:57:03 +0000751
Owen Anderson19625972007-09-16 08:04:16 +0000752bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
753 if (!isa<PHINode>(inst))
754 return true;
755
756 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
757 UI != E; ++UI)
758 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
759 if (use_phi->getParent() == inst->getParent())
760 return false;
761
762 return true;
763}
764
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000765/// GetValueForBlock - Get the value to use within the specified basic block.
766/// available values are in Phis.
767Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
Chris Lattner3d7103e2008-03-21 21:14:38 +0000768 DenseMap<BasicBlock*, Value*> &Phis,
769 bool top_level) {
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000770
771 // If we have already computed this value, return the previously computed val.
Owen Andersoned7f9932007-08-03 19:59:35 +0000772 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
773 if (V != Phis.end() && !top_level) return V->second;
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000774
Owen Anderson3f75d122007-08-01 22:01:54 +0000775 BasicBlock* singlePred = BB->getSinglePredecessor();
Owen Anderson30463f12007-08-03 11:03:26 +0000776 if (singlePred) {
Owen Andersoned7f9932007-08-03 19:59:35 +0000777 Value *ret = GetValueForBlock(singlePred, orig, Phis);
778 Phis[BB] = ret;
779 return ret;
Owen Anderson30463f12007-08-03 11:03:26 +0000780 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000781
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000782 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
783 // now, then get values to fill in the incoming values for the PHI.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000784 PHINode *PN = PHINode::Create(orig->getType(), orig->getName()+".rle",
785 BB->begin());
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000786 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
Owen Andersoned7f9932007-08-03 19:59:35 +0000787
788 if (Phis.count(BB) == 0)
789 Phis.insert(std::make_pair(BB, PN));
Owen Anderson48a2c562007-07-30 16:57:08 +0000790
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000791 // Fill in the incoming values for the block.
Owen Anderson9f577412007-07-31 17:43:14 +0000792 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
793 Value* val = GetValueForBlock(*PI, orig, Phis);
Owen Anderson9f577412007-07-31 17:43:14 +0000794 PN->addIncoming(val, *PI);
795 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000796
Nick Lewycky8fba1d02008-02-14 07:11:24 +0000797 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
798 AA.copyValue(orig, PN);
Owen Anderson9f577412007-07-31 17:43:14 +0000799
Owen Andersone0143452007-08-16 22:02:55 +0000800 // Attempt to collapse PHI nodes that are trivially redundant
Owen Andersone02ad522007-08-16 22:51:56 +0000801 Value* v = CollapsePhi(PN);
Chris Lattner3d7103e2008-03-21 21:14:38 +0000802 if (!v) {
803 // Cache our phi construction results
804 phiMap[orig->getPointerOperand()].insert(PN);
805 return PN;
Owen Anderson9f577412007-07-31 17:43:14 +0000806 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000807
808 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
Owen Anderson9f577412007-07-31 17:43:14 +0000809
Chris Lattner3d7103e2008-03-21 21:14:38 +0000810 MD.removeInstruction(PN);
811 PN->replaceAllUsesWith(v);
812
813 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
814 E = Phis.end(); I != E; ++I)
815 if (I->second == PN)
816 I->second = v;
817
818 PN->eraseFromParent();
819
820 Phis[BB] = v;
821 return v;
Owen Anderson5d72a422007-07-25 19:57:03 +0000822}
823
Owen Andersone0143452007-08-16 22:02:55 +0000824/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
825/// non-local by performing PHI construction.
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000826bool GVN::processNonLocalLoad(LoadInst* L,
Chris Lattner7de20452008-03-21 22:01:16 +0000827 SmallVectorImpl<Instruction*> &toErase) {
Owen Anderson5d72a422007-07-25 19:57:03 +0000828 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
829
Owen Andersone0143452007-08-16 22:02:55 +0000830 // Find the non-local dependencies of the load
Owen Anderson5d72a422007-07-25 19:57:03 +0000831 DenseMap<BasicBlock*, Value*> deps;
Owen Anderson3f75d122007-08-01 22:01:54 +0000832 MD.getNonLocalDependency(L, deps);
Owen Anderson5d72a422007-07-25 19:57:03 +0000833
834 DenseMap<BasicBlock*, Value*> repl;
Owen Anderson5b299672007-08-07 23:12:31 +0000835
Owen Andersone0143452007-08-16 22:02:55 +0000836 // Filter out useless results (non-locals, etc)
Owen Anderson5d72a422007-07-25 19:57:03 +0000837 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
Chris Lattner3d7103e2008-03-21 21:14:38 +0000838 I != E; ++I) {
839 if (I->second == MemoryDependenceAnalysis::None)
Owen Anderson5d72a422007-07-25 19:57:03 +0000840 return false;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000841
842 if (I->second == MemoryDependenceAnalysis::NonLocal)
Owen Andersonb484d1f2007-07-30 17:29:24 +0000843 continue;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000844
845 if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
846 if (S->getPointerOperand() != L->getPointerOperand())
Owen Anderson5d72a422007-07-25 19:57:03 +0000847 return false;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000848 repl[I->first] = S->getOperand(0);
Owen Anderson5d72a422007-07-25 19:57:03 +0000849 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000850 if (LD->getPointerOperand() != L->getPointerOperand())
Owen Anderson5d72a422007-07-25 19:57:03 +0000851 return false;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000852 repl[I->first] = LD;
Owen Anderson5d72a422007-07-25 19:57:03 +0000853 } else {
854 return false;
855 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000856 }
Owen Anderson5d72a422007-07-25 19:57:03 +0000857
Owen Andersone0143452007-08-16 22:02:55 +0000858 // Use cached PHI construction information from previous runs
Owen Anderson5b299672007-08-07 23:12:31 +0000859 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
860 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
861 I != E; ++I) {
862 if ((*I)->getParent() == L->getParent()) {
863 MD.removeInstruction(L);
864 L->replaceAllUsesWith(*I);
865 toErase.push_back(L);
866 NumGVNLoad++;
Owen Anderson5b299672007-08-07 23:12:31 +0000867 return true;
Owen Anderson5b299672007-08-07 23:12:31 +0000868 }
Chris Lattner3d7103e2008-03-21 21:14:38 +0000869
870 repl.insert(std::make_pair((*I)->getParent(), *I));
Owen Anderson5b299672007-08-07 23:12:31 +0000871 }
872
Owen Andersone0143452007-08-16 22:02:55 +0000873 // Perform PHI construction
Owen Anderson6ce3ae22007-07-25 22:03:06 +0000874 SmallPtrSet<BasicBlock*, 4> visited;
Owen Andersonc6a31b92007-08-02 17:56:05 +0000875 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
Owen Anderson5d72a422007-07-25 19:57:03 +0000876
877 MD.removeInstruction(L);
878 L->replaceAllUsesWith(v);
879 toErase.push_back(L);
Owen Anderson5b299672007-08-07 23:12:31 +0000880 NumGVNLoad++;
Owen Anderson5d72a422007-07-25 19:57:03 +0000881
882 return true;
883}
884
Owen Andersone0143452007-08-16 22:02:55 +0000885/// processLoad - Attempt to eliminate a load, first by eliminating it
886/// locally, and then attempting non-local elimination if that fails.
Chris Lattner7de20452008-03-21 22:01:16 +0000887bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
888 SmallVectorImpl<Instruction*> &toErase) {
Owen Anderson85c40642007-07-24 17:55:58 +0000889 if (L->isVolatile()) {
890 lastLoad[L->getPointerOperand()] = L;
891 return false;
892 }
893
894 Value* pointer = L->getPointerOperand();
895 LoadInst*& last = lastLoad[pointer];
896
897 // ... to a pointer that has been loaded from before...
898 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
Owen Andersoncc8b3a82007-08-14 17:59:48 +0000899 bool removedNonLocal = false;
Owen Anderson935e39b2007-08-09 04:42:44 +0000900 Instruction* dep = MD.getDependency(L);
Owen Anderson5d72a422007-07-25 19:57:03 +0000901 if (dep == MemoryDependenceAnalysis::NonLocal &&
Owen Andersoncc8b3a82007-08-14 17:59:48 +0000902 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
903 removedNonLocal = processNonLocalLoad(L, toErase);
904
905 if (!removedNonLocal)
906 last = L;
907
908 return removedNonLocal;
909 }
910
911
Owen Anderson85c40642007-07-24 17:55:58 +0000912 bool deletedLoad = false;
913
Owen Andersone0143452007-08-16 22:02:55 +0000914 // Walk up the dependency chain until we either find
915 // a dependency we can use, or we can't walk any further
Owen Anderson85c40642007-07-24 17:55:58 +0000916 while (dep != MemoryDependenceAnalysis::None &&
917 dep != MemoryDependenceAnalysis::NonLocal &&
918 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
919 // ... that depends on a store ...
920 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
921 if (S->getPointerOperand() == pointer) {
922 // Remove it!
923 MD.removeInstruction(L);
924
925 L->replaceAllUsesWith(S->getOperand(0));
926 toErase.push_back(L);
927 deletedLoad = true;
928 NumGVNLoad++;
929 }
930
931 // Whether we removed it or not, we can't
932 // go any further
933 break;
934 } else if (!last) {
935 // If we don't depend on a store, and we haven't
936 // been loaded before, bail.
937 break;
938 } else if (dep == last) {
939 // Remove it!
940 MD.removeInstruction(L);
941
942 L->replaceAllUsesWith(last);
943 toErase.push_back(L);
944 deletedLoad = true;
945 NumGVNLoad++;
946
947 break;
948 } else {
Owen Anderson935e39b2007-08-09 04:42:44 +0000949 dep = MD.getDependency(L, dep);
Owen Anderson85c40642007-07-24 17:55:58 +0000950 }
951 }
Eli Friedman350307f2008-02-12 12:08:14 +0000952
953 if (dep != MemoryDependenceAnalysis::None &&
954 dep != MemoryDependenceAnalysis::NonLocal &&
955 isa<AllocationInst>(dep)) {
956 // Check that this load is actually from the
957 // allocation we found
958 Value* v = L->getOperand(0);
959 while (true) {
960 if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
961 v = BC->getOperand(0);
962 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
963 v = GEP->getOperand(0);
964 else
965 break;
966 }
967 if (v == dep) {
968 // If this load depends directly on an allocation, there isn't
969 // anything stored there; therefore, we can optimize this load
970 // to undef.
971 MD.removeInstruction(L);
972
973 L->replaceAllUsesWith(UndefValue::get(L->getType()));
974 toErase.push_back(L);
975 deletedLoad = true;
976 NumGVNLoad++;
977 }
978 }
979
Owen Anderson85c40642007-07-24 17:55:58 +0000980 if (!deletedLoad)
981 last = L;
982
983 return deletedLoad;
984}
985
Chris Lattner248ba4d2008-03-22 00:31:52 +0000986/// isBytewiseValue - If the specified value can be set by repeating the same
987/// byte in memory, return the i8 value that it is represented with. This is
988/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
989/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
990/// byte store (e.g. i16 0x1234), return null.
991static Value *isBytewiseValue(Value *V) {
992 // All byte-wide stores are splatable, even of arbitrary variables.
993 if (V->getType() == Type::Int8Ty) return V;
994
995 // Constant float and double values can be handled as integer values if the
996 // corresponding integer value is "byteable". An important case is 0.0.
997 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
998 if (CFP->getType() == Type::FloatTy)
999 V = ConstantExpr::getBitCast(CFP, Type::Int32Ty);
1000 if (CFP->getType() == Type::DoubleTy)
1001 V = ConstantExpr::getBitCast(CFP, Type::Int64Ty);
1002 // Don't handle long double formats, which have strange constraints.
1003 }
1004
1005 // We can handle constant integers that are power of two in size and a
1006 // multiple of 8 bits.
1007 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1008 unsigned Width = CI->getBitWidth();
1009 if (isPowerOf2_32(Width) && Width > 8) {
1010 // We can handle this value if the recursive binary decomposition is the
1011 // same at all levels.
1012 APInt Val = CI->getValue();
1013 APInt Val2;
1014 while (Val.getBitWidth() != 8) {
1015 unsigned NextWidth = Val.getBitWidth()/2;
1016 Val2 = Val.lshr(NextWidth);
1017 Val2.trunc(Val.getBitWidth()/2);
1018 Val.trunc(Val.getBitWidth()/2);
1019
1020 // If the top/bottom halves aren't the same, reject it.
1021 if (Val != Val2)
1022 return 0;
1023 }
1024 return ConstantInt::get(Val);
1025 }
1026 }
1027
1028 // Conceptually, we could handle things like:
1029 // %a = zext i8 %X to i16
1030 // %b = shl i16 %a, 8
1031 // %c = or i16 %a, %b
1032 // but until there is an example that actually needs this, it doesn't seem
1033 // worth worrying about.
1034 return 0;
1035}
1036
Chris Lattner60b9cb42008-03-22 05:37:16 +00001037static int64_t GetOffsetFromIndex(const GetElementPtrInst *GEP, unsigned Idx,
1038 bool &VariableIdxFound, TargetData &TD) {
1039 // Skip over the first indices.
1040 gep_type_iterator GTI = gep_type_begin(GEP);
1041 for (unsigned i = 1; i != Idx; ++i, ++GTI)
1042 /*skip along*/;
1043
1044 // Compute the offset implied by the rest of the indices.
1045 int64_t Offset = 0;
1046 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
1047 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
1048 if (OpC == 0)
1049 return VariableIdxFound = true;
1050 if (OpC->isZero()) continue; // No offset.
1051
1052 // Handle struct indices, which add their field offset to the pointer.
1053 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1054 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1055 continue;
1056 }
1057
1058 // Otherwise, we have a sequential type like an array or vector. Multiply
1059 // the index by the ElementSize.
1060 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
1061 Offset += Size*OpC->getSExtValue();
1062 }
1063
1064 return Offset;
1065}
1066
Chris Lattner49650d62008-03-28 06:45:13 +00001067/// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
1068/// constant offset, and return that constant offset. For example, Ptr1 might
1069/// be &A[42], and Ptr2 might be &A[40]. In this case offset would be -8.
1070static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
1071 TargetData &TD) {
Chris Lattner60b9cb42008-03-22 05:37:16 +00001072 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
1073 // base. After that base, they may have some number of common (and
1074 // potentially variable) indices. After that they handle some constant
1075 // offset, which determines their offset from each other. At this point, we
1076 // handle no other case.
1077 GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
1078 GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
1079 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
1080 return false;
1081
1082 // Skip any common indices and track the GEP types.
1083 unsigned Idx = 1;
1084 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
1085 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
1086 break;
1087
1088 bool VariableIdxFound = false;
1089 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
1090 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
1091 if (VariableIdxFound) return false;
1092
Chris Lattner49650d62008-03-28 06:45:13 +00001093 Offset = Offset2-Offset1;
1094 return true;
Chris Lattner248ba4d2008-03-22 00:31:52 +00001095}
1096
1097
Chris Lattner49650d62008-03-28 06:45:13 +00001098/// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
1099/// This allows us to analyze stores like:
1100/// store 0 -> P+1
1101/// store 0 -> P+0
1102/// store 0 -> P+3
1103/// store 0 -> P+2
1104/// which sometimes happens with stores to arrays of structs etc. When we see
1105/// the first store, we make a range [1, 2). The second store extends the range
1106/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
1107/// two ranges into [0, 3) which is memset'able.
1108namespace {
1109struct MemsetRange {
1110 // Start/End - A semi range that describes the span that this range covers.
1111 // The range is closed at the start and open at the end: [Start, End).
1112 int64_t Start, End;
1113
1114 /// StartPtr - The getelementptr instruction that points to the start of the
1115 /// range.
1116 Value *StartPtr;
1117
1118 /// Alignment - The known alignment of the first store.
1119 unsigned Alignment;
1120
1121 /// TheStores - The actual stores that make up this range.
1122 SmallVector<StoreInst*, 16> TheStores;
Chris Lattner49650d62008-03-28 06:45:13 +00001123
Chris Lattner9c5be3c2008-03-29 04:36:18 +00001124 bool isProfitableToUseMemset(const TargetData &TD) const;
1125
1126};
1127} // end anon namespace
1128
1129bool MemsetRange::isProfitableToUseMemset(const TargetData &TD) const {
1130 // If we found more than 8 stores to merge or 64 bytes, use memset.
1131 if (TheStores.size() >= 8 || End-Start >= 64) return true;
1132
1133 // Assume that the code generator is capable of merging pairs of stores
1134 // together if it wants to.
1135 if (TheStores.size() <= 2) return false;
1136
1137 // If we have fewer than 8 stores, it can still be worthwhile to do this.
1138 // For example, merging 4 i8 stores into an i32 store is useful almost always.
1139 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
1140 // memset will be split into 2 32-bit stores anyway) and doing so can
1141 // pessimize the llvm optimizer.
1142 //
1143 // Since we don't have perfect knowledge here, make some assumptions: assume
1144 // the maximum GPR width is the same size as the pointer size and assume that
1145 // this width can be stored. If so, check to see whether we will end up
1146 // actually reducing the number of stores used.
1147 unsigned Bytes = unsigned(End-Start);
1148 unsigned NumPointerStores = Bytes/TD.getPointerSize();
1149
1150 // Assume the remaining bytes if any are done a byte at a time.
1151 unsigned NumByteStores = Bytes - NumPointerStores*TD.getPointerSize();
1152
1153 // If we will reduce the # stores (according to this heuristic), do the
1154 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
1155 // etc.
1156 return TheStores.size() > NumPointerStores+NumByteStores;
1157}
1158
1159
1160namespace {
Chris Lattner49650d62008-03-28 06:45:13 +00001161class MemsetRanges {
1162 /// Ranges - A sorted list of the memset ranges. We use std::list here
1163 /// because each element is relatively large and expensive to copy.
1164 std::list<MemsetRange> Ranges;
1165 typedef std::list<MemsetRange>::iterator range_iterator;
1166 TargetData &TD;
1167public:
1168 MemsetRanges(TargetData &td) : TD(td) {}
1169
1170 typedef std::list<MemsetRange>::const_iterator const_iterator;
1171 const_iterator begin() const { return Ranges.begin(); }
1172 const_iterator end() const { return Ranges.end(); }
Chris Lattner0802cb42008-03-29 04:52:12 +00001173 bool empty() const { return Ranges.empty(); }
Chris Lattner49650d62008-03-28 06:45:13 +00001174
1175 void addStore(int64_t OffsetFromFirst, StoreInst *SI);
1176};
1177
Chris Lattner9c5be3c2008-03-29 04:36:18 +00001178} // end anon namespace
1179
Chris Lattner49650d62008-03-28 06:45:13 +00001180
1181/// addStore - Add a new store to the MemsetRanges data structure. This adds a
1182/// new range for the specified store at the specified offset, merging into
1183/// existing ranges as appropriate.
1184void MemsetRanges::addStore(int64_t Start, StoreInst *SI) {
1185 int64_t End = Start+TD.getTypeStoreSize(SI->getOperand(0)->getType());
1186
1187 // Do a linear search of the ranges to see if this can be joined and/or to
1188 // find the insertion point in the list. We keep the ranges sorted for
1189 // simplicity here. This is a linear search of a linked list, which is ugly,
1190 // however the number of ranges is limited, so this won't get crazy slow.
1191 range_iterator I = Ranges.begin(), E = Ranges.end();
1192
1193 while (I != E && Start > I->End)
1194 ++I;
1195
1196 // We now know that I == E, in which case we didn't find anything to merge
1197 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
1198 // to insert a new range. Handle this now.
1199 if (I == E || End < I->Start) {
1200 MemsetRange &R = *Ranges.insert(I, MemsetRange());
1201 R.Start = Start;
1202 R.End = End;
1203 R.StartPtr = SI->getPointerOperand();
1204 R.Alignment = SI->getAlignment();
1205 R.TheStores.push_back(SI);
1206 return;
1207 }
1208
1209 // This store overlaps with I, add it.
1210 I->TheStores.push_back(SI);
1211
1212 // At this point, we may have an interval that completely contains our store.
1213 // If so, just add it to the interval and return.
1214 if (I->Start <= Start && I->End >= End)
1215 return;
1216
1217 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
1218 // but is not entirely contained within the range.
1219
1220 // See if the range extends the start of the range. In this case, it couldn't
1221 // possibly cause it to join the prior range, because otherwise we would have
1222 // stopped on *it*.
Chris Lattner3a3f49f2008-03-29 05:15:47 +00001223 if (Start < I->Start) {
Chris Lattner49650d62008-03-28 06:45:13 +00001224 I->Start = Start;
Chris Lattner3a3f49f2008-03-29 05:15:47 +00001225 I->StartPtr = SI->getPointerOperand();
1226 }
Chris Lattner49650d62008-03-28 06:45:13 +00001227
1228 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
1229 // is in or right at the end of I), and that End >= I->Start. Extend I out to
1230 // End.
1231 if (End > I->End) {
1232 I->End = End;
1233 range_iterator NextI = I;;
1234 while (++NextI != E && End >= NextI->Start) {
1235 // Merge the range in.
1236 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
1237 if (NextI->End > I->End)
1238 I->End = NextI->End;
1239 Ranges.erase(NextI);
1240 NextI = I;
1241 }
1242 }
1243}
1244
1245
1246
Chris Lattner248ba4d2008-03-22 00:31:52 +00001247/// processStore - When GVN is scanning forward over instructions, we look for
1248/// some other patterns to fold away. In particular, this looks for stores to
1249/// neighboring locations of memory. If it sees enough consequtive ones
1250/// (currently 4) it attempts to merge them together into a memcpy/memset.
1251bool GVN::processStore(StoreInst *SI, SmallVectorImpl<Instruction*> &toErase) {
Evan Chenge856f8e2008-03-24 05:28:38 +00001252 if (!FormMemSet) return false;
Chris Lattner248ba4d2008-03-22 00:31:52 +00001253 if (SI->isVolatile()) return false;
1254
1255 // There are two cases that are interesting for this code to handle: memcpy
1256 // and memset. Right now we only handle memset.
1257
1258 // Ensure that the value being stored is something that can be memset'able a
1259 // byte at a time like "0" or "-1" or any width, as well as things like
1260 // 0xA0A0A0A0 and 0.0.
1261 Value *ByteVal = isBytewiseValue(SI->getOperand(0));
1262 if (!ByteVal)
1263 return false;
1264
1265 TargetData &TD = getAnalysis<TargetData>();
1266 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
1267
Chris Lattner49650d62008-03-28 06:45:13 +00001268 // Okay, so we now have a single store that can be splatable. Scan to find
1269 // all subsequent stores of the same value to offset from the same pointer.
1270 // Join these together into ranges, so we can decide whether contiguous blocks
1271 // are stored.
1272 MemsetRanges Ranges(TD);
1273
Chris Lattner248ba4d2008-03-22 00:31:52 +00001274 Value *StartPtr = SI->getPointerOperand();
Chris Lattner248ba4d2008-03-22 00:31:52 +00001275
Chris Lattner60b9cb42008-03-22 05:37:16 +00001276 BasicBlock::iterator BI = SI;
Chris Lattner248ba4d2008-03-22 00:31:52 +00001277 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
1278 if (isa<CallInst>(BI) || isa<InvokeInst>(BI)) {
1279 // If the call is readnone, ignore it, otherwise bail out. We don't even
1280 // allow readonly here because we don't want something like:
1281 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
1282 if (AA.getModRefBehavior(CallSite::get(BI)) ==
1283 AliasAnalysis::DoesNotAccessMemory)
1284 continue;
Chris Lattner1be83222008-03-22 04:13:49 +00001285
1286 // TODO: If this is a memset, try to join it in.
1287
Chris Lattner248ba4d2008-03-22 00:31:52 +00001288 break;
1289 } else if (isa<VAArgInst>(BI) || isa<LoadInst>(BI))
1290 break;
1291
1292 // If this is a non-store instruction it is fine, ignore it.
1293 StoreInst *NextStore = dyn_cast<StoreInst>(BI);
1294 if (NextStore == 0) continue;
1295
1296 // If this is a store, see if we can merge it in.
1297 if (NextStore->isVolatile()) break;
1298
1299 // Check to see if this stored value is of the same byte-splattable value.
1300 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
1301 break;
Chris Lattner248ba4d2008-03-22 00:31:52 +00001302
Chris Lattner49650d62008-03-28 06:45:13 +00001303 // Check to see if this store is to a constant offset from the start ptr.
1304 int64_t Offset;
1305 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset, TD))
1306 break;
1307
1308 Ranges.addStore(Offset, NextStore);
Chris Lattner248ba4d2008-03-22 00:31:52 +00001309 }
Chris Lattner0802cb42008-03-29 04:52:12 +00001310
1311 // If we have no ranges, then we just had a single store with nothing that
1312 // could be merged in. This is a very common case of course.
1313 if (Ranges.empty())
1314 return false;
1315
1316 // If we had at least one store that could be merged in, add the starting
1317 // store as well. We try to avoid this unless there is at least something
1318 // interesting as a small compile-time optimization.
1319 Ranges.addStore(0, SI);
1320
Chris Lattner248ba4d2008-03-22 00:31:52 +00001321
Chris Lattner49650d62008-03-28 06:45:13 +00001322 Function *MemSetF = 0;
Chris Lattner248ba4d2008-03-22 00:31:52 +00001323
Chris Lattner49650d62008-03-28 06:45:13 +00001324 // Now that we have full information about ranges, loop over the ranges and
1325 // emit memset's for anything big enough to be worthwhile.
1326 bool MadeChange = false;
1327 for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
1328 I != E; ++I) {
1329 const MemsetRange &Range = *I;
1330
Chris Lattner9c5be3c2008-03-29 04:36:18 +00001331 if (Range.TheStores.size() == 1) continue;
1332
1333 // If it is profitable to lower this range to memset, do so now.
1334 if (!Range.isProfitableToUseMemset(TD))
Chris Lattner49650d62008-03-28 06:45:13 +00001335 continue;
1336
1337 // Otherwise, we do want to transform this! Create a new memset. We put
Chris Lattner3a3f49f2008-03-29 05:15:47 +00001338 // the memset right before the first instruction that isn't part of this
1339 // memset block. This ensure that the memset is dominated by any addressing
1340 // instruction needed by the start of the block.
1341 BasicBlock::iterator InsertPt = BI;
Chris Lattner248ba4d2008-03-22 00:31:52 +00001342
Chris Lattner49650d62008-03-28 06:45:13 +00001343 if (MemSetF == 0)
1344 MemSetF = Intrinsic::getDeclaration(SI->getParent()->getParent()
Chris Lattner1be83222008-03-22 04:13:49 +00001345 ->getParent(), Intrinsic::memset_i64);
Chris Lattner49650d62008-03-28 06:45:13 +00001346
Chris Lattner3a3f49f2008-03-29 05:15:47 +00001347 // Get the starting pointer of the block.
1348 StartPtr = Range.StartPtr;
Chris Lattner1be83222008-03-22 04:13:49 +00001349
Chris Lattner49650d62008-03-28 06:45:13 +00001350 // Cast the start ptr to be i8* as memset requires.
1351 const Type *i8Ptr = PointerType::getUnqual(Type::Int8Ty);
1352 if (StartPtr->getType() != i8Ptr)
1353 StartPtr = new BitCastInst(StartPtr, i8Ptr, StartPtr->getNameStart(),
1354 InsertPt);
Chris Lattner1be83222008-03-22 04:13:49 +00001355
Chris Lattner49650d62008-03-28 06:45:13 +00001356 Value *Ops[] = {
1357 StartPtr, ByteVal, // Start, value
1358 ConstantInt::get(Type::Int64Ty, Range.End-Range.Start), // size
1359 ConstantInt::get(Type::Int32Ty, Range.Alignment) // align
1360 };
Gabor Greifd6da1d02008-04-06 20:25:17 +00001361 Value *C = CallInst::Create(MemSetF, Ops, Ops+4, "", InsertPt);
Chris Lattner9c5be3c2008-03-29 04:36:18 +00001362 DEBUG(cerr << "Replace stores:\n";
1363 for (unsigned i = 0, e = Range.TheStores.size(); i != e; ++i)
1364 cerr << *Range.TheStores[i];
1365 cerr << "With: " << *C); C=C;
Chris Lattner1be83222008-03-22 04:13:49 +00001366
Chris Lattner49650d62008-03-28 06:45:13 +00001367 // Zap all the stores.
1368 toErase.append(Range.TheStores.begin(), Range.TheStores.end());
1369 ++NumMemSetInfer;
1370 MadeChange = true;
1371 }
Chris Lattner1be83222008-03-22 04:13:49 +00001372
Chris Lattner49650d62008-03-28 06:45:13 +00001373 return MadeChange;
Chris Lattner248ba4d2008-03-22 00:31:52 +00001374}
1375
1376
Owen Andersone41ab4c2008-03-12 07:37:44 +00001377/// performCallSlotOptzn - takes a memcpy and a call that it depends on,
1378/// and checks for the possibility of a call slot optimization by having
1379/// the call write its result directly into the destination of the memcpy.
Chris Lattner7de20452008-03-21 22:01:16 +00001380bool GVN::performCallSlotOptzn(MemCpyInst *cpy, CallInst *C,
1381 SmallVectorImpl<Instruction*> &toErase) {
Owen Andersone41ab4c2008-03-12 07:37:44 +00001382 // The general transformation to keep in mind is
1383 //
1384 // call @func(..., src, ...)
1385 // memcpy(dest, src, ...)
1386 //
1387 // ->
1388 //
1389 // memcpy(dest, src, ...)
1390 // call @func(..., dest, ...)
1391 //
1392 // Since moving the memcpy is technically awkward, we additionally check that
1393 // src only holds uninitialized values at the moment of the call, meaning that
1394 // the memcpy can be discarded rather than moved.
Owen Anderson556d0e52008-02-19 03:27:34 +00001395
Owen Anderson364b1eb2008-02-19 07:07:51 +00001396 // Deliberately get the source and destination with bitcasts stripped away,
1397 // because we'll need to do type comparisons based on the underlying type.
Owen Anderson282dd322008-02-18 09:24:53 +00001398 Value* cpyDest = cpy->getDest();
Owen Anderson29f73562008-02-19 06:35:43 +00001399 Value* cpySrc = cpy->getSource();
1400 CallSite CS = CallSite::get(C);
Owen Andersone41ab4c2008-03-12 07:37:44 +00001401
1402 // We need to be able to reason about the size of the memcpy, so we require
1403 // that it be a constant.
1404 ConstantInt* cpyLength = dyn_cast<ConstantInt>(cpy->getLength());
1405 if (!cpyLength)
Owen Anderson282dd322008-02-18 09:24:53 +00001406 return false;
Owen Andersone41ab4c2008-03-12 07:37:44 +00001407
1408 // Require that src be an alloca. This simplifies the reasoning considerably.
1409 AllocaInst* srcAlloca = dyn_cast<AllocaInst>(cpySrc);
1410 if (!srcAlloca)
1411 return false;
1412
1413 // Check that all of src is copied to dest.
1414 TargetData& TD = getAnalysis<TargetData>();
1415
1416 ConstantInt* srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
1417 if (!srcArraySize)
1418 return false;
1419
1420 uint64_t srcSize = TD.getABITypeSize(srcAlloca->getAllocatedType()) *
1421 srcArraySize->getZExtValue();
1422
1423 if (cpyLength->getZExtValue() < srcSize)
1424 return false;
1425
1426 // Check that accessing the first srcSize bytes of dest will not cause a
1427 // trap. Otherwise the transform is invalid since it might cause a trap
1428 // to occur earlier than it otherwise would.
1429 if (AllocaInst* A = dyn_cast<AllocaInst>(cpyDest)) {
1430 // The destination is an alloca. Check it is larger than srcSize.
1431 ConstantInt* destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
1432 if (!destArraySize)
1433 return false;
1434
1435 uint64_t destSize = TD.getABITypeSize(A->getAllocatedType()) *
1436 destArraySize->getZExtValue();
1437
1438 if (destSize < srcSize)
1439 return false;
1440 } else if (Argument* A = dyn_cast<Argument>(cpyDest)) {
1441 // If the destination is an sret parameter then only accesses that are
1442 // outside of the returned struct type can trap.
1443 if (!A->hasStructRetAttr())
1444 return false;
1445
1446 const Type* StructTy = cast<PointerType>(A->getType())->getElementType();
1447 uint64_t destSize = TD.getABITypeSize(StructTy);
1448
1449 if (destSize < srcSize)
1450 return false;
1451 } else {
1452 return false;
1453 }
1454
1455 // Check that src is not accessed except via the call and the memcpy. This
1456 // guarantees that it holds only undefined values when passed in (so the final
1457 // memcpy can be dropped), that it is not read or written between the call and
1458 // the memcpy, and that writing beyond the end of it is undefined.
Owen Andersone41ab4c2008-03-12 07:37:44 +00001459 SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
1460 srcAlloca->use_end());
1461 while (!srcUseList.empty()) {
1462 User* UI = srcUseList.back();
1463 srcUseList.pop_back();
1464
1465 if (isa<GetElementPtrInst>(UI) || isa<BitCastInst>(UI)) {
1466 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
1467 I != E; ++I)
1468 srcUseList.push_back(*I);
1469 } else if (UI != C && UI != cpy) {
1470 return false;
1471 }
1472 }
1473
Owen Anderson05744bd2008-02-25 00:40:41 +00001474 // Since we're changing the parameter to the callsite, we need to make sure
1475 // that what would be the new parameter dominates the callsite.
1476 DominatorTree& DT = getAnalysis<DominatorTree>();
1477 if (Instruction* cpyDestInst = dyn_cast<Instruction>(cpyDest))
1478 if (!DT.dominates(cpyDestInst, C))
1479 return false;
Owen Andersone41ab4c2008-03-12 07:37:44 +00001480
1481 // In addition to knowing that the call does not access src in some
1482 // unexpected manner, for example via a global, which we deduce from
1483 // the use analysis, we also need to know that it does not sneakily
1484 // access dest. We rely on AA to figure this out for us.
Owen Anderson29f73562008-02-19 06:35:43 +00001485 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
Owen Andersone41ab4c2008-03-12 07:37:44 +00001486 if (AA.getModRefInfo(C, cpy->getRawDest(), srcSize) !=
Owen Anderson29f73562008-02-19 06:35:43 +00001487 AliasAnalysis::NoModRef)
1488 return false;
Owen Andersone41ab4c2008-03-12 07:37:44 +00001489
1490 // All the checks have passed, so do the transformation.
1491 for (unsigned i = 0; i < CS.arg_size(); ++i)
Owen Anderson78a334f2008-03-13 22:07:10 +00001492 if (CS.getArgument(i) == cpySrc) {
1493 if (cpySrc->getType() != cpyDest->getType())
1494 cpyDest = CastInst::createPointerCast(cpyDest, cpySrc->getType(),
1495 cpyDest->getName(), C);
Owen Andersone41ab4c2008-03-12 07:37:44 +00001496 CS.setArgument(i, cpyDest);
Owen Anderson78a334f2008-03-13 22:07:10 +00001497 }
Owen Andersone41ab4c2008-03-12 07:37:44 +00001498
Owen Anderson29f73562008-02-19 06:35:43 +00001499 // Drop any cached information about the call, because we may have changed
1500 // its dependence information by changing its parameter.
Owen Anderson282dd322008-02-18 09:24:53 +00001501 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1502 MD.dropInstruction(C);
Owen Andersone41ab4c2008-03-12 07:37:44 +00001503
Owen Anderson282dd322008-02-18 09:24:53 +00001504 // Remove the memcpy
Owen Andersonff8e2d32008-02-20 08:23:02 +00001505 MD.removeInstruction(cpy);
Owen Anderson282dd322008-02-18 09:24:53 +00001506 toErase.push_back(cpy);
Owen Andersone41ab4c2008-03-12 07:37:44 +00001507
Owen Anderson282dd322008-02-18 09:24:53 +00001508 return true;
1509}
1510
Owen Anderson8d272d52008-02-12 21:15:18 +00001511/// processMemCpy - perform simplication of memcpy's. If we have memcpy A which
1512/// copies X to Y, and memcpy B which copies Y to Z, then we can rewrite B to be
1513/// a memcpy from X to Z (or potentially a memmove, depending on circumstances).
1514/// This allows later passes to remove the first memcpy altogether.
Owen Andersonba958332008-02-19 03:09:45 +00001515bool GVN::processMemCpy(MemCpyInst* M, MemCpyInst* MDep,
Chris Lattner7de20452008-03-21 22:01:16 +00001516 SmallVectorImpl<Instruction*> &toErase) {
Owen Anderson8d272d52008-02-12 21:15:18 +00001517 // We can only transforms memcpy's where the dest of one is the source of the
1518 // other
Owen Anderson8d272d52008-02-12 21:15:18 +00001519 if (M->getSource() != MDep->getDest())
1520 return false;
1521
1522 // Second, the length of the memcpy's must be the same, or the preceeding one
1523 // must be larger than the following one.
1524 ConstantInt* C1 = dyn_cast<ConstantInt>(MDep->getLength());
1525 ConstantInt* C2 = dyn_cast<ConstantInt>(M->getLength());
1526 if (!C1 || !C2)
1527 return false;
1528
Owen Andersonc318b562008-02-26 23:06:17 +00001529 uint64_t DepSize = C1->getValue().getZExtValue();
1530 uint64_t CpySize = C2->getValue().getZExtValue();
Owen Anderson8d272d52008-02-12 21:15:18 +00001531
1532 if (DepSize < CpySize)
1533 return false;
1534
1535 // Finally, we have to make sure that the dest of the second does not
1536 // alias the source of the first
1537 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1538 if (AA.alias(M->getRawDest(), CpySize, MDep->getRawSource(), DepSize) !=
1539 AliasAnalysis::NoAlias)
1540 return false;
1541 else if (AA.alias(M->getRawDest(), CpySize, M->getRawSource(), CpySize) !=
1542 AliasAnalysis::NoAlias)
1543 return false;
1544 else if (AA.alias(MDep->getRawDest(), DepSize, MDep->getRawSource(), DepSize)
1545 != AliasAnalysis::NoAlias)
1546 return false;
1547
1548 // If all checks passed, then we can transform these memcpy's
Owen Andersonba958332008-02-19 03:09:45 +00001549 Function* MemCpyFun = Intrinsic::getDeclaration(
Owen Anderson8d272d52008-02-12 21:15:18 +00001550 M->getParent()->getParent()->getParent(),
Owen Andersonba958332008-02-19 03:09:45 +00001551 M->getIntrinsicID());
Owen Anderson8d272d52008-02-12 21:15:18 +00001552
1553 std::vector<Value*> args;
1554 args.push_back(M->getRawDest());
1555 args.push_back(MDep->getRawSource());
1556 args.push_back(M->getLength());
1557 args.push_back(M->getAlignment());
1558
Gabor Greifd6da1d02008-04-06 20:25:17 +00001559 CallInst* C = CallInst::Create(MemCpyFun, args.begin(), args.end(), "", M);
Owen Anderson8d272d52008-02-12 21:15:18 +00001560
Owen Andersonba958332008-02-19 03:09:45 +00001561 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
Owen Anderson8d272d52008-02-12 21:15:18 +00001562 if (MD.getDependency(C) == MDep) {
1563 MD.dropInstruction(M);
1564 toErase.push_back(M);
1565 return true;
Owen Anderson8d272d52008-02-12 21:15:18 +00001566 }
Chris Lattner3d7103e2008-03-21 21:14:38 +00001567
1568 MD.removeInstruction(C);
1569 toErase.push_back(C);
1570 return false;
Owen Anderson8d272d52008-02-12 21:15:18 +00001571}
1572
Owen Andersonf631bb62007-08-14 18:16:29 +00001573/// processInstruction - When calculating availability, handle an instruction
Owen Anderson85c40642007-07-24 17:55:58 +00001574/// by inserting it into the appropriate sets
Chris Lattner7de20452008-03-21 22:01:16 +00001575bool GVN::processInstruction(Instruction *I, ValueNumberedSet &currAvail,
1576 DenseMap<Value*, LoadInst*> &lastSeenLoad,
1577 SmallVectorImpl<Instruction*> &toErase) {
1578 if (LoadInst* L = dyn_cast<LoadInst>(I))
Owen Anderson85c40642007-07-24 17:55:58 +00001579 return processLoad(L, lastSeenLoad, toErase);
Chris Lattner7de20452008-03-21 22:01:16 +00001580
Chris Lattner248ba4d2008-03-22 00:31:52 +00001581 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1582 return processStore(SI, toErase);
1583
Owen Andersonced50f82008-04-07 09:59:07 +00001584 // Allocations are always uniquely numbered, so we can save time and memory
1585 // by fast failing them.
1586 if (isa<AllocationInst>(I))
1587 return false;
1588
Owen Anderson80033de2008-04-07 17:38:23 +00001589 // Allocations are always unique, so don't bother value numbering them.
1590 if (isa<AllocationInst>(I))
1591 return false;
1592
Chris Lattner7de20452008-03-21 22:01:16 +00001593 if (MemCpyInst* M = dyn_cast<MemCpyInst>(I)) {
Owen Andersonba958332008-02-19 03:09:45 +00001594 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1595
1596 // The are two possible optimizations we can do for memcpy:
1597 // a) memcpy-memcpy xform which exposes redundance for DSE
Owen Andersone41ab4c2008-03-12 07:37:44 +00001598 // b) call-memcpy xform for return slot optimization
Owen Andersonba958332008-02-19 03:09:45 +00001599 Instruction* dep = MD.getDependency(M);
1600 if (dep == MemoryDependenceAnalysis::None ||
1601 dep == MemoryDependenceAnalysis::NonLocal)
1602 return false;
Chris Lattnerfd18dcd2008-02-19 06:53:20 +00001603 if (MemCpyInst *MemCpy = dyn_cast<MemCpyInst>(dep))
1604 return processMemCpy(M, MemCpy, toErase);
Chris Lattner8bc7a0d2008-02-19 06:52:38 +00001605 if (CallInst* C = dyn_cast<CallInst>(dep))
Owen Andersone41ab4c2008-03-12 07:37:44 +00001606 return performCallSlotOptzn(M, C, toErase);
Chris Lattner8bc7a0d2008-02-19 06:52:38 +00001607 return false;
Owen Anderson85c40642007-07-24 17:55:58 +00001608 }
1609
1610 unsigned num = VN.lookup_or_add(I);
1611
Owen Andersone0143452007-08-16 22:02:55 +00001612 // Collapse PHI nodes
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001613 if (PHINode* p = dyn_cast<PHINode>(I)) {
Owen Andersone02ad522007-08-16 22:51:56 +00001614 Value* constVal = CollapsePhi(p);
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001615
1616 if (constVal) {
Owen Andersone02ad522007-08-16 22:51:56 +00001617 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1618 PI != PE; ++PI)
1619 if (PI->second.count(p))
1620 PI->second.erase(p);
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001621
Owen Andersone02ad522007-08-16 22:51:56 +00001622 p->replaceAllUsesWith(constVal);
1623 toErase.push_back(p);
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001624 }
Owen Andersone0143452007-08-16 22:02:55 +00001625 // Perform value-number based elimination
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001626 } else if (currAvail.test(num)) {
Owen Anderson85c40642007-07-24 17:55:58 +00001627 Value* repl = find_leader(currAvail, num);
1628
Owen Anderson8b6f04e2007-11-26 02:26:36 +00001629 if (CallInst* CI = dyn_cast<CallInst>(I)) {
1630 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
Duncan Sands00b24b52007-12-01 07:51:45 +00001631 if (!AA.doesNotAccessMemory(CI)) {
Owen Anderson8b6f04e2007-11-26 02:26:36 +00001632 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
Owen Andersonfb3f6f22007-11-29 18:02:22 +00001633 if (cast<Instruction>(repl)->getParent() != CI->getParent() ||
1634 MD.getDependency(CI) != MD.getDependency(cast<CallInst>(repl))) {
Owen Anderson8b6f04e2007-11-26 02:26:36 +00001635 // There must be an intervening may-alias store, so nothing from
1636 // this point on will be able to be replaced with the preceding call
1637 currAvail.erase(repl);
1638 currAvail.insert(I);
1639
1640 return false;
1641 }
1642 }
1643 }
1644
Owen Andersonc772be72007-12-08 01:37:09 +00001645 // Remove it!
1646 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1647 MD.removeInstruction(I);
1648
Owen Anderson5aff8002007-07-31 23:27:13 +00001649 VN.erase(I);
Owen Anderson85c40642007-07-24 17:55:58 +00001650 I->replaceAllUsesWith(repl);
1651 toErase.push_back(I);
1652 return true;
1653 } else if (!I->isTerminator()) {
1654 currAvail.set(num);
1655 currAvail.insert(I);
1656 }
1657
1658 return false;
1659}
1660
1661// GVN::runOnFunction - This is the main transformation entry point for a
1662// function.
1663//
Owen Andersonbe168b32007-08-14 18:04:11 +00001664bool GVN::runOnFunction(Function& F) {
Owen Anderson5e9366f2007-10-18 19:39:33 +00001665 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1666
Owen Andersonbe168b32007-08-14 18:04:11 +00001667 bool changed = false;
1668 bool shouldContinue = true;
1669
1670 while (shouldContinue) {
1671 shouldContinue = iterateOnFunction(F);
1672 changed |= shouldContinue;
1673 }
1674
1675 return changed;
1676}
1677
1678
1679// GVN::iterateOnFunction - Executes one iteration of GVN
1680bool GVN::iterateOnFunction(Function &F) {
Owen Anderson85c40642007-07-24 17:55:58 +00001681 // Clean out global sets from any previous functions
1682 VN.clear();
1683 availableOut.clear();
Owen Anderson5b299672007-08-07 23:12:31 +00001684 phiMap.clear();
Owen Anderson85c40642007-07-24 17:55:58 +00001685
1686 bool changed_function = false;
1687
1688 DominatorTree &DT = getAnalysis<DominatorTree>();
1689
Chris Lattner3a3f49f2008-03-29 05:15:47 +00001690 SmallVector<Instruction*, 8> toErase;
Chris Lattner98054902008-03-21 21:33:23 +00001691 DenseMap<Value*, LoadInst*> lastSeenLoad;
Owen Andersonced50f82008-04-07 09:59:07 +00001692 DenseMap<DomTreeNode*, size_t> numChildrenVisited;
Chris Lattner98054902008-03-21 21:33:23 +00001693
Owen Anderson85c40642007-07-24 17:55:58 +00001694 // Top-down walk of the dominator tree
1695 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1696 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1697
1698 // Get the set to update for this block
1699 ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
Chris Lattner98054902008-03-21 21:33:23 +00001700 lastSeenLoad.clear();
1701
Owen Anderson85c40642007-07-24 17:55:58 +00001702 BasicBlock* BB = DI->getBlock();
1703
1704 // A block inherits AVAIL_OUT from its dominator
Owen Andersonced50f82008-04-07 09:59:07 +00001705 if (DI->getIDom() != 0) {
Owen Anderson85c40642007-07-24 17:55:58 +00001706 currAvail = availableOut[DI->getIDom()->getBlock()];
Owen Andersonced50f82008-04-07 09:59:07 +00001707
1708 numChildrenVisited[DI->getIDom()]++;
1709
1710 if (numChildrenVisited[DI->getIDom()] == DI->getIDom()->getNumChildren()) {
1711 availableOut.erase(DI->getIDom()->getBlock());
1712 numChildrenVisited.erase(DI->getIDom());
1713 }
1714 }
Owen Anderson85c40642007-07-24 17:55:58 +00001715
1716 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
Chris Lattner3a3f49f2008-03-29 05:15:47 +00001717 BI != BE;) {
Owen Andersonbf8a3eb2007-08-02 18:16:06 +00001718 changed_function |= processInstruction(BI, currAvail,
1719 lastSeenLoad, toErase);
Chris Lattner3a3f49f2008-03-29 05:15:47 +00001720 if (toErase.empty()) {
1721 ++BI;
1722 continue;
1723 }
Owen Anderson5d72a422007-07-25 19:57:03 +00001724
Chris Lattner3a3f49f2008-03-29 05:15:47 +00001725 // If we need some instructions deleted, do it now.
Owen Anderson5d72a422007-07-25 19:57:03 +00001726 NumGVNInstr += toErase.size();
1727
Chris Lattner3a3f49f2008-03-29 05:15:47 +00001728 // Avoid iterator invalidation.
1729 bool AtStart = BI == BB->begin();
1730 if (!AtStart)
1731 --BI;
Owen Andersonc772be72007-12-08 01:37:09 +00001732
Owen Anderson5d72a422007-07-25 19:57:03 +00001733 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
Chris Lattner3d7103e2008-03-21 21:14:38 +00001734 E = toErase.end(); I != E; ++I)
Owen Anderson5d72a422007-07-25 19:57:03 +00001735 (*I)->eraseFromParent();
Owen Andersonc772be72007-12-08 01:37:09 +00001736
Chris Lattner3a3f49f2008-03-29 05:15:47 +00001737 if (AtStart)
1738 BI = BB->begin();
1739 else
1740 ++BI;
1741
Owen Anderson5d72a422007-07-25 19:57:03 +00001742 toErase.clear();
Owen Anderson85c40642007-07-24 17:55:58 +00001743 }
1744 }
1745
Owen Anderson85c40642007-07-24 17:55:58 +00001746 return changed_function;
1747}