blob: 2ae19820299adad6ea56e99b0eeba20838b4adc4 [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"
Owen Andersonacfa3ad2007-07-26 18:26:51 +000026#include "llvm/Value.h"
Owen Anderson85c40642007-07-24 17:55:58 +000027#include "llvm/ADT/DenseMap.h"
28#include "llvm/ADT/DepthFirstIterator.h"
Owen Andersona03e7862008-12-15 02:03:00 +000029#include "llvm/ADT/PostOrderIterator.h"
Owen Anderson85c40642007-07-24 17:55:58 +000030#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/SmallVector.h"
32#include "llvm/ADT/Statistic.h"
Owen Anderson5e9366f2007-10-18 19:39:33 +000033#include "llvm/Analysis/Dominators.h"
34#include "llvm/Analysis/AliasAnalysis.h"
Victor Hernandez48c3c542009-09-18 22:35:49 +000035#include "llvm/Analysis/MallocHelper.h"
Owen Anderson85c40642007-07-24 17:55:58 +000036#include "llvm/Analysis/MemoryDependenceAnalysis.h"
37#include "llvm/Support/CFG.h"
Owen Andersona2bf7662008-06-19 19:57:25 +000038#include "llvm/Support/CommandLine.h"
Chris Lattner9c5be3c2008-03-29 04:36:18 +000039#include "llvm/Support/Debug.h"
Edwin Török675d5622009-07-11 20:10:48 +000040#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar005975c2009-07-25 00:23:56 +000041#include "llvm/Support/raw_ostream.h"
Chris Lattner7741aa52009-09-20 19:03:47 +000042#include "llvm/Target/TargetData.h"
Owen Andersonec747c42008-06-19 19:54:19 +000043#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dale Johannesena19b67f2009-06-17 20:48:23 +000044#include "llvm/Transforms/Utils/Local.h"
Duncan Sands05f68372008-10-08 07:23:46 +000045#include <cstdio>
Owen Anderson85c40642007-07-24 17:55:58 +000046using namespace llvm;
47
Bill Wendling3858cae2008-12-22 22:14:07 +000048STATISTIC(NumGVNInstr, "Number of instructions deleted");
49STATISTIC(NumGVNLoad, "Number of loads deleted");
50STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
Owen Anderson7558f202008-07-15 16:28:06 +000051STATISTIC(NumGVNBlocks, "Number of blocks merged");
Bill Wendling3858cae2008-12-22 22:14:07 +000052STATISTIC(NumPRELoad, "Number of loads PRE'd");
Chris Lattner1be83222008-03-22 04:13:49 +000053
Evan Cheng019a2e12008-06-20 01:01:07 +000054static cl::opt<bool> EnablePRE("enable-pre",
Owen Anderson3a053612008-07-17 19:41:00 +000055 cl::init(true), cl::Hidden);
Dan Gohman828f89f2009-06-15 18:30:15 +000056static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
Owen Andersona2bf7662008-06-19 19:57:25 +000057
Owen Anderson85c40642007-07-24 17:55:58 +000058//===----------------------------------------------------------------------===//
59// ValueTable Class
60//===----------------------------------------------------------------------===//
61
62/// This class holds the mapping between values and value numbers. It is used
63/// as an efficient mechanism to determine the expression-wise equivalence of
64/// two values.
65namespace {
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +000066 struct Expression {
Dan Gohman7ce405e2009-06-04 22:49:04 +000067 enum ExpressionOpcode { ADD, FADD, SUB, FSUB, MUL, FMUL,
68 UDIV, SDIV, FDIV, UREM, SREM,
Daniel Dunbar3be44e62009-09-20 02:20:51 +000069 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
70 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
71 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
72 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
73 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
Owen Anderson85c40642007-07-24 17:55:58 +000074 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
75 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
Daniel Dunbar3be44e62009-09-20 02:20:51 +000076 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
Owen Anderson771d1122008-05-13 08:17:22 +000077 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
Owen Andersonb0cc5ed2008-06-19 17:25:39 +000078 EMPTY, TOMBSTONE };
Owen Anderson85c40642007-07-24 17:55:58 +000079
80 ExpressionOpcode opcode;
81 const Type* type;
82 uint32_t firstVN;
83 uint32_t secondVN;
84 uint32_t thirdVN;
85 SmallVector<uint32_t, 4> varargs;
Chris Lattnerff36c952009-09-21 02:42:51 +000086 Value *function;
Daniel Dunbar3be44e62009-09-20 02:20:51 +000087
Owen Anderson85c40642007-07-24 17:55:58 +000088 Expression() { }
89 Expression(ExpressionOpcode o) : opcode(o) { }
Daniel Dunbar3be44e62009-09-20 02:20:51 +000090
Owen Anderson85c40642007-07-24 17:55:58 +000091 bool operator==(const Expression &other) const {
92 if (opcode != other.opcode)
93 return false;
94 else if (opcode == EMPTY || opcode == TOMBSTONE)
95 return true;
96 else if (type != other.type)
97 return false;
Owen Anderson5e9366f2007-10-18 19:39:33 +000098 else if (function != other.function)
99 return false;
Owen Anderson85c40642007-07-24 17:55:58 +0000100 else if (firstVN != other.firstVN)
101 return false;
102 else if (secondVN != other.secondVN)
103 return false;
104 else if (thirdVN != other.thirdVN)
105 return false;
106 else {
107 if (varargs.size() != other.varargs.size())
108 return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000109
Owen Anderson85c40642007-07-24 17:55:58 +0000110 for (size_t i = 0; i < varargs.size(); ++i)
111 if (varargs[i] != other.varargs[i])
112 return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000113
Owen Anderson85c40642007-07-24 17:55:58 +0000114 return true;
115 }
116 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000117
Owen Anderson85c40642007-07-24 17:55:58 +0000118 bool operator!=(const Expression &other) const {
Bill Wendling9b5d4b72008-12-22 22:16:31 +0000119 return !(*this == other);
Owen Anderson85c40642007-07-24 17:55:58 +0000120 }
121 };
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000122
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +0000123 class ValueTable {
Owen Anderson85c40642007-07-24 17:55:58 +0000124 private:
125 DenseMap<Value*, uint32_t> valueNumbering;
126 DenseMap<Expression, uint32_t> expressionNumbering;
Owen Andersonbcf2bd52008-05-12 20:15:55 +0000127 AliasAnalysis* AA;
128 MemoryDependenceAnalysis* MD;
129 DominatorTree* DT;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000130
Owen Anderson85c40642007-07-24 17:55:58 +0000131 uint32_t nextValueNumber;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000132
Owen Anderson85c40642007-07-24 17:55:58 +0000133 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
134 Expression::ExpressionOpcode getOpcode(CmpInst* C);
135 Expression::ExpressionOpcode getOpcode(CastInst* C);
136 Expression create_expression(BinaryOperator* BO);
137 Expression create_expression(CmpInst* C);
138 Expression create_expression(ShuffleVectorInst* V);
139 Expression create_expression(ExtractElementInst* C);
140 Expression create_expression(InsertElementInst* V);
141 Expression create_expression(SelectInst* V);
142 Expression create_expression(CastInst* C);
143 Expression create_expression(GetElementPtrInst* G);
Owen Anderson5e9366f2007-10-18 19:39:33 +0000144 Expression create_expression(CallInst* C);
Owen Anderson771d1122008-05-13 08:17:22 +0000145 Expression create_expression(Constant* C);
Owen Anderson85c40642007-07-24 17:55:58 +0000146 public:
Dan Gohman936a6522009-04-01 16:37:47 +0000147 ValueTable() : nextValueNumber(1) { }
Chris Lattnerff36c952009-09-21 02:42:51 +0000148 uint32_t lookup_or_add(Value *V);
149 uint32_t lookup(Value *V) const;
150 void add(Value *V, uint32_t num);
Owen Anderson85c40642007-07-24 17:55:58 +0000151 void clear();
Chris Lattnerff36c952009-09-21 02:42:51 +0000152 void erase(Value *v);
Owen Anderson85c40642007-07-24 17:55:58 +0000153 unsigned size();
Owen Andersonbcf2bd52008-05-12 20:15:55 +0000154 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
Chris Lattner02ca4422008-12-01 00:40:32 +0000155 AliasAnalysis *getAliasAnalysis() const { return AA; }
Owen Andersonbcf2bd52008-05-12 20:15:55 +0000156 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
157 void setDomTree(DominatorTree* D) { DT = D; }
Owen Anderson8a8d13c2008-07-03 17:44:33 +0000158 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
Bill Wendling2a023742008-12-22 21:36:08 +0000159 void verifyRemoved(const Value *) const;
Owen Anderson85c40642007-07-24 17:55:58 +0000160 };
161}
162
163namespace llvm {
Chris Lattner92eea072007-09-17 18:34:04 +0000164template <> struct DenseMapInfo<Expression> {
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000165 static inline Expression getEmptyKey() {
166 return Expression(Expression::EMPTY);
167 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000168
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000169 static inline Expression getTombstoneKey() {
170 return Expression(Expression::TOMBSTONE);
171 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000172
Owen Anderson85c40642007-07-24 17:55:58 +0000173 static unsigned getHashValue(const Expression e) {
174 unsigned hash = e.opcode;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000175
Owen Anderson85c40642007-07-24 17:55:58 +0000176 hash = e.firstVN + hash * 37;
177 hash = e.secondVN + hash * 37;
178 hash = e.thirdVN + hash * 37;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000179
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000180 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
181 (unsigned)((uintptr_t)e.type >> 9)) +
182 hash * 37;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000183
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000184 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
185 E = e.varargs.end(); I != E; ++I)
Owen Anderson85c40642007-07-24 17:55:58 +0000186 hash = *I + hash * 37;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000187
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +0000188 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
189 (unsigned)((uintptr_t)e.function >> 9)) +
190 hash * 37;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000191
Owen Anderson85c40642007-07-24 17:55:58 +0000192 return hash;
193 }
Chris Lattner92eea072007-09-17 18:34:04 +0000194 static bool isEqual(const Expression &LHS, const Expression &RHS) {
195 return LHS == RHS;
196 }
Owen Anderson85c40642007-07-24 17:55:58 +0000197 static bool isPod() { return true; }
198};
199}
200
201//===----------------------------------------------------------------------===//
202// ValueTable Internal Functions
203//===----------------------------------------------------------------------===//
Chris Lattner3d7103e2008-03-21 21:14:38 +0000204Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
Owen Anderson85c40642007-07-24 17:55:58 +0000205 switch(BO->getOpcode()) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000206 default: // THIS SHOULD NEVER HAPPEN
Edwin Törökbd448e32009-07-14 16:55:14 +0000207 llvm_unreachable("Binary operator with unknown opcode?");
Chris Lattner3d7103e2008-03-21 21:14:38 +0000208 case Instruction::Add: return Expression::ADD;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000209 case Instruction::FAdd: return Expression::FADD;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000210 case Instruction::Sub: return Expression::SUB;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000211 case Instruction::FSub: return Expression::FSUB;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000212 case Instruction::Mul: return Expression::MUL;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000213 case Instruction::FMul: return Expression::FMUL;
Chris Lattner3d7103e2008-03-21 21:14:38 +0000214 case Instruction::UDiv: return Expression::UDIV;
215 case Instruction::SDiv: return Expression::SDIV;
216 case Instruction::FDiv: return Expression::FDIV;
217 case Instruction::URem: return Expression::UREM;
218 case Instruction::SRem: return Expression::SREM;
219 case Instruction::FRem: return Expression::FREM;
220 case Instruction::Shl: return Expression::SHL;
221 case Instruction::LShr: return Expression::LSHR;
222 case Instruction::AShr: return Expression::ASHR;
223 case Instruction::And: return Expression::AND;
224 case Instruction::Or: return Expression::OR;
225 case Instruction::Xor: return Expression::XOR;
Owen Anderson85c40642007-07-24 17:55:58 +0000226 }
227}
228
229Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
Nick Lewycky8f5253b2009-07-08 03:04:38 +0000230 if (isa<ICmpInst>(C)) {
Owen Anderson85c40642007-07-24 17:55:58 +0000231 switch (C->getPredicate()) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000232 default: // THIS SHOULD NEVER HAPPEN
Edwin Törökbd448e32009-07-14 16:55:14 +0000233 llvm_unreachable("Comparison with unknown predicate?");
Chris Lattner3d7103e2008-03-21 21:14:38 +0000234 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ;
235 case ICmpInst::ICMP_NE: return Expression::ICMPNE;
236 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
237 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
238 case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
239 case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
240 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
241 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
242 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
243 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
Owen Anderson85c40642007-07-24 17:55:58 +0000244 }
Nick Lewycky8f5253b2009-07-08 03:04:38 +0000245 } else {
246 switch (C->getPredicate()) {
247 default: // THIS SHOULD NEVER HAPPEN
Edwin Törökbd448e32009-07-14 16:55:14 +0000248 llvm_unreachable("Comparison with unknown predicate?");
Nick Lewycky8f5253b2009-07-08 03:04:38 +0000249 case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
250 case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
251 case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
252 case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
253 case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
254 case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
255 case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
256 case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
257 case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
258 case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
259 case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
260 case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
261 case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
262 case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
263 }
Owen Anderson85c40642007-07-24 17:55:58 +0000264 }
265}
266
Chris Lattner3d7103e2008-03-21 21:14:38 +0000267Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
Owen Anderson85c40642007-07-24 17:55:58 +0000268 switch(C->getOpcode()) {
Chris Lattner3d7103e2008-03-21 21:14:38 +0000269 default: // THIS SHOULD NEVER HAPPEN
Edwin Törökbd448e32009-07-14 16:55:14 +0000270 llvm_unreachable("Cast operator with unknown opcode?");
Chris Lattner3d7103e2008-03-21 21:14:38 +0000271 case Instruction::Trunc: return Expression::TRUNC;
272 case Instruction::ZExt: return Expression::ZEXT;
273 case Instruction::SExt: return Expression::SEXT;
274 case Instruction::FPToUI: return Expression::FPTOUI;
275 case Instruction::FPToSI: return Expression::FPTOSI;
276 case Instruction::UIToFP: return Expression::UITOFP;
277 case Instruction::SIToFP: return Expression::SITOFP;
278 case Instruction::FPTrunc: return Expression::FPTRUNC;
279 case Instruction::FPExt: return Expression::FPEXT;
280 case Instruction::PtrToInt: return Expression::PTRTOINT;
281 case Instruction::IntToPtr: return Expression::INTTOPTR;
282 case Instruction::BitCast: return Expression::BITCAST;
Owen Anderson85c40642007-07-24 17:55:58 +0000283 }
284}
285
Owen Anderson5e9366f2007-10-18 19:39:33 +0000286Expression ValueTable::create_expression(CallInst* C) {
287 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000288
Owen Anderson5e9366f2007-10-18 19:39:33 +0000289 e.type = C->getType();
290 e.firstVN = 0;
291 e.secondVN = 0;
292 e.thirdVN = 0;
293 e.function = C->getCalledFunction();
294 e.opcode = Expression::CALL;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000295
Owen Anderson5e9366f2007-10-18 19:39:33 +0000296 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
297 I != E; ++I)
Owen Anderson07f478f2008-04-11 05:11:49 +0000298 e.varargs.push_back(lookup_or_add(*I));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000299
Owen Anderson5e9366f2007-10-18 19:39:33 +0000300 return e;
301}
302
Owen Anderson85c40642007-07-24 17:55:58 +0000303Expression ValueTable::create_expression(BinaryOperator* BO) {
304 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000305
Owen Anderson07f478f2008-04-11 05:11:49 +0000306 e.firstVN = lookup_or_add(BO->getOperand(0));
307 e.secondVN = lookup_or_add(BO->getOperand(1));
Owen Anderson85c40642007-07-24 17:55:58 +0000308 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000309 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000310 e.type = BO->getType();
311 e.opcode = getOpcode(BO);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000312
Owen Anderson85c40642007-07-24 17:55:58 +0000313 return e;
314}
315
316Expression ValueTable::create_expression(CmpInst* C) {
317 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000318
Owen Anderson07f478f2008-04-11 05:11:49 +0000319 e.firstVN = lookup_or_add(C->getOperand(0));
320 e.secondVN = lookup_or_add(C->getOperand(1));
Owen Anderson85c40642007-07-24 17:55:58 +0000321 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000322 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000323 e.type = C->getType();
324 e.opcode = getOpcode(C);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000325
Owen Anderson85c40642007-07-24 17:55:58 +0000326 return e;
327}
328
329Expression ValueTable::create_expression(CastInst* C) {
330 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000331
Owen Anderson07f478f2008-04-11 05:11:49 +0000332 e.firstVN = lookup_or_add(C->getOperand(0));
Owen Anderson85c40642007-07-24 17:55:58 +0000333 e.secondVN = 0;
334 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000335 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000336 e.type = C->getType();
337 e.opcode = getOpcode(C);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000338
Owen Anderson85c40642007-07-24 17:55:58 +0000339 return e;
340}
341
342Expression ValueTable::create_expression(ShuffleVectorInst* S) {
343 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000344
Owen Anderson07f478f2008-04-11 05:11:49 +0000345 e.firstVN = lookup_or_add(S->getOperand(0));
346 e.secondVN = lookup_or_add(S->getOperand(1));
347 e.thirdVN = lookup_or_add(S->getOperand(2));
Owen Anderson5e9366f2007-10-18 19:39:33 +0000348 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000349 e.type = S->getType();
350 e.opcode = Expression::SHUFFLE;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000351
Owen Anderson85c40642007-07-24 17:55:58 +0000352 return e;
353}
354
355Expression ValueTable::create_expression(ExtractElementInst* E) {
356 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000357
Owen Anderson07f478f2008-04-11 05:11:49 +0000358 e.firstVN = lookup_or_add(E->getOperand(0));
359 e.secondVN = lookup_or_add(E->getOperand(1));
Owen Anderson85c40642007-07-24 17:55:58 +0000360 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000361 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000362 e.type = E->getType();
363 e.opcode = Expression::EXTRACT;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000364
Owen Anderson85c40642007-07-24 17:55:58 +0000365 return e;
366}
367
368Expression ValueTable::create_expression(InsertElementInst* I) {
369 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000370
Owen Anderson07f478f2008-04-11 05:11:49 +0000371 e.firstVN = lookup_or_add(I->getOperand(0));
372 e.secondVN = lookup_or_add(I->getOperand(1));
373 e.thirdVN = lookup_or_add(I->getOperand(2));
Owen Anderson5e9366f2007-10-18 19:39:33 +0000374 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000375 e.type = I->getType();
376 e.opcode = Expression::INSERT;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000377
Owen Anderson85c40642007-07-24 17:55:58 +0000378 return e;
379}
380
381Expression ValueTable::create_expression(SelectInst* I) {
382 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000383
Owen Anderson07f478f2008-04-11 05:11:49 +0000384 e.firstVN = lookup_or_add(I->getCondition());
385 e.secondVN = lookup_or_add(I->getTrueValue());
386 e.thirdVN = lookup_or_add(I->getFalseValue());
Owen Anderson5e9366f2007-10-18 19:39:33 +0000387 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000388 e.type = I->getType();
389 e.opcode = Expression::SELECT;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000390
Owen Anderson85c40642007-07-24 17:55:58 +0000391 return e;
392}
393
394Expression ValueTable::create_expression(GetElementPtrInst* G) {
395 Expression e;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000396
Owen Anderson07f478f2008-04-11 05:11:49 +0000397 e.firstVN = lookup_or_add(G->getPointerOperand());
Owen Anderson85c40642007-07-24 17:55:58 +0000398 e.secondVN = 0;
399 e.thirdVN = 0;
Owen Anderson5e9366f2007-10-18 19:39:33 +0000400 e.function = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000401 e.type = G->getType();
402 e.opcode = Expression::GEP;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000403
Owen Anderson85c40642007-07-24 17:55:58 +0000404 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
405 I != E; ++I)
Owen Anderson07f478f2008-04-11 05:11:49 +0000406 e.varargs.push_back(lookup_or_add(*I));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000407
Owen Anderson85c40642007-07-24 17:55:58 +0000408 return e;
409}
410
411//===----------------------------------------------------------------------===//
412// ValueTable External Functions
413//===----------------------------------------------------------------------===//
414
Owen Andersone6b4ff82008-06-18 21:41:49 +0000415/// add - Insert a value into the table with a specified value number.
Chris Lattnerff36c952009-09-21 02:42:51 +0000416void ValueTable::add(Value *V, uint32_t num) {
Owen Andersone6b4ff82008-06-18 21:41:49 +0000417 valueNumbering.insert(std::make_pair(V, num));
418}
419
Owen Anderson85c40642007-07-24 17:55:58 +0000420/// lookup_or_add - Returns the value number for the specified value, assigning
421/// it a new number if it did not have one before.
Chris Lattnerff36c952009-09-21 02:42:51 +0000422uint32_t ValueTable::lookup_or_add(Value *V) {
Owen Anderson85c40642007-07-24 17:55:58 +0000423 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
424 if (VI != valueNumbering.end())
425 return VI->second;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000426
Owen Anderson5e9366f2007-10-18 19:39:33 +0000427 if (CallInst* C = dyn_cast<CallInst>(V)) {
Owen Anderson07f478f2008-04-11 05:11:49 +0000428 if (AA->doesNotAccessMemory(C)) {
Owen Anderson5e9366f2007-10-18 19:39:33 +0000429 Expression e = create_expression(C);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000430
Owen Anderson5e9366f2007-10-18 19:39:33 +0000431 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
432 if (EI != expressionNumbering.end()) {
433 valueNumbering.insert(std::make_pair(V, EI->second));
434 return EI->second;
435 } else {
436 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
437 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000438
Owen Anderson5e9366f2007-10-18 19:39:33 +0000439 return nextValueNumber++;
440 }
Owen Andersona0b2b8e2008-04-17 05:36:50 +0000441 } else if (AA->onlyReadsMemory(C)) {
442 Expression e = create_expression(C);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000443
Owen Anderson771d1122008-05-13 08:17:22 +0000444 if (expressionNumbering.find(e) == expressionNumbering.end()) {
Owen Andersona0b2b8e2008-04-17 05:36:50 +0000445 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
446 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Owen Anderson771d1122008-05-13 08:17:22 +0000447 return nextValueNumber++;
448 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000449
Chris Lattner12cafbf2008-11-29 02:29:27 +0000450 MemDepResult local_dep = MD->getDependency(C);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000451
Chris Lattner4531da82008-12-05 21:04:20 +0000452 if (!local_dep.isDef() && !local_dep.isNonLocal()) {
Owen Anderson64fcc592008-05-13 23:18:30 +0000453 valueNumbering.insert(std::make_pair(V, nextValueNumber));
454 return nextValueNumber++;
Chris Lattnerd33b6662008-11-30 23:39:23 +0000455 }
Chris Lattner4531da82008-12-05 21:04:20 +0000456
457 if (local_dep.isDef()) {
458 CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000459
Chris Lattner4531da82008-12-05 21:04:20 +0000460 if (local_cdep->getNumOperands() != C->getNumOperands()) {
Owen Anderson64fcc592008-05-13 23:18:30 +0000461 valueNumbering.insert(std::make_pair(V, nextValueNumber));
462 return nextValueNumber++;
463 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000464
Chris Lattnerd33b6662008-11-30 23:39:23 +0000465 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
466 uint32_t c_vn = lookup_or_add(C->getOperand(i));
467 uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
468 if (c_vn != cd_vn) {
469 valueNumbering.insert(std::make_pair(V, nextValueNumber));
470 return nextValueNumber++;
471 }
472 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000473
Chris Lattnerd33b6662008-11-30 23:39:23 +0000474 uint32_t v = lookup_or_add(local_cdep);
475 valueNumbering.insert(std::make_pair(V, v));
476 return v;
Owen Anderson64fcc592008-05-13 23:18:30 +0000477 }
Chris Lattner46876282008-12-01 01:15:42 +0000478
Chris Lattner4531da82008-12-05 21:04:20 +0000479 // Non-local case.
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000480 const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
Chris Lattner35d5cf52008-12-09 19:38:05 +0000481 MD->getNonLocalCallDependency(CallSite(C));
Chris Lattner4531da82008-12-05 21:04:20 +0000482 // FIXME: call/call dependencies for readonly calls should return def, not
483 // clobber! Move the checking logic to MemDep!
Owen Anderson3ebaca72008-05-13 13:41:23 +0000484 CallInst* cdep = 0;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000485
Chris Lattnerd33b6662008-11-30 23:39:23 +0000486 // Check to see if we have a single dominating call instruction that is
487 // identical to C.
Chris Lattner46876282008-12-01 01:15:42 +0000488 for (unsigned i = 0, e = deps.size(); i != e; ++i) {
489 const MemoryDependenceAnalysis::NonLocalDepEntry *I = &deps[i];
Chris Lattnerd33b6662008-11-30 23:39:23 +0000490 // Ignore non-local dependencies.
491 if (I->second.isNonLocal())
492 continue;
Owen Anderson771d1122008-05-13 08:17:22 +0000493
Chris Lattnerd33b6662008-11-30 23:39:23 +0000494 // We don't handle non-depedencies. If we already have a call, reject
495 // instruction dependencies.
Chris Lattner4531da82008-12-05 21:04:20 +0000496 if (I->second.isClobber() || cdep != 0) {
Chris Lattnerd33b6662008-11-30 23:39:23 +0000497 cdep = 0;
498 break;
Owen Anderson771d1122008-05-13 08:17:22 +0000499 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000500
Chris Lattnerd33b6662008-11-30 23:39:23 +0000501 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->second.getInst());
502 // FIXME: All duplicated with non-local case.
503 if (NonLocalDepCall && DT->properlyDominates(I->first, C->getParent())){
504 cdep = NonLocalDepCall;
505 continue;
506 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000507
Chris Lattnerd33b6662008-11-30 23:39:23 +0000508 cdep = 0;
509 break;
Owen Anderson771d1122008-05-13 08:17:22 +0000510 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000511
Owen Anderson3ebaca72008-05-13 13:41:23 +0000512 if (!cdep) {
Owen Anderson771d1122008-05-13 08:17:22 +0000513 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Owen Andersona0b2b8e2008-04-17 05:36:50 +0000514 return nextValueNumber++;
515 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000516
Chris Lattner4531da82008-12-05 21:04:20 +0000517 if (cdep->getNumOperands() != C->getNumOperands()) {
Owen Anderson771d1122008-05-13 08:17:22 +0000518 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Owen Andersona0b2b8e2008-04-17 05:36:50 +0000519 return nextValueNumber++;
Owen Andersona0b2b8e2008-04-17 05:36:50 +0000520 }
Chris Lattnerd33b6662008-11-30 23:39:23 +0000521 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
522 uint32_t c_vn = lookup_or_add(C->getOperand(i));
523 uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
524 if (c_vn != cd_vn) {
525 valueNumbering.insert(std::make_pair(V, nextValueNumber));
526 return nextValueNumber++;
527 }
528 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000529
Chris Lattnerd33b6662008-11-30 23:39:23 +0000530 uint32_t v = lookup_or_add(cdep);
531 valueNumbering.insert(std::make_pair(V, v));
532 return v;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000533
Owen Anderson5e9366f2007-10-18 19:39:33 +0000534 } else {
535 valueNumbering.insert(std::make_pair(V, nextValueNumber));
536 return nextValueNumber++;
537 }
538 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
Owen Anderson85c40642007-07-24 17:55:58 +0000539 Expression e = create_expression(BO);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000540
Owen Anderson85c40642007-07-24 17:55:58 +0000541 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
542 if (EI != expressionNumbering.end()) {
543 valueNumbering.insert(std::make_pair(V, EI->second));
544 return EI->second;
545 } else {
546 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
547 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000548
Owen Anderson85c40642007-07-24 17:55:58 +0000549 return nextValueNumber++;
550 }
551 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
552 Expression e = create_expression(C);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000553
Owen Anderson85c40642007-07-24 17:55:58 +0000554 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
555 if (EI != expressionNumbering.end()) {
556 valueNumbering.insert(std::make_pair(V, EI->second));
557 return EI->second;
558 } else {
559 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
560 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000561
Owen Anderson85c40642007-07-24 17:55:58 +0000562 return nextValueNumber++;
563 }
564 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
565 Expression e = create_expression(U);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000566
Owen Anderson85c40642007-07-24 17:55:58 +0000567 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
568 if (EI != expressionNumbering.end()) {
569 valueNumbering.insert(std::make_pair(V, EI->second));
570 return EI->second;
571 } else {
572 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
573 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000574
Owen Anderson85c40642007-07-24 17:55:58 +0000575 return nextValueNumber++;
576 }
577 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
578 Expression e = create_expression(U);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000579
Owen Anderson85c40642007-07-24 17:55:58 +0000580 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
581 if (EI != expressionNumbering.end()) {
582 valueNumbering.insert(std::make_pair(V, EI->second));
583 return EI->second;
584 } else {
585 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
586 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000587
Owen Anderson85c40642007-07-24 17:55:58 +0000588 return nextValueNumber++;
589 }
590 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
591 Expression e = create_expression(U);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000592
Owen Anderson85c40642007-07-24 17:55:58 +0000593 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
594 if (EI != expressionNumbering.end()) {
595 valueNumbering.insert(std::make_pair(V, EI->second));
596 return EI->second;
597 } else {
598 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
599 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000600
Owen Anderson85c40642007-07-24 17:55:58 +0000601 return nextValueNumber++;
602 }
603 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
604 Expression e = create_expression(U);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000605
Owen Anderson85c40642007-07-24 17:55:58 +0000606 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
607 if (EI != expressionNumbering.end()) {
608 valueNumbering.insert(std::make_pair(V, EI->second));
609 return EI->second;
610 } else {
611 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
612 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000613
Owen Anderson85c40642007-07-24 17:55:58 +0000614 return nextValueNumber++;
615 }
616 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
617 Expression e = create_expression(U);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000618
Owen Anderson85c40642007-07-24 17:55:58 +0000619 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
620 if (EI != expressionNumbering.end()) {
621 valueNumbering.insert(std::make_pair(V, EI->second));
622 return EI->second;
623 } else {
624 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
625 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000626
Owen Anderson85c40642007-07-24 17:55:58 +0000627 return nextValueNumber++;
628 }
629 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
630 Expression e = create_expression(U);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000631
Owen Anderson85c40642007-07-24 17:55:58 +0000632 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
633 if (EI != expressionNumbering.end()) {
634 valueNumbering.insert(std::make_pair(V, EI->second));
635 return EI->second;
636 } else {
637 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
638 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000639
Owen Anderson85c40642007-07-24 17:55:58 +0000640 return nextValueNumber++;
641 }
642 } else {
643 valueNumbering.insert(std::make_pair(V, nextValueNumber));
644 return nextValueNumber++;
645 }
646}
647
648/// lookup - Returns the value number of the specified value. Fails if
649/// the value has not yet been numbered.
Chris Lattnerff36c952009-09-21 02:42:51 +0000650uint32_t ValueTable::lookup(Value *V) const {
Owen Anderson85c40642007-07-24 17:55:58 +0000651 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
Chris Lattner3d7103e2008-03-21 21:14:38 +0000652 assert(VI != valueNumbering.end() && "Value not numbered?");
653 return VI->second;
Owen Anderson85c40642007-07-24 17:55:58 +0000654}
655
656/// clear - Remove all entries from the ValueTable
657void ValueTable::clear() {
658 valueNumbering.clear();
659 expressionNumbering.clear();
660 nextValueNumber = 1;
661}
662
Owen Anderson5aff8002007-07-31 23:27:13 +0000663/// erase - Remove a value from the value numbering
Chris Lattnerff36c952009-09-21 02:42:51 +0000664void ValueTable::erase(Value *V) {
Owen Anderson5aff8002007-07-31 23:27:13 +0000665 valueNumbering.erase(V);
666}
667
Bill Wendling2a023742008-12-22 21:36:08 +0000668/// verifyRemoved - Verify that the value is removed from all internal data
669/// structures.
670void ValueTable::verifyRemoved(const Value *V) const {
671 for (DenseMap<Value*, uint32_t>::iterator
672 I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
673 assert(I->first != V && "Inst still occurs in value numbering map!");
674 }
675}
676
Owen Anderson85c40642007-07-24 17:55:58 +0000677//===----------------------------------------------------------------------===//
Bill Wendling42f17f62008-12-22 22:32:22 +0000678// GVN Pass
Owen Anderson85c40642007-07-24 17:55:58 +0000679//===----------------------------------------------------------------------===//
680
681namespace {
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +0000682 struct ValueNumberScope {
Owen Anderson2a412722008-06-20 01:15:47 +0000683 ValueNumberScope* parent;
684 DenseMap<uint32_t, Value*> table;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000685
Owen Anderson2a412722008-06-20 01:15:47 +0000686 ValueNumberScope(ValueNumberScope* p) : parent(p) { }
687 };
688}
689
690namespace {
Owen Anderson85c40642007-07-24 17:55:58 +0000691
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +0000692 class GVN : public FunctionPass {
Owen Anderson85c40642007-07-24 17:55:58 +0000693 bool runOnFunction(Function &F);
694 public:
695 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +0000696 GVN() : FunctionPass(&ID) { }
Owen Anderson85c40642007-07-24 17:55:58 +0000697
698 private:
Chris Lattner02ca4422008-12-01 00:40:32 +0000699 MemoryDependenceAnalysis *MD;
700 DominatorTree *DT;
701
Owen Anderson85c40642007-07-24 17:55:58 +0000702 ValueTable VN;
Owen Anderson2a412722008-06-20 01:15:47 +0000703 DenseMap<BasicBlock*, ValueNumberScope*> localAvail;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000704
Owen Anderson5b299672007-08-07 23:12:31 +0000705 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
706 PhiMapType phiMap;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000707
708
Owen Anderson85c40642007-07-24 17:55:58 +0000709 // This transformation requires dominator postdominator info
710 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Anderson85c40642007-07-24 17:55:58 +0000711 AU.addRequired<DominatorTree>();
712 AU.addRequired<MemoryDependenceAnalysis>();
Owen Anderson5e9366f2007-10-18 19:39:33 +0000713 AU.addRequired<AliasAnalysis>();
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000714
Owen Andersonaef6a922008-06-23 17:49:45 +0000715 AU.addPreserved<DominatorTree>();
Owen Anderson5e9366f2007-10-18 19:39:33 +0000716 AU.addPreserved<AliasAnalysis>();
Owen Anderson85c40642007-07-24 17:55:58 +0000717 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000718
Owen Anderson85c40642007-07-24 17:55:58 +0000719 // Helper fuctions
720 // FIXME: eliminate or document these better
Owen Anderson85c40642007-07-24 17:55:58 +0000721 bool processLoad(LoadInst* L,
Chris Lattner7de20452008-03-21 22:01:16 +0000722 SmallVectorImpl<Instruction*> &toErase);
Chris Lattnerff36c952009-09-21 02:42:51 +0000723 bool processInstruction(Instruction *I,
Chris Lattner7de20452008-03-21 22:01:16 +0000724 SmallVectorImpl<Instruction*> &toErase);
Owen Andersonbf8a3eb2007-08-02 18:16:06 +0000725 bool processNonLocalLoad(LoadInst* L,
Chris Lattner7de20452008-03-21 22:01:16 +0000726 SmallVectorImpl<Instruction*> &toErase);
Chris Lattnerff36c952009-09-21 02:42:51 +0000727 bool processBlock(BasicBlock *BB);
728 Value *GetValueForBlock(BasicBlock *BB, Instruction *orig,
Owen Andersonc6a31b92007-08-02 17:56:05 +0000729 DenseMap<BasicBlock*, Value*> &Phis,
730 bool top_level = false);
Owen Andersone6b4ff82008-06-18 21:41:49 +0000731 void dump(DenseMap<uint32_t, Value*>& d);
Owen Andersonbe168b32007-08-14 18:04:11 +0000732 bool iterateOnFunction(Function &F);
Chris Lattnerff36c952009-09-21 02:42:51 +0000733 Value *CollapsePhi(PHINode* p);
Owen Andersone6b4ff82008-06-18 21:41:49 +0000734 bool performPRE(Function& F);
Chris Lattnerff36c952009-09-21 02:42:51 +0000735 Value *lookupNumber(BasicBlock *BB, uint32_t num);
736 Value *AttemptRedundancyElimination(Instruction *orig, unsigned valno);
Nuno Lopes274474b2008-10-10 16:25:50 +0000737 void cleanupGlobalSets();
Bill Wendling2a023742008-12-22 21:36:08 +0000738 void verifyRemoved(const Instruction *I) const;
Owen Anderson85c40642007-07-24 17:55:58 +0000739 };
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000740
Owen Anderson85c40642007-07-24 17:55:58 +0000741 char GVN::ID = 0;
Owen Anderson85c40642007-07-24 17:55:58 +0000742}
743
744// createGVNPass - The public interface to this file...
745FunctionPass *llvm::createGVNPass() { return new GVN(); }
746
747static RegisterPass<GVN> X("gvn",
748 "Global Value Numbering");
749
Owen Andersone6b4ff82008-06-18 21:41:49 +0000750void GVN::dump(DenseMap<uint32_t, Value*>& d) {
Owen Anderson5d72a422007-07-25 19:57:03 +0000751 printf("{\n");
Owen Andersone6b4ff82008-06-18 21:41:49 +0000752 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
Owen Anderson5d72a422007-07-25 19:57:03 +0000753 E = d.end(); I != E; ++I) {
Owen Andersone6b4ff82008-06-18 21:41:49 +0000754 printf("%d\n", I->first);
Owen Anderson5d72a422007-07-25 19:57:03 +0000755 I->second->dump();
756 }
757 printf("}\n");
758}
759
Chris Lattnerff36c952009-09-21 02:42:51 +0000760static bool isSafeReplacement(PHINode* p, Instruction *inst) {
Owen Andersond68b1af2009-08-26 22:55:11 +0000761 if (!isa<PHINode>(inst))
762 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000763
Owen Andersond68b1af2009-08-26 22:55:11 +0000764 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
765 UI != E; ++UI)
766 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
767 if (use_phi->getParent() == inst->getParent())
768 return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000769
Owen Andersond68b1af2009-08-26 22:55:11 +0000770 return true;
771}
772
Chris Lattnerff36c952009-09-21 02:42:51 +0000773Value *GVN::CollapsePhi(PHINode *PN) {
774 Value *ConstVal = PN->hasConstantValue(DT);
775 if (!ConstVal) return 0;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000776
Chris Lattnerff36c952009-09-21 02:42:51 +0000777 Instruction *Inst = dyn_cast<Instruction>(ConstVal);
778 if (!Inst)
779 return ConstVal;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000780
Chris Lattnerff36c952009-09-21 02:42:51 +0000781 if (DT->dominates(Inst, PN))
782 if (isSafeReplacement(PN, Inst))
783 return Inst;
Owen Andersone02ad522007-08-16 22:51:56 +0000784 return 0;
785}
Owen Anderson5d72a422007-07-25 19:57:03 +0000786
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000787/// GetValueForBlock - Get the value to use within the specified basic block.
788/// available values are in Phis.
Chris Lattnerff36c952009-09-21 02:42:51 +0000789Value *GVN::GetValueForBlock(BasicBlock *BB, Instruction *Orig,
Chris Lattner3d7103e2008-03-21 21:14:38 +0000790 DenseMap<BasicBlock*, Value*> &Phis,
Chris Lattnerff36c952009-09-21 02:42:51 +0000791 bool TopLevel) {
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000792
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000793 // If we have already computed this value, return the previously computed val.
Owen Andersoned7f9932007-08-03 19:59:35 +0000794 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
Chris Lattnerff36c952009-09-21 02:42:51 +0000795 if (V != Phis.end() && !TopLevel) return V->second;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000796
Owen Andersonc3714b22008-07-02 18:15:31 +0000797 // If the block is unreachable, just return undef, since this path
798 // can't actually occur at runtime.
Chris Lattner02ca4422008-12-01 00:40:32 +0000799 if (!DT->isReachableFromEntry(BB))
Chris Lattnerff36c952009-09-21 02:42:51 +0000800 return Phis[BB] = UndefValue::get(Orig->getType());
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000801
Chris Lattner4bab29b2008-12-09 19:21:47 +0000802 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
Chris Lattnerff36c952009-09-21 02:42:51 +0000803 Value *ret = GetValueForBlock(Pred, Orig, Phis);
Owen Andersoned7f9932007-08-03 19:59:35 +0000804 Phis[BB] = ret;
805 return ret;
Owen Anderson30463f12007-08-03 11:03:26 +0000806 }
Chris Lattner4bab29b2008-12-09 19:21:47 +0000807
808 // Get the number of predecessors of this block so we can reserve space later.
809 // If there is already a PHI in it, use the #preds from it, otherwise count.
810 // Getting it from the PHI is constant time.
811 unsigned NumPreds;
812 if (PHINode *ExistingPN = dyn_cast<PHINode>(BB->begin()))
813 NumPreds = ExistingPN->getNumIncomingValues();
814 else
815 NumPreds = std::distance(pred_begin(BB), pred_end(BB));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000816
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000817 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
818 // now, then get values to fill in the incoming values for the PHI.
Chris Lattnerff36c952009-09-21 02:42:51 +0000819 PHINode *PN = PHINode::Create(Orig->getType(), Orig->getName()+".rle",
Gabor Greifd6da1d02008-04-06 20:25:17 +0000820 BB->begin());
Chris Lattner4bab29b2008-12-09 19:21:47 +0000821 PN->reserveOperandSpace(NumPreds);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000822
Chris Lattner4bab29b2008-12-09 19:21:47 +0000823 Phis.insert(std::make_pair(BB, PN));
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000824
Owen Andersonacfa3ad2007-07-26 18:26:51 +0000825 // Fill in the incoming values for the block.
Owen Anderson9f577412007-07-31 17:43:14 +0000826 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Chris Lattnerff36c952009-09-21 02:42:51 +0000827 Value *val = GetValueForBlock(*PI, Orig, Phis);
Owen Anderson9f577412007-07-31 17:43:14 +0000828 PN->addIncoming(val, *PI);
829 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000830
Chris Lattnerff36c952009-09-21 02:42:51 +0000831 VN.getAliasAnalysis()->copyValue(Orig, PN);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000832
Owen Andersone0143452007-08-16 22:02:55 +0000833 // Attempt to collapse PHI nodes that are trivially redundant
Chris Lattnerff36c952009-09-21 02:42:51 +0000834 Value *v = CollapsePhi(PN);
Chris Lattner3d7103e2008-03-21 21:14:38 +0000835 if (!v) {
836 // Cache our phi construction results
Chris Lattnerff36c952009-09-21 02:42:51 +0000837 if (LoadInst* L = dyn_cast<LoadInst>(Orig))
Owen Anderson5e5e5612008-12-14 19:10:35 +0000838 phiMap[L->getPointerOperand()].insert(PN);
839 else
Chris Lattnerff36c952009-09-21 02:42:51 +0000840 phiMap[Orig].insert(PN);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000841
Chris Lattner3d7103e2008-03-21 21:14:38 +0000842 return PN;
Owen Anderson9f577412007-07-31 17:43:14 +0000843 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000844
Chris Lattner3d7103e2008-03-21 21:14:38 +0000845 PN->replaceAllUsesWith(v);
Chris Lattnerf81b0142008-12-09 22:06:23 +0000846 if (isa<PointerType>(v->getType()))
847 MD->invalidateCachedPointerInfo(v);
Chris Lattner3d7103e2008-03-21 21:14:38 +0000848
849 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
850 E = Phis.end(); I != E; ++I)
851 if (I->second == PN)
852 I->second = v;
853
Dan Gohman7e124382009-07-31 20:24:18 +0000854 DEBUG(errs() << "GVN removed: " << *PN << '\n');
Chris Lattner02ca4422008-12-01 00:40:32 +0000855 MD->removeInstruction(PN);
Chris Lattner3d7103e2008-03-21 21:14:38 +0000856 PN->eraseFromParent();
Bill Wendling2a023742008-12-22 21:36:08 +0000857 DEBUG(verifyRemoved(PN));
Chris Lattner3d7103e2008-03-21 21:14:38 +0000858
859 Phis[BB] = v;
860 return v;
Owen Anderson5d72a422007-07-25 19:57:03 +0000861}
862
Chris Lattnerdcded152008-12-02 08:16:11 +0000863/// IsValueFullyAvailableInBlock - Return true if we can prove that the value
864/// we're analyzing is fully available in the specified block. As we go, keep
Chris Lattner159b98f2008-12-05 07:49:08 +0000865/// track of which blocks we know are fully alive in FullyAvailableBlocks. This
866/// map is actually a tri-state map with the following values:
867/// 0) we know the block *is not* fully available.
868/// 1) we know the block *is* fully available.
869/// 2) we do not know whether the block is fully available or not, but we are
870/// currently speculating that it will be.
871/// 3) we are speculating for this block and have used that to speculate for
872/// other blocks.
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000873static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
Chris Lattner159b98f2008-12-05 07:49:08 +0000874 DenseMap<BasicBlock*, char> &FullyAvailableBlocks) {
Chris Lattnerdcded152008-12-02 08:16:11 +0000875 // Optimistically assume that the block is fully available and check to see
876 // if we already know about this block in one lookup.
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000877 std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
Chris Lattner159b98f2008-12-05 07:49:08 +0000878 FullyAvailableBlocks.insert(std::make_pair(BB, 2));
Chris Lattnerdcded152008-12-02 08:16:11 +0000879
880 // If the entry already existed for this block, return the precomputed value.
Chris Lattner159b98f2008-12-05 07:49:08 +0000881 if (!IV.second) {
882 // If this is a speculative "available" value, mark it as being used for
883 // speculation of other blocks.
884 if (IV.first->second == 2)
885 IV.first->second = 3;
886 return IV.first->second != 0;
887 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000888
Chris Lattnerdcded152008-12-02 08:16:11 +0000889 // Otherwise, see if it is fully available in all predecessors.
890 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000891
Chris Lattnerdcded152008-12-02 08:16:11 +0000892 // If this block has no predecessors, it isn't live-in here.
893 if (PI == PE)
Chris Lattner159b98f2008-12-05 07:49:08 +0000894 goto SpeculationFailure;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000895
Chris Lattnerdcded152008-12-02 08:16:11 +0000896 for (; PI != PE; ++PI)
897 // If the value isn't fully available in one of our predecessors, then it
898 // isn't fully available in this block either. Undo our previous
899 // optimistic assumption and bail out.
900 if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
Chris Lattner159b98f2008-12-05 07:49:08 +0000901 goto SpeculationFailure;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000902
Chris Lattnerdcded152008-12-02 08:16:11 +0000903 return true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000904
Chris Lattner159b98f2008-12-05 07:49:08 +0000905// SpeculationFailure - If we get here, we found out that this is not, after
906// all, a fully-available block. We have a problem if we speculated on this and
907// used the speculation to mark other blocks as available.
908SpeculationFailure:
909 char &BBVal = FullyAvailableBlocks[BB];
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000910
Chris Lattner159b98f2008-12-05 07:49:08 +0000911 // If we didn't speculate on this, just return with it set to false.
912 if (BBVal == 2) {
913 BBVal = 0;
914 return false;
915 }
916
917 // If we did speculate on this value, we could have blocks set to 1 that are
918 // incorrect. Walk the (transitive) successors of this block and mark them as
919 // 0 if set to one.
920 SmallVector<BasicBlock*, 32> BBWorklist;
921 BBWorklist.push_back(BB);
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000922
Chris Lattner159b98f2008-12-05 07:49:08 +0000923 while (!BBWorklist.empty()) {
924 BasicBlock *Entry = BBWorklist.pop_back_val();
925 // Note that this sets blocks to 0 (unavailable) if they happen to not
926 // already be in FullyAvailableBlocks. This is safe.
927 char &EntryVal = FullyAvailableBlocks[Entry];
928 if (EntryVal == 0) continue; // Already unavailable.
929
930 // Mark as unavailable.
931 EntryVal = 0;
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000932
Chris Lattner159b98f2008-12-05 07:49:08 +0000933 for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I)
934 BBWorklist.push_back(*I);
935 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +0000936
Chris Lattner159b98f2008-12-05 07:49:08 +0000937 return false;
Chris Lattnerdcded152008-12-02 08:16:11 +0000938}
939
Chris Lattnerd6b1d052009-09-20 20:09:34 +0000940
941/// CoerceAvailableValueToLoadType - If we saw a store of a value to memory, and
942/// then a load from a must-aliased pointer of a different type, try to coerce
943/// the stored value. LoadedTy is the type of the load we want to replace and
944/// InsertPt is the place to insert new instructions.
945///
946/// If we can't do it, return null.
947static Value *CoerceAvailableValueToLoadType(Value *StoredVal,
948 const Type *LoadedTy,
949 Instruction *InsertPt,
950 const TargetData &TD) {
951 const Type *StoredValTy = StoredVal->getType();
952
953 uint64_t StoreSize = TD.getTypeSizeInBits(StoredValTy);
954 uint64_t LoadSize = TD.getTypeSizeInBits(LoadedTy);
955
956 // If the store and reload are the same size, we can always reuse it.
957 if (StoreSize == LoadSize) {
958 if (isa<PointerType>(StoredValTy) && isa<PointerType>(LoadedTy)) {
959 // Pointer to Pointer -> use bitcast.
960 return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
961 }
962
963 // Convert source pointers to integers, which can be bitcast.
964 if (isa<PointerType>(StoredValTy)) {
965 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
966 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
967 }
968
969 const Type *TypeToCastTo = LoadedTy;
970 if (isa<PointerType>(TypeToCastTo))
971 TypeToCastTo = TD.getIntPtrType(StoredValTy->getContext());
972
973 if (StoredValTy != TypeToCastTo)
974 StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
975
976 // Cast to pointer if the load needs a pointer type.
977 if (isa<PointerType>(LoadedTy))
978 StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
979
980 return StoredVal;
981 }
982
983 // If the loaded value is smaller than the available value, then we can
984 // extract out a piece from it. If the available value is too small, then we
985 // can't do anything.
986 if (StoreSize < LoadSize)
987 return 0;
988
989 // Convert source pointers to integers, which can be manipulated.
990 if (isa<PointerType>(StoredValTy)) {
991 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
992 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
993 }
994
995 // Convert vectors and fp to integer, which can be manipulated.
996 if (!isa<IntegerType>(StoredValTy)) {
997 StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
998 StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
999 }
1000
1001 // If this is a big-endian system, we need to shift the value down to the low
1002 // bits so that a truncate will work.
1003 if (TD.isBigEndian()) {
1004 Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
1005 StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
1006 }
1007
1008 // Truncate the integer to the right size now.
1009 const Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
1010 StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
1011
1012 if (LoadedTy == NewIntTy)
1013 return StoredVal;
1014
1015 // If the result is a pointer, inttoptr.
1016 if (isa<PointerType>(LoadedTy))
1017 return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
1018
1019 // Otherwise, bitcast.
1020 return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
1021}
1022
1023static void
1024GetAvailableBlockValues(DenseMap<BasicBlock*, Value*> &BlockReplValues,
1025 SmallVector<std::pair<BasicBlock*,
1026 Value*>, 16> &ValuesPerBlock,
1027 const Type *LoadTy,
1028 const TargetData *TD) {
1029
1030 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
1031 BasicBlock *BB = ValuesPerBlock[i].first;
1032 Value *AvailableVal = ValuesPerBlock[i].second;
1033
1034 Value *&BlockEntry = BlockReplValues[BB];
1035 if (BlockEntry) continue;
1036
1037 if (AvailableVal->getType() != LoadTy) {
1038 assert(TD && "Need target data to handle type mismatch case");
1039 AvailableVal = CoerceAvailableValueToLoadType(AvailableVal, LoadTy,
1040 BB->getTerminator(), *TD);
1041 DEBUG(errs() << "GVN COERCED NONLOCAL VAL:\n"
1042 << *ValuesPerBlock[i].second << '\n'
1043 << *AvailableVal << '\n' << "\n\n\n");
1044 }
1045 BlockEntry = AvailableVal;
1046 }
1047}
1048
Owen Andersone0143452007-08-16 22:02:55 +00001049/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
1050/// non-local by performing PHI construction.
Chris Lattnerdcded152008-12-02 08:16:11 +00001051bool GVN::processNonLocalLoad(LoadInst *LI,
Chris Lattner7de20452008-03-21 22:01:16 +00001052 SmallVectorImpl<Instruction*> &toErase) {
Chris Lattnerdcded152008-12-02 08:16:11 +00001053 // Find the non-local dependencies of the load.
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001054 SmallVector<MemoryDependenceAnalysis::NonLocalDepEntry, 64> Deps;
Chris Lattneraf713862008-12-09 19:25:07 +00001055 MD->getNonLocalPointerDependency(LI->getOperand(0), true, LI->getParent(),
1056 Deps);
Dan Gohman7e124382009-07-31 20:24:18 +00001057 //DEBUG(errs() << "INVESTIGATING NONLOCAL LOAD: "
1058 // << Deps.size() << *LI << '\n');
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001059
Owen Anderson90e717d2008-08-26 22:07:42 +00001060 // If we had to process more than one hundred blocks to find the
1061 // dependencies, this load isn't worth worrying about. Optimizing
1062 // it will be too expensive.
Chris Lattneraf713862008-12-09 19:25:07 +00001063 if (Deps.size() > 100)
Owen Anderson90e717d2008-08-26 22:07:42 +00001064 return false;
Chris Lattner8d1686f2008-12-18 00:51:32 +00001065
1066 // If we had a phi translation failure, we'll have a single entry which is a
1067 // clobber in the current block. Reject this early.
Edwin Török3ffffac2009-06-17 18:48:18 +00001068 if (Deps.size() == 1 && Deps[0].second.isClobber()) {
1069 DEBUG(
Dan Gohman0be10b02009-07-25 01:43:01 +00001070 errs() << "GVN: non-local load ";
1071 WriteAsOperand(errs(), LI);
Dan Gohman7e124382009-07-31 20:24:18 +00001072 errs() << " is clobbered by " << *Deps[0].second.getInst() << '\n';
Edwin Török3ffffac2009-06-17 18:48:18 +00001073 );
Chris Lattner8d1686f2008-12-18 00:51:32 +00001074 return false;
Edwin Török3ffffac2009-06-17 18:48:18 +00001075 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001076
Chris Lattnerdcded152008-12-02 08:16:11 +00001077 // Filter out useless results (non-locals, etc). Keep track of the blocks
1078 // where we have a value available in repl, also keep track of whether we see
1079 // dependencies that produce an unknown value for the load (such as a call
1080 // that could potentially clobber the load).
1081 SmallVector<std::pair<BasicBlock*, Value*>, 16> ValuesPerBlock;
1082 SmallVector<BasicBlock*, 16> UnavailableBlocks;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001083
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001084 const TargetData *TD = 0;
1085
Chris Lattneraf713862008-12-09 19:25:07 +00001086 for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
1087 BasicBlock *DepBB = Deps[i].first;
1088 MemDepResult DepInfo = Deps[i].second;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001089
Chris Lattner4531da82008-12-05 21:04:20 +00001090 if (DepInfo.isClobber()) {
1091 UnavailableBlocks.push_back(DepBB);
1092 continue;
1093 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001094
Chris Lattner4531da82008-12-05 21:04:20 +00001095 Instruction *DepInst = DepInfo.getInst();
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001096
Chris Lattner4531da82008-12-05 21:04:20 +00001097 // Loading the allocation -> undef.
Victor Hernandez48c3c542009-09-18 22:35:49 +00001098 if (isa<AllocationInst>(DepInst) || isMalloc(DepInst)) {
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001099 ValuesPerBlock.push_back(std::make_pair(DepBB,
Owen Andersonb99ecca2009-07-30 23:03:37 +00001100 UndefValue::get(LI->getType())));
Chris Lattner46876282008-12-01 01:15:42 +00001101 continue;
1102 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001103
Chris Lattneraf713862008-12-09 19:25:07 +00001104 if (StoreInst* S = dyn_cast<StoreInst>(DepInst)) {
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001105 // Reject loads and stores that are to the same address but are of
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001106 // different types if we have to.
Chris Lattnerdcded152008-12-02 08:16:11 +00001107 if (S->getOperand(0)->getType() != LI->getType()) {
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001108 if (TD == 0)
1109 TD = getAnalysisIfAvailable<TargetData>();
1110
1111 // If the stored value is larger or equal to the loaded value, we can
1112 // reuse it.
1113 if (TD == 0 ||
1114 TD->getTypeSizeInBits(S->getOperand(0)->getType()) <
1115 TD->getTypeSizeInBits(LI->getType())) {
1116 UnavailableBlocks.push_back(DepBB);
1117 continue;
1118 }
Chris Lattnerdcded152008-12-02 08:16:11 +00001119 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001120
Chris Lattnerdcded152008-12-02 08:16:11 +00001121 ValuesPerBlock.push_back(std::make_pair(DepBB, S->getOperand(0)));
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001122
Chris Lattneraf713862008-12-09 19:25:07 +00001123 } else if (LoadInst* LD = dyn_cast<LoadInst>(DepInst)) {
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001124 // If the types mismatch and we can't handle it, reject reuse of the load.
Chris Lattnerdcded152008-12-02 08:16:11 +00001125 if (LD->getType() != LI->getType()) {
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001126 if (TD == 0)
1127 TD = getAnalysisIfAvailable<TargetData>();
1128
1129 // If the stored value is larger or equal to the loaded value, we can
1130 // reuse it.
1131 if (TD == 0 ||
1132 TD->getTypeSizeInBits(LD->getType()) <
1133 TD->getTypeSizeInBits(LI->getType())) {
1134 UnavailableBlocks.push_back(DepBB);
1135 continue;
1136 }
Chris Lattnerdcded152008-12-02 08:16:11 +00001137 }
Chris Lattnerdcded152008-12-02 08:16:11 +00001138 ValuesPerBlock.push_back(std::make_pair(DepBB, LD));
Owen Anderson5d72a422007-07-25 19:57:03 +00001139 } else {
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001140 // FIXME: Handle memset/memcpy.
Chris Lattnerdcded152008-12-02 08:16:11 +00001141 UnavailableBlocks.push_back(DepBB);
1142 continue;
Owen Anderson5d72a422007-07-25 19:57:03 +00001143 }
Chris Lattner3d7103e2008-03-21 21:14:38 +00001144 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001145
Chris Lattnerdcded152008-12-02 08:16:11 +00001146 // If we have no predecessors that produce a known value for this load, exit
1147 // early.
1148 if (ValuesPerBlock.empty()) return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001149
Chris Lattnerdcded152008-12-02 08:16:11 +00001150 // If all of the instructions we depend on produce a known value for this
1151 // load, then it is fully redundant and we can use PHI insertion to compute
1152 // its value. Insert PHIs and remove the fully redundant value now.
1153 if (UnavailableBlocks.empty()) {
1154 // Use cached PHI construction information from previous runs
1155 SmallPtrSet<Instruction*, 4> &p = phiMap[LI->getPointerOperand()];
Chris Lattneraf713862008-12-09 19:25:07 +00001156 // FIXME: What does phiMap do? Are we positive it isn't getting invalidated?
Chris Lattnerdcded152008-12-02 08:16:11 +00001157 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
1158 I != E; ++I) {
1159 if ((*I)->getParent() == LI->getParent()) {
Dan Gohman7e124382009-07-31 20:24:18 +00001160 DEBUG(errs() << "GVN REMOVING NONLOCAL LOAD #1: " << *LI << '\n');
Chris Lattnerdcded152008-12-02 08:16:11 +00001161 LI->replaceAllUsesWith(*I);
Chris Lattnerf81b0142008-12-09 22:06:23 +00001162 if (isa<PointerType>((*I)->getType()))
1163 MD->invalidateCachedPointerInfo(*I);
Chris Lattnerdcded152008-12-02 08:16:11 +00001164 toErase.push_back(LI);
1165 NumGVNLoad++;
1166 return true;
1167 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001168
Chris Lattnerdcded152008-12-02 08:16:11 +00001169 ValuesPerBlock.push_back(std::make_pair((*I)->getParent(), *I));
Owen Anderson5b299672007-08-07 23:12:31 +00001170 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001171
Dan Gohman7e124382009-07-31 20:24:18 +00001172 DEBUG(errs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001173
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001174 // Convert the block information to a map, and insert coersions as needed.
Chris Lattnerdcded152008-12-02 08:16:11 +00001175 DenseMap<BasicBlock*, Value*> BlockReplValues;
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001176 GetAvailableBlockValues(BlockReplValues, ValuesPerBlock, LI->getType(), TD);
1177
Chris Lattnerdcded152008-12-02 08:16:11 +00001178 // Perform PHI construction.
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001179 Value *V = GetValueForBlock(LI->getParent(), LI, BlockReplValues, true);
1180 LI->replaceAllUsesWith(V);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001181
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001182 if (isa<PHINode>(V))
1183 V->takeName(LI);
1184 if (isa<PointerType>(V->getType()))
1185 MD->invalidateCachedPointerInfo(V);
Chris Lattnerdcded152008-12-02 08:16:11 +00001186 toErase.push_back(LI);
1187 NumGVNLoad++;
1188 return true;
1189 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001190
Chris Lattnerdcded152008-12-02 08:16:11 +00001191 if (!EnablePRE || !EnableLoadPRE)
1192 return false;
1193
1194 // Okay, we have *some* definitions of the value. This means that the value
1195 // is available in some of our (transitive) predecessors. Lets think about
1196 // doing PRE of this load. This will involve inserting a new load into the
1197 // predecessor when it's not available. We could do this in general, but
1198 // prefer to not increase code size. As such, we only do this when we know
1199 // that we only have to insert *one* load (which means we're basically moving
1200 // the load, not inserting a new one).
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001201
Owen Andersondd37b182009-05-31 09:03:40 +00001202 SmallPtrSet<BasicBlock *, 4> Blockers;
1203 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1204 Blockers.insert(UnavailableBlocks[i]);
1205
1206 // Lets find first basic block with more than one predecessor. Walk backwards
1207 // through predecessors if needed.
Chris Lattnerdcded152008-12-02 08:16:11 +00001208 BasicBlock *LoadBB = LI->getParent();
Owen Andersondd37b182009-05-31 09:03:40 +00001209 BasicBlock *TmpBB = LoadBB;
1210
1211 bool isSinglePred = false;
Dale Johannesena19b67f2009-06-17 20:48:23 +00001212 bool allSingleSucc = true;
Owen Andersondd37b182009-05-31 09:03:40 +00001213 while (TmpBB->getSinglePredecessor()) {
1214 isSinglePred = true;
1215 TmpBB = TmpBB->getSinglePredecessor();
1216 if (!TmpBB) // If haven't found any, bail now.
1217 return false;
1218 if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1219 return false;
1220 if (Blockers.count(TmpBB))
1221 return false;
Dale Johannesena19b67f2009-06-17 20:48:23 +00001222 if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1223 allSingleSucc = false;
Owen Andersondd37b182009-05-31 09:03:40 +00001224 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001225
Owen Andersondd37b182009-05-31 09:03:40 +00001226 assert(TmpBB);
1227 LoadBB = TmpBB;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001228
Chris Lattnerdcded152008-12-02 08:16:11 +00001229 // If we have a repl set with LI itself in it, this means we have a loop where
1230 // at least one of the values is LI. Since this means that we won't be able
1231 // to eliminate LI even if we insert uses in the other predecessors, we will
1232 // end up increasing code size. Reject this by scanning for LI.
1233 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1234 if (ValuesPerBlock[i].second == LI)
1235 return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001236
Owen Andersondd37b182009-05-31 09:03:40 +00001237 if (isSinglePred) {
1238 bool isHot = false;
1239 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1240 if (Instruction *I = dyn_cast<Instruction>(ValuesPerBlock[i].second))
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001241 // "Hot" Instruction is in some loop (because it dominates its dep.
1242 // instruction).
1243 if (DT->dominates(LI, I)) {
1244 isHot = true;
1245 break;
1246 }
Owen Andersondd37b182009-05-31 09:03:40 +00001247
1248 // We are interested only in "hot" instructions. We don't want to do any
1249 // mis-optimizations here.
1250 if (!isHot)
1251 return false;
1252 }
1253
Chris Lattnerdcded152008-12-02 08:16:11 +00001254 // Okay, we have some hope :). Check to see if the loaded value is fully
1255 // available in all but one predecessor.
1256 // FIXME: If we could restructure the CFG, we could make a common pred with
1257 // all the preds that don't have an available LI and insert a new load into
1258 // that one block.
1259 BasicBlock *UnavailablePred = 0;
1260
Chris Lattner159b98f2008-12-05 07:49:08 +00001261 DenseMap<BasicBlock*, char> FullyAvailableBlocks;
Chris Lattnerdcded152008-12-02 08:16:11 +00001262 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1263 FullyAvailableBlocks[ValuesPerBlock[i].first] = true;
1264 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1265 FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1266
1267 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1268 PI != E; ++PI) {
1269 if (IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
1270 continue;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001271
Chris Lattnerdcded152008-12-02 08:16:11 +00001272 // If this load is not available in multiple predecessors, reject it.
1273 if (UnavailablePred && UnavailablePred != *PI)
1274 return false;
1275 UnavailablePred = *PI;
1276 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001277
Chris Lattnerdcded152008-12-02 08:16:11 +00001278 assert(UnavailablePred != 0 &&
1279 "Fully available value should be eliminated above!");
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001280
Chris Lattnerdcded152008-12-02 08:16:11 +00001281 // If the loaded pointer is PHI node defined in this block, do PHI translation
1282 // to get its value in the predecessor.
1283 Value *LoadPtr = LI->getOperand(0)->DoPHITranslation(LoadBB, UnavailablePred);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001284
Chris Lattnerdcded152008-12-02 08:16:11 +00001285 // Make sure the value is live in the predecessor. If it was defined by a
1286 // non-PHI instruction in this block, we don't know how to recompute it above.
1287 if (Instruction *LPInst = dyn_cast<Instruction>(LoadPtr))
1288 if (!DT->dominates(LPInst->getParent(), UnavailablePred)) {
Daniel Dunbar005975c2009-07-25 00:23:56 +00001289 DEBUG(errs() << "COULDN'T PRE LOAD BECAUSE PTR IS UNAVAILABLE IN PRED: "
Dan Gohman7e124382009-07-31 20:24:18 +00001290 << *LPInst << '\n' << *LI << "\n");
Chris Lattnerdcded152008-12-02 08:16:11 +00001291 return false;
1292 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001293
Chris Lattnerdcded152008-12-02 08:16:11 +00001294 // We don't currently handle critical edges :(
1295 if (UnavailablePred->getTerminator()->getNumSuccessors() != 1) {
Daniel Dunbar005975c2009-07-25 00:23:56 +00001296 DEBUG(errs() << "COULD NOT PRE LOAD BECAUSE OF CRITICAL EDGE '"
Dan Gohman7e124382009-07-31 20:24:18 +00001297 << UnavailablePred->getName() << "': " << *LI << '\n');
Chris Lattnerdcded152008-12-02 08:16:11 +00001298 return false;
Owen Anderson5b299672007-08-07 23:12:31 +00001299 }
Dale Johannesena19b67f2009-06-17 20:48:23 +00001300
1301 // Make sure it is valid to move this load here. We have to watch out for:
1302 // @1 = getelementptr (i8* p, ...
1303 // test p and branch if == 0
1304 // load @1
1305 // It is valid to have the getelementptr before the test, even if p can be 0,
1306 // as getelementptr only does address arithmetic.
1307 // If we are not pushing the value through any multiple-successor blocks
1308 // we do not have this case. Otherwise, check that the load is safe to
1309 // put anywhere; this can be improved, but should be conservatively safe.
1310 if (!allSingleSucc &&
1311 !isSafeToLoadUnconditionally(LoadPtr, UnavailablePred->getTerminator()))
1312 return false;
1313
Chris Lattnerdcded152008-12-02 08:16:11 +00001314 // Okay, we can eliminate this load by inserting a reload in the predecessor
1315 // and using PHI construction to get the value in the other predecessors, do
1316 // it.
Dan Gohman7e124382009-07-31 20:24:18 +00001317 DEBUG(errs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001318
Chris Lattnerdcded152008-12-02 08:16:11 +00001319 Value *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1320 LI->getAlignment(),
1321 UnavailablePred->getTerminator());
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001322
Owen Anderson1c057ee2009-05-29 05:37:54 +00001323 SmallPtrSet<Instruction*, 4> &p = phiMap[LI->getPointerOperand()];
1324 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
1325 I != E; ++I)
1326 ValuesPerBlock.push_back(std::make_pair((*I)->getParent(), *I));
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001327
Chris Lattnerdcded152008-12-02 08:16:11 +00001328 DenseMap<BasicBlock*, Value*> BlockReplValues;
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001329 GetAvailableBlockValues(BlockReplValues, ValuesPerBlock, LI->getType(), TD);
Chris Lattnerdcded152008-12-02 08:16:11 +00001330 BlockReplValues[UnavailablePred] = NewLoad;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001331
Chris Lattnerdcded152008-12-02 08:16:11 +00001332 // Perform PHI construction.
Chris Lattnerd6b1d052009-09-20 20:09:34 +00001333 Value *V = GetValueForBlock(LI->getParent(), LI, BlockReplValues, true);
1334 LI->replaceAllUsesWith(V);
1335 if (isa<PHINode>(V))
1336 V->takeName(LI);
1337 if (isa<PointerType>(V->getType()))
1338 MD->invalidateCachedPointerInfo(V);
Chris Lattnerdcded152008-12-02 08:16:11 +00001339 toErase.push_back(LI);
1340 NumPRELoad++;
Owen Anderson5d72a422007-07-25 19:57:03 +00001341 return true;
1342}
1343
Owen Andersone0143452007-08-16 22:02:55 +00001344/// processLoad - Attempt to eliminate a load, first by eliminating it
1345/// locally, and then attempting non-local elimination if that fails.
Chris Lattner4531da82008-12-05 21:04:20 +00001346bool GVN::processLoad(LoadInst *L, SmallVectorImpl<Instruction*> &toErase) {
1347 if (L->isVolatile())
Owen Anderson85c40642007-07-24 17:55:58 +00001348 return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001349
Owen Anderson85c40642007-07-24 17:55:58 +00001350 // ... to a pointer that has been loaded from before...
Chris Lattnerff36c952009-09-21 02:42:51 +00001351 MemDepResult Dep = MD->getDependency(L);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001352
Chris Lattner4531da82008-12-05 21:04:20 +00001353 // If the value isn't available, don't do anything!
Chris Lattnerff36c952009-09-21 02:42:51 +00001354 if (Dep.isClobber()) {
Chris Lattner7741aa52009-09-20 19:03:47 +00001355 // FIXME: In the future, we should handle things like:
1356 // store i32 123, i32* %P
1357 // %A = bitcast i32* %P to i8*
1358 // %B = gep i8* %A, i32 1
1359 // %C = load i8* %B
1360 //
1361 // We could do that by recognizing if the clobber instructions are obviously
1362 // a common base + constant offset, and if the previous store (or memset)
1363 // completely covers this load. This sort of thing can happen in bitfield
1364 // access code.
Edwin Török47cf8842009-05-29 09:46:03 +00001365 DEBUG(
1366 // fast print dep, using operator<< on instruction would be too slow
Dan Gohman0be10b02009-07-25 01:43:01 +00001367 errs() << "GVN: load ";
1368 WriteAsOperand(errs(), L);
Chris Lattnerff36c952009-09-21 02:42:51 +00001369 Instruction *I = Dep.getInst();
Dan Gohman7e124382009-07-31 20:24:18 +00001370 errs() << " is clobbered by " << *I << '\n';
Edwin Török47cf8842009-05-29 09:46:03 +00001371 );
Chris Lattner4531da82008-12-05 21:04:20 +00001372 return false;
Edwin Török47cf8842009-05-29 09:46:03 +00001373 }
Chris Lattner4531da82008-12-05 21:04:20 +00001374
1375 // If it is defined in another block, try harder.
Chris Lattnerff36c952009-09-21 02:42:51 +00001376 if (Dep.isNonLocal())
Chris Lattner4531da82008-12-05 21:04:20 +00001377 return processNonLocalLoad(L, toErase);
Eli Friedman350307f2008-02-12 12:08:14 +00001378
Chris Lattnerff36c952009-09-21 02:42:51 +00001379 Instruction *DepInst = Dep.getInst();
Chris Lattner4531da82008-12-05 21:04:20 +00001380 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
Chris Lattner7741aa52009-09-20 19:03:47 +00001381 Value *StoredVal = DepSI->getOperand(0);
1382
1383 // The store and load are to a must-aliased pointer, but they may not
1384 // actually have the same type. See if we know how to reuse the stored
1385 // value (depending on its type).
1386 const TargetData *TD = 0;
1387 if (StoredVal->getType() != L->getType() &&
1388 (TD = getAnalysisIfAvailable<TargetData>())) {
Chris Lattner3de5c8c2009-09-20 19:31:14 +00001389 StoredVal = CoerceAvailableValueToLoadType(StoredVal, L->getType(), L, *TD);
Chris Lattner7741aa52009-09-20 19:03:47 +00001390 if (StoredVal == 0)
1391 return false;
1392
1393 DEBUG(errs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
1394 << '\n' << *L << "\n\n\n");
1395 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001396
Chris Lattner4531da82008-12-05 21:04:20 +00001397 // Remove it!
Chris Lattner7741aa52009-09-20 19:03:47 +00001398 L->replaceAllUsesWith(StoredVal);
1399 if (isa<PointerType>(StoredVal->getType()))
1400 MD->invalidateCachedPointerInfo(StoredVal);
Chris Lattner4531da82008-12-05 21:04:20 +00001401 toErase.push_back(L);
1402 NumGVNLoad++;
1403 return true;
1404 }
1405
1406 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
Chris Lattner7741aa52009-09-20 19:03:47 +00001407 Value *AvailableVal = DepLI;
1408
1409 // The loads are of a must-aliased pointer, but they may not actually have
1410 // the same type. See if we know how to reuse the previously loaded value
1411 // (depending on its type).
1412 const TargetData *TD = 0;
1413 if (DepLI->getType() != L->getType() &&
1414 (TD = getAnalysisIfAvailable<TargetData>())) {
Chris Lattner3de5c8c2009-09-20 19:31:14 +00001415 AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(), L, *TD);
Chris Lattner7741aa52009-09-20 19:03:47 +00001416 if (AvailableVal == 0)
1417 return false;
1418
1419 DEBUG(errs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
1420 << "\n" << *L << "\n\n\n");
1421 }
1422
Chris Lattner4531da82008-12-05 21:04:20 +00001423 // Remove it!
Chris Lattner7741aa52009-09-20 19:03:47 +00001424 L->replaceAllUsesWith(AvailableVal);
Chris Lattnerf81b0142008-12-09 22:06:23 +00001425 if (isa<PointerType>(DepLI->getType()))
1426 MD->invalidateCachedPointerInfo(DepLI);
Chris Lattner4531da82008-12-05 21:04:20 +00001427 toErase.push_back(L);
1428 NumGVNLoad++;
1429 return true;
1430 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001431
Chris Lattner7741aa52009-09-20 19:03:47 +00001432 // FIXME: We should handle memset/memcpy/memmove as dependent instructions to
1433 // forward the value if available.
Chris Lattner3de5c8c2009-09-20 19:31:14 +00001434 //if (isa<MemIntrinsic>(DepInst))
1435 // errs() << "LOAD DEPENDS ON MEM: " << *L << "\n" << *DepInst << "\n\n";
Chris Lattner7741aa52009-09-20 19:03:47 +00001436
1437
Chris Lattner8ea60462008-11-30 01:39:32 +00001438 // If this load really doesn't depend on anything, then we must be loading an
1439 // undef value. This can happen when loading for a fresh allocation with no
1440 // intervening stores, for example.
Victor Hernandez48c3c542009-09-18 22:35:49 +00001441 if (isa<AllocationInst>(DepInst) || isMalloc(DepInst)) {
Owen Andersonb99ecca2009-07-30 23:03:37 +00001442 L->replaceAllUsesWith(UndefValue::get(L->getType()));
Chris Lattner8ea60462008-11-30 01:39:32 +00001443 toErase.push_back(L);
Chris Lattner8ea60462008-11-30 01:39:32 +00001444 NumGVNLoad++;
Chris Lattner4531da82008-12-05 21:04:20 +00001445 return true;
Eli Friedman350307f2008-02-12 12:08:14 +00001446 }
1447
Chris Lattner4531da82008-12-05 21:04:20 +00001448 return false;
Owen Anderson85c40642007-07-24 17:55:58 +00001449}
1450
Chris Lattnerff36c952009-09-21 02:42:51 +00001451Value *GVN::lookupNumber(BasicBlock *BB, uint32_t num) {
Owen Andersonaef6a922008-06-23 17:49:45 +00001452 DenseMap<BasicBlock*, ValueNumberScope*>::iterator I = localAvail.find(BB);
1453 if (I == localAvail.end())
1454 return 0;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001455
Chris Lattnerff36c952009-09-21 02:42:51 +00001456 ValueNumberScope *Locals = I->second;
1457 while (Locals) {
1458 DenseMap<uint32_t, Value*>::iterator I = Locals->table.find(num);
1459 if (I != Locals->table.end())
Owen Anderson2a412722008-06-20 01:15:47 +00001460 return I->second;
Chris Lattnerff36c952009-09-21 02:42:51 +00001461 Locals = Locals->parent;
Owen Anderson2a412722008-06-20 01:15:47 +00001462 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001463
Owen Anderson2a412722008-06-20 01:15:47 +00001464 return 0;
1465}
1466
Owen Andersona03e7862008-12-15 02:03:00 +00001467/// AttemptRedundancyElimination - If the "fast path" of redundancy elimination
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001468/// by inheritance from the dominator fails, see if we can perform phi
Owen Andersona03e7862008-12-15 02:03:00 +00001469/// construction to eliminate the redundancy.
Chris Lattnerff36c952009-09-21 02:42:51 +00001470Value *GVN::AttemptRedundancyElimination(Instruction *orig, unsigned valno) {
1471 BasicBlock *BaseBlock = orig->getParent();
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001472
Owen Andersona03e7862008-12-15 02:03:00 +00001473 SmallPtrSet<BasicBlock*, 4> Visited;
1474 SmallVector<BasicBlock*, 8> Stack;
1475 Stack.push_back(BaseBlock);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001476
Owen Andersona03e7862008-12-15 02:03:00 +00001477 DenseMap<BasicBlock*, Value*> Results;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001478
Owen Andersona03e7862008-12-15 02:03:00 +00001479 // Walk backwards through our predecessors, looking for instances of the
1480 // value number we're looking for. Instances are recorded in the Results
1481 // map, which is then used to perform phi construction.
1482 while (!Stack.empty()) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001483 BasicBlock *Current = Stack.back();
Owen Andersona03e7862008-12-15 02:03:00 +00001484 Stack.pop_back();
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001485
Owen Andersona03e7862008-12-15 02:03:00 +00001486 // If we've walked all the way to a proper dominator, then give up. Cases
1487 // where the instance is in the dominator will have been caught by the fast
1488 // path, and any cases that require phi construction further than this are
1489 // probably not worth it anyways. Note that this is a SIGNIFICANT compile
1490 // time improvement.
1491 if (DT->properlyDominates(Current, orig->getParent())) return 0;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001492
Owen Andersona03e7862008-12-15 02:03:00 +00001493 DenseMap<BasicBlock*, ValueNumberScope*>::iterator LA =
1494 localAvail.find(Current);
1495 if (LA == localAvail.end()) return 0;
Chris Lattner6f33e552009-01-19 22:00:18 +00001496 DenseMap<uint32_t, Value*>::iterator V = LA->second->table.find(valno);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001497
Owen Andersona03e7862008-12-15 02:03:00 +00001498 if (V != LA->second->table.end()) {
1499 // Found an instance, record it.
1500 Results.insert(std::make_pair(Current, V->second));
1501 continue;
1502 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001503
Owen Andersona03e7862008-12-15 02:03:00 +00001504 // If we reach the beginning of the function, then give up.
1505 if (pred_begin(Current) == pred_end(Current))
1506 return 0;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001507
Owen Andersona03e7862008-12-15 02:03:00 +00001508 for (pred_iterator PI = pred_begin(Current), PE = pred_end(Current);
1509 PI != PE; ++PI)
1510 if (Visited.insert(*PI))
1511 Stack.push_back(*PI);
1512 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001513
Owen Andersona03e7862008-12-15 02:03:00 +00001514 // If we didn't find instances, give up. Otherwise, perform phi construction.
1515 if (Results.size() == 0)
1516 return 0;
1517 else
1518 return GetValueForBlock(BaseBlock, orig, Results, true);
1519}
1520
Owen Andersonf631bb62007-08-14 18:16:29 +00001521/// processInstruction - When calculating availability, handle an instruction
Owen Anderson85c40642007-07-24 17:55:58 +00001522/// by inserting it into the appropriate sets
Owen Anderson9334fc62008-06-12 19:25:32 +00001523bool GVN::processInstruction(Instruction *I,
Chris Lattner7de20452008-03-21 22:01:16 +00001524 SmallVectorImpl<Instruction*> &toErase) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001525 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1526 bool Changed = processLoad(LI, toErase);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001527
Chris Lattnerff36c952009-09-21 02:42:51 +00001528 if (!Changed) {
1529 unsigned Num = VN.lookup_or_add(LI);
1530 localAvail[I->getParent()]->table.insert(std::make_pair(Num, LI));
Owen Andersone6b4ff82008-06-18 21:41:49 +00001531 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001532
Chris Lattnerff36c952009-09-21 02:42:51 +00001533 return Changed;
Owen Andersone6b4ff82008-06-18 21:41:49 +00001534 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001535
Chris Lattnerff36c952009-09-21 02:42:51 +00001536 uint32_t NextNum = VN.getNextUnusedValueNumber();
1537 unsigned Num = VN.lookup_or_add(I);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001538
Chris Lattnerff36c952009-09-21 02:42:51 +00001539 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1540 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001541
Owen Andersonef8bf0f2009-04-01 23:53:49 +00001542 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
1543 return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001544
Chris Lattnerff36c952009-09-21 02:42:51 +00001545 Value *BranchCond = BI->getCondition();
1546 uint32_t CondVN = VN.lookup_or_add(BranchCond);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001547
Chris Lattnerff36c952009-09-21 02:42:51 +00001548 BasicBlock *TrueSucc = BI->getSuccessor(0);
1549 BasicBlock *FalseSucc = BI->getSuccessor(1);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001550
Chris Lattnerff36c952009-09-21 02:42:51 +00001551 if (TrueSucc->getSinglePredecessor())
1552 localAvail[TrueSucc]->table[CondVN] =
1553 ConstantInt::getTrue(TrueSucc->getContext());
1554 if (FalseSucc->getSinglePredecessor())
1555 localAvail[FalseSucc]->table[CondVN] =
1556 ConstantInt::getFalse(TrueSucc->getContext());
Owen Andersonef8bf0f2009-04-01 23:53:49 +00001557
1558 return false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001559
Owen Andersonced50f82008-04-07 09:59:07 +00001560 // Allocations are always uniquely numbered, so we can save time and memory
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001561 // by fast failing them.
Victor Hernandez48c3c542009-09-18 22:35:49 +00001562 } else if (isa<AllocationInst>(I) || isMalloc(I) || isa<TerminatorInst>(I)) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001563 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Owen Andersonced50f82008-04-07 09:59:07 +00001564 return false;
Owen Andersone6b4ff82008-06-18 21:41:49 +00001565 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001566
Owen Andersone0143452007-08-16 22:02:55 +00001567 // Collapse PHI nodes
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001568 if (PHINode* p = dyn_cast<PHINode>(I)) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001569 Value *constVal = CollapsePhi(p);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001570
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001571 if (constVal) {
Owen Andersone02ad522007-08-16 22:51:56 +00001572 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1573 PI != PE; ++PI)
Chris Lattner4bab29b2008-12-09 19:21:47 +00001574 PI->second.erase(p);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001575
Owen Andersone02ad522007-08-16 22:51:56 +00001576 p->replaceAllUsesWith(constVal);
Chris Lattnerf81b0142008-12-09 22:06:23 +00001577 if (isa<PointerType>(constVal->getType()))
1578 MD->invalidateCachedPointerInfo(constVal);
Owen Anderson575f2812008-12-23 00:49:51 +00001579 VN.erase(p);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001580
Owen Andersone02ad522007-08-16 22:51:56 +00001581 toErase.push_back(p);
Owen Andersone6b4ff82008-06-18 21:41:49 +00001582 } else {
Chris Lattnerff36c952009-09-21 02:42:51 +00001583 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Owen Anderson98f6a6b2007-08-14 18:33:27 +00001584 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001585
Owen Anderson8a8d13c2008-07-03 17:44:33 +00001586 // If the number we were assigned was a brand new VN, then we don't
1587 // need to do a lookup to see if the number already exists
1588 // somewhere in the domtree: it can't!
Chris Lattnerff36c952009-09-21 02:42:51 +00001589 } else if (Num == NextNum) {
1590 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001591
Owen Andersona03e7862008-12-15 02:03:00 +00001592 // Perform fast-path value-number based elimination of values inherited from
1593 // dominators.
Chris Lattnerff36c952009-09-21 02:42:51 +00001594 } else if (Value *repl = lookupNumber(I->getParent(), Num)) {
Owen Andersonc772be72007-12-08 01:37:09 +00001595 // Remove it!
Owen Anderson5aff8002007-07-31 23:27:13 +00001596 VN.erase(I);
Owen Anderson85c40642007-07-24 17:55:58 +00001597 I->replaceAllUsesWith(repl);
Chris Lattnerf81b0142008-12-09 22:06:23 +00001598 if (isa<PointerType>(repl->getType()))
1599 MD->invalidateCachedPointerInfo(repl);
Owen Anderson85c40642007-07-24 17:55:58 +00001600 toErase.push_back(I);
1601 return true;
Owen Andersona03e7862008-12-15 02:03:00 +00001602
1603#if 0
1604 // Perform slow-pathvalue-number based elimination with phi construction.
Chris Lattnerff36c952009-09-21 02:42:51 +00001605 } else if (Value *repl = AttemptRedundancyElimination(I, Num)) {
Owen Andersona03e7862008-12-15 02:03:00 +00001606 // Remove it!
1607 VN.erase(I);
1608 I->replaceAllUsesWith(repl);
1609 if (isa<PointerType>(repl->getType()))
1610 MD->invalidateCachedPointerInfo(repl);
1611 toErase.push_back(I);
1612 return true;
1613#endif
Owen Anderson8a8d13c2008-07-03 17:44:33 +00001614 } else {
Chris Lattnerff36c952009-09-21 02:42:51 +00001615 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Owen Anderson85c40642007-07-24 17:55:58 +00001616 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001617
Owen Anderson85c40642007-07-24 17:55:58 +00001618 return false;
1619}
1620
Bill Wendling42f17f62008-12-22 22:32:22 +00001621/// runOnFunction - This is the main transformation entry point for a function.
Owen Andersonbe168b32007-08-14 18:04:11 +00001622bool GVN::runOnFunction(Function& F) {
Chris Lattner02ca4422008-12-01 00:40:32 +00001623 MD = &getAnalysis<MemoryDependenceAnalysis>();
1624 DT = &getAnalysis<DominatorTree>();
Owen Andersonbcf2bd52008-05-12 20:15:55 +00001625 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
Chris Lattner02ca4422008-12-01 00:40:32 +00001626 VN.setMemDep(MD);
1627 VN.setDomTree(DT);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001628
Chris Lattnerff36c952009-09-21 02:42:51 +00001629 bool Changed = false;
1630 bool ShouldContinue = true;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001631
Owen Anderson26ed2572008-07-16 17:52:31 +00001632 // Merge unconditional branches, allowing PRE to catch more
1633 // optimization opportunities.
1634 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001635 BasicBlock *BB = FI;
Owen Anderson26ed2572008-07-16 17:52:31 +00001636 ++FI;
Owen Andersonf59eef82008-07-17 00:01:40 +00001637 bool removedBlock = MergeBlockIntoPredecessor(BB, this);
1638 if (removedBlock) NumGVNBlocks++;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001639
Chris Lattnerff36c952009-09-21 02:42:51 +00001640 Changed |= removedBlock;
Owen Anderson26ed2572008-07-16 17:52:31 +00001641 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001642
Chris Lattner4bab29b2008-12-09 19:21:47 +00001643 unsigned Iteration = 0;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001644
Chris Lattnerff36c952009-09-21 02:42:51 +00001645 while (ShouldContinue) {
Dan Gohman0be10b02009-07-25 01:43:01 +00001646 DEBUG(errs() << "GVN iteration: " << Iteration << "\n");
Chris Lattnerff36c952009-09-21 02:42:51 +00001647 ShouldContinue = iterateOnFunction(F);
1648 Changed |= ShouldContinue;
Chris Lattner4bab29b2008-12-09 19:21:47 +00001649 ++Iteration;
Owen Andersonbe168b32007-08-14 18:04:11 +00001650 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001651
Owen Anderson916f4732008-07-18 18:03:38 +00001652 if (EnablePRE) {
Owen Anderson9c935902008-09-03 23:06:07 +00001653 bool PREChanged = true;
1654 while (PREChanged) {
1655 PREChanged = performPRE(F);
Chris Lattnerff36c952009-09-21 02:42:51 +00001656 Changed |= PREChanged;
Owen Anderson9c935902008-09-03 23:06:07 +00001657 }
Owen Anderson916f4732008-07-18 18:03:38 +00001658 }
Chris Lattner4bab29b2008-12-09 19:21:47 +00001659 // FIXME: Should perform GVN again after PRE does something. PRE can move
1660 // computations into blocks where they become fully redundant. Note that
1661 // we can't do this until PRE's critical edge splitting updates memdep.
1662 // Actually, when this happens, we should just fully integrate PRE into GVN.
Nuno Lopes274474b2008-10-10 16:25:50 +00001663
1664 cleanupGlobalSets();
1665
Chris Lattnerff36c952009-09-21 02:42:51 +00001666 return Changed;
Owen Andersonbe168b32007-08-14 18:04:11 +00001667}
1668
1669
Chris Lattnerff36c952009-09-21 02:42:51 +00001670bool GVN::processBlock(BasicBlock *BB) {
Chris Lattner4bab29b2008-12-09 19:21:47 +00001671 // FIXME: Kill off toErase by doing erasing eagerly in a helper function (and
1672 // incrementing BI before processing an instruction).
Owen Anderson9334fc62008-06-12 19:25:32 +00001673 SmallVector<Instruction*, 8> toErase;
Chris Lattnerff36c952009-09-21 02:42:51 +00001674 bool ChangedFunction = false;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001675
Owen Anderson9334fc62008-06-12 19:25:32 +00001676 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1677 BI != BE;) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001678 ChangedFunction |= processInstruction(BI, toErase);
Owen Anderson9334fc62008-06-12 19:25:32 +00001679 if (toErase.empty()) {
1680 ++BI;
1681 continue;
1682 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001683
Owen Anderson9334fc62008-06-12 19:25:32 +00001684 // If we need some instructions deleted, do it now.
1685 NumGVNInstr += toErase.size();
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001686
Owen Anderson9334fc62008-06-12 19:25:32 +00001687 // Avoid iterator invalidation.
1688 bool AtStart = BI == BB->begin();
1689 if (!AtStart)
1690 --BI;
1691
1692 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
Chris Lattner02ca4422008-12-01 00:40:32 +00001693 E = toErase.end(); I != E; ++I) {
Dan Gohman7e124382009-07-31 20:24:18 +00001694 DEBUG(errs() << "GVN removed: " << **I << '\n');
Chris Lattner02ca4422008-12-01 00:40:32 +00001695 MD->removeInstruction(*I);
Owen Anderson9334fc62008-06-12 19:25:32 +00001696 (*I)->eraseFromParent();
Bill Wendling84049422008-12-22 21:57:30 +00001697 DEBUG(verifyRemoved(*I));
Chris Lattner02ca4422008-12-01 00:40:32 +00001698 }
Chris Lattner4bab29b2008-12-09 19:21:47 +00001699 toErase.clear();
Owen Anderson9334fc62008-06-12 19:25:32 +00001700
1701 if (AtStart)
1702 BI = BB->begin();
1703 else
1704 ++BI;
Owen Anderson9334fc62008-06-12 19:25:32 +00001705 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001706
Chris Lattnerff36c952009-09-21 02:42:51 +00001707 return ChangedFunction;
Owen Anderson9334fc62008-06-12 19:25:32 +00001708}
1709
Owen Andersone6b4ff82008-06-18 21:41:49 +00001710/// performPRE - Perform a purely local form of PRE that looks for diamond
1711/// control flow patterns and attempts to perform simple PRE at the join point.
1712bool GVN::performPRE(Function& F) {
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001713 bool Changed = false;
Owen Andersonec747c42008-06-19 19:54:19 +00001714 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
Chris Lattner3304b562008-12-01 07:29:03 +00001715 DenseMap<BasicBlock*, Value*> predMap;
Owen Andersone6b4ff82008-06-18 21:41:49 +00001716 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
1717 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001718 BasicBlock *CurrentBlock = *DI;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001719
Owen Andersone6b4ff82008-06-18 21:41:49 +00001720 // Nothing to PRE in the entry block.
1721 if (CurrentBlock == &F.getEntryBlock()) continue;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001722
Owen Andersone6b4ff82008-06-18 21:41:49 +00001723 for (BasicBlock::iterator BI = CurrentBlock->begin(),
1724 BE = CurrentBlock->end(); BI != BE; ) {
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001725 Instruction *CurInst = BI++;
Duncan Sands2f500832009-05-06 06:49:50 +00001726
Victor Hernandez48c3c542009-09-18 22:35:49 +00001727 if (isa<AllocationInst>(CurInst) || isMalloc(CurInst) ||
1728 isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
Owen Anderson35b47072009-08-13 21:58:54 +00001729 (CurInst->getType() == Type::getVoidTy(F.getContext())) ||
Duncan Sands2f500832009-05-06 06:49:50 +00001730 CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
John Criswell6e0aa282009-03-10 15:04:53 +00001731 isa<DbgInfoIntrinsic>(CurInst))
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001732 continue;
Duncan Sands2f500832009-05-06 06:49:50 +00001733
Chris Lattnerff36c952009-09-21 02:42:51 +00001734 uint32_t ValNo = VN.lookup(CurInst);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001735
Owen Andersone6b4ff82008-06-18 21:41:49 +00001736 // Look for the predecessors for PRE opportunities. We're
1737 // only trying to solve the basic diamond case, where
1738 // a value is computed in the successor and one predecessor,
1739 // but not the other. We also explicitly disallow cases
1740 // where the successor is its own predecessor, because they're
1741 // more complicated to get right.
Chris Lattnerff36c952009-09-21 02:42:51 +00001742 unsigned NumWith = 0;
1743 unsigned NumWithout = 0;
1744 BasicBlock *PREPred = 0;
Chris Lattner3304b562008-12-01 07:29:03 +00001745 predMap.clear();
1746
Owen Andersone6b4ff82008-06-18 21:41:49 +00001747 for (pred_iterator PI = pred_begin(CurrentBlock),
1748 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
1749 // We're not interested in PRE where the block is its
Owen Anderson2a412722008-06-20 01:15:47 +00001750 // own predecessor, on in blocks with predecessors
1751 // that are not reachable.
1752 if (*PI == CurrentBlock) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001753 NumWithout = 2;
Owen Anderson2a412722008-06-20 01:15:47 +00001754 break;
1755 } else if (!localAvail.count(*PI)) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001756 NumWithout = 2;
Owen Anderson2a412722008-06-20 01:15:47 +00001757 break;
1758 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001759
1760 DenseMap<uint32_t, Value*>::iterator predV =
Chris Lattnerff36c952009-09-21 02:42:51 +00001761 localAvail[*PI]->table.find(ValNo);
Owen Anderson2a412722008-06-20 01:15:47 +00001762 if (predV == localAvail[*PI]->table.end()) {
Owen Andersone6b4ff82008-06-18 21:41:49 +00001763 PREPred = *PI;
Chris Lattnerff36c952009-09-21 02:42:51 +00001764 NumWithout++;
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001765 } else if (predV->second == CurInst) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001766 NumWithout = 2;
Owen Andersone6b4ff82008-06-18 21:41:49 +00001767 } else {
Owen Anderson2a412722008-06-20 01:15:47 +00001768 predMap[*PI] = predV->second;
Chris Lattnerff36c952009-09-21 02:42:51 +00001769 NumWith++;
Owen Andersone6b4ff82008-06-18 21:41:49 +00001770 }
1771 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001772
Owen Andersone6b4ff82008-06-18 21:41:49 +00001773 // Don't do PRE when it might increase code size, i.e. when
1774 // we would need to insert instructions in more than one pred.
Chris Lattnerff36c952009-09-21 02:42:51 +00001775 if (NumWithout != 1 || NumWith == 0)
Owen Andersone6b4ff82008-06-18 21:41:49 +00001776 continue;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001777
Owen Andersonec747c42008-06-19 19:54:19 +00001778 // We can't do PRE safely on a critical edge, so instead we schedule
1779 // the edge to be split and perform the PRE the next time we iterate
1780 // on the function.
Chris Lattnerff36c952009-09-21 02:42:51 +00001781 unsigned SuccNum = 0;
Owen Andersonec747c42008-06-19 19:54:19 +00001782 for (unsigned i = 0, e = PREPred->getTerminator()->getNumSuccessors();
1783 i != e; ++i)
Owen Anderson9c935902008-09-03 23:06:07 +00001784 if (PREPred->getTerminator()->getSuccessor(i) == CurrentBlock) {
Chris Lattnerff36c952009-09-21 02:42:51 +00001785 SuccNum = i;
Owen Andersonec747c42008-06-19 19:54:19 +00001786 break;
1787 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001788
Chris Lattnerff36c952009-09-21 02:42:51 +00001789 if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
1790 toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
Owen Andersonec747c42008-06-19 19:54:19 +00001791 continue;
1792 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001793
Owen Andersone6b4ff82008-06-18 21:41:49 +00001794 // Instantiate the expression the in predecessor that lacked it.
1795 // Because we are going top-down through the block, all value numbers
1796 // will be available in the predecessor by the time we need them. Any
1797 // that weren't original present will have been instantiated earlier
1798 // in this loop.
Chris Lattnerff36c952009-09-21 02:42:51 +00001799 Instruction *PREInstr = CurInst->clone(CurInst->getContext());
Owen Andersone6b4ff82008-06-18 21:41:49 +00001800 bool success = true;
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001801 for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
1802 Value *Op = PREInstr->getOperand(i);
1803 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
1804 continue;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001805
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001806 if (Value *V = lookupNumber(PREPred, VN.lookup(Op))) {
1807 PREInstr->setOperand(i, V);
1808 } else {
1809 success = false;
1810 break;
Owen Anderson14c612f2008-07-11 20:05:13 +00001811 }
Owen Andersone6b4ff82008-06-18 21:41:49 +00001812 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001813
Owen Andersone6b4ff82008-06-18 21:41:49 +00001814 // Fail out if we encounter an operand that is not available in
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001815 // the PRE predecessor. This is typically because of loads which
Owen Andersone6b4ff82008-06-18 21:41:49 +00001816 // are not value numbered precisely.
1817 if (!success) {
1818 delete PREInstr;
Bill Wendling3858cae2008-12-22 22:14:07 +00001819 DEBUG(verifyRemoved(PREInstr));
Owen Andersone6b4ff82008-06-18 21:41:49 +00001820 continue;
1821 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001822
Owen Andersone6b4ff82008-06-18 21:41:49 +00001823 PREInstr->insertBefore(PREPred->getTerminator());
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001824 PREInstr->setName(CurInst->getName() + ".pre");
Owen Anderson2a412722008-06-20 01:15:47 +00001825 predMap[PREPred] = PREInstr;
Chris Lattnerff36c952009-09-21 02:42:51 +00001826 VN.add(PREInstr, ValNo);
Owen Andersone6b4ff82008-06-18 21:41:49 +00001827 NumGVNPRE++;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001828
Owen Andersone6b4ff82008-06-18 21:41:49 +00001829 // Update the availability map to include the new instruction.
Chris Lattnerff36c952009-09-21 02:42:51 +00001830 localAvail[PREPred]->table.insert(std::make_pair(ValNo, PREInstr));
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001831
Owen Andersone6b4ff82008-06-18 21:41:49 +00001832 // Create a PHI to make the value available in this block.
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001833 PHINode* Phi = PHINode::Create(CurInst->getType(),
1834 CurInst->getName() + ".pre-phi",
Owen Andersone6b4ff82008-06-18 21:41:49 +00001835 CurrentBlock->begin());
1836 for (pred_iterator PI = pred_begin(CurrentBlock),
1837 PE = pred_end(CurrentBlock); PI != PE; ++PI)
Owen Anderson2a412722008-06-20 01:15:47 +00001838 Phi->addIncoming(predMap[*PI], *PI);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001839
Chris Lattnerff36c952009-09-21 02:42:51 +00001840 VN.add(Phi, ValNo);
1841 localAvail[CurrentBlock]->table[ValNo] = Phi;
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001842
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001843 CurInst->replaceAllUsesWith(Phi);
Chris Lattnerf81b0142008-12-09 22:06:23 +00001844 if (isa<PointerType>(Phi->getType()))
1845 MD->invalidateCachedPointerInfo(Phi);
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001846 VN.erase(CurInst);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001847
Dan Gohman7e124382009-07-31 20:24:18 +00001848 DEBUG(errs() << "GVN PRE removed: " << *CurInst << '\n');
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001849 MD->removeInstruction(CurInst);
1850 CurInst->eraseFromParent();
Bill Wendling84049422008-12-22 21:57:30 +00001851 DEBUG(verifyRemoved(CurInst));
Chris Lattner66a3a3e2008-12-01 07:35:54 +00001852 Changed = true;
Owen Andersone6b4ff82008-06-18 21:41:49 +00001853 }
1854 }
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001855
Owen Andersonec747c42008-06-19 19:54:19 +00001856 for (SmallVector<std::pair<TerminatorInst*, unsigned>, 4>::iterator
Anton Korobeynikov2e8710c2008-12-05 19:38:49 +00001857 I = toSplit.begin(), E = toSplit.end(); I != E; ++I)
Owen Andersonec747c42008-06-19 19:54:19 +00001858 SplitCriticalEdge(I->first, I->second, this);
Daniel Dunbar3be44e62009-09-20 02:20:51 +00001859
Anton Korobeynikov2e8710c2008-12-05 19:38:49 +00001860 return Changed || toSplit.size();
Owen Andersone6b4ff82008-06-18 21:41:49 +00001861}
1862
Bill Wendling42f17f62008-12-22 22:32:22 +00001863/// iterateOnFunction - Executes one iteration of GVN
Owen Andersonbe168b32007-08-14 18:04:11 +00001864bool GVN::iterateOnFunction(Function &F) {
Nuno Lopes274474b2008-10-10 16:25:50 +00001865 cleanupGlobalSets();
Chris Lattner98054902008-03-21 21:33:23 +00001866
Owen Andersonef8bf0f2009-04-01 23:53:49 +00001867 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
1868 DE = df_end(DT->getRootNode()); DI != DE; ++DI) {
1869 if (DI->getIDom())
1870 localAvail[DI->getBlock()] =
1871 new ValueNumberScope(localAvail[DI->getIDom()->getBlock()]);
1872 else
1873 localAvail[DI->getBlock()] = new ValueNumberScope(0);
1874 }
1875
Owen Anderson85c40642007-07-24 17:55:58 +00001876 // Top-down walk of the dominator tree
Chris Lattnerff36c952009-09-21 02:42:51 +00001877 bool Changed = false;
Owen Andersonef136f52008-12-15 03:52:17 +00001878#if 0
1879 // Needed for value numbering with phi construction to work.
Owen Andersona03e7862008-12-15 02:03:00 +00001880 ReversePostOrderTraversal<Function*> RPOT(&F);
1881 for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
1882 RE = RPOT.end(); RI != RE; ++RI)
Chris Lattnerff36c952009-09-21 02:42:51 +00001883 Changed |= processBlock(*RI);
Owen Andersonef136f52008-12-15 03:52:17 +00001884#else
1885 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
1886 DE = df_end(DT->getRootNode()); DI != DE; ++DI)
Chris Lattnerff36c952009-09-21 02:42:51 +00001887 Changed |= processBlock(DI->getBlock());
Owen Andersonef136f52008-12-15 03:52:17 +00001888#endif
1889
Chris Lattnerff36c952009-09-21 02:42:51 +00001890 return Changed;
Owen Anderson85c40642007-07-24 17:55:58 +00001891}
Nuno Lopes274474b2008-10-10 16:25:50 +00001892
1893void GVN::cleanupGlobalSets() {
1894 VN.clear();
1895 phiMap.clear();
1896
1897 for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
1898 I = localAvail.begin(), E = localAvail.end(); I != E; ++I)
1899 delete I->second;
1900 localAvail.clear();
1901}
Bill Wendling2a023742008-12-22 21:36:08 +00001902
1903/// verifyRemoved - Verify that the specified instruction does not occur in our
1904/// internal data structures.
Bill Wendlingf9c0e9e2008-12-22 22:28:56 +00001905void GVN::verifyRemoved(const Instruction *Inst) const {
1906 VN.verifyRemoved(Inst);
Bill Wendling3858cae2008-12-22 22:14:07 +00001907
1908 // Walk through the PHI map to make sure the instruction isn't hiding in there
1909 // somewhere.
1910 for (PhiMapType::iterator
Bill Wendlingf9c0e9e2008-12-22 22:28:56 +00001911 I = phiMap.begin(), E = phiMap.end(); I != E; ++I) {
1912 assert(I->first != Inst && "Inst is still a key in PHI map!");
Bill Wendling3858cae2008-12-22 22:14:07 +00001913
1914 for (SmallPtrSet<Instruction*, 4>::iterator
Bill Wendlingf9c0e9e2008-12-22 22:28:56 +00001915 II = I->second.begin(), IE = I->second.end(); II != IE; ++II) {
1916 assert(*II != Inst && "Inst is still a value in PHI map!");
1917 }
1918 }
1919
1920 // Walk through the value number scope to make sure the instruction isn't
1921 // ferreted away in it.
1922 for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
1923 I = localAvail.begin(), E = localAvail.end(); I != E; ++I) {
1924 const ValueNumberScope *VNS = I->second;
1925
1926 while (VNS) {
1927 for (DenseMap<uint32_t, Value*>::iterator
1928 II = VNS->table.begin(), IE = VNS->table.end(); II != IE; ++II) {
1929 assert(II->second != Inst && "Inst still in value numbering scope!");
1930 }
1931
1932 VNS = VNS->parent;
Bill Wendling3858cae2008-12-22 22:14:07 +00001933 }
1934 }
Bill Wendling2a023742008-12-22 21:36:08 +00001935}