blob: bd5b02895ec306a1eee184bf7d2b32092a0cf651 [file] [log] [blame]
Chris Lattner159b98f2008-12-05 07:49:08 +00001//===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
Owen Anderson85c40642007-07-24 17:55:58 +00002//
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//
John Criswell6e0aa282009-03-10 15:04:53 +000013// Note that this pass does the value numbering itself; it does not use the
Matthijs Kooijman9aac1db2008-06-05 07:55:49 +000014// ValueNumbering analysis passes.
15//
Owen Anderson85c40642007-07-24 17:55:58 +000016//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "gvn"
Owen Anderson85c40642007-07-24 17:55:58 +000019#include "llvm/Transforms/Scalar.h"
Owen Anderson5d72a422007-07-25 19:57:03 +000020#include "llvm/BasicBlock.h"
Owen Andersonacfa3ad2007-07-26 18:26:51 +000021#include "llvm/Constants.h"
Owen Anderson85c40642007-07-24 17:55:58 +000022#include "llvm/DerivedTypes.h"
Owen Andersonacfa3ad2007-07-26 18:26:51 +000023#include "llvm/Function.h"
Devang Patela7379552009-03-06 02:59:27 +000024#include "llvm/IntrinsicInst.h"
Owen Anderson24be4c12009-07-03 00:17:18 +000025#include "llvm/LLVMContext.h"
Chris Lattner0907b522009-09-21 05:57:11 +000026#include "llvm/Operator.h"
Owen Andersonacfa3ad2007-07-26 18:26:51 +000027#include "llvm/Value.h"
Owen Anderson85c40642007-07-24 17:55:58 +000028#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/DepthFirstIterator.h"
Owen Andersona03e7862008-12-15 02:03:00 +000030#include "llvm/ADT/PostOrderIterator.h"
Owen Anderson85c40642007-07-24 17:55:58 +000031#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/Statistic.h"
Owen Anderson5e9366f2007-10-18 19:39:33 +000034#include "llvm/Analysis/Dominators.h"
35#include "llvm/Analysis/AliasAnalysis.h"
Victor Hernandez48c3c542009-09-18 22:35:49 +000036#include "llvm/Analysis/MallocHelper.h"
Owen Anderson85c40642007-07-24 17:55:58 +000037#include "llvm/Analysis/MemoryDependenceAnalysis.h"
38#include "llvm/Support/CFG.h"
Owen Andersona2bf7662008-06-19 19:57:25 +000039#include "llvm/Support/CommandLine.h"
Chris Lattner9c5be3c2008-03-29 04:36:18 +000040#include "llvm/Support/Debug.h"
Edwin Török675d5622009-07-11 20:10:48 +000041#include "llvm/Support/ErrorHandling.h"
Chris Lattner0907b522009-09-21 05:57:11 +000042#include "llvm/Support/GetElementPtrTypeIterator.h"
Daniel Dunbar005975c2009-07-25 00:23:56 +000043#include "llvm/Support/raw_ostream.h"
Chris Lattner7741aa52009-09-20 19:03:47 +000044#include "llvm/Target/TargetData.h"
Owen Andersonec747c42008-06-19 19:54:19 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dale Johannesena19b67f2009-06-17 20:48:23 +000046#include "llvm/Transforms/Utils/Local.h"
Duncan Sands05f68372008-10-08 07:23:46 +000047#include <cstdio>
Owen Anderson85c40642007-07-24 17:55:58 +000048using namespace llvm;
49
Bill Wendling3858cae2008-12-22 22:14:07 +000050STATISTIC(NumGVNInstr, "Number of instructions deleted");
51STATISTIC(NumGVNLoad, "Number of loads deleted");
52STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
Owen Anderson7558f202008-07-15 16:28:06 +000053STATISTIC(NumGVNBlocks, "Number of blocks merged");
Bill Wendling3858cae2008-12-22 22:14:07 +000054STATISTIC(NumPRELoad, "Number of loads PRE'd");
Chris Lattner1be83222008-03-22 04:13:49 +000055
Evan Cheng019a2e12008-06-20 01:01:07 +000056static cl::opt<bool> EnablePRE("enable-pre",
Owen Anderson3a053612008-07-17 19:41:00 +000057 cl::init(true), cl::Hidden);
Dan Gohman828f89f2009-06-15 18:30:15 +000058static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
Owen Andersona2bf7662008-06-19 19:57:25 +000059
Owen Anderson85c40642007-07-24 17:55:58 +000060//===----------------------------------------------------------------------===//
61// ValueTable Class
62//===----------------------------------------------------------------------===//
63
64/// This class holds the mapping between values and value numbers. It is used
65/// as an efficient mechanism to determine the expression-wise equivalence of
66/// two values.
67namespace {
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +000068 struct Expression {
Dan Gohman7ce405e2009-06-04 22:49:04 +000069 enum ExpressionOpcode { ADD, FADD, SUB, FSUB, MUL, FMUL,
70 UDIV, SDIV, FDIV, UREM, SREM,
Daniel Dunbar3be44e62009-09-20 02:20:51 +000071 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
72 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
73 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
74 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
75 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
Owen Anderson85c40642007-07-24 17:55:58 +000076 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
77 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
Daniel Dunbar3be44e62009-09-20 02:20:51 +000078 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
Owen Anderson771d1122008-05-13 08:17:22 +000079 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
Owen Andersonb0cc5ed2008-06-19 17:25:39 +000080 EMPTY, TOMBSTONE };
Owen Anderson85c40642007-07-24 17:55:58 +000081
82 ExpressionOpcode opcode;
83 const Type* type;
84 uint32_t firstVN;
85 uint32_t secondVN;
86 uint32_t thirdVN;
87 SmallVector<uint32_t, 4> varargs;
Chris Lattnerff36c952009-09-21 02:42:51 +000088 Value *function;
Daniel Dunbar3be44e62009-09-20 02:20:51 +000089
Owen Anderson85c40642007-07-24 17:55:58 +000090 Expression() { }
91 Expression(ExpressionOpcode o) : opcode(o) { }
Daniel Dunbar3be44e62009-09-20 02:20:51 +000092
Owen Anderson85c40642007-07-24 17:55:58 +000093 bool operator==(const Expression &other) const {
94 if (opcode != other.opcode)
95 return false;
96 else if (opcode == EMPTY || opcode == TOMBSTONE)
97 return true;
98 else if (type != other.type)
99 return false;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000100 else if (function != other.function)
101 return false;
Owen Anderson85c40642007-07-24 17:55:58 +0000102 else if (firstVN != other.firstVN)
103 return false;
104 else if (secondVN != other.secondVN)
105 return false;
106 else if (thirdVN != other.thirdVN)
107 return false;
108 else {
109 if (varargs.size() != other.varargs.size())
110 return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000111
Owen Anderson85c40642007-07-24 17:55:58 +0000112 for (size_t i = 0; i < varargs.size(); ++i)
113 if (varargs[i] != other.varargs[i])
114 return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000115
Owen Anderson85c40642007-07-24 17:55:58 +0000116 return true;
117 }
118 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000119
Owen Anderson85c40642007-07-24 17:55:58 +0000120 bool operator!=(const Expression &other) const {
Bill Wendling9b5d4b72008-12-22 22:16:31 +0000121 return !(*this == other);
Owen Anderson85c40642007-07-24 17:55:58 +0000122 }
123 };
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000124
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +0000125 class ValueTable {
Owen Anderson85c40642007-07-24 17:55:58 +0000126 private:
127 DenseMap<Value*, uint32_t> valueNumbering;
128 DenseMap<Expression, uint32_t> expressionNumbering;
Owen Andersonbcf2bd52008-05-12 20:15:55 +0000129 AliasAnalysis* AA;
130 MemoryDependenceAnalysis* MD;
131 DominatorTree* DT;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000132
Owen Anderson85c40642007-07-24 17:55:58 +0000133 uint32_t nextValueNumber;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000134
Owen Anderson85c40642007-07-24 17:55:58 +0000135 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 Anderson771d1122008-05-13 08:17:22 +0000147 Expression create_expression(Constant* C);
Owen Anderson85c40642007-07-24 17:55:58 +0000148 public:
Dan Gohman936a6522009-04-01 16:37:47 +0000149 ValueTable() : nextValueNumber(1) { }
Chris Lattnerff36c952009-09-21 02:42:51 +0000150 uint32_t lookup_or_add(Value *V);
151 uint32_t lookup(Value *V) const;
152 void add(Value *V, uint32_t num);
Owen Anderson85c40642007-07-24 17:55:58 +0000153 void clear();
Chris Lattnerff36c952009-09-21 02:42:51 +0000154 void erase(Value *v);
Owen Anderson85c40642007-07-24 17:55:58 +0000155 unsigned size();
Owen Andersonbcf2bd52008-05-12 20:15:55 +0000156 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
Chris Lattner02ca4422008-12-01 00:40:32 +0000157 AliasAnalysis *getAliasAnalysis() const { return AA; }
Owen Andersonbcf2bd52008-05-12 20:15:55 +0000158 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
159 void setDomTree(DominatorTree* D) { DT = D; }
Owen Anderson8a8d13c2008-07-03 17:44:33 +0000160 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
Bill Wendling2a023742008-12-22 21:36:08 +0000161 void verifyRemoved(const Value *) const;
Owen Anderson85c40642007-07-24 17:55:58 +0000162 };
163}
164
165namespace llvm {
Chris Lattner92eea072007-09-17 18:34:04 +0000166template <> struct DenseMapInfo<Expression> {
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000167 static inline Expression getEmptyKey() {
168 return Expression(Expression::EMPTY);
169 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000170
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000171 static inline Expression getTombstoneKey() {
172 return Expression(Expression::TOMBSTONE);
173 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000174
Owen Anderson85c40642007-07-24 17:55:58 +0000175 static unsigned getHashValue(const Expression e) {
176 unsigned hash = e.opcode;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000177
Owen Anderson85c40642007-07-24 17:55:58 +0000178 hash = e.firstVN + hash * 37;
179 hash = e.secondVN + hash * 37;
180 hash = e.thirdVN + hash * 37;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000181
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000182 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
183 (unsigned)((uintptr_t)e.type >> 9)) +
184 hash * 37;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000185
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000186 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
187 E = e.varargs.end(); I != E; ++I)
Owen Anderson85c40642007-07-24 17:55:58 +0000188 hash = *I + hash * 37;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000189
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000190 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
191 (unsigned)((uintptr_t)e.function >> 9)) +
192 hash * 37;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000193
Owen Anderson85c40642007-07-24 17:55:58 +0000194 return hash;
195 }
Chris Lattner92eea072007-09-17 18:34:04 +0000196 static bool isEqual(const Expression &LHS, const Expression &RHS) {
197 return LHS == RHS;
198 }
Owen Anderson85c40642007-07-24 17:55:58 +0000199 static bool isPod() { return true; }
200};
201}
202
203//===----------------------------------------------------------------------===//
204// ValueTable Internal Functions
205//===----------------------------------------------------------------------===//
Chris Lattner3d7103e2008-03-21 21:14:38 +0000206Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
Owen Anderson85c40642007-07-24 17:55:58 +0000207 switch(BO->getOpcode()) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000208 default: // THIS SHOULD NEVER HAPPEN
Edwin Törökbd448e32009-07-14 16:55:14 +0000209 llvm_unreachable("Binary operator with unknown opcode?");
Chris Lattner3d7103e2008-03-21 21:14:38 +0000210 case Instruction::Add: return Expression::ADD;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000211 case Instruction::FAdd: return Expression::FADD;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000212 case Instruction::Sub: return Expression::SUB;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000213 case Instruction::FSub: return Expression::FSUB;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000214 case Instruction::Mul: return Expression::MUL;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000215 case Instruction::FMul: return Expression::FMUL;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000216 case Instruction::UDiv: return Expression::UDIV;
217 case Instruction::SDiv: return Expression::SDIV;
218 case Instruction::FDiv: return Expression::FDIV;
219 case Instruction::URem: return Expression::UREM;
220 case Instruction::SRem: return Expression::SREM;
221 case Instruction::FRem: return Expression::FREM;
222 case Instruction::Shl: return Expression::SHL;
223 case Instruction::LShr: return Expression::LSHR;
224 case Instruction::AShr: return Expression::ASHR;
225 case Instruction::And: return Expression::AND;
226 case Instruction::Or: return Expression::OR;
227 case Instruction::Xor: return Expression::XOR;
Owen Anderson85c40642007-07-24 17:55:58 +0000228 }
229}
230
231Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
Nick Lewycky8f5253b2009-07-08 03:04:38 +0000232 if (isa<ICmpInst>(C)) {
Owen Anderson85c40642007-07-24 17:55:58 +0000233 switch (C->getPredicate()) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000234 default: // THIS SHOULD NEVER HAPPEN
Edwin Törökbd448e32009-07-14 16:55:14 +0000235 llvm_unreachable("Comparison with unknown predicate?");
Chris Lattner3d7103e2008-03-21 21:14:38 +0000236 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ;
237 case ICmpInst::ICMP_NE: return Expression::ICMPNE;
238 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
239 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
240 case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
241 case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
242 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
243 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
244 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
245 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
Owen Anderson85c40642007-07-24 17:55:58 +0000246 }
Nick Lewycky8f5253b2009-07-08 03:04:38 +0000247 } else {
248 switch (C->getPredicate()) {
249 default: // THIS SHOULD NEVER HAPPEN
Edwin Törökbd448e32009-07-14 16:55:14 +0000250 llvm_unreachable("Comparison with unknown predicate?");
Nick Lewycky8f5253b2009-07-08 03:04:38 +0000251 case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
252 case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
253 case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
254 case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
255 case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
256 case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
257 case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
258 case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
259 case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
260 case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
261 case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
262 case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
263 case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
264 case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
265 }
Owen Anderson85c40642007-07-24 17:55:58 +0000266 }
267}
268
Chris Lattner3d7103e2008-03-21 21:14:38 +0000269Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
Owen Anderson85c40642007-07-24 17:55:58 +0000270 switch(C->getOpcode()) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000271 default: // THIS SHOULD NEVER HAPPEN
Edwin Törökbd448e32009-07-14 16:55:14 +0000272 llvm_unreachable("Cast operator with unknown opcode?");
Chris Lattner3d7103e2008-03-21 21:14:38 +0000273 case Instruction::Trunc: return Expression::TRUNC;
274 case Instruction::ZExt: return Expression::ZEXT;
275 case Instruction::SExt: return Expression::SEXT;
276 case Instruction::FPToUI: return Expression::FPTOUI;
277 case Instruction::FPToSI: return Expression::FPTOSI;
278 case Instruction::UIToFP: return Expression::UITOFP;
279 case Instruction::SIToFP: return Expression::SITOFP;
280 case Instruction::FPTrunc: return Expression::FPTRUNC;
281 case Instruction::FPExt: return Expression::FPEXT;
282 case Instruction::PtrToInt: return Expression::PTRTOINT;
283 case Instruction::IntToPtr: return Expression::INTTOPTR;
284 case Instruction::BitCast: return Expression::BITCAST;
Owen Anderson85c40642007-07-24 17:55:58 +0000285 }
286}
287
Owen Anderson5e9366f2007-10-18 19:39:33 +0000288Expression ValueTable::create_expression(CallInst* C) {
289 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000290
Owen Anderson5e9366f2007-10-18 19:39:33 +0000291 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;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000297
Owen Anderson5e9366f2007-10-18 19:39:33 +0000298 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
299 I != E; ++I)
Owen Anderson07f478f2008-04-11 05:11:49 +0000300 e.varargs.push_back(lookup_or_add(*I));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000301
Owen Anderson5e9366f2007-10-18 19:39:33 +0000302 return e;
303}
304
Owen Anderson85c40642007-07-24 17:55:58 +0000305Expression ValueTable::create_expression(BinaryOperator* BO) {
306 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000307
Owen Anderson07f478f2008-04-11 05:11:49 +0000308 e.firstVN = lookup_or_add(BO->getOperand(0));
309 e.secondVN = lookup_or_add(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);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000314
Owen Anderson85c40642007-07-24 17:55:58 +0000315 return e;
316}
317
318Expression ValueTable::create_expression(CmpInst* C) {
319 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000320
Owen Anderson07f478f2008-04-11 05:11:49 +0000321 e.firstVN = lookup_or_add(C->getOperand(0));
322 e.secondVN = lookup_or_add(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);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000327
Owen Anderson85c40642007-07-24 17:55:58 +0000328 return e;
329}
330
331Expression ValueTable::create_expression(CastInst* C) {
332 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000333
Owen Anderson07f478f2008-04-11 05:11:49 +0000334 e.firstVN = lookup_or_add(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);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000340
Owen Anderson85c40642007-07-24 17:55:58 +0000341 return e;
342}
343
344Expression ValueTable::create_expression(ShuffleVectorInst* S) {
345 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000346
Owen Anderson07f478f2008-04-11 05:11:49 +0000347 e.firstVN = lookup_or_add(S->getOperand(0));
348 e.secondVN = lookup_or_add(S->getOperand(1));
349 e.thirdVN = lookup_or_add(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;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000353
Owen Anderson85c40642007-07-24 17:55:58 +0000354 return e;
355}
356
357Expression ValueTable::create_expression(ExtractElementInst* E) {
358 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000359
Owen Anderson07f478f2008-04-11 05:11:49 +0000360 e.firstVN = lookup_or_add(E->getOperand(0));
361 e.secondVN = lookup_or_add(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;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000366
Owen Anderson85c40642007-07-24 17:55:58 +0000367 return e;
368}
369
370Expression ValueTable::create_expression(InsertElementInst* I) {
371 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000372
Owen Anderson07f478f2008-04-11 05:11:49 +0000373 e.firstVN = lookup_or_add(I->getOperand(0));
374 e.secondVN = lookup_or_add(I->getOperand(1));
375 e.thirdVN = lookup_or_add(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;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000379
Owen Anderson85c40642007-07-24 17:55:58 +0000380 return e;
381}
382
383Expression ValueTable::create_expression(SelectInst* I) {
384 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000385
Owen Anderson07f478f2008-04-11 05:11:49 +0000386 e.firstVN = lookup_or_add(I->getCondition());
387 e.secondVN = lookup_or_add(I->getTrueValue());
388 e.thirdVN = lookup_or_add(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;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000392
Owen Anderson85c40642007-07-24 17:55:58 +0000393 return e;
394}
395
396Expression ValueTable::create_expression(GetElementPtrInst* G) {
397 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000398
Owen Anderson07f478f2008-04-11 05:11:49 +0000399 e.firstVN = lookup_or_add(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;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000405
Owen Anderson85c40642007-07-24 17:55:58 +0000406 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
407 I != E; ++I)
Owen Anderson07f478f2008-04-11 05:11:49 +0000408 e.varargs.push_back(lookup_or_add(*I));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000409
Owen Anderson85c40642007-07-24 17:55:58 +0000410 return e;
411}
412
413//===----------------------------------------------------------------------===//
414// ValueTable External Functions
415//===----------------------------------------------------------------------===//
416
Owen Andersone6b4ff82008-06-18 21:41:49 +0000417/// add - Insert a value into the table with a specified value number.
Chris Lattnerff36c952009-09-21 02:42:51 +0000418void ValueTable::add(Value *V, uint32_t num) {
Owen Andersone6b4ff82008-06-18 21:41:49 +0000419 valueNumbering.insert(std::make_pair(V, num));
420}
421
Owen Anderson85c40642007-07-24 17:55:58 +0000422/// lookup_or_add - Returns the value number for the specified value, assigning
423/// it a new number if it did not have one before.
Chris Lattnerff36c952009-09-21 02:42:51 +0000424uint32_t ValueTable::lookup_or_add(Value *V) {
Owen Anderson85c40642007-07-24 17:55:58 +0000425 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
426 if (VI != valueNumbering.end())
427 return VI->second;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000428
Owen Anderson5e9366f2007-10-18 19:39:33 +0000429 if (CallInst* C = dyn_cast<CallInst>(V)) {
Owen Anderson07f478f2008-04-11 05:11:49 +0000430 if (AA->doesNotAccessMemory(C)) {
Owen Anderson5e9366f2007-10-18 19:39:33 +0000431 Expression e = create_expression(C);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000432
Owen Anderson5e9366f2007-10-18 19:39:33 +0000433 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
434 if (EI != expressionNumbering.end()) {
435 valueNumbering.insert(std::make_pair(V, EI->second));
436 return EI->second;
437 } else {
438 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
439 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000440
Owen Anderson5e9366f2007-10-18 19:39:33 +0000441 return nextValueNumber++;
442 }
Owen Andersona0b2b8e2008-04-17 05:36:50 +0000443 } else if (AA->onlyReadsMemory(C)) {
444 Expression e = create_expression(C);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000445
Owen Anderson771d1122008-05-13 08:17:22 +0000446 if (expressionNumbering.find(e) == expressionNumbering.end()) {
Owen Andersona0b2b8e2008-04-17 05:36:50 +0000447 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
448 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Owen Anderson771d1122008-05-13 08:17:22 +0000449 return nextValueNumber++;
450 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000451
Chris Lattner12cafbf2008-11-29 02:29:27 +0000452 MemDepResult local_dep = MD->getDependency(C);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000453
Chris Lattner4531da82008-12-05 21:04:20 +0000454 if (!local_dep.isDef() && !local_dep.isNonLocal()) {
Owen Anderson64fcc592008-05-13 23:18:30 +0000455 valueNumbering.insert(std::make_pair(V, nextValueNumber));
456 return nextValueNumber++;
Chris Lattnerd33b6662008-11-30 23:39:23 +0000457 }
Chris Lattner4531da82008-12-05 21:04:20 +0000458
459 if (local_dep.isDef()) {
460 CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000461
Chris Lattner4531da82008-12-05 21:04:20 +0000462 if (local_cdep->getNumOperands() != C->getNumOperands()) {
Owen Anderson64fcc592008-05-13 23:18:30 +0000463 valueNumbering.insert(std::make_pair(V, nextValueNumber));
464 return nextValueNumber++;
465 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000466
Chris Lattnerd33b6662008-11-30 23:39:23 +0000467 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
468 uint32_t c_vn = lookup_or_add(C->getOperand(i));
469 uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
470 if (c_vn != cd_vn) {
471 valueNumbering.insert(std::make_pair(V, nextValueNumber));
472 return nextValueNumber++;
473 }
474 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000475
Chris Lattnerd33b6662008-11-30 23:39:23 +0000476 uint32_t v = lookup_or_add(local_cdep);
477 valueNumbering.insert(std::make_pair(V, v));
478 return v;
Owen Anderson64fcc592008-05-13 23:18:30 +0000479 }
Chris Lattner46876282008-12-01 01:15:42 +0000480
Chris Lattner4531da82008-12-05 21:04:20 +0000481 // Non-local case.
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000482 const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
Chris Lattner35d5cf52008-12-09 19:38:05 +0000483 MD->getNonLocalCallDependency(CallSite(C));
Chris Lattner4531da82008-12-05 21:04:20 +0000484 // FIXME: call/call dependencies for readonly calls should return def, not
485 // clobber! Move the checking logic to MemDep!
Owen Anderson3ebaca72008-05-13 13:41:23 +0000486 CallInst* cdep = 0;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000487
Chris Lattnerd33b6662008-11-30 23:39:23 +0000488 // Check to see if we have a single dominating call instruction that is
489 // identical to C.
Chris Lattner46876282008-12-01 01:15:42 +0000490 for (unsigned i = 0, e = deps.size(); i != e; ++i) {
491 const MemoryDependenceAnalysis::NonLocalDepEntry *I = &deps[i];
Chris Lattnerd33b6662008-11-30 23:39:23 +0000492 // Ignore non-local dependencies.
493 if (I->second.isNonLocal())
494 continue;
Owen Anderson771d1122008-05-13 08:17:22 +0000495
Chris Lattnerd33b6662008-11-30 23:39:23 +0000496 // We don't handle non-depedencies. If we already have a call, reject
497 // instruction dependencies.
Chris Lattner4531da82008-12-05 21:04:20 +0000498 if (I->second.isClobber() || cdep != 0) {
Chris Lattnerd33b6662008-11-30 23:39:23 +0000499 cdep = 0;
500 break;
Owen Anderson771d1122008-05-13 08:17:22 +0000501 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000502
Chris Lattnerd33b6662008-11-30 23:39:23 +0000503 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->second.getInst());
504 // FIXME: All duplicated with non-local case.
505 if (NonLocalDepCall && DT->properlyDominates(I->first, C->getParent())){
506 cdep = NonLocalDepCall;
507 continue;
508 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000509
Chris Lattnerd33b6662008-11-30 23:39:23 +0000510 cdep = 0;
511 break;
Owen Anderson771d1122008-05-13 08:17:22 +0000512 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000513
Owen Anderson3ebaca72008-05-13 13:41:23 +0000514 if (!cdep) {
Owen Anderson771d1122008-05-13 08:17:22 +0000515 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Owen Andersona0b2b8e2008-04-17 05:36:50 +0000516 return nextValueNumber++;
517 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000518
Chris Lattner4531da82008-12-05 21:04:20 +0000519 if (cdep->getNumOperands() != C->getNumOperands()) {
Owen Anderson771d1122008-05-13 08:17:22 +0000520 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Owen Andersona0b2b8e2008-04-17 05:36:50 +0000521 return nextValueNumber++;
Owen Andersona0b2b8e2008-04-17 05:36:50 +0000522 }
Chris Lattnerd33b6662008-11-30 23:39:23 +0000523 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
524 uint32_t c_vn = lookup_or_add(C->getOperand(i));
525 uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
526 if (c_vn != cd_vn) {
527 valueNumbering.insert(std::make_pair(V, nextValueNumber));
528 return nextValueNumber++;
529 }
530 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000531
Chris Lattnerd33b6662008-11-30 23:39:23 +0000532 uint32_t v = lookup_or_add(cdep);
533 valueNumbering.insert(std::make_pair(V, v));
534 return v;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000535
Owen Anderson5e9366f2007-10-18 19:39:33 +0000536 } else {
537 valueNumbering.insert(std::make_pair(V, nextValueNumber));
538 return nextValueNumber++;
539 }
540 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
Owen Anderson85c40642007-07-24 17:55:58 +0000541 Expression e = create_expression(BO);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000542
Owen Anderson85c40642007-07-24 17:55:58 +0000543 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
544 if (EI != expressionNumbering.end()) {
545 valueNumbering.insert(std::make_pair(V, EI->second));
546 return EI->second;
547 } else {
548 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
549 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000550
Owen Anderson85c40642007-07-24 17:55:58 +0000551 return nextValueNumber++;
552 }
553 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
554 Expression e = create_expression(C);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000555
Owen Anderson85c40642007-07-24 17:55:58 +0000556 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
557 if (EI != expressionNumbering.end()) {
558 valueNumbering.insert(std::make_pair(V, EI->second));
559 return EI->second;
560 } else {
561 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
562 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000563
Owen Anderson85c40642007-07-24 17:55:58 +0000564 return nextValueNumber++;
565 }
566 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
567 Expression e = create_expression(U);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000568
Owen Anderson85c40642007-07-24 17:55:58 +0000569 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
570 if (EI != expressionNumbering.end()) {
571 valueNumbering.insert(std::make_pair(V, EI->second));
572 return EI->second;
573 } else {
574 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
575 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000576
Owen Anderson85c40642007-07-24 17:55:58 +0000577 return nextValueNumber++;
578 }
579 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
580 Expression e = create_expression(U);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000581
Owen Anderson85c40642007-07-24 17:55:58 +0000582 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
583 if (EI != expressionNumbering.end()) {
584 valueNumbering.insert(std::make_pair(V, EI->second));
585 return EI->second;
586 } else {
587 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
588 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000589
Owen Anderson85c40642007-07-24 17:55:58 +0000590 return nextValueNumber++;
591 }
592 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
593 Expression e = create_expression(U);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000594
Owen Anderson85c40642007-07-24 17:55:58 +0000595 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
596 if (EI != expressionNumbering.end()) {
597 valueNumbering.insert(std::make_pair(V, EI->second));
598 return EI->second;
599 } else {
600 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
601 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000602
Owen Anderson85c40642007-07-24 17:55:58 +0000603 return nextValueNumber++;
604 }
605 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
606 Expression e = create_expression(U);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000607
Owen Anderson85c40642007-07-24 17:55:58 +0000608 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
609 if (EI != expressionNumbering.end()) {
610 valueNumbering.insert(std::make_pair(V, EI->second));
611 return EI->second;
612 } else {
613 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
614 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000615
Owen Anderson85c40642007-07-24 17:55:58 +0000616 return nextValueNumber++;
617 }
618 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
619 Expression e = create_expression(U);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000620
Owen Anderson85c40642007-07-24 17:55:58 +0000621 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
622 if (EI != expressionNumbering.end()) {
623 valueNumbering.insert(std::make_pair(V, EI->second));
624 return EI->second;
625 } else {
626 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
627 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000628
Owen Anderson85c40642007-07-24 17:55:58 +0000629 return nextValueNumber++;
630 }
631 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
632 Expression e = create_expression(U);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000633
Owen Anderson85c40642007-07-24 17:55:58 +0000634 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
635 if (EI != expressionNumbering.end()) {
636 valueNumbering.insert(std::make_pair(V, EI->second));
637 return EI->second;
638 } else {
639 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
640 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000641
Owen Anderson85c40642007-07-24 17:55:58 +0000642 return nextValueNumber++;
643 }
644 } else {
645 valueNumbering.insert(std::make_pair(V, nextValueNumber));
646 return nextValueNumber++;
647 }
648}
649
650/// lookup - Returns the value number of the specified value. Fails if
651/// the value has not yet been numbered.
Chris Lattnerff36c952009-09-21 02:42:51 +0000652uint32_t ValueTable::lookup(Value *V) const {
Owen Anderson85c40642007-07-24 17:55:58 +0000653 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
Chris Lattner3d7103e2008-03-21 21:14:38 +0000654 assert(VI != valueNumbering.end() && "Value not numbered?");
655 return VI->second;
Owen Anderson85c40642007-07-24 17:55:58 +0000656}
657
658/// clear - Remove all entries from the ValueTable
659void ValueTable::clear() {
660 valueNumbering.clear();
661 expressionNumbering.clear();
662 nextValueNumber = 1;
663}
664
Owen Anderson5aff8002007-07-31 23:27:13 +0000665/// erase - Remove a value from the value numbering
Chris Lattnerff36c952009-09-21 02:42:51 +0000666void ValueTable::erase(Value *V) {
Owen Anderson5aff8002007-07-31 23:27:13 +0000667 valueNumbering.erase(V);
668}
669
Bill Wendling2a023742008-12-22 21:36:08 +0000670/// verifyRemoved - Verify that the value is removed from all internal data
671/// structures.
672void ValueTable::verifyRemoved(const Value *V) const {
673 for (DenseMap<Value*, uint32_t>::iterator
674 I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
675 assert(I->first != V && "Inst still occurs in value numbering map!");
676 }
677}
678
Owen Anderson85c40642007-07-24 17:55:58 +0000679//===----------------------------------------------------------------------===//
Bill Wendling42f17f62008-12-22 22:32:22 +0000680// GVN Pass
Owen Anderson85c40642007-07-24 17:55:58 +0000681//===----------------------------------------------------------------------===//
682
683namespace {
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +0000684 struct ValueNumberScope {
Owen Anderson2a412722008-06-20 01:15:47 +0000685 ValueNumberScope* parent;
686 DenseMap<uint32_t, Value*> table;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000687
Owen Anderson2a412722008-06-20 01:15:47 +0000688 ValueNumberScope(ValueNumberScope* p) : parent(p) { }
689 };
690}
691
692namespace {
Owen Anderson85c40642007-07-24 17:55:58 +0000693
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +0000694 class GVN : public FunctionPass {
Owen Anderson85c40642007-07-24 17:55:58 +0000695 bool runOnFunction(Function &F);
696 public:
697 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +0000698 GVN() : FunctionPass(&ID) { }
Owen Anderson85c40642007-07-24 17:55:58 +0000699
700 private:
Chris Lattner02ca4422008-12-01 00:40:32 +0000701 MemoryDependenceAnalysis *MD;
702 DominatorTree *DT;
703
Owen Anderson85c40642007-07-24 17:55:58 +0000704 ValueTable VN;
Owen Anderson2a412722008-06-20 01:15:47 +0000705 DenseMap<BasicBlock*, ValueNumberScope*> localAvail;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000706
Owen Anderson5b299672007-08-07 23:12:31 +0000707 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
708 PhiMapType phiMap;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000709
710
Owen Anderson85c40642007-07-24 17:55:58 +0000711 // This transformation requires dominator postdominator info
712 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Anderson85c40642007-07-24 17:55:58 +0000713 AU.addRequired<DominatorTree>();
714 AU.addRequired<MemoryDependenceAnalysis>();
Owen Anderson5e9366f2007-10-18 19:39:33 +0000715 AU.addRequired<AliasAnalysis>();
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000716
Owen Andersonaef6a922008-06-23 17:49:45 +0000717 AU.addPreserved<DominatorTree>();
Owen Anderson5e9366f2007-10-18 19:39:33 +0000718 AU.addPreserved<AliasAnalysis>();
Owen Anderson85c40642007-07-24 17:55:58 +0000719 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000720
Owen Anderson85c40642007-07-24 17:55:58 +0000721 // Helper fuctions
722 // FIXME: eliminate or document these better
Owen Anderson85c40642007-07-24 17:55:58 +0000723 bool processLoad(LoadInst* L,
Chris Lattner7de20452008-03-21 22:01:16 +0000724 SmallVectorImpl<Instruction*> &toErase);
Chris Lattnerff36c952009-09-21 02:42:51 +0000725 bool processInstruction(Instruction *I,
Chris Lattner7de20452008-03-21 22:01:16 +0000726 SmallVectorImpl<Instruction*> &toErase);
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000727 bool processNonLocalLoad(LoadInst* L,
Chris Lattner7de20452008-03-21 22:01:16 +0000728 SmallVectorImpl<Instruction*> &toErase);
Chris Lattnerff36c952009-09-21 02:42:51 +0000729 bool processBlock(BasicBlock *BB);
730 Value *GetValueForBlock(BasicBlock *BB, Instruction *orig,
Owen Andersonc6a31b92007-08-02 17:56:05 +0000731 DenseMap<BasicBlock*, Value*> &Phis,
732 bool top_level = false);
Owen Andersone6b4ff82008-06-18 21:41:49 +0000733 void dump(DenseMap<uint32_t, Value*>& d);
Owen Andersonbe168b32007-08-14 18:04:11 +0000734 bool iterateOnFunction(Function &F);
Chris Lattnerff36c952009-09-21 02:42:51 +0000735 Value *CollapsePhi(PHINode* p);
Owen Andersone6b4ff82008-06-18 21:41:49 +0000736 bool performPRE(Function& F);
Chris Lattnerff36c952009-09-21 02:42:51 +0000737 Value *lookupNumber(BasicBlock *BB, uint32_t num);
738 Value *AttemptRedundancyElimination(Instruction *orig, unsigned valno);
Nuno Lopes274474b2008-10-10 16:25:50 +0000739 void cleanupGlobalSets();
Bill Wendling2a023742008-12-22 21:36:08 +0000740 void verifyRemoved(const Instruction *I) const;
Owen Anderson85c40642007-07-24 17:55:58 +0000741 };
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000742
Owen Anderson85c40642007-07-24 17:55:58 +0000743 char GVN::ID = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000744}
745
746// createGVNPass - The public interface to this file...
747FunctionPass *llvm::createGVNPass() { return new GVN(); }
748
749static RegisterPass<GVN> X("gvn",
750 "Global Value Numbering");
751
Owen Andersone6b4ff82008-06-18 21:41:49 +0000752void GVN::dump(DenseMap<uint32_t, Value*>& d) {
Owen Anderson5d72a422007-07-25 19:57:03 +0000753 printf("{\n");
Owen Andersone6b4ff82008-06-18 21:41:49 +0000754 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
Owen Anderson5d72a422007-07-25 19:57:03 +0000755 E = d.end(); I != E; ++I) {
Owen Andersone6b4ff82008-06-18 21:41:49 +0000756 printf("%d\n", I->first);
Owen Anderson5d72a422007-07-25 19:57:03 +0000757 I->second->dump();
758 }
759 printf("}\n");
760}
761
Chris Lattnerff36c952009-09-21 02:42:51 +0000762static bool isSafeReplacement(PHINode* p, Instruction *inst) {
Owen Andersond68b1af2009-08-26 22:55:11 +0000763 if (!isa<PHINode>(inst))
764 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000765
Owen Andersond68b1af2009-08-26 22:55:11 +0000766 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
767 UI != E; ++UI)
768 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
769 if (use_phi->getParent() == inst->getParent())
770 return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000771
Owen Andersond68b1af2009-08-26 22:55:11 +0000772 return true;
773}
774
Chris Lattnerff36c952009-09-21 02:42:51 +0000775Value *GVN::CollapsePhi(PHINode *PN) {
776 Value *ConstVal = PN->hasConstantValue(DT);
777 if (!ConstVal) return 0;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000778
Chris Lattnerff36c952009-09-21 02:42:51 +0000779 Instruction *Inst = dyn_cast<Instruction>(ConstVal);
780 if (!Inst)
781 return ConstVal;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000782
Chris Lattnerff36c952009-09-21 02:42:51 +0000783 if (DT->dominates(Inst, PN))
784 if (isSafeReplacement(PN, Inst))
785 return Inst;
Owen Andersone02ad522007-08-16 22:51:56 +0000786 return 0;
787}
Owen Anderson5d72a422007-07-25 19:57:03 +0000788
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000789/// GetValueForBlock - Get the value to use within the specified basic block.
790/// available values are in Phis.
Chris Lattnerff36c952009-09-21 02:42:51 +0000791Value *GVN::GetValueForBlock(BasicBlock *BB, Instruction *Orig,
Chris Lattner3d7103e2008-03-21 21:14:38 +0000792 DenseMap<BasicBlock*, Value*> &Phis,
Chris Lattnerff36c952009-09-21 02:42:51 +0000793 bool TopLevel) {
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000794
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000795 // If we have already computed this value, return the previously computed val.
Owen Andersoned7f9932007-08-03 19:59:35 +0000796 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
Chris Lattnerff36c952009-09-21 02:42:51 +0000797 if (V != Phis.end() && !TopLevel) return V->second;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000798
Owen Andersonc3714b22008-07-02 18:15:31 +0000799 // If the block is unreachable, just return undef, since this path
800 // can't actually occur at runtime.
Chris Lattner02ca4422008-12-01 00:40:32 +0000801 if (!DT->isReachableFromEntry(BB))
Chris Lattnerff36c952009-09-21 02:42:51 +0000802 return Phis[BB] = UndefValue::get(Orig->getType());
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000803
Chris Lattner4bab29b2008-12-09 19:21:47 +0000804 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
Chris Lattnerff36c952009-09-21 02:42:51 +0000805 Value *ret = GetValueForBlock(Pred, Orig, Phis);
Owen Andersoned7f9932007-08-03 19:59:35 +0000806 Phis[BB] = ret;
807 return ret;
Owen Anderson30463f12007-08-03 11:03:26 +0000808 }
Chris Lattner4bab29b2008-12-09 19:21:47 +0000809
810 // Get the number of predecessors of this block so we can reserve space later.
811 // If there is already a PHI in it, use the #preds from it, otherwise count.
812 // Getting it from the PHI is constant time.
813 unsigned NumPreds;
814 if (PHINode *ExistingPN = dyn_cast<PHINode>(BB->begin()))
815 NumPreds = ExistingPN->getNumIncomingValues();
816 else
817 NumPreds = std::distance(pred_begin(BB), pred_end(BB));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000818
Chris Lattner34635fd2009-10-10 06:22:45 +0000819 // Otherwise, we may need to insert a PHI node. Do so now, then get values to
820 // fill in the incoming values for the PHI. If the PHI ends up not being
821 // needed, we can always remove it later.
Chris Lattnerff36c952009-09-21 02:42:51 +0000822 PHINode *PN = PHINode::Create(Orig->getType(), Orig->getName()+".rle",
Gabor Greifd6da1d02008-04-06 20:25:17 +0000823 BB->begin());
Chris Lattner4bab29b2008-12-09 19:21:47 +0000824 PN->reserveOperandSpace(NumPreds);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000825
Chris Lattner4bab29b2008-12-09 19:21:47 +0000826 Phis.insert(std::make_pair(BB, PN));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000827
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000828 // Fill in the incoming values for the block.
Owen Anderson9f577412007-07-31 17:43:14 +0000829 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Chris Lattnerff36c952009-09-21 02:42:51 +0000830 Value *val = GetValueForBlock(*PI, Orig, Phis);
Owen Anderson9f577412007-07-31 17:43:14 +0000831 PN->addIncoming(val, *PI);
832 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000833
Chris Lattnerff36c952009-09-21 02:42:51 +0000834 VN.getAliasAnalysis()->copyValue(Orig, PN);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000835
Chris Lattner34635fd2009-10-10 06:22:45 +0000836 // Attempt to collapse PHI nodes that are trivially redundant. This happens
837 // when we construct a PHI that ends up not being needed.
Chris Lattnerff36c952009-09-21 02:42:51 +0000838 Value *v = CollapsePhi(PN);
Chris Lattner3d7103e2008-03-21 21:14:38 +0000839 if (!v) {
840 // Cache our phi construction results
Chris Lattnerff36c952009-09-21 02:42:51 +0000841 if (LoadInst* L = dyn_cast<LoadInst>(Orig))
Owen Anderson5e5e5612008-12-14 19:10:35 +0000842 phiMap[L->getPointerOperand()].insert(PN);
843 else
Chris Lattnerff36c952009-09-21 02:42:51 +0000844 phiMap[Orig].insert(PN);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000845
Chris Lattner3d7103e2008-03-21 21:14:38 +0000846 return PN;
Owen Anderson9f577412007-07-31 17:43:14 +0000847 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000848
Chris Lattner3d7103e2008-03-21 21:14:38 +0000849 PN->replaceAllUsesWith(v);
Chris Lattnerf81b0142008-12-09 22:06:23 +0000850 if (isa<PointerType>(v->getType()))
851 MD->invalidateCachedPointerInfo(v);
Chris Lattner3d7103e2008-03-21 21:14:38 +0000852
853 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
854 E = Phis.end(); I != E; ++I)
855 if (I->second == PN)
856 I->second = v;
857
Dan Gohman7e124382009-07-31 20:24:18 +0000858 DEBUG(errs() << "GVN removed: " << *PN << '\n');
Chris Lattner02ca4422008-12-01 00:40:32 +0000859 MD->removeInstruction(PN);
Chris Lattner3d7103e2008-03-21 21:14:38 +0000860 PN->eraseFromParent();
Bill Wendling2a023742008-12-22 21:36:08 +0000861 DEBUG(verifyRemoved(PN));
Chris Lattner3d7103e2008-03-21 21:14:38 +0000862
863 Phis[BB] = v;
864 return v;
Owen Anderson5d72a422007-07-25 19:57:03 +0000865}
866
Chris Lattnerdcded152008-12-02 08:16:11 +0000867/// IsValueFullyAvailableInBlock - Return true if we can prove that the value
868/// we're analyzing is fully available in the specified block. As we go, keep
Chris Lattner159b98f2008-12-05 07:49:08 +0000869/// track of which blocks we know are fully alive in FullyAvailableBlocks. This
870/// map is actually a tri-state map with the following values:
871/// 0) we know the block *is not* fully available.
872/// 1) we know the block *is* fully available.
873/// 2) we do not know whether the block is fully available or not, but we are
874/// currently speculating that it will be.
875/// 3) we are speculating for this block and have used that to speculate for
876/// other blocks.
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000877static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
Chris Lattner159b98f2008-12-05 07:49:08 +0000878 DenseMap<BasicBlock*, char> &FullyAvailableBlocks) {
Chris Lattnerdcded152008-12-02 08:16:11 +0000879 // Optimistically assume that the block is fully available and check to see
880 // if we already know about this block in one lookup.
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000881 std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
Chris Lattner159b98f2008-12-05 07:49:08 +0000882 FullyAvailableBlocks.insert(std::make_pair(BB, 2));
Chris Lattnerdcded152008-12-02 08:16:11 +0000883
884 // If the entry already existed for this block, return the precomputed value.
Chris Lattner159b98f2008-12-05 07:49:08 +0000885 if (!IV.second) {
886 // If this is a speculative "available" value, mark it as being used for
887 // speculation of other blocks.
888 if (IV.first->second == 2)
889 IV.first->second = 3;
890 return IV.first->second != 0;
891 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000892
Chris Lattnerdcded152008-12-02 08:16:11 +0000893 // Otherwise, see if it is fully available in all predecessors.
894 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000895
Chris Lattnerdcded152008-12-02 08:16:11 +0000896 // If this block has no predecessors, it isn't live-in here.
897 if (PI == PE)
Chris Lattner159b98f2008-12-05 07:49:08 +0000898 goto SpeculationFailure;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000899
Chris Lattnerdcded152008-12-02 08:16:11 +0000900 for (; PI != PE; ++PI)
901 // If the value isn't fully available in one of our predecessors, then it
902 // isn't fully available in this block either. Undo our previous
903 // optimistic assumption and bail out.
904 if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
Chris Lattner159b98f2008-12-05 07:49:08 +0000905 goto SpeculationFailure;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000906
Chris Lattnerdcded152008-12-02 08:16:11 +0000907 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000908
Chris Lattner159b98f2008-12-05 07:49:08 +0000909// SpeculationFailure - If we get here, we found out that this is not, after
910// all, a fully-available block. We have a problem if we speculated on this and
911// used the speculation to mark other blocks as available.
912SpeculationFailure:
913 char &BBVal = FullyAvailableBlocks[BB];
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000914
Chris Lattner159b98f2008-12-05 07:49:08 +0000915 // If we didn't speculate on this, just return with it set to false.
916 if (BBVal == 2) {
917 BBVal = 0;
918 return false;
919 }
920
921 // If we did speculate on this value, we could have blocks set to 1 that are
922 // incorrect. Walk the (transitive) successors of this block and mark them as
923 // 0 if set to one.
924 SmallVector<BasicBlock*, 32> BBWorklist;
925 BBWorklist.push_back(BB);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000926
Chris Lattner159b98f2008-12-05 07:49:08 +0000927 while (!BBWorklist.empty()) {
928 BasicBlock *Entry = BBWorklist.pop_back_val();
929 // Note that this sets blocks to 0 (unavailable) if they happen to not
930 // already be in FullyAvailableBlocks. This is safe.
931 char &EntryVal = FullyAvailableBlocks[Entry];
932 if (EntryVal == 0) continue; // Already unavailable.
933
934 // Mark as unavailable.
935 EntryVal = 0;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000936
Chris Lattner159b98f2008-12-05 07:49:08 +0000937 for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I)
938 BBWorklist.push_back(*I);
939 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000940
Chris Lattner159b98f2008-12-05 07:49:08 +0000941 return false;
Chris Lattnerdcded152008-12-02 08:16:11 +0000942}
943
Chris Lattnerd6b1d052009-09-20 20:09:34 +0000944
Chris Lattner012b3602009-09-21 17:24:04 +0000945/// CanCoerceMustAliasedValueToLoad - Return true if
946/// CoerceAvailableValueToLoadType will succeed.
947static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
948 const Type *LoadTy,
949 const TargetData &TD) {
950 // If the loaded or stored value is an first class array or struct, don't try
951 // to transform them. We need to be able to bitcast to integer.
952 if (isa<StructType>(LoadTy) || isa<ArrayType>(LoadTy) ||
953 isa<StructType>(StoredVal->getType()) ||
954 isa<ArrayType>(StoredVal->getType()))
955 return false;
956
957 // The store has to be at least as big as the load.
958 if (TD.getTypeSizeInBits(StoredVal->getType()) <
959 TD.getTypeSizeInBits(LoadTy))
960 return false;
961
962 return true;
963}
964
965
Chris Lattnerd6b1d052009-09-20 20:09:34 +0000966/// CoerceAvailableValueToLoadType - If we saw a store of a value to memory, and
967/// then a load from a must-aliased pointer of a different type, try to coerce
968/// the stored value. LoadedTy is the type of the load we want to replace and
969/// InsertPt is the place to insert new instructions.
970///
971/// If we can't do it, return null.
972static Value *CoerceAvailableValueToLoadType(Value *StoredVal,
973 const Type *LoadedTy,
974 Instruction *InsertPt,
975 const TargetData &TD) {
Chris Lattner012b3602009-09-21 17:24:04 +0000976 if (!CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, TD))
977 return 0;
978
Chris Lattnerd6b1d052009-09-20 20:09:34 +0000979 const Type *StoredValTy = StoredVal->getType();
980
981 uint64_t StoreSize = TD.getTypeSizeInBits(StoredValTy);
982 uint64_t LoadSize = TD.getTypeSizeInBits(LoadedTy);
983
984 // If the store and reload are the same size, we can always reuse it.
985 if (StoreSize == LoadSize) {
986 if (isa<PointerType>(StoredValTy) && isa<PointerType>(LoadedTy)) {
987 // Pointer to Pointer -> use bitcast.
988 return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
989 }
990
991 // Convert source pointers to integers, which can be bitcast.
992 if (isa<PointerType>(StoredValTy)) {
993 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
994 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
995 }
996
997 const Type *TypeToCastTo = LoadedTy;
998 if (isa<PointerType>(TypeToCastTo))
999 TypeToCastTo = TD.getIntPtrType(StoredValTy->getContext());
1000
1001 if (StoredValTy != TypeToCastTo)
1002 StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
1003
1004 // Cast to pointer if the load needs a pointer type.
1005 if (isa<PointerType>(LoadedTy))
1006 StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
1007
1008 return StoredVal;
1009 }
1010
1011 // If the loaded value is smaller than the available value, then we can
1012 // extract out a piece from it. If the available value is too small, then we
1013 // can't do anything.
Chris Lattner012b3602009-09-21 17:24:04 +00001014 assert(StoreSize >= LoadSize && "CanCoerceMustAliasedValueToLoad fail");
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001015
1016 // Convert source pointers to integers, which can be manipulated.
1017 if (isa<PointerType>(StoredValTy)) {
1018 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
1019 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
1020 }
1021
1022 // Convert vectors and fp to integer, which can be manipulated.
1023 if (!isa<IntegerType>(StoredValTy)) {
1024 StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
1025 StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
1026 }
1027
1028 // If this is a big-endian system, we need to shift the value down to the low
1029 // bits so that a truncate will work.
1030 if (TD.isBigEndian()) {
1031 Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
1032 StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
1033 }
1034
1035 // Truncate the integer to the right size now.
1036 const Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
1037 StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
1038
1039 if (LoadedTy == NewIntTy)
1040 return StoredVal;
1041
1042 // If the result is a pointer, inttoptr.
1043 if (isa<PointerType>(LoadedTy))
1044 return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
1045
1046 // Otherwise, bitcast.
1047 return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
1048}
1049
Chris Lattner8f912082009-09-21 06:24:16 +00001050/// GetBaseWithConstantOffset - Analyze the specified pointer to see if it can
1051/// be expressed as a base pointer plus a constant offset. Return the base and
1052/// offset to the caller.
1053static Value *GetBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001054 const TargetData &TD) {
Chris Lattner8f912082009-09-21 06:24:16 +00001055 Operator *PtrOp = dyn_cast<Operator>(Ptr);
1056 if (PtrOp == 0) return Ptr;
1057
1058 // Just look through bitcasts.
1059 if (PtrOp->getOpcode() == Instruction::BitCast)
1060 return GetBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
1061
1062 // If this is a GEP with constant indices, we can look through it.
1063 GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
1064 if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
1065
1066 gep_type_iterator GTI = gep_type_begin(GEP);
1067 for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
1068 ++I, ++GTI) {
1069 ConstantInt *OpC = cast<ConstantInt>(*I);
1070 if (OpC->isZero()) continue;
1071
1072 // Handle a struct and array indices which add their offset to the pointer.
1073 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001074 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
Chris Lattner8f912082009-09-21 06:24:16 +00001075 } else {
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001076 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner8f912082009-09-21 06:24:16 +00001077 Offset += OpC->getSExtValue()*Size;
1078 }
1079 }
1080
1081 // Re-sign extend from the pointer size if needed to get overflow edge cases
1082 // right.
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001083 unsigned PtrSize = TD.getPointerSizeInBits();
Chris Lattner8f912082009-09-21 06:24:16 +00001084 if (PtrSize < 64)
1085 Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
1086
1087 return GetBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
1088}
1089
1090
1091/// AnalyzeLoadFromClobberingStore - This function is called when we have a
1092/// memdep query of a load that ends up being a clobbering store. This means
1093/// that the store *may* provide bits used by the load but we can't be sure
1094/// because the pointers don't mustalias. Check this case to see if there is
1095/// anything more we can do before we give up. This returns -1 if we have to
1096/// give up, or a byte number in the stored value of the piece that feeds the
1097/// load.
1098static int AnalyzeLoadFromClobberingStore(LoadInst *L, StoreInst *DepSI,
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001099 const TargetData &TD) {
Chris Lattner012b3602009-09-21 17:24:04 +00001100 // If the loaded or stored value is an first class array or struct, don't try
1101 // to transform them. We need to be able to bitcast to integer.
1102 if (isa<StructType>(L->getType()) || isa<ArrayType>(L->getType()) ||
1103 isa<StructType>(DepSI->getOperand(0)->getType()) ||
1104 isa<ArrayType>(DepSI->getOperand(0)->getType()))
1105 return -1;
1106
Chris Lattner8f912082009-09-21 06:24:16 +00001107 int64_t StoreOffset = 0, LoadOffset = 0;
1108 Value *StoreBase =
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001109 GetBaseWithConstantOffset(DepSI->getPointerOperand(), StoreOffset, TD);
Chris Lattner8f912082009-09-21 06:24:16 +00001110 Value *LoadBase =
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001111 GetBaseWithConstantOffset(L->getPointerOperand(), LoadOffset, TD);
Chris Lattner8f912082009-09-21 06:24:16 +00001112 if (StoreBase != LoadBase)
1113 return -1;
1114
1115 // If the load and store are to the exact same address, they should have been
1116 // a must alias. AA must have gotten confused.
1117 // FIXME: Study to see if/when this happens.
1118 if (LoadOffset == StoreOffset) {
1119#if 0
1120 errs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
1121 << "Base = " << *StoreBase << "\n"
1122 << "Store Ptr = " << *DepSI->getPointerOperand() << "\n"
1123 << "Store Offs = " << StoreOffset << " - " << *DepSI << "\n"
1124 << "Load Ptr = " << *L->getPointerOperand() << "\n"
1125 << "Load Offs = " << LoadOffset << " - " << *L << "\n\n";
1126 errs() << "'" << L->getParent()->getParent()->getName() << "'"
1127 << *L->getParent();
1128#endif
1129 return -1;
1130 }
1131
1132 // If the load and store don't overlap at all, the store doesn't provide
1133 // anything to the load. In this case, they really don't alias at all, AA
1134 // must have gotten confused.
1135 // FIXME: Investigate cases where this bails out, e.g. rdar://7238614. Then
1136 // remove this check, as it is duplicated with what we have below.
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001137 uint64_t StoreSize = TD.getTypeSizeInBits(DepSI->getOperand(0)->getType());
1138 uint64_t LoadSize = TD.getTypeSizeInBits(L->getType());
Chris Lattner8f912082009-09-21 06:24:16 +00001139
1140 if ((StoreSize & 7) | (LoadSize & 7))
1141 return -1;
1142 StoreSize >>= 3; // Convert to bytes.
1143 LoadSize >>= 3;
1144
1145
1146 bool isAAFailure = false;
1147 if (StoreOffset < LoadOffset) {
1148 isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
1149 } else {
1150 isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
1151 }
1152 if (isAAFailure) {
1153#if 0
1154 errs() << "STORE LOAD DEP WITH COMMON BASE:\n"
1155 << "Base = " << *StoreBase << "\n"
1156 << "Store Ptr = " << *DepSI->getPointerOperand() << "\n"
1157 << "Store Offs = " << StoreOffset << " - " << *DepSI << "\n"
1158 << "Load Ptr = " << *L->getPointerOperand() << "\n"
1159 << "Load Offs = " << LoadOffset << " - " << *L << "\n\n";
1160 errs() << "'" << L->getParent()->getParent()->getName() << "'"
1161 << *L->getParent();
1162#endif
1163 return -1;
1164 }
1165
1166 // If the Load isn't completely contained within the stored bits, we don't
1167 // have all the bits to feed it. We could do something crazy in the future
1168 // (issue a smaller load then merge the bits in) but this seems unlikely to be
1169 // valuable.
1170 if (StoreOffset > LoadOffset ||
1171 StoreOffset+StoreSize < LoadOffset+LoadSize)
1172 return -1;
1173
1174 // Okay, we can do this transformation. Return the number of bytes into the
1175 // store that the load is.
1176 return LoadOffset-StoreOffset;
1177}
1178
1179
1180/// GetStoreValueForLoad - This function is called when we have a
1181/// memdep query of a load that ends up being a clobbering store. This means
1182/// that the store *may* provide bits used by the load but we can't be sure
1183/// because the pointers don't mustalias. Check this case to see if there is
1184/// anything more we can do before we give up.
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001185static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
1186 const Type *LoadTy,
1187 Instruction *InsertPt, const TargetData &TD){
Chris Lattner8f912082009-09-21 06:24:16 +00001188 LLVMContext &Ctx = SrcVal->getType()->getContext();
1189
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001190 uint64_t StoreSize = TD.getTypeSizeInBits(SrcVal->getType())/8;
1191 uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy)/8;
Chris Lattner8f912082009-09-21 06:24:16 +00001192
1193
1194 // Compute which bits of the stored value are being used by the load. Convert
1195 // to an integer type to start with.
1196 if (isa<PointerType>(SrcVal->getType()))
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001197 SrcVal = new PtrToIntInst(SrcVal, TD.getIntPtrType(Ctx), "tmp", InsertPt);
Chris Lattner8f912082009-09-21 06:24:16 +00001198 if (!isa<IntegerType>(SrcVal->getType()))
1199 SrcVal = new BitCastInst(SrcVal, IntegerType::get(Ctx, StoreSize*8),
1200 "tmp", InsertPt);
1201
1202 // Shift the bits to the least significant depending on endianness.
1203 unsigned ShiftAmt;
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001204 if (TD.isLittleEndian()) {
Chris Lattner8f912082009-09-21 06:24:16 +00001205 ShiftAmt = Offset*8;
1206 } else {
Chris Lattner1846fa02009-09-21 17:55:47 +00001207 ShiftAmt = (StoreSize-LoadSize-Offset)*8;
Chris Lattner8f912082009-09-21 06:24:16 +00001208 }
1209
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001210 if (ShiftAmt)
1211 SrcVal = BinaryOperator::CreateLShr(SrcVal,
1212 ConstantInt::get(SrcVal->getType(), ShiftAmt), "tmp", InsertPt);
Chris Lattner8f912082009-09-21 06:24:16 +00001213
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001214 if (LoadSize != StoreSize)
1215 SrcVal = new TruncInst(SrcVal, IntegerType::get(Ctx, LoadSize*8),
1216 "tmp", InsertPt);
Chris Lattner8f912082009-09-21 06:24:16 +00001217
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001218 return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, TD);
Chris Lattner8f912082009-09-21 06:24:16 +00001219}
1220
Chris Lattner19b84b32009-09-21 06:30:24 +00001221struct AvailableValueInBlock {
1222 /// BB - The basic block in question.
1223 BasicBlock *BB;
1224 /// V - The value that is live out of the block.
1225 Value *V;
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001226 /// Offset - The byte offset in V that is interesting for the load query.
1227 unsigned Offset;
Chris Lattner19b84b32009-09-21 06:30:24 +00001228
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001229 static AvailableValueInBlock get(BasicBlock *BB, Value *V,
1230 unsigned Offset = 0) {
Chris Lattner19b84b32009-09-21 06:30:24 +00001231 AvailableValueInBlock Res;
1232 Res.BB = BB;
1233 Res.V = V;
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001234 Res.Offset = Offset;
Chris Lattner19b84b32009-09-21 06:30:24 +00001235 return Res;
1236 }
1237};
1238
Chris Lattner8f912082009-09-21 06:24:16 +00001239/// GetAvailableBlockValues - Given the ValuesPerBlock list, convert all of the
1240/// available values to values of the expected LoadTy in their blocks and insert
1241/// the new values into BlockReplValues.
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001242static void
1243GetAvailableBlockValues(DenseMap<BasicBlock*, Value*> &BlockReplValues,
Chris Lattner19b84b32009-09-21 06:30:24 +00001244 const SmallVector<AvailableValueInBlock, 16> &ValuesPerBlock,
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001245 const Type *LoadTy,
1246 const TargetData *TD) {
1247
1248 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
Chris Lattner19b84b32009-09-21 06:30:24 +00001249 BasicBlock *BB = ValuesPerBlock[i].BB;
1250 Value *AvailableVal = ValuesPerBlock[i].V;
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001251 unsigned Offset = ValuesPerBlock[i].Offset;
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001252
1253 Value *&BlockEntry = BlockReplValues[BB];
1254 if (BlockEntry) continue;
1255
1256 if (AvailableVal->getType() != LoadTy) {
1257 assert(TD && "Need target data to handle type mismatch case");
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001258 AvailableVal = GetStoreValueForLoad(AvailableVal, Offset, LoadTy,
1259 BB->getTerminator(), *TD);
1260
1261 if (Offset) {
1262 DEBUG(errs() << "GVN COERCED NONLOCAL VAL:\n"
1263 << *ValuesPerBlock[i].V << '\n'
1264 << *AvailableVal << '\n' << "\n\n\n");
1265 }
1266
1267
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001268 DEBUG(errs() << "GVN COERCED NONLOCAL VAL:\n"
Chris Lattner19b84b32009-09-21 06:30:24 +00001269 << *ValuesPerBlock[i].V << '\n'
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001270 << *AvailableVal << '\n' << "\n\n\n");
1271 }
1272 BlockEntry = AvailableVal;
1273 }
1274}
1275
Owen Andersone0143452007-08-16 22:02:55 +00001276/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
1277/// non-local by performing PHI construction.
Chris Lattnerdcded152008-12-02 08:16:11 +00001278bool GVN::processNonLocalLoad(LoadInst *LI,
Chris Lattner7de20452008-03-21 22:01:16 +00001279 SmallVectorImpl<Instruction*> &toErase) {
Chris Lattnerdcded152008-12-02 08:16:11 +00001280 // Find the non-local dependencies of the load.
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001281 SmallVector<MemoryDependenceAnalysis::NonLocalDepEntry, 64> Deps;
Chris Lattneraf713862008-12-09 19:25:07 +00001282 MD->getNonLocalPointerDependency(LI->getOperand(0), true, LI->getParent(),
1283 Deps);
Dan Gohman7e124382009-07-31 20:24:18 +00001284 //DEBUG(errs() << "INVESTIGATING NONLOCAL LOAD: "
1285 // << Deps.size() << *LI << '\n');
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001286
Owen Anderson90e717d2008-08-26 22:07:42 +00001287 // If we had to process more than one hundred blocks to find the
1288 // dependencies, this load isn't worth worrying about. Optimizing
1289 // it will be too expensive.
Chris Lattneraf713862008-12-09 19:25:07 +00001290 if (Deps.size() > 100)
Owen Anderson90e717d2008-08-26 22:07:42 +00001291 return false;
Chris Lattner8d1686f2008-12-18 00:51:32 +00001292
1293 // If we had a phi translation failure, we'll have a single entry which is a
1294 // clobber in the current block. Reject this early.
Edwin Török3ffffac2009-06-17 18:48:18 +00001295 if (Deps.size() == 1 && Deps[0].second.isClobber()) {
1296 DEBUG(
Dan Gohman0be10b02009-07-25 01:43:01 +00001297 errs() << "GVN: non-local load ";
1298 WriteAsOperand(errs(), LI);
Dan Gohman7e124382009-07-31 20:24:18 +00001299 errs() << " is clobbered by " << *Deps[0].second.getInst() << '\n';
Edwin Török3ffffac2009-06-17 18:48:18 +00001300 );
Chris Lattner8d1686f2008-12-18 00:51:32 +00001301 return false;
Edwin Török3ffffac2009-06-17 18:48:18 +00001302 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001303
Chris Lattnerdcded152008-12-02 08:16:11 +00001304 // Filter out useless results (non-locals, etc). Keep track of the blocks
1305 // where we have a value available in repl, also keep track of whether we see
1306 // dependencies that produce an unknown value for the load (such as a call
1307 // that could potentially clobber the load).
Chris Lattner19b84b32009-09-21 06:30:24 +00001308 SmallVector<AvailableValueInBlock, 16> ValuesPerBlock;
Chris Lattnerdcded152008-12-02 08:16:11 +00001309 SmallVector<BasicBlock*, 16> UnavailableBlocks;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001310
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001311 const TargetData *TD = 0;
1312
Chris Lattneraf713862008-12-09 19:25:07 +00001313 for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
1314 BasicBlock *DepBB = Deps[i].first;
1315 MemDepResult DepInfo = Deps[i].second;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001316
Chris Lattner4531da82008-12-05 21:04:20 +00001317 if (DepInfo.isClobber()) {
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001318 // If the dependence is to a store that writes to a superset of the bits
1319 // read by the load, we can extract the bits we need for the load from the
1320 // stored value.
1321 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
1322 if (TD == 0)
1323 TD = getAnalysisIfAvailable<TargetData>();
1324 if (TD) {
1325 int Offset = AnalyzeLoadFromClobberingStore(LI, DepSI, *TD);
1326 if (Offset != -1) {
1327 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1328 DepSI->getOperand(0),
1329 Offset));
1330 continue;
1331 }
1332 }
1333 }
1334
1335 // FIXME: Handle memset/memcpy.
Chris Lattner4531da82008-12-05 21:04:20 +00001336 UnavailableBlocks.push_back(DepBB);
1337 continue;
1338 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001339
Chris Lattner4531da82008-12-05 21:04:20 +00001340 Instruction *DepInst = DepInfo.getInst();
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001341
Chris Lattner4531da82008-12-05 21:04:20 +00001342 // Loading the allocation -> undef.
Victor Hernandez48c3c542009-09-18 22:35:49 +00001343 if (isa<AllocationInst>(DepInst) || isMalloc(DepInst)) {
Chris Lattner19b84b32009-09-21 06:30:24 +00001344 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1345 UndefValue::get(LI->getType())));
Chris Lattner46876282008-12-01 01:15:42 +00001346 continue;
1347 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001348
Chris Lattner19b84b32009-09-21 06:30:24 +00001349 if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001350 // Reject loads and stores that are to the same address but are of
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001351 // different types if we have to.
Chris Lattnerdcded152008-12-02 08:16:11 +00001352 if (S->getOperand(0)->getType() != LI->getType()) {
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001353 if (TD == 0)
1354 TD = getAnalysisIfAvailable<TargetData>();
1355
1356 // If the stored value is larger or equal to the loaded value, we can
1357 // reuse it.
Chris Lattner012b3602009-09-21 17:24:04 +00001358 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(S->getOperand(0),
1359 LI->getType(), *TD)) {
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001360 UnavailableBlocks.push_back(DepBB);
1361 continue;
1362 }
Chris Lattnerdcded152008-12-02 08:16:11 +00001363 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001364
Chris Lattner19b84b32009-09-21 06:30:24 +00001365 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1366 S->getOperand(0)));
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001367 continue;
1368 }
1369
1370 if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001371 // If the types mismatch and we can't handle it, reject reuse of the load.
Chris Lattnerdcded152008-12-02 08:16:11 +00001372 if (LD->getType() != LI->getType()) {
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001373 if (TD == 0)
1374 TD = getAnalysisIfAvailable<TargetData>();
1375
1376 // If the stored value is larger or equal to the loaded value, we can
1377 // reuse it.
Chris Lattner012b3602009-09-21 17:24:04 +00001378 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(LD, LI->getType(),*TD)){
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001379 UnavailableBlocks.push_back(DepBB);
1380 continue;
1381 }
Chris Lattnerdcded152008-12-02 08:16:11 +00001382 }
Chris Lattner19b84b32009-09-21 06:30:24 +00001383 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB, LD));
Chris Lattnerdcded152008-12-02 08:16:11 +00001384 continue;
Owen Anderson5d72a422007-07-25 19:57:03 +00001385 }
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001386
1387 UnavailableBlocks.push_back(DepBB);
1388 continue;
Chris Lattner3d7103e2008-03-21 21:14:38 +00001389 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001390
Chris Lattnerdcded152008-12-02 08:16:11 +00001391 // If we have no predecessors that produce a known value for this load, exit
1392 // early.
1393 if (ValuesPerBlock.empty()) return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001394
Chris Lattnerdcded152008-12-02 08:16:11 +00001395 // If all of the instructions we depend on produce a known value for this
1396 // load, then it is fully redundant and we can use PHI insertion to compute
1397 // its value. Insert PHIs and remove the fully redundant value now.
1398 if (UnavailableBlocks.empty()) {
1399 // Use cached PHI construction information from previous runs
1400 SmallPtrSet<Instruction*, 4> &p = phiMap[LI->getPointerOperand()];
Chris Lattneraf713862008-12-09 19:25:07 +00001401 // FIXME: What does phiMap do? Are we positive it isn't getting invalidated?
Chris Lattnerdcded152008-12-02 08:16:11 +00001402 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
1403 I != E; ++I) {
1404 if ((*I)->getParent() == LI->getParent()) {
Dan Gohman7e124382009-07-31 20:24:18 +00001405 DEBUG(errs() << "GVN REMOVING NONLOCAL LOAD #1: " << *LI << '\n');
Chris Lattnerdcded152008-12-02 08:16:11 +00001406 LI->replaceAllUsesWith(*I);
Chris Lattnerf81b0142008-12-09 22:06:23 +00001407 if (isa<PointerType>((*I)->getType()))
1408 MD->invalidateCachedPointerInfo(*I);
Chris Lattnerdcded152008-12-02 08:16:11 +00001409 toErase.push_back(LI);
1410 NumGVNLoad++;
1411 return true;
1412 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001413
Chris Lattner19b84b32009-09-21 06:30:24 +00001414 ValuesPerBlock.push_back(AvailableValueInBlock::get((*I)->getParent(),
1415 *I));
Owen Anderson5b299672007-08-07 23:12:31 +00001416 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001417
Dan Gohman7e124382009-07-31 20:24:18 +00001418 DEBUG(errs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001419
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001420 // Convert the block information to a map, and insert coersions as needed.
Chris Lattnerdcded152008-12-02 08:16:11 +00001421 DenseMap<BasicBlock*, Value*> BlockReplValues;
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001422 GetAvailableBlockValues(BlockReplValues, ValuesPerBlock, LI->getType(), TD);
1423
Chris Lattnerdcded152008-12-02 08:16:11 +00001424 // Perform PHI construction.
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001425 Value *V = GetValueForBlock(LI->getParent(), LI, BlockReplValues, true);
1426 LI->replaceAllUsesWith(V);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001427
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001428 if (isa<PHINode>(V))
1429 V->takeName(LI);
1430 if (isa<PointerType>(V->getType()))
1431 MD->invalidateCachedPointerInfo(V);
Chris Lattnerdcded152008-12-02 08:16:11 +00001432 toErase.push_back(LI);
1433 NumGVNLoad++;
1434 return true;
1435 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001436
Chris Lattnerdcded152008-12-02 08:16:11 +00001437 if (!EnablePRE || !EnableLoadPRE)
1438 return false;
1439
1440 // Okay, we have *some* definitions of the value. This means that the value
1441 // is available in some of our (transitive) predecessors. Lets think about
1442 // doing PRE of this load. This will involve inserting a new load into the
1443 // predecessor when it's not available. We could do this in general, but
1444 // prefer to not increase code size. As such, we only do this when we know
1445 // that we only have to insert *one* load (which means we're basically moving
1446 // the load, not inserting a new one).
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001447
Owen Andersondd37b182009-05-31 09:03:40 +00001448 SmallPtrSet<BasicBlock *, 4> Blockers;
1449 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1450 Blockers.insert(UnavailableBlocks[i]);
1451
1452 // Lets find first basic block with more than one predecessor. Walk backwards
1453 // through predecessors if needed.
Chris Lattnerdcded152008-12-02 08:16:11 +00001454 BasicBlock *LoadBB = LI->getParent();
Owen Andersondd37b182009-05-31 09:03:40 +00001455 BasicBlock *TmpBB = LoadBB;
1456
1457 bool isSinglePred = false;
Dale Johannesena19b67f2009-06-17 20:48:23 +00001458 bool allSingleSucc = true;
Owen Andersondd37b182009-05-31 09:03:40 +00001459 while (TmpBB->getSinglePredecessor()) {
1460 isSinglePred = true;
1461 TmpBB = TmpBB->getSinglePredecessor();
1462 if (!TmpBB) // If haven't found any, bail now.
1463 return false;
1464 if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1465 return false;
1466 if (Blockers.count(TmpBB))
1467 return false;
Dale Johannesena19b67f2009-06-17 20:48:23 +00001468 if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1469 allSingleSucc = false;
Owen Andersondd37b182009-05-31 09:03:40 +00001470 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001471
Owen Andersondd37b182009-05-31 09:03:40 +00001472 assert(TmpBB);
1473 LoadBB = TmpBB;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001474
Chris Lattnerdcded152008-12-02 08:16:11 +00001475 // If we have a repl set with LI itself in it, this means we have a loop where
1476 // at least one of the values is LI. Since this means that we won't be able
1477 // to eliminate LI even if we insert uses in the other predecessors, we will
1478 // end up increasing code size. Reject this by scanning for LI.
1479 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
Chris Lattner19b84b32009-09-21 06:30:24 +00001480 if (ValuesPerBlock[i].V == LI)
Chris Lattnerdcded152008-12-02 08:16:11 +00001481 return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001482
Owen Andersondd37b182009-05-31 09:03:40 +00001483 if (isSinglePred) {
1484 bool isHot = false;
1485 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
Chris Lattner19b84b32009-09-21 06:30:24 +00001486 if (Instruction *I = dyn_cast<Instruction>(ValuesPerBlock[i].V))
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001487 // "Hot" Instruction is in some loop (because it dominates its dep.
1488 // instruction).
1489 if (DT->dominates(LI, I)) {
1490 isHot = true;
1491 break;
1492 }
Owen Andersondd37b182009-05-31 09:03:40 +00001493
1494 // We are interested only in "hot" instructions. We don't want to do any
1495 // mis-optimizations here.
1496 if (!isHot)
1497 return false;
1498 }
1499
Chris Lattnerdcded152008-12-02 08:16:11 +00001500 // Okay, we have some hope :). Check to see if the loaded value is fully
1501 // available in all but one predecessor.
1502 // FIXME: If we could restructure the CFG, we could make a common pred with
1503 // all the preds that don't have an available LI and insert a new load into
1504 // that one block.
1505 BasicBlock *UnavailablePred = 0;
1506
Chris Lattner159b98f2008-12-05 07:49:08 +00001507 DenseMap<BasicBlock*, char> FullyAvailableBlocks;
Chris Lattnerdcded152008-12-02 08:16:11 +00001508 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
Chris Lattner19b84b32009-09-21 06:30:24 +00001509 FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
Chris Lattnerdcded152008-12-02 08:16:11 +00001510 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1511 FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1512
1513 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1514 PI != E; ++PI) {
1515 if (IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
1516 continue;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001517
Chris Lattnerdcded152008-12-02 08:16:11 +00001518 // If this load is not available in multiple predecessors, reject it.
1519 if (UnavailablePred && UnavailablePred != *PI)
1520 return false;
1521 UnavailablePred = *PI;
1522 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001523
Chris Lattnerdcded152008-12-02 08:16:11 +00001524 assert(UnavailablePred != 0 &&
1525 "Fully available value should be eliminated above!");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001526
Chris Lattnerdcded152008-12-02 08:16:11 +00001527 // If the loaded pointer is PHI node defined in this block, do PHI translation
1528 // to get its value in the predecessor.
1529 Value *LoadPtr = LI->getOperand(0)->DoPHITranslation(LoadBB, UnavailablePred);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001530
Chris Lattnerdcded152008-12-02 08:16:11 +00001531 // Make sure the value is live in the predecessor. If it was defined by a
1532 // non-PHI instruction in this block, we don't know how to recompute it above.
1533 if (Instruction *LPInst = dyn_cast<Instruction>(LoadPtr))
1534 if (!DT->dominates(LPInst->getParent(), UnavailablePred)) {
Daniel Dunbar005975c2009-07-25 00:23:56 +00001535 DEBUG(errs() << "COULDN'T PRE LOAD BECAUSE PTR IS UNAVAILABLE IN PRED: "
Dan Gohman7e124382009-07-31 20:24:18 +00001536 << *LPInst << '\n' << *LI << "\n");
Chris Lattnerdcded152008-12-02 08:16:11 +00001537 return false;
1538 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001539
Chris Lattnerdcded152008-12-02 08:16:11 +00001540 // We don't currently handle critical edges :(
1541 if (UnavailablePred->getTerminator()->getNumSuccessors() != 1) {
Daniel Dunbar005975c2009-07-25 00:23:56 +00001542 DEBUG(errs() << "COULD NOT PRE LOAD BECAUSE OF CRITICAL EDGE '"
Dan Gohman7e124382009-07-31 20:24:18 +00001543 << UnavailablePred->getName() << "': " << *LI << '\n');
Chris Lattnerdcded152008-12-02 08:16:11 +00001544 return false;
Owen Anderson5b299672007-08-07 23:12:31 +00001545 }
Dale Johannesena19b67f2009-06-17 20:48:23 +00001546
1547 // Make sure it is valid to move this load here. We have to watch out for:
1548 // @1 = getelementptr (i8* p, ...
1549 // test p and branch if == 0
1550 // load @1
1551 // It is valid to have the getelementptr before the test, even if p can be 0,
1552 // as getelementptr only does address arithmetic.
1553 // If we are not pushing the value through any multiple-successor blocks
1554 // we do not have this case. Otherwise, check that the load is safe to
1555 // put anywhere; this can be improved, but should be conservatively safe.
1556 if (!allSingleSucc &&
1557 !isSafeToLoadUnconditionally(LoadPtr, UnavailablePred->getTerminator()))
1558 return false;
1559
Chris Lattnerdcded152008-12-02 08:16:11 +00001560 // Okay, we can eliminate this load by inserting a reload in the predecessor
1561 // and using PHI construction to get the value in the other predecessors, do
1562 // it.
Dan Gohman7e124382009-07-31 20:24:18 +00001563 DEBUG(errs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001564
Chris Lattnerdcded152008-12-02 08:16:11 +00001565 Value *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1566 LI->getAlignment(),
1567 UnavailablePred->getTerminator());
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001568
Owen Anderson1c057ee2009-05-29 05:37:54 +00001569 SmallPtrSet<Instruction*, 4> &p = phiMap[LI->getPointerOperand()];
1570 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
1571 I != E; ++I)
Chris Lattner19b84b32009-09-21 06:30:24 +00001572 ValuesPerBlock.push_back(AvailableValueInBlock::get((*I)->getParent(), *I));
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001573
Chris Lattnerdcded152008-12-02 08:16:11 +00001574 DenseMap<BasicBlock*, Value*> BlockReplValues;
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001575 GetAvailableBlockValues(BlockReplValues, ValuesPerBlock, LI->getType(), TD);
Chris Lattnerdcded152008-12-02 08:16:11 +00001576 BlockReplValues[UnavailablePred] = NewLoad;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001577
Chris Lattnerdcded152008-12-02 08:16:11 +00001578 // Perform PHI construction.
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001579 Value *V = GetValueForBlock(LI->getParent(), LI, BlockReplValues, true);
1580 LI->replaceAllUsesWith(V);
1581 if (isa<PHINode>(V))
1582 V->takeName(LI);
1583 if (isa<PointerType>(V->getType()))
1584 MD->invalidateCachedPointerInfo(V);
Chris Lattnerdcded152008-12-02 08:16:11 +00001585 toErase.push_back(LI);
1586 NumPRELoad++;
Owen Anderson5d72a422007-07-25 19:57:03 +00001587 return true;
1588}
1589
Owen Andersone0143452007-08-16 22:02:55 +00001590/// processLoad - Attempt to eliminate a load, first by eliminating it
1591/// locally, and then attempting non-local elimination if that fails.
Chris Lattner4531da82008-12-05 21:04:20 +00001592bool GVN::processLoad(LoadInst *L, SmallVectorImpl<Instruction*> &toErase) {
1593 if (L->isVolatile())
Owen Anderson85c40642007-07-24 17:55:58 +00001594 return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001595
Owen Anderson85c40642007-07-24 17:55:58 +00001596 // ... to a pointer that has been loaded from before...
Chris Lattnerff36c952009-09-21 02:42:51 +00001597 MemDepResult Dep = MD->getDependency(L);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001598
Chris Lattner4531da82008-12-05 21:04:20 +00001599 // If the value isn't available, don't do anything!
Chris Lattnerff36c952009-09-21 02:42:51 +00001600 if (Dep.isClobber()) {
Chris Lattner0907b522009-09-21 05:57:11 +00001601 // FIXME: We should handle memset/memcpy/memmove as dependent instructions
1602 // to forward the value if available.
1603 //if (isa<MemIntrinsic>(Dep.getInst()))
1604 //errs() << "LOAD DEPENDS ON MEM: " << *L << "\n" << *Dep.getInst()<<"\n\n";
1605
1606 // Check to see if we have something like this:
Chris Lattner7741aa52009-09-20 19:03:47 +00001607 // store i32 123, i32* %P
1608 // %A = bitcast i32* %P to i8*
1609 // %B = gep i8* %A, i32 1
1610 // %C = load i8* %B
1611 //
1612 // We could do that by recognizing if the clobber instructions are obviously
1613 // a common base + constant offset, and if the previous store (or memset)
1614 // completely covers this load. This sort of thing can happen in bitfield
1615 // access code.
Chris Lattner0907b522009-09-21 05:57:11 +00001616 if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst()))
Chris Lattner41eb59c2009-09-21 06:22:46 +00001617 if (const TargetData *TD = getAnalysisIfAvailable<TargetData>()) {
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001618 int Offset = AnalyzeLoadFromClobberingStore(L, DepSI, *TD);
Chris Lattner41eb59c2009-09-21 06:22:46 +00001619 if (Offset != -1) {
1620 Value *AvailVal = GetStoreValueForLoad(DepSI->getOperand(0), Offset,
Chris Lattneraae7fcb2009-09-21 06:48:08 +00001621 L->getType(), L, *TD);
Chris Lattner0907b522009-09-21 05:57:11 +00001622 DEBUG(errs() << "GVN COERCED STORE BITS:\n" << *DepSI << '\n'
1623 << *AvailVal << '\n' << *L << "\n\n\n");
1624
1625 // Replace the load!
1626 L->replaceAllUsesWith(AvailVal);
1627 if (isa<PointerType>(AvailVal->getType()))
1628 MD->invalidateCachedPointerInfo(AvailVal);
1629 toErase.push_back(L);
1630 NumGVNLoad++;
1631 return true;
1632 }
Chris Lattner41eb59c2009-09-21 06:22:46 +00001633 }
Chris Lattner0907b522009-09-21 05:57:11 +00001634
Edwin Török47cf8842009-05-29 09:46:03 +00001635 DEBUG(
1636 // fast print dep, using operator<< on instruction would be too slow
Dan Gohman0be10b02009-07-25 01:43:01 +00001637 errs() << "GVN: load ";
1638 WriteAsOperand(errs(), L);
Chris Lattnerff36c952009-09-21 02:42:51 +00001639 Instruction *I = Dep.getInst();
Dan Gohman7e124382009-07-31 20:24:18 +00001640 errs() << " is clobbered by " << *I << '\n';
Edwin Török47cf8842009-05-29 09:46:03 +00001641 );
Chris Lattner4531da82008-12-05 21:04:20 +00001642 return false;
Edwin Török47cf8842009-05-29 09:46:03 +00001643 }
Chris Lattner4531da82008-12-05 21:04:20 +00001644
1645 // If it is defined in another block, try harder.
Chris Lattnerff36c952009-09-21 02:42:51 +00001646 if (Dep.isNonLocal())
Chris Lattner4531da82008-12-05 21:04:20 +00001647 return processNonLocalLoad(L, toErase);
Eli Friedman350307f2008-02-12 12:08:14 +00001648
Chris Lattnerff36c952009-09-21 02:42:51 +00001649 Instruction *DepInst = Dep.getInst();
Chris Lattner4531da82008-12-05 21:04:20 +00001650 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
Chris Lattner7741aa52009-09-20 19:03:47 +00001651 Value *StoredVal = DepSI->getOperand(0);
1652
1653 // The store and load are to a must-aliased pointer, but they may not
1654 // actually have the same type. See if we know how to reuse the stored
1655 // value (depending on its type).
1656 const TargetData *TD = 0;
1657 if (StoredVal->getType() != L->getType() &&
1658 (TD = getAnalysisIfAvailable<TargetData>())) {
Chris Lattner012b3602009-09-21 17:24:04 +00001659 StoredVal = CoerceAvailableValueToLoadType(StoredVal, L->getType(),
1660 L, *TD);
Chris Lattner7741aa52009-09-20 19:03:47 +00001661 if (StoredVal == 0)
1662 return false;
1663
1664 DEBUG(errs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
1665 << '\n' << *L << "\n\n\n");
1666 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001667
Chris Lattner4531da82008-12-05 21:04:20 +00001668 // Remove it!
Chris Lattner7741aa52009-09-20 19:03:47 +00001669 L->replaceAllUsesWith(StoredVal);
1670 if (isa<PointerType>(StoredVal->getType()))
1671 MD->invalidateCachedPointerInfo(StoredVal);
Chris Lattner4531da82008-12-05 21:04:20 +00001672 toErase.push_back(L);
1673 NumGVNLoad++;
1674 return true;
1675 }
1676
1677 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
Chris Lattner7741aa52009-09-20 19:03:47 +00001678 Value *AvailableVal = DepLI;
1679
1680 // The loads are of a must-aliased pointer, but they may not actually have
1681 // the same type. See if we know how to reuse the previously loaded value
1682 // (depending on its type).
1683 const TargetData *TD = 0;
1684 if (DepLI->getType() != L->getType() &&
1685 (TD = getAnalysisIfAvailable<TargetData>())) {
Chris Lattner012b3602009-09-21 17:24:04 +00001686 AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(), L,*TD);
Chris Lattner7741aa52009-09-20 19:03:47 +00001687 if (AvailableVal == 0)
1688 return false;
1689
1690 DEBUG(errs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
1691 << "\n" << *L << "\n\n\n");
1692 }
1693
Chris Lattner4531da82008-12-05 21:04:20 +00001694 // Remove it!
Chris Lattner7741aa52009-09-20 19:03:47 +00001695 L->replaceAllUsesWith(AvailableVal);
Chris Lattnerf81b0142008-12-09 22:06:23 +00001696 if (isa<PointerType>(DepLI->getType()))
1697 MD->invalidateCachedPointerInfo(DepLI);
Chris Lattner4531da82008-12-05 21:04:20 +00001698 toErase.push_back(L);
1699 NumGVNLoad++;
1700 return true;
1701 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001702
Chris Lattner8ea60462008-11-30 01:39:32 +00001703 // If this load really doesn't depend on anything, then we must be loading an
1704 // undef value. This can happen when loading for a fresh allocation with no
1705 // intervening stores, for example.
Victor Hernandez48c3c542009-09-18 22:35:49 +00001706 if (isa<AllocationInst>(DepInst) || isMalloc(DepInst)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +00001707 L->replaceAllUsesWith(UndefValue::get(L->getType()));
Chris Lattner8ea60462008-11-30 01:39:32 +00001708 toErase.push_back(L);
Chris Lattner8ea60462008-11-30 01:39:32 +00001709 NumGVNLoad++;
Chris Lattner4531da82008-12-05 21:04:20 +00001710 return true;
Eli Friedman350307f2008-02-12 12:08:14 +00001711 }
1712
Chris Lattner4531da82008-12-05 21:04:20 +00001713 return false;
Owen Anderson85c40642007-07-24 17:55:58 +00001714}
1715
Chris Lattnerff36c952009-09-21 02:42:51 +00001716Value *GVN::lookupNumber(BasicBlock *BB, uint32_t num) {
Owen Andersonaef6a922008-06-23 17:49:45 +00001717 DenseMap<BasicBlock*, ValueNumberScope*>::iterator I = localAvail.find(BB);
1718 if (I == localAvail.end())
1719 return 0;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001720
Chris Lattnerff36c952009-09-21 02:42:51 +00001721 ValueNumberScope *Locals = I->second;
1722 while (Locals) {
1723 DenseMap<uint32_t, Value*>::iterator I = Locals->table.find(num);
1724 if (I != Locals->table.end())
Owen Anderson2a412722008-06-20 01:15:47 +00001725 return I->second;
Chris Lattnerff36c952009-09-21 02:42:51 +00001726 Locals = Locals->parent;
Owen Anderson2a412722008-06-20 01:15:47 +00001727 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001728
Owen Anderson2a412722008-06-20 01:15:47 +00001729 return 0;
1730}
1731
Owen Andersona03e7862008-12-15 02:03:00 +00001732/// AttemptRedundancyElimination - If the "fast path" of redundancy elimination
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001733/// by inheritance from the dominator fails, see if we can perform phi
Owen Andersona03e7862008-12-15 02:03:00 +00001734/// construction to eliminate the redundancy.
Chris Lattnerff36c952009-09-21 02:42:51 +00001735Value *GVN::AttemptRedundancyElimination(Instruction *orig, unsigned valno) {
1736 BasicBlock *BaseBlock = orig->getParent();
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001737
Owen Andersona03e7862008-12-15 02:03:00 +00001738 SmallPtrSet<BasicBlock*, 4> Visited;
1739 SmallVector<BasicBlock*, 8> Stack;
1740 Stack.push_back(BaseBlock);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001741
Owen Andersona03e7862008-12-15 02:03:00 +00001742 DenseMap<BasicBlock*, Value*> Results;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001743
Owen Andersona03e7862008-12-15 02:03:00 +00001744 // Walk backwards through our predecessors, looking for instances of the
1745 // value number we're looking for. Instances are recorded in the Results
1746 // map, which is then used to perform phi construction.
1747 while (!Stack.empty()) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001748 BasicBlock *Current = Stack.back();
Owen Andersona03e7862008-12-15 02:03:00 +00001749 Stack.pop_back();
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001750
Owen Andersona03e7862008-12-15 02:03:00 +00001751 // If we've walked all the way to a proper dominator, then give up. Cases
1752 // where the instance is in the dominator will have been caught by the fast
1753 // path, and any cases that require phi construction further than this are
1754 // probably not worth it anyways. Note that this is a SIGNIFICANT compile
1755 // time improvement.
1756 if (DT->properlyDominates(Current, orig->getParent())) return 0;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001757
Owen Andersona03e7862008-12-15 02:03:00 +00001758 DenseMap<BasicBlock*, ValueNumberScope*>::iterator LA =
1759 localAvail.find(Current);
1760 if (LA == localAvail.end()) return 0;
Chris Lattner6f33e552009-01-19 22:00:18 +00001761 DenseMap<uint32_t, Value*>::iterator V = LA->second->table.find(valno);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001762
Owen Andersona03e7862008-12-15 02:03:00 +00001763 if (V != LA->second->table.end()) {
1764 // Found an instance, record it.
1765 Results.insert(std::make_pair(Current, V->second));
1766 continue;
1767 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001768
Owen Andersona03e7862008-12-15 02:03:00 +00001769 // If we reach the beginning of the function, then give up.
1770 if (pred_begin(Current) == pred_end(Current))
1771 return 0;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001772
Owen Andersona03e7862008-12-15 02:03:00 +00001773 for (pred_iterator PI = pred_begin(Current), PE = pred_end(Current);
1774 PI != PE; ++PI)
1775 if (Visited.insert(*PI))
1776 Stack.push_back(*PI);
1777 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001778
Owen Andersona03e7862008-12-15 02:03:00 +00001779 // If we didn't find instances, give up. Otherwise, perform phi construction.
1780 if (Results.size() == 0)
1781 return 0;
Chris Lattner34635fd2009-10-10 06:22:45 +00001782
1783 return GetValueForBlock(BaseBlock, orig, Results, true);
Owen Andersona03e7862008-12-15 02:03:00 +00001784}
1785
Owen Andersonf631bb62007-08-14 18:16:29 +00001786/// processInstruction - When calculating availability, handle an instruction
Owen Anderson85c40642007-07-24 17:55:58 +00001787/// by inserting it into the appropriate sets
Owen Anderson9334fc62008-06-12 19:25:32 +00001788bool GVN::processInstruction(Instruction *I,
Chris Lattner7de20452008-03-21 22:01:16 +00001789 SmallVectorImpl<Instruction*> &toErase) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001790 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1791 bool Changed = processLoad(LI, toErase);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001792
Chris Lattnerff36c952009-09-21 02:42:51 +00001793 if (!Changed) {
1794 unsigned Num = VN.lookup_or_add(LI);
1795 localAvail[I->getParent()]->table.insert(std::make_pair(Num, LI));
Owen Andersone6b4ff82008-06-18 21:41:49 +00001796 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001797
Chris Lattnerff36c952009-09-21 02:42:51 +00001798 return Changed;
Owen Andersone6b4ff82008-06-18 21:41:49 +00001799 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001800
Chris Lattnerff36c952009-09-21 02:42:51 +00001801 uint32_t NextNum = VN.getNextUnusedValueNumber();
1802 unsigned Num = VN.lookup_or_add(I);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001803
Chris Lattnerff36c952009-09-21 02:42:51 +00001804 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1805 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001806
Owen Andersonef8bf0f2009-04-01 23:53:49 +00001807 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
1808 return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001809
Chris Lattnerff36c952009-09-21 02:42:51 +00001810 Value *BranchCond = BI->getCondition();
1811 uint32_t CondVN = VN.lookup_or_add(BranchCond);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001812
Chris Lattnerff36c952009-09-21 02:42:51 +00001813 BasicBlock *TrueSucc = BI->getSuccessor(0);
1814 BasicBlock *FalseSucc = BI->getSuccessor(1);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001815
Chris Lattnerff36c952009-09-21 02:42:51 +00001816 if (TrueSucc->getSinglePredecessor())
1817 localAvail[TrueSucc]->table[CondVN] =
1818 ConstantInt::getTrue(TrueSucc->getContext());
1819 if (FalseSucc->getSinglePredecessor())
1820 localAvail[FalseSucc]->table[CondVN] =
1821 ConstantInt::getFalse(TrueSucc->getContext());
Owen Andersonef8bf0f2009-04-01 23:53:49 +00001822
1823 return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001824
Owen Andersonced50f82008-04-07 09:59:07 +00001825 // Allocations are always uniquely numbered, so we can save time and memory
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001826 // by fast failing them.
Chris Lattner1d1bc8e2009-09-27 21:46:50 +00001827 } else if (isa<AllocationInst>(I) || isa<TerminatorInst>(I)) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001828 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Owen Andersonced50f82008-04-07 09:59:07 +00001829 return false;
Owen Andersone6b4ff82008-06-18 21:41:49 +00001830 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001831
Owen Andersone0143452007-08-16 22:02:55 +00001832 // Collapse PHI nodes
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001833 if (PHINode* p = dyn_cast<PHINode>(I)) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001834 Value *constVal = CollapsePhi(p);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001835
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001836 if (constVal) {
Owen Andersone02ad522007-08-16 22:51:56 +00001837 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1838 PI != PE; ++PI)
Chris Lattner4bab29b2008-12-09 19:21:47 +00001839 PI->second.erase(p);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001840
Owen Andersone02ad522007-08-16 22:51:56 +00001841 p->replaceAllUsesWith(constVal);
Chris Lattnerf81b0142008-12-09 22:06:23 +00001842 if (isa<PointerType>(constVal->getType()))
1843 MD->invalidateCachedPointerInfo(constVal);
Owen Anderson575f2812008-12-23 00:49:51 +00001844 VN.erase(p);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001845
Owen Andersone02ad522007-08-16 22:51:56 +00001846 toErase.push_back(p);
Owen Andersone6b4ff82008-06-18 21:41:49 +00001847 } else {
Chris Lattnerff36c952009-09-21 02:42:51 +00001848 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001849 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001850
Owen Anderson8a8d13c2008-07-03 17:44:33 +00001851 // If the number we were assigned was a brand new VN, then we don't
1852 // need to do a lookup to see if the number already exists
1853 // somewhere in the domtree: it can't!
Chris Lattnerff36c952009-09-21 02:42:51 +00001854 } else if (Num == NextNum) {
1855 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001856
Owen Andersona03e7862008-12-15 02:03:00 +00001857 // Perform fast-path value-number based elimination of values inherited from
1858 // dominators.
Chris Lattnerff36c952009-09-21 02:42:51 +00001859 } else if (Value *repl = lookupNumber(I->getParent(), Num)) {
Owen Andersonc772be72007-12-08 01:37:09 +00001860 // Remove it!
Owen Anderson5aff8002007-07-31 23:27:13 +00001861 VN.erase(I);
Owen Anderson85c40642007-07-24 17:55:58 +00001862 I->replaceAllUsesWith(repl);
Chris Lattnerf81b0142008-12-09 22:06:23 +00001863 if (isa<PointerType>(repl->getType()))
1864 MD->invalidateCachedPointerInfo(repl);
Owen Anderson85c40642007-07-24 17:55:58 +00001865 toErase.push_back(I);
1866 return true;
Owen Andersona03e7862008-12-15 02:03:00 +00001867
1868#if 0
1869 // Perform slow-pathvalue-number based elimination with phi construction.
Chris Lattnerff36c952009-09-21 02:42:51 +00001870 } else if (Value *repl = AttemptRedundancyElimination(I, Num)) {
Owen Andersona03e7862008-12-15 02:03:00 +00001871 // Remove it!
1872 VN.erase(I);
1873 I->replaceAllUsesWith(repl);
1874 if (isa<PointerType>(repl->getType()))
1875 MD->invalidateCachedPointerInfo(repl);
1876 toErase.push_back(I);
1877 return true;
1878#endif
Owen Anderson8a8d13c2008-07-03 17:44:33 +00001879 } else {
Chris Lattnerff36c952009-09-21 02:42:51 +00001880 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Owen Anderson85c40642007-07-24 17:55:58 +00001881 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001882
Owen Anderson85c40642007-07-24 17:55:58 +00001883 return false;
1884}
1885
Bill Wendling42f17f62008-12-22 22:32:22 +00001886/// runOnFunction - This is the main transformation entry point for a function.
Owen Andersonbe168b32007-08-14 18:04:11 +00001887bool GVN::runOnFunction(Function& F) {
Chris Lattner02ca4422008-12-01 00:40:32 +00001888 MD = &getAnalysis<MemoryDependenceAnalysis>();
1889 DT = &getAnalysis<DominatorTree>();
Owen Andersonbcf2bd52008-05-12 20:15:55 +00001890 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
Chris Lattner02ca4422008-12-01 00:40:32 +00001891 VN.setMemDep(MD);
1892 VN.setDomTree(DT);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001893
Chris Lattnerff36c952009-09-21 02:42:51 +00001894 bool Changed = false;
1895 bool ShouldContinue = true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001896
Owen Anderson26ed2572008-07-16 17:52:31 +00001897 // Merge unconditional branches, allowing PRE to catch more
1898 // optimization opportunities.
1899 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001900 BasicBlock *BB = FI;
Owen Anderson26ed2572008-07-16 17:52:31 +00001901 ++FI;
Owen Andersonf59eef82008-07-17 00:01:40 +00001902 bool removedBlock = MergeBlockIntoPredecessor(BB, this);
1903 if (removedBlock) NumGVNBlocks++;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001904
Chris Lattnerff36c952009-09-21 02:42:51 +00001905 Changed |= removedBlock;
Owen Anderson26ed2572008-07-16 17:52:31 +00001906 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001907
Chris Lattner4bab29b2008-12-09 19:21:47 +00001908 unsigned Iteration = 0;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001909
Chris Lattnerff36c952009-09-21 02:42:51 +00001910 while (ShouldContinue) {
Dan Gohman0be10b02009-07-25 01:43:01 +00001911 DEBUG(errs() << "GVN iteration: " << Iteration << "\n");
Chris Lattnerff36c952009-09-21 02:42:51 +00001912 ShouldContinue = iterateOnFunction(F);
1913 Changed |= ShouldContinue;
Chris Lattner4bab29b2008-12-09 19:21:47 +00001914 ++Iteration;
Owen Andersonbe168b32007-08-14 18:04:11 +00001915 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001916
Owen Anderson916f4732008-07-18 18:03:38 +00001917 if (EnablePRE) {
Owen Anderson9c935902008-09-03 23:06:07 +00001918 bool PREChanged = true;
1919 while (PREChanged) {
1920 PREChanged = performPRE(F);
Chris Lattnerff36c952009-09-21 02:42:51 +00001921 Changed |= PREChanged;
Owen Anderson9c935902008-09-03 23:06:07 +00001922 }
Owen Anderson916f4732008-07-18 18:03:38 +00001923 }
Chris Lattner4bab29b2008-12-09 19:21:47 +00001924 // FIXME: Should perform GVN again after PRE does something. PRE can move
1925 // computations into blocks where they become fully redundant. Note that
1926 // we can't do this until PRE's critical edge splitting updates memdep.
1927 // Actually, when this happens, we should just fully integrate PRE into GVN.
Nuno Lopes274474b2008-10-10 16:25:50 +00001928
1929 cleanupGlobalSets();
1930
Chris Lattnerff36c952009-09-21 02:42:51 +00001931 return Changed;
Owen Andersonbe168b32007-08-14 18:04:11 +00001932}
1933
1934
Chris Lattnerff36c952009-09-21 02:42:51 +00001935bool GVN::processBlock(BasicBlock *BB) {
Chris Lattner4bab29b2008-12-09 19:21:47 +00001936 // FIXME: Kill off toErase by doing erasing eagerly in a helper function (and
1937 // incrementing BI before processing an instruction).
Owen Anderson9334fc62008-06-12 19:25:32 +00001938 SmallVector<Instruction*, 8> toErase;
Chris Lattnerff36c952009-09-21 02:42:51 +00001939 bool ChangedFunction = false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001940
Owen Anderson9334fc62008-06-12 19:25:32 +00001941 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1942 BI != BE;) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001943 ChangedFunction |= processInstruction(BI, toErase);
Owen Anderson9334fc62008-06-12 19:25:32 +00001944 if (toErase.empty()) {
1945 ++BI;
1946 continue;
1947 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001948
Owen Anderson9334fc62008-06-12 19:25:32 +00001949 // If we need some instructions deleted, do it now.
1950 NumGVNInstr += toErase.size();
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001951
Owen Anderson9334fc62008-06-12 19:25:32 +00001952 // Avoid iterator invalidation.
1953 bool AtStart = BI == BB->begin();
1954 if (!AtStart)
1955 --BI;
1956
1957 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
Chris Lattner02ca4422008-12-01 00:40:32 +00001958 E = toErase.end(); I != E; ++I) {
Dan Gohman7e124382009-07-31 20:24:18 +00001959 DEBUG(errs() << "GVN removed: " << **I << '\n');
Chris Lattner02ca4422008-12-01 00:40:32 +00001960 MD->removeInstruction(*I);
Owen Anderson9334fc62008-06-12 19:25:32 +00001961 (*I)->eraseFromParent();
Bill Wendling84049422008-12-22 21:57:30 +00001962 DEBUG(verifyRemoved(*I));
Chris Lattner02ca4422008-12-01 00:40:32 +00001963 }
Chris Lattner4bab29b2008-12-09 19:21:47 +00001964 toErase.clear();
Owen Anderson9334fc62008-06-12 19:25:32 +00001965
1966 if (AtStart)
1967 BI = BB->begin();
1968 else
1969 ++BI;
Owen Anderson9334fc62008-06-12 19:25:32 +00001970 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001971
Chris Lattnerff36c952009-09-21 02:42:51 +00001972 return ChangedFunction;
Owen Anderson9334fc62008-06-12 19:25:32 +00001973}
1974
Owen Andersone6b4ff82008-06-18 21:41:49 +00001975/// performPRE - Perform a purely local form of PRE that looks for diamond
1976/// control flow patterns and attempts to perform simple PRE at the join point.
1977bool GVN::performPRE(Function& F) {
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001978 bool Changed = false;
Owen Andersonec747c42008-06-19 19:54:19 +00001979 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
Chris Lattner3304b562008-12-01 07:29:03 +00001980 DenseMap<BasicBlock*, Value*> predMap;
Owen Andersone6b4ff82008-06-18 21:41:49 +00001981 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
1982 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001983 BasicBlock *CurrentBlock = *DI;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001984
Owen Andersone6b4ff82008-06-18 21:41:49 +00001985 // Nothing to PRE in the entry block.
1986 if (CurrentBlock == &F.getEntryBlock()) continue;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001987
Owen Andersone6b4ff82008-06-18 21:41:49 +00001988 for (BasicBlock::iterator BI = CurrentBlock->begin(),
1989 BE = CurrentBlock->end(); BI != BE; ) {
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001990 Instruction *CurInst = BI++;
Duncan Sands2f500832009-05-06 06:49:50 +00001991
Chris Lattner1d1bc8e2009-09-27 21:46:50 +00001992 if (isa<AllocationInst>(CurInst) ||
Victor Hernandez48c3c542009-09-18 22:35:49 +00001993 isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
Owen Anderson35b47072009-08-13 21:58:54 +00001994 (CurInst->getType() == Type::getVoidTy(F.getContext())) ||
Duncan Sands2f500832009-05-06 06:49:50 +00001995 CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
John Criswell6e0aa282009-03-10 15:04:53 +00001996 isa<DbgInfoIntrinsic>(CurInst))
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001997 continue;
Duncan Sands2f500832009-05-06 06:49:50 +00001998
Chris Lattnerff36c952009-09-21 02:42:51 +00001999 uint32_t ValNo = VN.lookup(CurInst);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002000
Owen Andersone6b4ff82008-06-18 21:41:49 +00002001 // Look for the predecessors for PRE opportunities. We're
2002 // only trying to solve the basic diamond case, where
2003 // a value is computed in the successor and one predecessor,
2004 // but not the other. We also explicitly disallow cases
2005 // where the successor is its own predecessor, because they're
2006 // more complicated to get right.
Chris Lattnerff36c952009-09-21 02:42:51 +00002007 unsigned NumWith = 0;
2008 unsigned NumWithout = 0;
2009 BasicBlock *PREPred = 0;
Chris Lattner3304b562008-12-01 07:29:03 +00002010 predMap.clear();
2011
Owen Andersone6b4ff82008-06-18 21:41:49 +00002012 for (pred_iterator PI = pred_begin(CurrentBlock),
2013 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
2014 // We're not interested in PRE where the block is its
Owen Anderson2a412722008-06-20 01:15:47 +00002015 // own predecessor, on in blocks with predecessors
2016 // that are not reachable.
2017 if (*PI == CurrentBlock) {
Chris Lattnerff36c952009-09-21 02:42:51 +00002018 NumWithout = 2;
Owen Anderson2a412722008-06-20 01:15:47 +00002019 break;
2020 } else if (!localAvail.count(*PI)) {
Chris Lattnerff36c952009-09-21 02:42:51 +00002021 NumWithout = 2;
Owen Anderson2a412722008-06-20 01:15:47 +00002022 break;
2023 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002024
2025 DenseMap<uint32_t, Value*>::iterator predV =
Chris Lattnerff36c952009-09-21 02:42:51 +00002026 localAvail[*PI]->table.find(ValNo);
Owen Anderson2a412722008-06-20 01:15:47 +00002027 if (predV == localAvail[*PI]->table.end()) {
Owen Andersone6b4ff82008-06-18 21:41:49 +00002028 PREPred = *PI;
Chris Lattnerff36c952009-09-21 02:42:51 +00002029 NumWithout++;
Chris Lattner66a3a3e2008-12-01 07:35:54 +00002030 } else if (predV->second == CurInst) {
Chris Lattnerff36c952009-09-21 02:42:51 +00002031 NumWithout = 2;
Owen Andersone6b4ff82008-06-18 21:41:49 +00002032 } else {
Owen Anderson2a412722008-06-20 01:15:47 +00002033 predMap[*PI] = predV->second;
Chris Lattnerff36c952009-09-21 02:42:51 +00002034 NumWith++;
Owen Andersone6b4ff82008-06-18 21:41:49 +00002035 }
2036 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002037
Owen Andersone6b4ff82008-06-18 21:41:49 +00002038 // Don't do PRE when it might increase code size, i.e. when
2039 // we would need to insert instructions in more than one pred.
Chris Lattnerff36c952009-09-21 02:42:51 +00002040 if (NumWithout != 1 || NumWith == 0)
Owen Andersone6b4ff82008-06-18 21:41:49 +00002041 continue;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002042
Owen Andersonec747c42008-06-19 19:54:19 +00002043 // We can't do PRE safely on a critical edge, so instead we schedule
2044 // the edge to be split and perform the PRE the next time we iterate
2045 // on the function.
Chris Lattnerff36c952009-09-21 02:42:51 +00002046 unsigned SuccNum = 0;
Owen Andersonec747c42008-06-19 19:54:19 +00002047 for (unsigned i = 0, e = PREPred->getTerminator()->getNumSuccessors();
2048 i != e; ++i)
Owen Anderson9c935902008-09-03 23:06:07 +00002049 if (PREPred->getTerminator()->getSuccessor(i) == CurrentBlock) {
Chris Lattnerff36c952009-09-21 02:42:51 +00002050 SuccNum = i;
Owen Andersonec747c42008-06-19 19:54:19 +00002051 break;
2052 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002053
Chris Lattnerff36c952009-09-21 02:42:51 +00002054 if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
2055 toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
Owen Andersonec747c42008-06-19 19:54:19 +00002056 continue;
2057 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002058
Owen Andersone6b4ff82008-06-18 21:41:49 +00002059 // Instantiate the expression the in predecessor that lacked it.
2060 // Because we are going top-down through the block, all value numbers
2061 // will be available in the predecessor by the time we need them. Any
2062 // that weren't original present will have been instantiated earlier
2063 // in this loop.
Nick Lewyckyc94270c2009-09-27 07:38:41 +00002064 Instruction *PREInstr = CurInst->clone();
Owen Andersone6b4ff82008-06-18 21:41:49 +00002065 bool success = true;
Chris Lattner66a3a3e2008-12-01 07:35:54 +00002066 for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
2067 Value *Op = PREInstr->getOperand(i);
2068 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
2069 continue;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002070
Chris Lattner66a3a3e2008-12-01 07:35:54 +00002071 if (Value *V = lookupNumber(PREPred, VN.lookup(Op))) {
2072 PREInstr->setOperand(i, V);
2073 } else {
2074 success = false;
2075 break;
Owen Anderson14c612f2008-07-11 20:05:13 +00002076 }
Owen Andersone6b4ff82008-06-18 21:41:49 +00002077 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002078
Owen Andersone6b4ff82008-06-18 21:41:49 +00002079 // Fail out if we encounter an operand that is not available in
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002080 // the PRE predecessor. This is typically because of loads which
Owen Andersone6b4ff82008-06-18 21:41:49 +00002081 // are not value numbered precisely.
2082 if (!success) {
2083 delete PREInstr;
Bill Wendling3858cae2008-12-22 22:14:07 +00002084 DEBUG(verifyRemoved(PREInstr));
Owen Andersone6b4ff82008-06-18 21:41:49 +00002085 continue;
2086 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002087
Owen Andersone6b4ff82008-06-18 21:41:49 +00002088 PREInstr->insertBefore(PREPred->getTerminator());
Chris Lattner66a3a3e2008-12-01 07:35:54 +00002089 PREInstr->setName(CurInst->getName() + ".pre");
Owen Anderson2a412722008-06-20 01:15:47 +00002090 predMap[PREPred] = PREInstr;
Chris Lattnerff36c952009-09-21 02:42:51 +00002091 VN.add(PREInstr, ValNo);
Owen Andersone6b4ff82008-06-18 21:41:49 +00002092 NumGVNPRE++;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002093
Owen Andersone6b4ff82008-06-18 21:41:49 +00002094 // Update the availability map to include the new instruction.
Chris Lattnerff36c952009-09-21 02:42:51 +00002095 localAvail[PREPred]->table.insert(std::make_pair(ValNo, PREInstr));
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002096
Owen Andersone6b4ff82008-06-18 21:41:49 +00002097 // Create a PHI to make the value available in this block.
Chris Lattner66a3a3e2008-12-01 07:35:54 +00002098 PHINode* Phi = PHINode::Create(CurInst->getType(),
2099 CurInst->getName() + ".pre-phi",
Owen Andersone6b4ff82008-06-18 21:41:49 +00002100 CurrentBlock->begin());
2101 for (pred_iterator PI = pred_begin(CurrentBlock),
2102 PE = pred_end(CurrentBlock); PI != PE; ++PI)
Owen Anderson2a412722008-06-20 01:15:47 +00002103 Phi->addIncoming(predMap[*PI], *PI);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002104
Chris Lattnerff36c952009-09-21 02:42:51 +00002105 VN.add(Phi, ValNo);
2106 localAvail[CurrentBlock]->table[ValNo] = Phi;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002107
Chris Lattner66a3a3e2008-12-01 07:35:54 +00002108 CurInst->replaceAllUsesWith(Phi);
Chris Lattnerf81b0142008-12-09 22:06:23 +00002109 if (isa<PointerType>(Phi->getType()))
2110 MD->invalidateCachedPointerInfo(Phi);
Chris Lattner66a3a3e2008-12-01 07:35:54 +00002111 VN.erase(CurInst);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002112
Dan Gohman7e124382009-07-31 20:24:18 +00002113 DEBUG(errs() << "GVN PRE removed: " << *CurInst << '\n');
Chris Lattner66a3a3e2008-12-01 07:35:54 +00002114 MD->removeInstruction(CurInst);
2115 CurInst->eraseFromParent();
Bill Wendling84049422008-12-22 21:57:30 +00002116 DEBUG(verifyRemoved(CurInst));
Chris Lattner66a3a3e2008-12-01 07:35:54 +00002117 Changed = true;
Owen Andersone6b4ff82008-06-18 21:41:49 +00002118 }
2119 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002120
Owen Andersonec747c42008-06-19 19:54:19 +00002121 for (SmallVector<std::pair<TerminatorInst*, unsigned>, 4>::iterator
Anton Korobeynikov2e8710c2008-12-05 19:38:49 +00002122 I = toSplit.begin(), E = toSplit.end(); I != E; ++I)
Owen Andersonec747c42008-06-19 19:54:19 +00002123 SplitCriticalEdge(I->first, I->second, this);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00002124
Anton Korobeynikov2e8710c2008-12-05 19:38:49 +00002125 return Changed || toSplit.size();
Owen Andersone6b4ff82008-06-18 21:41:49 +00002126}
2127
Bill Wendling42f17f62008-12-22 22:32:22 +00002128/// iterateOnFunction - Executes one iteration of GVN
Owen Andersonbe168b32007-08-14 18:04:11 +00002129bool GVN::iterateOnFunction(Function &F) {
Nuno Lopes274474b2008-10-10 16:25:50 +00002130 cleanupGlobalSets();
Chris Lattner98054902008-03-21 21:33:23 +00002131
Owen Andersonef8bf0f2009-04-01 23:53:49 +00002132 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
2133 DE = df_end(DT->getRootNode()); DI != DE; ++DI) {
2134 if (DI->getIDom())
2135 localAvail[DI->getBlock()] =
2136 new ValueNumberScope(localAvail[DI->getIDom()->getBlock()]);
2137 else
2138 localAvail[DI->getBlock()] = new ValueNumberScope(0);
2139 }
2140
Owen Anderson85c40642007-07-24 17:55:58 +00002141 // Top-down walk of the dominator tree
Chris Lattnerff36c952009-09-21 02:42:51 +00002142 bool Changed = false;
Owen Andersonef136f52008-12-15 03:52:17 +00002143#if 0
2144 // Needed for value numbering with phi construction to work.
Owen Andersona03e7862008-12-15 02:03:00 +00002145 ReversePostOrderTraversal<Function*> RPOT(&F);
2146 for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
2147 RE = RPOT.end(); RI != RE; ++RI)
Chris Lattnerff36c952009-09-21 02:42:51 +00002148 Changed |= processBlock(*RI);
Owen Andersonef136f52008-12-15 03:52:17 +00002149#else
2150 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
2151 DE = df_end(DT->getRootNode()); DI != DE; ++DI)
Chris Lattnerff36c952009-09-21 02:42:51 +00002152 Changed |= processBlock(DI->getBlock());
Owen Andersonef136f52008-12-15 03:52:17 +00002153#endif
2154
Chris Lattnerff36c952009-09-21 02:42:51 +00002155 return Changed;
Owen Anderson85c40642007-07-24 17:55:58 +00002156}
Nuno Lopes274474b2008-10-10 16:25:50 +00002157
2158void GVN::cleanupGlobalSets() {
2159 VN.clear();
2160 phiMap.clear();
2161
2162 for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
2163 I = localAvail.begin(), E = localAvail.end(); I != E; ++I)
2164 delete I->second;
2165 localAvail.clear();
2166}
Bill Wendling2a023742008-12-22 21:36:08 +00002167
2168/// verifyRemoved - Verify that the specified instruction does not occur in our
2169/// internal data structures.
Bill Wendlingf9c0e9e2008-12-22 22:28:56 +00002170void GVN::verifyRemoved(const Instruction *Inst) const {
2171 VN.verifyRemoved(Inst);
Bill Wendling3858cae2008-12-22 22:14:07 +00002172
2173 // Walk through the PHI map to make sure the instruction isn't hiding in there
2174 // somewhere.
2175 for (PhiMapType::iterator
Bill Wendlingf9c0e9e2008-12-22 22:28:56 +00002176 I = phiMap.begin(), E = phiMap.end(); I != E; ++I) {
2177 assert(I->first != Inst && "Inst is still a key in PHI map!");
Bill Wendling3858cae2008-12-22 22:14:07 +00002178
2179 for (SmallPtrSet<Instruction*, 4>::iterator
Bill Wendlingf9c0e9e2008-12-22 22:28:56 +00002180 II = I->second.begin(), IE = I->second.end(); II != IE; ++II) {
2181 assert(*II != Inst && "Inst is still a value in PHI map!");
2182 }
2183 }
2184
2185 // Walk through the value number scope to make sure the instruction isn't
2186 // ferreted away in it.
2187 for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
2188 I = localAvail.begin(), E = localAvail.end(); I != E; ++I) {
2189 const ValueNumberScope *VNS = I->second;
2190
2191 while (VNS) {
2192 for (DenseMap<uint32_t, Value*>::iterator
2193 II = VNS->table.begin(), IE = VNS->table.end(); II != IE; ++II) {
2194 assert(II->second != Inst && "Inst still in value numbering scope!");
2195 }
2196
2197 VNS = VNS->parent;
Bill Wendling3858cae2008-12-22 22:14:07 +00002198 }
2199 }
Bill Wendling2a023742008-12-22 21:36:08 +00002200}