blob: a4f92c23cb2602089db1e877dc156f09dd2e6fd3 [file] [log] [blame]
Chris Lattnerd2a653a2008-12-05 07:49:08 +00001//===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
Owen Andersonab6ec2e2007-07-24 17:55:58 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Owen Andersonab6ec2e2007-07-24 17:55:58 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs global value numbering to eliminate fully redundant
11// instructions. It also performs simple dead load elimination.
12//
John Criswell073e4d12009-03-10 15:04:53 +000013// Note that this pass does the value numbering itself; it does not use the
Matthijs Kooijman5afc2742008-06-05 07:55:49 +000014// ValueNumbering analysis passes.
15//
Owen Andersonab6ec2e2007-07-24 17:55:58 +000016//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "gvn"
Owen Andersonab6ec2e2007-07-24 17:55:58 +000019#include "llvm/Transforms/Scalar.h"
Owen Anderson5e5599b2007-07-25 19:57:03 +000020#include "llvm/BasicBlock.h"
Owen Andersondbf23cc2007-07-26 18:26:51 +000021#include "llvm/Constants.h"
Owen Andersonab6ec2e2007-07-24 17:55:58 +000022#include "llvm/DerivedTypes.h"
Owen Andersondbf23cc2007-07-26 18:26:51 +000023#include "llvm/Function.h"
Devang Patele8c6d312009-03-06 02:59:27 +000024#include "llvm/IntrinsicInst.h"
Owen Andersonb5618da2009-07-03 00:17:18 +000025#include "llvm/LLVMContext.h"
Chris Lattner0a9616d2009-09-21 05:57:11 +000026#include "llvm/Operator.h"
Owen Andersondbf23cc2007-07-26 18:26:51 +000027#include "llvm/Value.h"
Owen Andersonab6ec2e2007-07-24 17:55:58 +000028#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/DepthFirstIterator.h"
Owen Andersonbfe133e2008-12-15 02:03:00 +000030#include "llvm/ADT/PostOrderIterator.h"
Owen Andersonab6ec2e2007-07-24 17:55:58 +000031#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/Statistic.h"
Owen Anderson09b83ba2007-10-18 19:39:33 +000034#include "llvm/Analysis/Dominators.h"
35#include "llvm/Analysis/AliasAnalysis.h"
Victor Hernandez5d034492009-09-18 22:35:49 +000036#include "llvm/Analysis/MallocHelper.h"
Owen Andersonab6ec2e2007-07-24 17:55:58 +000037#include "llvm/Analysis/MemoryDependenceAnalysis.h"
38#include "llvm/Support/CFG.h"
Owen Andersone780d662008-06-19 19:57:25 +000039#include "llvm/Support/CommandLine.h"
Chris Lattnerd528b212008-03-29 04:36:18 +000040#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000041#include "llvm/Support/ErrorHandling.h"
Chris Lattner0a9616d2009-09-21 05:57:11 +000042#include "llvm/Support/GetElementPtrTypeIterator.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000043#include "llvm/Support/raw_ostream.h"
Chris Lattner1dd48c32009-09-20 19:03:47 +000044#include "llvm/Target/TargetData.h"
Owen Andersonfdf9f162008-06-19 19:54:19 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dale Johannesen81b64632009-06-17 20:48:23 +000046#include "llvm/Transforms/Utils/Local.h"
Duncan Sands26ff6f92008-10-08 07:23:46 +000047#include <cstdio>
Owen Andersonab6ec2e2007-07-24 17:55:58 +000048using namespace llvm;
49
Bill Wendling3c793442008-12-22 22:14:07 +000050STATISTIC(NumGVNInstr, "Number of instructions deleted");
51STATISTIC(NumGVNLoad, "Number of loads deleted");
52STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
Owen Anderson53d546e2008-07-15 16:28:06 +000053STATISTIC(NumGVNBlocks, "Number of blocks merged");
Bill Wendling3c793442008-12-22 22:14:07 +000054STATISTIC(NumPRELoad, "Number of loads PRE'd");
Chris Lattner168be762008-03-22 04:13:49 +000055
Evan Cheng9598f932008-06-20 01:01:07 +000056static cl::opt<bool> EnablePRE("enable-pre",
Owen Andersonaddbe3e2008-07-17 19:41:00 +000057 cl::init(true), cl::Hidden);
Dan Gohmana8f8a852009-06-15 18:30:15 +000058static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
Owen Andersone780d662008-06-19 19:57:25 +000059
Owen Andersonab6ec2e2007-07-24 17:55:58 +000060//===----------------------------------------------------------------------===//
61// ValueTable Class
62//===----------------------------------------------------------------------===//
63
64/// This class holds the mapping between values and value numbers. It is used
65/// as an efficient mechanism to determine the expression-wise equivalence of
66/// two values.
67namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +000068 struct Expression {
Dan Gohmana5b96452009-06-04 22:49:04 +000069 enum ExpressionOpcode { ADD, FADD, SUB, FSUB, MUL, FMUL,
70 UDIV, SDIV, FDIV, UREM, SREM,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000071 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
72 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
73 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
74 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
75 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
Owen Andersonab6ec2e2007-07-24 17:55:58 +000076 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
77 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000078 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
Owen Anderson69057b82008-05-13 08:17:22 +000079 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
Owen Anderson45d37012008-06-19 17:25:39 +000080 EMPTY, TOMBSTONE };
Owen Andersonab6ec2e2007-07-24 17:55:58 +000081
82 ExpressionOpcode opcode;
83 const Type* type;
84 uint32_t firstVN;
85 uint32_t secondVN;
86 uint32_t thirdVN;
87 SmallVector<uint32_t, 4> varargs;
Chris Lattner1eefa9c2009-09-21 02:42:51 +000088 Value *function;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000089
Owen Andersonab6ec2e2007-07-24 17:55:58 +000090 Expression() { }
91 Expression(ExpressionOpcode o) : opcode(o) { }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000092
Owen Andersonab6ec2e2007-07-24 17:55:58 +000093 bool operator==(const Expression &other) const {
94 if (opcode != other.opcode)
95 return false;
96 else if (opcode == EMPTY || opcode == TOMBSTONE)
97 return true;
98 else if (type != other.type)
99 return false;
Owen Anderson09b83ba2007-10-18 19:39:33 +0000100 else if (function != other.function)
101 return false;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000102 else if (firstVN != other.firstVN)
103 return false;
104 else if (secondVN != other.secondVN)
105 return false;
106 else if (thirdVN != other.thirdVN)
107 return false;
108 else {
109 if (varargs.size() != other.varargs.size())
110 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000111
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000112 for (size_t i = 0; i < varargs.size(); ++i)
113 if (varargs[i] != other.varargs[i])
114 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000115
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000116 return true;
117 }
118 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000119
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000120 bool operator!=(const Expression &other) const {
Bill Wendling86f01cb2008-12-22 22:16:31 +0000121 return !(*this == other);
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000122 }
123 };
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000124
Chris Lattner2dd09db2009-09-02 06:11:42 +0000125 class ValueTable {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000126 private:
127 DenseMap<Value*, uint32_t> valueNumbering;
128 DenseMap<Expression, uint32_t> expressionNumbering;
Owen Andersonf7928602008-05-12 20:15:55 +0000129 AliasAnalysis* AA;
130 MemoryDependenceAnalysis* MD;
131 DominatorTree* DT;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000132
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000133 uint32_t nextValueNumber;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000134
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000135 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
136 Expression::ExpressionOpcode getOpcode(CmpInst* C);
137 Expression::ExpressionOpcode getOpcode(CastInst* C);
138 Expression create_expression(BinaryOperator* BO);
139 Expression create_expression(CmpInst* C);
140 Expression create_expression(ShuffleVectorInst* V);
141 Expression create_expression(ExtractElementInst* C);
142 Expression create_expression(InsertElementInst* V);
143 Expression create_expression(SelectInst* V);
144 Expression create_expression(CastInst* C);
145 Expression create_expression(GetElementPtrInst* G);
Owen Anderson09b83ba2007-10-18 19:39:33 +0000146 Expression create_expression(CallInst* C);
Owen Anderson69057b82008-05-13 08:17:22 +0000147 Expression create_expression(Constant* C);
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000148 public:
Dan Gohmanc4971722009-04-01 16:37:47 +0000149 ValueTable() : nextValueNumber(1) { }
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000150 uint32_t lookup_or_add(Value *V);
151 uint32_t lookup(Value *V) const;
152 void add(Value *V, uint32_t num);
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000153 void clear();
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000154 void erase(Value *v);
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000155 unsigned size();
Owen Andersonf7928602008-05-12 20:15:55 +0000156 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
Chris Lattner8541ede2008-12-01 00:40:32 +0000157 AliasAnalysis *getAliasAnalysis() const { return AA; }
Owen Andersonf7928602008-05-12 20:15:55 +0000158 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
159 void setDomTree(DominatorTree* D) { DT = D; }
Owen Anderson3ea90a72008-07-03 17:44:33 +0000160 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
Bill Wendling6b18a392008-12-22 21:36:08 +0000161 void verifyRemoved(const Value *) const;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000162 };
163}
164
165namespace llvm {
Chris Lattner0625bd62007-09-17 18:34:04 +0000166template <> struct DenseMapInfo<Expression> {
Owen Anderson9699a6e2007-08-02 18:16:06 +0000167 static inline Expression getEmptyKey() {
168 return Expression(Expression::EMPTY);
169 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000170
Owen Anderson9699a6e2007-08-02 18:16:06 +0000171 static inline Expression getTombstoneKey() {
172 return Expression(Expression::TOMBSTONE);
173 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000174
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000175 static unsigned getHashValue(const Expression e) {
176 unsigned hash = e.opcode;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000177
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000178 hash = e.firstVN + hash * 37;
179 hash = e.secondVN + hash * 37;
180 hash = e.thirdVN + hash * 37;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000181
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000182 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
183 (unsigned)((uintptr_t)e.type >> 9)) +
184 hash * 37;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000185
Owen Anderson9699a6e2007-08-02 18:16:06 +0000186 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
187 E = e.varargs.end(); I != E; ++I)
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000188 hash = *I + hash * 37;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000189
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000190 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
191 (unsigned)((uintptr_t)e.function >> 9)) +
192 hash * 37;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000193
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000194 return hash;
195 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000196 static bool isEqual(const Expression &LHS, const Expression &RHS) {
197 return LHS == RHS;
198 }
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000199 static bool isPod() { return true; }
200};
201}
202
203//===----------------------------------------------------------------------===//
204// ValueTable Internal Functions
205//===----------------------------------------------------------------------===//
Chris Lattner2876a642008-03-21 21:14:38 +0000206Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000207 switch(BO->getOpcode()) {
Chris Lattner2876a642008-03-21 21:14:38 +0000208 default: // THIS SHOULD NEVER HAPPEN
Torok Edwinfbcc6632009-07-14 16:55:14 +0000209 llvm_unreachable("Binary operator with unknown opcode?");
Chris Lattner2876a642008-03-21 21:14:38 +0000210 case Instruction::Add: return Expression::ADD;
Dan Gohmana5b96452009-06-04 22:49:04 +0000211 case Instruction::FAdd: return Expression::FADD;
Chris Lattner2876a642008-03-21 21:14:38 +0000212 case Instruction::Sub: return Expression::SUB;
Dan Gohmana5b96452009-06-04 22:49:04 +0000213 case Instruction::FSub: return Expression::FSUB;
Chris Lattner2876a642008-03-21 21:14:38 +0000214 case Instruction::Mul: return Expression::MUL;
Dan Gohmana5b96452009-06-04 22:49:04 +0000215 case Instruction::FMul: return Expression::FMUL;
Chris Lattner2876a642008-03-21 21:14:38 +0000216 case Instruction::UDiv: return Expression::UDIV;
217 case Instruction::SDiv: return Expression::SDIV;
218 case Instruction::FDiv: return Expression::FDIV;
219 case Instruction::URem: return Expression::UREM;
220 case Instruction::SRem: return Expression::SREM;
221 case Instruction::FRem: return Expression::FREM;
222 case Instruction::Shl: return Expression::SHL;
223 case Instruction::LShr: return Expression::LSHR;
224 case Instruction::AShr: return Expression::ASHR;
225 case Instruction::And: return Expression::AND;
226 case Instruction::Or: return Expression::OR;
227 case Instruction::Xor: return Expression::XOR;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000228 }
229}
230
231Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +0000232 if (isa<ICmpInst>(C)) {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000233 switch (C->getPredicate()) {
Chris Lattner2876a642008-03-21 21:14:38 +0000234 default: // THIS SHOULD NEVER HAPPEN
Torok Edwinfbcc6632009-07-14 16:55:14 +0000235 llvm_unreachable("Comparison with unknown predicate?");
Chris Lattner2876a642008-03-21 21:14:38 +0000236 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ;
237 case ICmpInst::ICMP_NE: return Expression::ICMPNE;
238 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
239 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
240 case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
241 case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
242 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
243 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
244 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
245 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000246 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +0000247 } else {
248 switch (C->getPredicate()) {
249 default: // THIS SHOULD NEVER HAPPEN
Torok Edwinfbcc6632009-07-14 16:55:14 +0000250 llvm_unreachable("Comparison with unknown predicate?");
Nick Lewyckya21d3da2009-07-08 03:04:38 +0000251 case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
252 case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
253 case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
254 case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
255 case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
256 case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
257 case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
258 case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
259 case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
260 case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
261 case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
262 case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
263 case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
264 case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
265 }
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000266 }
267}
268
Chris Lattner2876a642008-03-21 21:14:38 +0000269Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000270 switch(C->getOpcode()) {
Chris Lattner2876a642008-03-21 21:14:38 +0000271 default: // THIS SHOULD NEVER HAPPEN
Torok Edwinfbcc6632009-07-14 16:55:14 +0000272 llvm_unreachable("Cast operator with unknown opcode?");
Chris Lattner2876a642008-03-21 21:14:38 +0000273 case Instruction::Trunc: return Expression::TRUNC;
274 case Instruction::ZExt: return Expression::ZEXT;
275 case Instruction::SExt: return Expression::SEXT;
276 case Instruction::FPToUI: return Expression::FPTOUI;
277 case Instruction::FPToSI: return Expression::FPTOSI;
278 case Instruction::UIToFP: return Expression::UITOFP;
279 case Instruction::SIToFP: return Expression::SITOFP;
280 case Instruction::FPTrunc: return Expression::FPTRUNC;
281 case Instruction::FPExt: return Expression::FPEXT;
282 case Instruction::PtrToInt: return Expression::PTRTOINT;
283 case Instruction::IntToPtr: return Expression::INTTOPTR;
284 case Instruction::BitCast: return Expression::BITCAST;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000285 }
286}
287
Owen Anderson09b83ba2007-10-18 19:39:33 +0000288Expression ValueTable::create_expression(CallInst* C) {
289 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000290
Owen Anderson09b83ba2007-10-18 19:39:33 +0000291 e.type = C->getType();
292 e.firstVN = 0;
293 e.secondVN = 0;
294 e.thirdVN = 0;
295 e.function = C->getCalledFunction();
296 e.opcode = Expression::CALL;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000297
Owen Anderson09b83ba2007-10-18 19:39:33 +0000298 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
299 I != E; ++I)
Owen Anderson1e73f292008-04-11 05:11:49 +0000300 e.varargs.push_back(lookup_or_add(*I));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000301
Owen Anderson09b83ba2007-10-18 19:39:33 +0000302 return e;
303}
304
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000305Expression ValueTable::create_expression(BinaryOperator* BO) {
306 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000307
Owen Anderson1e73f292008-04-11 05:11:49 +0000308 e.firstVN = lookup_or_add(BO->getOperand(0));
309 e.secondVN = lookup_or_add(BO->getOperand(1));
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000310 e.thirdVN = 0;
Owen Anderson09b83ba2007-10-18 19:39:33 +0000311 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000312 e.type = BO->getType();
313 e.opcode = getOpcode(BO);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000314
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000315 return e;
316}
317
318Expression ValueTable::create_expression(CmpInst* C) {
319 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000320
Owen Anderson1e73f292008-04-11 05:11:49 +0000321 e.firstVN = lookup_or_add(C->getOperand(0));
322 e.secondVN = lookup_or_add(C->getOperand(1));
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000323 e.thirdVN = 0;
Owen Anderson09b83ba2007-10-18 19:39:33 +0000324 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000325 e.type = C->getType();
326 e.opcode = getOpcode(C);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000327
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000328 return e;
329}
330
331Expression ValueTable::create_expression(CastInst* C) {
332 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000333
Owen Anderson1e73f292008-04-11 05:11:49 +0000334 e.firstVN = lookup_or_add(C->getOperand(0));
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000335 e.secondVN = 0;
336 e.thirdVN = 0;
Owen Anderson09b83ba2007-10-18 19:39:33 +0000337 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000338 e.type = C->getType();
339 e.opcode = getOpcode(C);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000340
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000341 return e;
342}
343
344Expression ValueTable::create_expression(ShuffleVectorInst* S) {
345 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000346
Owen Anderson1e73f292008-04-11 05:11:49 +0000347 e.firstVN = lookup_or_add(S->getOperand(0));
348 e.secondVN = lookup_or_add(S->getOperand(1));
349 e.thirdVN = lookup_or_add(S->getOperand(2));
Owen Anderson09b83ba2007-10-18 19:39:33 +0000350 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000351 e.type = S->getType();
352 e.opcode = Expression::SHUFFLE;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000353
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000354 return e;
355}
356
357Expression ValueTable::create_expression(ExtractElementInst* E) {
358 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000359
Owen Anderson1e73f292008-04-11 05:11:49 +0000360 e.firstVN = lookup_or_add(E->getOperand(0));
361 e.secondVN = lookup_or_add(E->getOperand(1));
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000362 e.thirdVN = 0;
Owen Anderson09b83ba2007-10-18 19:39:33 +0000363 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000364 e.type = E->getType();
365 e.opcode = Expression::EXTRACT;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000366
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000367 return e;
368}
369
370Expression ValueTable::create_expression(InsertElementInst* I) {
371 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000372
Owen Anderson1e73f292008-04-11 05:11:49 +0000373 e.firstVN = lookup_or_add(I->getOperand(0));
374 e.secondVN = lookup_or_add(I->getOperand(1));
375 e.thirdVN = lookup_or_add(I->getOperand(2));
Owen Anderson09b83ba2007-10-18 19:39:33 +0000376 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000377 e.type = I->getType();
378 e.opcode = Expression::INSERT;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000379
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000380 return e;
381}
382
383Expression ValueTable::create_expression(SelectInst* I) {
384 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000385
Owen Anderson1e73f292008-04-11 05:11:49 +0000386 e.firstVN = lookup_or_add(I->getCondition());
387 e.secondVN = lookup_or_add(I->getTrueValue());
388 e.thirdVN = lookup_or_add(I->getFalseValue());
Owen Anderson09b83ba2007-10-18 19:39:33 +0000389 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000390 e.type = I->getType();
391 e.opcode = Expression::SELECT;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000392
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000393 return e;
394}
395
396Expression ValueTable::create_expression(GetElementPtrInst* G) {
397 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000398
Owen Anderson1e73f292008-04-11 05:11:49 +0000399 e.firstVN = lookup_or_add(G->getPointerOperand());
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000400 e.secondVN = 0;
401 e.thirdVN = 0;
Owen Anderson09b83ba2007-10-18 19:39:33 +0000402 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000403 e.type = G->getType();
404 e.opcode = Expression::GEP;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000405
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000406 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
407 I != E; ++I)
Owen Anderson1e73f292008-04-11 05:11:49 +0000408 e.varargs.push_back(lookup_or_add(*I));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000409
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000410 return e;
411}
412
413//===----------------------------------------------------------------------===//
414// ValueTable External Functions
415//===----------------------------------------------------------------------===//
416
Owen Anderson6a903bc2008-06-18 21:41:49 +0000417/// add - Insert a value into the table with a specified value number.
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000418void ValueTable::add(Value *V, uint32_t num) {
Owen Anderson6a903bc2008-06-18 21:41:49 +0000419 valueNumbering.insert(std::make_pair(V, num));
420}
421
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000422/// lookup_or_add - Returns the value number for the specified value, assigning
423/// it a new number if it did not have one before.
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000424uint32_t ValueTable::lookup_or_add(Value *V) {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000425 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
426 if (VI != valueNumbering.end())
427 return VI->second;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000428
Owen Anderson09b83ba2007-10-18 19:39:33 +0000429 if (CallInst* C = dyn_cast<CallInst>(V)) {
Owen Anderson1e73f292008-04-11 05:11:49 +0000430 if (AA->doesNotAccessMemory(C)) {
Owen Anderson09b83ba2007-10-18 19:39:33 +0000431 Expression e = create_expression(C);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000432
Owen Anderson09b83ba2007-10-18 19:39:33 +0000433 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
434 if (EI != expressionNumbering.end()) {
435 valueNumbering.insert(std::make_pair(V, EI->second));
436 return EI->second;
437 } else {
438 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
439 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000440
Owen Anderson09b83ba2007-10-18 19:39:33 +0000441 return nextValueNumber++;
442 }
Owen Andersonf9ae76d2008-04-17 05:36:50 +0000443 } else if (AA->onlyReadsMemory(C)) {
444 Expression e = create_expression(C);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000445
Owen Anderson69057b82008-05-13 08:17:22 +0000446 if (expressionNumbering.find(e) == expressionNumbering.end()) {
Owen Andersonf9ae76d2008-04-17 05:36:50 +0000447 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
448 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Owen Anderson69057b82008-05-13 08:17:22 +0000449 return nextValueNumber++;
450 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000451
Chris Lattner7f9c8a02008-11-29 02:29:27 +0000452 MemDepResult local_dep = MD->getDependency(C);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000453
Chris Lattner0e3d6332008-12-05 21:04:20 +0000454 if (!local_dep.isDef() && !local_dep.isNonLocal()) {
Owen Anderson17816b32008-05-13 23:18:30 +0000455 valueNumbering.insert(std::make_pair(V, nextValueNumber));
456 return nextValueNumber++;
Chris Lattner80c7d812008-11-30 23:39:23 +0000457 }
Chris Lattner0e3d6332008-12-05 21:04:20 +0000458
459 if (local_dep.isDef()) {
460 CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000461
Chris Lattner0e3d6332008-12-05 21:04:20 +0000462 if (local_cdep->getNumOperands() != C->getNumOperands()) {
Owen Anderson17816b32008-05-13 23:18:30 +0000463 valueNumbering.insert(std::make_pair(V, nextValueNumber));
464 return nextValueNumber++;
465 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000466
Chris Lattner80c7d812008-11-30 23:39:23 +0000467 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
468 uint32_t c_vn = lookup_or_add(C->getOperand(i));
469 uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
470 if (c_vn != cd_vn) {
471 valueNumbering.insert(std::make_pair(V, nextValueNumber));
472 return nextValueNumber++;
473 }
474 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000475
Chris Lattner80c7d812008-11-30 23:39:23 +0000476 uint32_t v = lookup_or_add(local_cdep);
477 valueNumbering.insert(std::make_pair(V, v));
478 return v;
Owen Anderson17816b32008-05-13 23:18:30 +0000479 }
Chris Lattner7e61daf2008-12-01 01:15:42 +0000480
Chris Lattner0e3d6332008-12-05 21:04:20 +0000481 // Non-local case.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000482 const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
Chris Lattner254314e2008-12-09 19:38:05 +0000483 MD->getNonLocalCallDependency(CallSite(C));
Chris Lattner0e3d6332008-12-05 21:04:20 +0000484 // FIXME: call/call dependencies for readonly calls should return def, not
485 // clobber! Move the checking logic to MemDep!
Owen Anderson8c2391d2008-05-13 13:41:23 +0000486 CallInst* cdep = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000487
Chris Lattner80c7d812008-11-30 23:39:23 +0000488 // Check to see if we have a single dominating call instruction that is
489 // identical to C.
Chris Lattner7e61daf2008-12-01 01:15:42 +0000490 for (unsigned i = 0, e = deps.size(); i != e; ++i) {
491 const MemoryDependenceAnalysis::NonLocalDepEntry *I = &deps[i];
Chris Lattner80c7d812008-11-30 23:39:23 +0000492 // Ignore non-local dependencies.
493 if (I->second.isNonLocal())
494 continue;
Owen Anderson69057b82008-05-13 08:17:22 +0000495
Chris Lattner80c7d812008-11-30 23:39:23 +0000496 // We don't handle non-depedencies. If we already have a call, reject
497 // instruction dependencies.
Chris Lattner0e3d6332008-12-05 21:04:20 +0000498 if (I->second.isClobber() || cdep != 0) {
Chris Lattner80c7d812008-11-30 23:39:23 +0000499 cdep = 0;
500 break;
Owen Anderson69057b82008-05-13 08:17:22 +0000501 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000502
Chris Lattner80c7d812008-11-30 23:39:23 +0000503 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->second.getInst());
504 // FIXME: All duplicated with non-local case.
505 if (NonLocalDepCall && DT->properlyDominates(I->first, C->getParent())){
506 cdep = NonLocalDepCall;
507 continue;
508 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000509
Chris Lattner80c7d812008-11-30 23:39:23 +0000510 cdep = 0;
511 break;
Owen Anderson69057b82008-05-13 08:17:22 +0000512 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000513
Owen Anderson8c2391d2008-05-13 13:41:23 +0000514 if (!cdep) {
Owen Anderson69057b82008-05-13 08:17:22 +0000515 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Owen Andersonf9ae76d2008-04-17 05:36:50 +0000516 return nextValueNumber++;
517 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000518
Chris Lattner0e3d6332008-12-05 21:04:20 +0000519 if (cdep->getNumOperands() != C->getNumOperands()) {
Owen Anderson69057b82008-05-13 08:17:22 +0000520 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Owen Andersonf9ae76d2008-04-17 05:36:50 +0000521 return nextValueNumber++;
Owen Andersonf9ae76d2008-04-17 05:36:50 +0000522 }
Chris Lattner80c7d812008-11-30 23:39:23 +0000523 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
524 uint32_t c_vn = lookup_or_add(C->getOperand(i));
525 uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
526 if (c_vn != cd_vn) {
527 valueNumbering.insert(std::make_pair(V, nextValueNumber));
528 return nextValueNumber++;
529 }
530 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000531
Chris Lattner80c7d812008-11-30 23:39:23 +0000532 uint32_t v = lookup_or_add(cdep);
533 valueNumbering.insert(std::make_pair(V, v));
534 return v;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000535
Owen Anderson09b83ba2007-10-18 19:39:33 +0000536 } else {
537 valueNumbering.insert(std::make_pair(V, nextValueNumber));
538 return nextValueNumber++;
539 }
540 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000541 Expression e = create_expression(BO);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000542
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000543 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
544 if (EI != expressionNumbering.end()) {
545 valueNumbering.insert(std::make_pair(V, EI->second));
546 return EI->second;
547 } else {
548 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
549 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000550
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000551 return nextValueNumber++;
552 }
553 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
554 Expression e = create_expression(C);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000555
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000556 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
557 if (EI != expressionNumbering.end()) {
558 valueNumbering.insert(std::make_pair(V, EI->second));
559 return EI->second;
560 } else {
561 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
562 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000563
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000564 return nextValueNumber++;
565 }
566 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
567 Expression e = create_expression(U);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000568
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000569 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
570 if (EI != expressionNumbering.end()) {
571 valueNumbering.insert(std::make_pair(V, EI->second));
572 return EI->second;
573 } else {
574 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
575 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000576
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000577 return nextValueNumber++;
578 }
579 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
580 Expression e = create_expression(U);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000581
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000582 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
583 if (EI != expressionNumbering.end()) {
584 valueNumbering.insert(std::make_pair(V, EI->second));
585 return EI->second;
586 } else {
587 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
588 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000589
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000590 return nextValueNumber++;
591 }
592 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
593 Expression e = create_expression(U);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000594
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000595 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
596 if (EI != expressionNumbering.end()) {
597 valueNumbering.insert(std::make_pair(V, EI->second));
598 return EI->second;
599 } else {
600 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
601 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000602
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000603 return nextValueNumber++;
604 }
605 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
606 Expression e = create_expression(U);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000607
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000608 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
609 if (EI != expressionNumbering.end()) {
610 valueNumbering.insert(std::make_pair(V, EI->second));
611 return EI->second;
612 } else {
613 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
614 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000615
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000616 return nextValueNumber++;
617 }
618 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
619 Expression e = create_expression(U);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000620
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000621 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
622 if (EI != expressionNumbering.end()) {
623 valueNumbering.insert(std::make_pair(V, EI->second));
624 return EI->second;
625 } else {
626 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
627 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000628
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000629 return nextValueNumber++;
630 }
631 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
632 Expression e = create_expression(U);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000633
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000634 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
635 if (EI != expressionNumbering.end()) {
636 valueNumbering.insert(std::make_pair(V, EI->second));
637 return EI->second;
638 } else {
639 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
640 valueNumbering.insert(std::make_pair(V, nextValueNumber));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000641
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000642 return nextValueNumber++;
643 }
644 } else {
645 valueNumbering.insert(std::make_pair(V, nextValueNumber));
646 return nextValueNumber++;
647 }
648}
649
650/// lookup - Returns the value number of the specified value. Fails if
651/// the value has not yet been numbered.
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000652uint32_t ValueTable::lookup(Value *V) const {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000653 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
Chris Lattner2876a642008-03-21 21:14:38 +0000654 assert(VI != valueNumbering.end() && "Value not numbered?");
655 return VI->second;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000656}
657
658/// clear - Remove all entries from the ValueTable
659void ValueTable::clear() {
660 valueNumbering.clear();
661 expressionNumbering.clear();
662 nextValueNumber = 1;
663}
664
Owen Anderson10ffa862007-07-31 23:27:13 +0000665/// erase - Remove a value from the value numbering
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000666void ValueTable::erase(Value *V) {
Owen Anderson10ffa862007-07-31 23:27:13 +0000667 valueNumbering.erase(V);
668}
669
Bill Wendling6b18a392008-12-22 21:36:08 +0000670/// verifyRemoved - Verify that the value is removed from all internal data
671/// structures.
672void ValueTable::verifyRemoved(const Value *V) const {
673 for (DenseMap<Value*, uint32_t>::iterator
674 I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
675 assert(I->first != V && "Inst still occurs in value numbering map!");
676 }
677}
678
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000679//===----------------------------------------------------------------------===//
Bill Wendling456e8852008-12-22 22:32:22 +0000680// GVN Pass
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000681//===----------------------------------------------------------------------===//
682
683namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +0000684 struct ValueNumberScope {
Owen Anderson1b3ea962008-06-20 01:15:47 +0000685 ValueNumberScope* parent;
686 DenseMap<uint32_t, Value*> table;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000687
Owen Anderson1b3ea962008-06-20 01:15:47 +0000688 ValueNumberScope(ValueNumberScope* p) : parent(p) { }
689 };
690}
691
692namespace {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000693
Chris Lattner2dd09db2009-09-02 06:11:42 +0000694 class GVN : public FunctionPass {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000695 bool runOnFunction(Function &F);
696 public:
697 static char ID; // Pass identification, replacement for typeid
Dan Gohmana79db302008-09-04 17:05:41 +0000698 GVN() : FunctionPass(&ID) { }
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000699
700 private:
Chris Lattner8541ede2008-12-01 00:40:32 +0000701 MemoryDependenceAnalysis *MD;
702 DominatorTree *DT;
703
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000704 ValueTable VN;
Owen Anderson1b3ea962008-06-20 01:15:47 +0000705 DenseMap<BasicBlock*, ValueNumberScope*> localAvail;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000706
Owen Anderson0cc1a762007-08-07 23:12:31 +0000707 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
708 PhiMapType phiMap;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000709
710
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000711 // This transformation requires dominator postdominator info
712 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000713 AU.addRequired<DominatorTree>();
714 AU.addRequired<MemoryDependenceAnalysis>();
Owen Anderson09b83ba2007-10-18 19:39:33 +0000715 AU.addRequired<AliasAnalysis>();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000716
Owen Anderson54e02192008-06-23 17:49:45 +0000717 AU.addPreserved<DominatorTree>();
Owen Anderson09b83ba2007-10-18 19:39:33 +0000718 AU.addPreserved<AliasAnalysis>();
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000719 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000720
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000721 // Helper fuctions
722 // FIXME: eliminate or document these better
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000723 bool processLoad(LoadInst* L,
Chris Lattner804209d2008-03-21 22:01:16 +0000724 SmallVectorImpl<Instruction*> &toErase);
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000725 bool processInstruction(Instruction *I,
Chris Lattner804209d2008-03-21 22:01:16 +0000726 SmallVectorImpl<Instruction*> &toErase);
Owen Anderson9699a6e2007-08-02 18:16:06 +0000727 bool processNonLocalLoad(LoadInst* L,
Chris Lattner804209d2008-03-21 22:01:16 +0000728 SmallVectorImpl<Instruction*> &toErase);
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000729 bool processBlock(BasicBlock *BB);
730 Value *GetValueForBlock(BasicBlock *BB, Instruction *orig,
Owen Anderson0ac1fc82007-08-02 17:56:05 +0000731 DenseMap<BasicBlock*, Value*> &Phis,
732 bool top_level = false);
Owen Anderson6a903bc2008-06-18 21:41:49 +0000733 void dump(DenseMap<uint32_t, Value*>& d);
Owen Anderson676070d2007-08-14 18:04:11 +0000734 bool iterateOnFunction(Function &F);
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000735 Value *CollapsePhi(PHINode* p);
Owen Anderson6a903bc2008-06-18 21:41:49 +0000736 bool performPRE(Function& F);
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000737 Value *lookupNumber(BasicBlock *BB, uint32_t num);
738 Value *AttemptRedundancyElimination(Instruction *orig, unsigned valno);
Nuno Lopese3127f32008-10-10 16:25:50 +0000739 void cleanupGlobalSets();
Bill Wendling6b18a392008-12-22 21:36:08 +0000740 void verifyRemoved(const Instruction *I) const;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000741 };
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000742
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000743 char GVN::ID = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000744}
745
746// createGVNPass - The public interface to this file...
747FunctionPass *llvm::createGVNPass() { return new GVN(); }
748
749static RegisterPass<GVN> X("gvn",
750 "Global Value Numbering");
751
Owen Anderson6a903bc2008-06-18 21:41:49 +0000752void GVN::dump(DenseMap<uint32_t, Value*>& d) {
Owen Anderson5e5599b2007-07-25 19:57:03 +0000753 printf("{\n");
Owen Anderson6a903bc2008-06-18 21:41:49 +0000754 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
Owen Anderson5e5599b2007-07-25 19:57:03 +0000755 E = d.end(); I != E; ++I) {
Owen Anderson6a903bc2008-06-18 21:41:49 +0000756 printf("%d\n", I->first);
Owen Anderson5e5599b2007-07-25 19:57:03 +0000757 I->second->dump();
758 }
759 printf("}\n");
760}
761
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000762static bool isSafeReplacement(PHINode* p, Instruction *inst) {
Owen Anderson109ca5a2009-08-26 22:55:11 +0000763 if (!isa<PHINode>(inst))
764 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000765
Owen Anderson109ca5a2009-08-26 22:55:11 +0000766 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
767 UI != E; ++UI)
768 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
769 if (use_phi->getParent() == inst->getParent())
770 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000771
Owen Anderson109ca5a2009-08-26 22:55:11 +0000772 return true;
773}
774
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000775Value *GVN::CollapsePhi(PHINode *PN) {
776 Value *ConstVal = PN->hasConstantValue(DT);
777 if (!ConstVal) return 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000778
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000779 Instruction *Inst = dyn_cast<Instruction>(ConstVal);
780 if (!Inst)
781 return ConstVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000782
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000783 if (DT->dominates(Inst, PN))
784 if (isSafeReplacement(PN, Inst))
785 return Inst;
Owen Andersonf5023a72007-08-16 22:51:56 +0000786 return 0;
787}
Owen Anderson5e5599b2007-07-25 19:57:03 +0000788
Owen Andersondbf23cc2007-07-26 18:26:51 +0000789/// GetValueForBlock - Get the value to use within the specified basic block.
790/// available values are in Phis.
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000791Value *GVN::GetValueForBlock(BasicBlock *BB, Instruction *Orig,
Chris Lattner2876a642008-03-21 21:14:38 +0000792 DenseMap<BasicBlock*, Value*> &Phis,
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000793 bool TopLevel) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000794
Owen Andersondbf23cc2007-07-26 18:26:51 +0000795 // If we have already computed this value, return the previously computed val.
Owen Anderson2d19aae2007-08-03 19:59:35 +0000796 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000797 if (V != Phis.end() && !TopLevel) return V->second;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000798
Owen Anderson6acc7822008-07-02 18:15:31 +0000799 // If the block is unreachable, just return undef, since this path
800 // can't actually occur at runtime.
Chris Lattner8541ede2008-12-01 00:40:32 +0000801 if (!DT->isReachableFromEntry(BB))
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000802 return Phis[BB] = UndefValue::get(Orig->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000803
Chris Lattner0a5a8d52008-12-09 19:21:47 +0000804 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000805 Value *ret = GetValueForBlock(Pred, Orig, Phis);
Owen Anderson2d19aae2007-08-03 19:59:35 +0000806 Phis[BB] = ret;
807 return ret;
Owen Anderson774761c2007-08-03 11:03:26 +0000808 }
Chris Lattner0a5a8d52008-12-09 19:21:47 +0000809
810 // Get the number of predecessors of this block so we can reserve space later.
811 // If there is already a PHI in it, use the #preds from it, otherwise count.
812 // Getting it from the PHI is constant time.
813 unsigned NumPreds;
814 if (PHINode *ExistingPN = dyn_cast<PHINode>(BB->begin()))
815 NumPreds = ExistingPN->getNumIncomingValues();
816 else
817 NumPreds = std::distance(pred_begin(BB), pred_end(BB));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000818
Owen Andersondbf23cc2007-07-26 18:26:51 +0000819 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
820 // now, then get values to fill in the incoming values for the PHI.
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000821 PHINode *PN = PHINode::Create(Orig->getType(), Orig->getName()+".rle",
Gabor Greife9ecc682008-04-06 20:25:17 +0000822 BB->begin());
Chris Lattner0a5a8d52008-12-09 19:21:47 +0000823 PN->reserveOperandSpace(NumPreds);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000824
Chris Lattner0a5a8d52008-12-09 19:21:47 +0000825 Phis.insert(std::make_pair(BB, PN));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000826
Owen Andersondbf23cc2007-07-26 18:26:51 +0000827 // Fill in the incoming values for the block.
Owen Andersond58fa6b02007-07-31 17:43:14 +0000828 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000829 Value *val = GetValueForBlock(*PI, Orig, Phis);
Owen Andersond58fa6b02007-07-31 17:43:14 +0000830 PN->addIncoming(val, *PI);
831 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000832
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000833 VN.getAliasAnalysis()->copyValue(Orig, PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000834
Owen Anderson221a4362007-08-16 22:02:55 +0000835 // Attempt to collapse PHI nodes that are trivially redundant
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000836 Value *v = CollapsePhi(PN);
Chris Lattner2876a642008-03-21 21:14:38 +0000837 if (!v) {
838 // Cache our phi construction results
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000839 if (LoadInst* L = dyn_cast<LoadInst>(Orig))
Owen Andersone34c2392008-12-14 19:10:35 +0000840 phiMap[L->getPointerOperand()].insert(PN);
841 else
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000842 phiMap[Orig].insert(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000843
Chris Lattner2876a642008-03-21 21:14:38 +0000844 return PN;
Owen Andersond58fa6b02007-07-31 17:43:14 +0000845 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000846
Chris Lattner2876a642008-03-21 21:14:38 +0000847 PN->replaceAllUsesWith(v);
Chris Lattnerfa9f99a2008-12-09 22:06:23 +0000848 if (isa<PointerType>(v->getType()))
849 MD->invalidateCachedPointerInfo(v);
Chris Lattner2876a642008-03-21 21:14:38 +0000850
851 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
852 E = Phis.end(); I != E; ++I)
853 if (I->second == PN)
854 I->second = v;
855
Dan Gohmanef3ef7f2009-07-31 20:24:18 +0000856 DEBUG(errs() << "GVN removed: " << *PN << '\n');
Chris Lattner8541ede2008-12-01 00:40:32 +0000857 MD->removeInstruction(PN);
Chris Lattner2876a642008-03-21 21:14:38 +0000858 PN->eraseFromParent();
Bill Wendling6b18a392008-12-22 21:36:08 +0000859 DEBUG(verifyRemoved(PN));
Chris Lattner2876a642008-03-21 21:14:38 +0000860
861 Phis[BB] = v;
862 return v;
Owen Anderson5e5599b2007-07-25 19:57:03 +0000863}
864
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000865/// IsValueFullyAvailableInBlock - Return true if we can prove that the value
866/// we're analyzing is fully available in the specified block. As we go, keep
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000867/// track of which blocks we know are fully alive in FullyAvailableBlocks. This
868/// map is actually a tri-state map with the following values:
869/// 0) we know the block *is not* fully available.
870/// 1) we know the block *is* fully available.
871/// 2) we do not know whether the block is fully available or not, but we are
872/// currently speculating that it will be.
873/// 3) we are speculating for this block and have used that to speculate for
874/// other blocks.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000875static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000876 DenseMap<BasicBlock*, char> &FullyAvailableBlocks) {
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000877 // Optimistically assume that the block is fully available and check to see
878 // if we already know about this block in one lookup.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000879 std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000880 FullyAvailableBlocks.insert(std::make_pair(BB, 2));
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000881
882 // If the entry already existed for this block, return the precomputed value.
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000883 if (!IV.second) {
884 // If this is a speculative "available" value, mark it as being used for
885 // speculation of other blocks.
886 if (IV.first->second == 2)
887 IV.first->second = 3;
888 return IV.first->second != 0;
889 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000890
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000891 // Otherwise, see if it is fully available in all predecessors.
892 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000893
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000894 // If this block has no predecessors, it isn't live-in here.
895 if (PI == PE)
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000896 goto SpeculationFailure;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000897
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000898 for (; PI != PE; ++PI)
899 // If the value isn't fully available in one of our predecessors, then it
900 // isn't fully available in this block either. Undo our previous
901 // optimistic assumption and bail out.
902 if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000903 goto SpeculationFailure;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000904
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000905 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000906
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000907// SpeculationFailure - If we get here, we found out that this is not, after
908// all, a fully-available block. We have a problem if we speculated on this and
909// used the speculation to mark other blocks as available.
910SpeculationFailure:
911 char &BBVal = FullyAvailableBlocks[BB];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000912
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000913 // If we didn't speculate on this, just return with it set to false.
914 if (BBVal == 2) {
915 BBVal = 0;
916 return false;
917 }
918
919 // If we did speculate on this value, we could have blocks set to 1 that are
920 // incorrect. Walk the (transitive) successors of this block and mark them as
921 // 0 if set to one.
922 SmallVector<BasicBlock*, 32> BBWorklist;
923 BBWorklist.push_back(BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000924
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000925 while (!BBWorklist.empty()) {
926 BasicBlock *Entry = BBWorklist.pop_back_val();
927 // Note that this sets blocks to 0 (unavailable) if they happen to not
928 // already be in FullyAvailableBlocks. This is safe.
929 char &EntryVal = FullyAvailableBlocks[Entry];
930 if (EntryVal == 0) continue; // Already unavailable.
931
932 // Mark as unavailable.
933 EntryVal = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000934
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000935 for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I)
936 BBWorklist.push_back(*I);
937 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000938
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000939 return false;
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000940}
941
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000942
943/// CoerceAvailableValueToLoadType - If we saw a store of a value to memory, and
944/// then a load from a must-aliased pointer of a different type, try to coerce
945/// the stored value. LoadedTy is the type of the load we want to replace and
946/// InsertPt is the place to insert new instructions.
947///
948/// If we can't do it, return null.
949static Value *CoerceAvailableValueToLoadType(Value *StoredVal,
950 const Type *LoadedTy,
951 Instruction *InsertPt,
952 const TargetData &TD) {
953 const Type *StoredValTy = StoredVal->getType();
954
955 uint64_t StoreSize = TD.getTypeSizeInBits(StoredValTy);
956 uint64_t LoadSize = TD.getTypeSizeInBits(LoadedTy);
957
958 // If the store and reload are the same size, we can always reuse it.
959 if (StoreSize == LoadSize) {
960 if (isa<PointerType>(StoredValTy) && isa<PointerType>(LoadedTy)) {
961 // Pointer to Pointer -> use bitcast.
962 return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
963 }
964
965 // Convert source pointers to integers, which can be bitcast.
966 if (isa<PointerType>(StoredValTy)) {
967 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
968 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
969 }
970
971 const Type *TypeToCastTo = LoadedTy;
972 if (isa<PointerType>(TypeToCastTo))
973 TypeToCastTo = TD.getIntPtrType(StoredValTy->getContext());
974
975 if (StoredValTy != TypeToCastTo)
976 StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
977
978 // Cast to pointer if the load needs a pointer type.
979 if (isa<PointerType>(LoadedTy))
980 StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
981
982 return StoredVal;
983 }
984
985 // If the loaded value is smaller than the available value, then we can
986 // extract out a piece from it. If the available value is too small, then we
987 // can't do anything.
988 if (StoreSize < LoadSize)
989 return 0;
990
991 // Convert source pointers to integers, which can be manipulated.
992 if (isa<PointerType>(StoredValTy)) {
993 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
994 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
995 }
996
997 // Convert vectors and fp to integer, which can be manipulated.
998 if (!isa<IntegerType>(StoredValTy)) {
999 StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
1000 StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
1001 }
1002
1003 // If this is a big-endian system, we need to shift the value down to the low
1004 // bits so that a truncate will work.
1005 if (TD.isBigEndian()) {
1006 Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
1007 StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
1008 }
1009
1010 // Truncate the integer to the right size now.
1011 const Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
1012 StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
1013
1014 if (LoadedTy == NewIntTy)
1015 return StoredVal;
1016
1017 // If the result is a pointer, inttoptr.
1018 if (isa<PointerType>(LoadedTy))
1019 return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
1020
1021 // Otherwise, bitcast.
1022 return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
1023}
1024
Chris Lattnerd28f9082009-09-21 06:24:16 +00001025/// GetBaseWithConstantOffset - Analyze the specified pointer to see if it can
1026/// be expressed as a base pointer plus a constant offset. Return the base and
1027/// offset to the caller.
1028static Value *GetBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
1029 const TargetData *TD) {
1030 Operator *PtrOp = dyn_cast<Operator>(Ptr);
1031 if (PtrOp == 0) return Ptr;
1032
1033 // Just look through bitcasts.
1034 if (PtrOp->getOpcode() == Instruction::BitCast)
1035 return GetBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
1036
1037 // If this is a GEP with constant indices, we can look through it.
1038 GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
1039 if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
1040
1041 gep_type_iterator GTI = gep_type_begin(GEP);
1042 for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
1043 ++I, ++GTI) {
1044 ConstantInt *OpC = cast<ConstantInt>(*I);
1045 if (OpC->isZero()) continue;
1046
1047 // Handle a struct and array indices which add their offset to the pointer.
1048 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1049 Offset += TD->getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1050 } else {
1051 uint64_t Size = TD->getTypeAllocSize(GTI.getIndexedType());
1052 Offset += OpC->getSExtValue()*Size;
1053 }
1054 }
1055
1056 // Re-sign extend from the pointer size if needed to get overflow edge cases
1057 // right.
1058 unsigned PtrSize = TD->getPointerSizeInBits();
1059 if (PtrSize < 64)
1060 Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
1061
1062 return GetBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
1063}
1064
1065
1066/// AnalyzeLoadFromClobberingStore - This function is called when we have a
1067/// memdep query of a load that ends up being a clobbering store. This means
1068/// that the store *may* provide bits used by the load but we can't be sure
1069/// because the pointers don't mustalias. Check this case to see if there is
1070/// anything more we can do before we give up. This returns -1 if we have to
1071/// give up, or a byte number in the stored value of the piece that feeds the
1072/// load.
1073static int AnalyzeLoadFromClobberingStore(LoadInst *L, StoreInst *DepSI,
1074 const TargetData *TD) {
1075 int64_t StoreOffset = 0, LoadOffset = 0;
1076 Value *StoreBase =
1077 GetBaseWithConstantOffset(DepSI->getPointerOperand(), StoreOffset, TD);
1078 Value *LoadBase =
1079 GetBaseWithConstantOffset(L->getPointerOperand(), LoadOffset, TD);
1080 if (StoreBase != LoadBase)
1081 return -1;
1082
1083 // If the load and store are to the exact same address, they should have been
1084 // a must alias. AA must have gotten confused.
1085 // FIXME: Study to see if/when this happens.
1086 if (LoadOffset == StoreOffset) {
1087#if 0
1088 errs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
1089 << "Base = " << *StoreBase << "\n"
1090 << "Store Ptr = " << *DepSI->getPointerOperand() << "\n"
1091 << "Store Offs = " << StoreOffset << " - " << *DepSI << "\n"
1092 << "Load Ptr = " << *L->getPointerOperand() << "\n"
1093 << "Load Offs = " << LoadOffset << " - " << *L << "\n\n";
1094 errs() << "'" << L->getParent()->getParent()->getName() << "'"
1095 << *L->getParent();
1096#endif
1097 return -1;
1098 }
1099
1100 // If the load and store don't overlap at all, the store doesn't provide
1101 // anything to the load. In this case, they really don't alias at all, AA
1102 // must have gotten confused.
1103 // FIXME: Investigate cases where this bails out, e.g. rdar://7238614. Then
1104 // remove this check, as it is duplicated with what we have below.
1105 uint64_t StoreSize = TD->getTypeSizeInBits(DepSI->getOperand(0)->getType());
1106 uint64_t LoadSize = TD->getTypeSizeInBits(L->getType());
1107
1108 if ((StoreSize & 7) | (LoadSize & 7))
1109 return -1;
1110 StoreSize >>= 3; // Convert to bytes.
1111 LoadSize >>= 3;
1112
1113
1114 bool isAAFailure = false;
1115 if (StoreOffset < LoadOffset) {
1116 isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
1117 } else {
1118 isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
1119 }
1120 if (isAAFailure) {
1121#if 0
1122 errs() << "STORE LOAD DEP WITH COMMON BASE:\n"
1123 << "Base = " << *StoreBase << "\n"
1124 << "Store Ptr = " << *DepSI->getPointerOperand() << "\n"
1125 << "Store Offs = " << StoreOffset << " - " << *DepSI << "\n"
1126 << "Load Ptr = " << *L->getPointerOperand() << "\n"
1127 << "Load Offs = " << LoadOffset << " - " << *L << "\n\n";
1128 errs() << "'" << L->getParent()->getParent()->getName() << "'"
1129 << *L->getParent();
1130#endif
1131 return -1;
1132 }
1133
1134 // If the Load isn't completely contained within the stored bits, we don't
1135 // have all the bits to feed it. We could do something crazy in the future
1136 // (issue a smaller load then merge the bits in) but this seems unlikely to be
1137 // valuable.
1138 if (StoreOffset > LoadOffset ||
1139 StoreOffset+StoreSize < LoadOffset+LoadSize)
1140 return -1;
1141
1142 // Okay, we can do this transformation. Return the number of bytes into the
1143 // store that the load is.
1144 return LoadOffset-StoreOffset;
1145}
1146
1147
1148/// GetStoreValueForLoad - This function is called when we have a
1149/// memdep query of a load that ends up being a clobbering store. This means
1150/// that the store *may* provide bits used by the load but we can't be sure
1151/// because the pointers don't mustalias. Check this case to see if there is
1152/// anything more we can do before we give up.
1153static Value *GetStoreValueForLoad(Value *SrcVal, int Offset,const Type *LoadTy,
1154 Instruction *InsertPt, const TargetData *TD){
1155 LLVMContext &Ctx = SrcVal->getType()->getContext();
1156
1157 uint64_t StoreSize = TD->getTypeSizeInBits(SrcVal->getType())/8;
1158 uint64_t LoadSize = TD->getTypeSizeInBits(LoadTy)/8;
1159
1160
1161 // Compute which bits of the stored value are being used by the load. Convert
1162 // to an integer type to start with.
1163 if (isa<PointerType>(SrcVal->getType()))
1164 SrcVal = new PtrToIntInst(SrcVal, TD->getIntPtrType(Ctx), "tmp", InsertPt);
1165 if (!isa<IntegerType>(SrcVal->getType()))
1166 SrcVal = new BitCastInst(SrcVal, IntegerType::get(Ctx, StoreSize*8),
1167 "tmp", InsertPt);
1168
1169 // Shift the bits to the least significant depending on endianness.
1170 unsigned ShiftAmt;
1171 if (TD->isLittleEndian()) {
1172 ShiftAmt = Offset*8;
1173 } else {
1174 ShiftAmt = StoreSize-LoadSize-Offset;
1175 }
1176
1177 SrcVal = BinaryOperator::CreateLShr(SrcVal,
1178 ConstantInt::get(SrcVal->getType(), ShiftAmt), "tmp", InsertPt);
1179
1180 SrcVal = new TruncInst(SrcVal, IntegerType::get(Ctx, LoadSize*8),
1181 "tmp", InsertPt);
1182
1183 return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, *TD);
1184}
1185
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001186struct AvailableValueInBlock {
1187 /// BB - The basic block in question.
1188 BasicBlock *BB;
1189 /// V - The value that is live out of the block.
1190 Value *V;
1191
1192 static AvailableValueInBlock get(BasicBlock *BB, Value *V) {
1193 AvailableValueInBlock Res;
1194 Res.BB = BB;
1195 Res.V = V;
1196 return Res;
1197 }
1198};
1199
Chris Lattnerd28f9082009-09-21 06:24:16 +00001200/// GetAvailableBlockValues - Given the ValuesPerBlock list, convert all of the
1201/// available values to values of the expected LoadTy in their blocks and insert
1202/// the new values into BlockReplValues.
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001203static void
1204GetAvailableBlockValues(DenseMap<BasicBlock*, Value*> &BlockReplValues,
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001205 const SmallVector<AvailableValueInBlock, 16> &ValuesPerBlock,
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001206 const Type *LoadTy,
1207 const TargetData *TD) {
1208
1209 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001210 BasicBlock *BB = ValuesPerBlock[i].BB;
1211 Value *AvailableVal = ValuesPerBlock[i].V;
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001212
1213 Value *&BlockEntry = BlockReplValues[BB];
1214 if (BlockEntry) continue;
1215
1216 if (AvailableVal->getType() != LoadTy) {
1217 assert(TD && "Need target data to handle type mismatch case");
1218 AvailableVal = CoerceAvailableValueToLoadType(AvailableVal, LoadTy,
1219 BB->getTerminator(), *TD);
1220 DEBUG(errs() << "GVN COERCED NONLOCAL VAL:\n"
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001221 << *ValuesPerBlock[i].V << '\n'
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001222 << *AvailableVal << '\n' << "\n\n\n");
1223 }
1224 BlockEntry = AvailableVal;
1225 }
1226}
1227
Owen Anderson221a4362007-08-16 22:02:55 +00001228/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
1229/// non-local by performing PHI construction.
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001230bool GVN::processNonLocalLoad(LoadInst *LI,
Chris Lattner804209d2008-03-21 22:01:16 +00001231 SmallVectorImpl<Instruction*> &toErase) {
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001232 // Find the non-local dependencies of the load.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001233 SmallVector<MemoryDependenceAnalysis::NonLocalDepEntry, 64> Deps;
Chris Lattnerb6fc4b82008-12-09 19:25:07 +00001234 MD->getNonLocalPointerDependency(LI->getOperand(0), true, LI->getParent(),
1235 Deps);
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001236 //DEBUG(errs() << "INVESTIGATING NONLOCAL LOAD: "
1237 // << Deps.size() << *LI << '\n');
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001238
Owen Andersonb39e0de2008-08-26 22:07:42 +00001239 // If we had to process more than one hundred blocks to find the
1240 // dependencies, this load isn't worth worrying about. Optimizing
1241 // it will be too expensive.
Chris Lattnerb6fc4b82008-12-09 19:25:07 +00001242 if (Deps.size() > 100)
Owen Andersonb39e0de2008-08-26 22:07:42 +00001243 return false;
Chris Lattnerb6372932008-12-18 00:51:32 +00001244
1245 // If we had a phi translation failure, we'll have a single entry which is a
1246 // clobber in the current block. Reject this early.
Torok Edwinba93ea72009-06-17 18:48:18 +00001247 if (Deps.size() == 1 && Deps[0].second.isClobber()) {
1248 DEBUG(
Dan Gohman1ddf98a2009-07-25 01:43:01 +00001249 errs() << "GVN: non-local load ";
1250 WriteAsOperand(errs(), LI);
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001251 errs() << " is clobbered by " << *Deps[0].second.getInst() << '\n';
Torok Edwinba93ea72009-06-17 18:48:18 +00001252 );
Chris Lattnerb6372932008-12-18 00:51:32 +00001253 return false;
Torok Edwinba93ea72009-06-17 18:48:18 +00001254 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001255
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001256 // Filter out useless results (non-locals, etc). Keep track of the blocks
1257 // where we have a value available in repl, also keep track of whether we see
1258 // dependencies that produce an unknown value for the load (such as a call
1259 // that could potentially clobber the load).
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001260 SmallVector<AvailableValueInBlock, 16> ValuesPerBlock;
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001261 SmallVector<BasicBlock*, 16> UnavailableBlocks;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001262
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001263 const TargetData *TD = 0;
1264
Chris Lattnerb6fc4b82008-12-09 19:25:07 +00001265 for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
1266 BasicBlock *DepBB = Deps[i].first;
1267 MemDepResult DepInfo = Deps[i].second;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001268
Chris Lattner0e3d6332008-12-05 21:04:20 +00001269 if (DepInfo.isClobber()) {
1270 UnavailableBlocks.push_back(DepBB);
1271 continue;
1272 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001273
Chris Lattner0e3d6332008-12-05 21:04:20 +00001274 Instruction *DepInst = DepInfo.getInst();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001275
Chris Lattner0e3d6332008-12-05 21:04:20 +00001276 // Loading the allocation -> undef.
Victor Hernandez5d034492009-09-18 22:35:49 +00001277 if (isa<AllocationInst>(DepInst) || isMalloc(DepInst)) {
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001278 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1279 UndefValue::get(LI->getType())));
Chris Lattner7e61daf2008-12-01 01:15:42 +00001280 continue;
1281 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001282
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001283 if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001284 // Reject loads and stores that are to the same address but are of
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001285 // different types if we have to.
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001286 if (S->getOperand(0)->getType() != LI->getType()) {
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001287 if (TD == 0)
1288 TD = getAnalysisIfAvailable<TargetData>();
1289
1290 // If the stored value is larger or equal to the loaded value, we can
1291 // reuse it.
1292 if (TD == 0 ||
1293 TD->getTypeSizeInBits(S->getOperand(0)->getType()) <
1294 TD->getTypeSizeInBits(LI->getType())) {
1295 UnavailableBlocks.push_back(DepBB);
1296 continue;
1297 }
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001298 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001299
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001300 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1301 S->getOperand(0)));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001302
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001303 } else if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001304 // If the types mismatch and we can't handle it, reject reuse of the load.
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001305 if (LD->getType() != LI->getType()) {
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001306 if (TD == 0)
1307 TD = getAnalysisIfAvailable<TargetData>();
1308
1309 // If the stored value is larger or equal to the loaded value, we can
1310 // reuse it.
1311 if (TD == 0 ||
1312 TD->getTypeSizeInBits(LD->getType()) <
1313 TD->getTypeSizeInBits(LI->getType())) {
1314 UnavailableBlocks.push_back(DepBB);
1315 continue;
1316 }
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001317 }
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001318 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB, LD));
Owen Anderson5e5599b2007-07-25 19:57:03 +00001319 } else {
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001320 // FIXME: Handle memset/memcpy.
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001321 UnavailableBlocks.push_back(DepBB);
1322 continue;
Owen Anderson5e5599b2007-07-25 19:57:03 +00001323 }
Chris Lattner2876a642008-03-21 21:14:38 +00001324 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001325
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001326 // If we have no predecessors that produce a known value for this load, exit
1327 // early.
1328 if (ValuesPerBlock.empty()) return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001329
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001330 // If all of the instructions we depend on produce a known value for this
1331 // load, then it is fully redundant and we can use PHI insertion to compute
1332 // its value. Insert PHIs and remove the fully redundant value now.
1333 if (UnavailableBlocks.empty()) {
1334 // Use cached PHI construction information from previous runs
1335 SmallPtrSet<Instruction*, 4> &p = phiMap[LI->getPointerOperand()];
Chris Lattnerb6fc4b82008-12-09 19:25:07 +00001336 // FIXME: What does phiMap do? Are we positive it isn't getting invalidated?
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001337 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
1338 I != E; ++I) {
1339 if ((*I)->getParent() == LI->getParent()) {
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001340 DEBUG(errs() << "GVN REMOVING NONLOCAL LOAD #1: " << *LI << '\n');
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001341 LI->replaceAllUsesWith(*I);
Chris Lattnerfa9f99a2008-12-09 22:06:23 +00001342 if (isa<PointerType>((*I)->getType()))
1343 MD->invalidateCachedPointerInfo(*I);
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001344 toErase.push_back(LI);
1345 NumGVNLoad++;
1346 return true;
1347 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001348
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001349 ValuesPerBlock.push_back(AvailableValueInBlock::get((*I)->getParent(),
1350 *I));
Owen Anderson0cc1a762007-08-07 23:12:31 +00001351 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001352
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001353 DEBUG(errs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001354
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001355 // Convert the block information to a map, and insert coersions as needed.
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001356 DenseMap<BasicBlock*, Value*> BlockReplValues;
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001357 GetAvailableBlockValues(BlockReplValues, ValuesPerBlock, LI->getType(), TD);
1358
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001359 // Perform PHI construction.
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001360 Value *V = GetValueForBlock(LI->getParent(), LI, BlockReplValues, true);
1361 LI->replaceAllUsesWith(V);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001362
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001363 if (isa<PHINode>(V))
1364 V->takeName(LI);
1365 if (isa<PointerType>(V->getType()))
1366 MD->invalidateCachedPointerInfo(V);
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001367 toErase.push_back(LI);
1368 NumGVNLoad++;
1369 return true;
1370 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001371
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001372 if (!EnablePRE || !EnableLoadPRE)
1373 return false;
1374
1375 // Okay, we have *some* definitions of the value. This means that the value
1376 // is available in some of our (transitive) predecessors. Lets think about
1377 // doing PRE of this load. This will involve inserting a new load into the
1378 // predecessor when it's not available. We could do this in general, but
1379 // prefer to not increase code size. As such, we only do this when we know
1380 // that we only have to insert *one* load (which means we're basically moving
1381 // the load, not inserting a new one).
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001382
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001383 SmallPtrSet<BasicBlock *, 4> Blockers;
1384 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1385 Blockers.insert(UnavailableBlocks[i]);
1386
1387 // Lets find first basic block with more than one predecessor. Walk backwards
1388 // through predecessors if needed.
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001389 BasicBlock *LoadBB = LI->getParent();
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001390 BasicBlock *TmpBB = LoadBB;
1391
1392 bool isSinglePred = false;
Dale Johannesen81b64632009-06-17 20:48:23 +00001393 bool allSingleSucc = true;
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001394 while (TmpBB->getSinglePredecessor()) {
1395 isSinglePred = true;
1396 TmpBB = TmpBB->getSinglePredecessor();
1397 if (!TmpBB) // If haven't found any, bail now.
1398 return false;
1399 if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1400 return false;
1401 if (Blockers.count(TmpBB))
1402 return false;
Dale Johannesen81b64632009-06-17 20:48:23 +00001403 if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1404 allSingleSucc = false;
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001405 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001406
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001407 assert(TmpBB);
1408 LoadBB = TmpBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001409
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001410 // If we have a repl set with LI itself in it, this means we have a loop where
1411 // at least one of the values is LI. Since this means that we won't be able
1412 // to eliminate LI even if we insert uses in the other predecessors, we will
1413 // end up increasing code size. Reject this by scanning for LI.
1414 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001415 if (ValuesPerBlock[i].V == LI)
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001416 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001417
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001418 if (isSinglePred) {
1419 bool isHot = false;
1420 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001421 if (Instruction *I = dyn_cast<Instruction>(ValuesPerBlock[i].V))
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001422 // "Hot" Instruction is in some loop (because it dominates its dep.
1423 // instruction).
1424 if (DT->dominates(LI, I)) {
1425 isHot = true;
1426 break;
1427 }
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001428
1429 // We are interested only in "hot" instructions. We don't want to do any
1430 // mis-optimizations here.
1431 if (!isHot)
1432 return false;
1433 }
1434
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001435 // Okay, we have some hope :). Check to see if the loaded value is fully
1436 // available in all but one predecessor.
1437 // FIXME: If we could restructure the CFG, we could make a common pred with
1438 // all the preds that don't have an available LI and insert a new load into
1439 // that one block.
1440 BasicBlock *UnavailablePred = 0;
1441
Chris Lattnerd2a653a2008-12-05 07:49:08 +00001442 DenseMap<BasicBlock*, char> FullyAvailableBlocks;
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001443 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001444 FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001445 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1446 FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1447
1448 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1449 PI != E; ++PI) {
1450 if (IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
1451 continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001452
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001453 // If this load is not available in multiple predecessors, reject it.
1454 if (UnavailablePred && UnavailablePred != *PI)
1455 return false;
1456 UnavailablePred = *PI;
1457 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001458
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001459 assert(UnavailablePred != 0 &&
1460 "Fully available value should be eliminated above!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001461
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001462 // If the loaded pointer is PHI node defined in this block, do PHI translation
1463 // to get its value in the predecessor.
1464 Value *LoadPtr = LI->getOperand(0)->DoPHITranslation(LoadBB, UnavailablePred);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001465
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001466 // Make sure the value is live in the predecessor. If it was defined by a
1467 // non-PHI instruction in this block, we don't know how to recompute it above.
1468 if (Instruction *LPInst = dyn_cast<Instruction>(LoadPtr))
1469 if (!DT->dominates(LPInst->getParent(), UnavailablePred)) {
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +00001470 DEBUG(errs() << "COULDN'T PRE LOAD BECAUSE PTR IS UNAVAILABLE IN PRED: "
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001471 << *LPInst << '\n' << *LI << "\n");
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001472 return false;
1473 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001474
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001475 // We don't currently handle critical edges :(
1476 if (UnavailablePred->getTerminator()->getNumSuccessors() != 1) {
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +00001477 DEBUG(errs() << "COULD NOT PRE LOAD BECAUSE OF CRITICAL EDGE '"
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001478 << UnavailablePred->getName() << "': " << *LI << '\n');
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001479 return false;
Owen Anderson0cc1a762007-08-07 23:12:31 +00001480 }
Dale Johannesen81b64632009-06-17 20:48:23 +00001481
1482 // Make sure it is valid to move this load here. We have to watch out for:
1483 // @1 = getelementptr (i8* p, ...
1484 // test p and branch if == 0
1485 // load @1
1486 // It is valid to have the getelementptr before the test, even if p can be 0,
1487 // as getelementptr only does address arithmetic.
1488 // If we are not pushing the value through any multiple-successor blocks
1489 // we do not have this case. Otherwise, check that the load is safe to
1490 // put anywhere; this can be improved, but should be conservatively safe.
1491 if (!allSingleSucc &&
1492 !isSafeToLoadUnconditionally(LoadPtr, UnavailablePred->getTerminator()))
1493 return false;
1494
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001495 // Okay, we can eliminate this load by inserting a reload in the predecessor
1496 // and using PHI construction to get the value in the other predecessors, do
1497 // it.
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001498 DEBUG(errs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001499
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001500 Value *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1501 LI->getAlignment(),
1502 UnavailablePred->getTerminator());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001503
Owen Anderson04cfdd32009-05-29 05:37:54 +00001504 SmallPtrSet<Instruction*, 4> &p = phiMap[LI->getPointerOperand()];
1505 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
1506 I != E; ++I)
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001507 ValuesPerBlock.push_back(AvailableValueInBlock::get((*I)->getParent(), *I));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001508
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001509 DenseMap<BasicBlock*, Value*> BlockReplValues;
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001510 GetAvailableBlockValues(BlockReplValues, ValuesPerBlock, LI->getType(), TD);
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001511 BlockReplValues[UnavailablePred] = NewLoad;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001512
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001513 // Perform PHI construction.
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001514 Value *V = GetValueForBlock(LI->getParent(), LI, BlockReplValues, true);
1515 LI->replaceAllUsesWith(V);
1516 if (isa<PHINode>(V))
1517 V->takeName(LI);
1518 if (isa<PointerType>(V->getType()))
1519 MD->invalidateCachedPointerInfo(V);
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001520 toErase.push_back(LI);
1521 NumPRELoad++;
Owen Anderson5e5599b2007-07-25 19:57:03 +00001522 return true;
1523}
1524
Owen Anderson221a4362007-08-16 22:02:55 +00001525/// processLoad - Attempt to eliminate a load, first by eliminating it
1526/// locally, and then attempting non-local elimination if that fails.
Chris Lattner0e3d6332008-12-05 21:04:20 +00001527bool GVN::processLoad(LoadInst *L, SmallVectorImpl<Instruction*> &toErase) {
1528 if (L->isVolatile())
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001529 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001530
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001531 // ... to a pointer that has been loaded from before...
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001532 MemDepResult Dep = MD->getDependency(L);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001533
Chris Lattner0e3d6332008-12-05 21:04:20 +00001534 // If the value isn't available, don't do anything!
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001535 if (Dep.isClobber()) {
Chris Lattner0a9616d2009-09-21 05:57:11 +00001536 // FIXME: We should handle memset/memcpy/memmove as dependent instructions
1537 // to forward the value if available.
1538 //if (isa<MemIntrinsic>(Dep.getInst()))
1539 //errs() << "LOAD DEPENDS ON MEM: " << *L << "\n" << *Dep.getInst()<<"\n\n";
1540
1541 // Check to see if we have something like this:
Chris Lattner1dd48c32009-09-20 19:03:47 +00001542 // store i32 123, i32* %P
1543 // %A = bitcast i32* %P to i8*
1544 // %B = gep i8* %A, i32 1
1545 // %C = load i8* %B
1546 //
1547 // We could do that by recognizing if the clobber instructions are obviously
1548 // a common base + constant offset, and if the previous store (or memset)
1549 // completely covers this load. This sort of thing can happen in bitfield
1550 // access code.
Chris Lattner0a9616d2009-09-21 05:57:11 +00001551 if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst()))
Chris Lattner9d7fb292009-09-21 06:22:46 +00001552 if (const TargetData *TD = getAnalysisIfAvailable<TargetData>()) {
1553 int Offset = AnalyzeLoadFromClobberingStore(L, DepSI, TD);
1554 if (Offset != -1) {
1555 Value *AvailVal = GetStoreValueForLoad(DepSI->getOperand(0), Offset,
1556 L->getType(), L, TD);
Chris Lattner0a9616d2009-09-21 05:57:11 +00001557 DEBUG(errs() << "GVN COERCED STORE BITS:\n" << *DepSI << '\n'
1558 << *AvailVal << '\n' << *L << "\n\n\n");
1559
1560 // Replace the load!
1561 L->replaceAllUsesWith(AvailVal);
1562 if (isa<PointerType>(AvailVal->getType()))
1563 MD->invalidateCachedPointerInfo(AvailVal);
1564 toErase.push_back(L);
1565 NumGVNLoad++;
1566 return true;
1567 }
Chris Lattner9d7fb292009-09-21 06:22:46 +00001568 }
Chris Lattner0a9616d2009-09-21 05:57:11 +00001569
Torok Edwin72070282009-05-29 09:46:03 +00001570 DEBUG(
1571 // fast print dep, using operator<< on instruction would be too slow
Dan Gohman1ddf98a2009-07-25 01:43:01 +00001572 errs() << "GVN: load ";
1573 WriteAsOperand(errs(), L);
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001574 Instruction *I = Dep.getInst();
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001575 errs() << " is clobbered by " << *I << '\n';
Torok Edwin72070282009-05-29 09:46:03 +00001576 );
Chris Lattner0e3d6332008-12-05 21:04:20 +00001577 return false;
Torok Edwin72070282009-05-29 09:46:03 +00001578 }
Chris Lattner0e3d6332008-12-05 21:04:20 +00001579
1580 // If it is defined in another block, try harder.
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001581 if (Dep.isNonLocal())
Chris Lattner0e3d6332008-12-05 21:04:20 +00001582 return processNonLocalLoad(L, toErase);
Eli Friedman716c10c2008-02-12 12:08:14 +00001583
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001584 Instruction *DepInst = Dep.getInst();
Chris Lattner0e3d6332008-12-05 21:04:20 +00001585 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
Chris Lattner1dd48c32009-09-20 19:03:47 +00001586 Value *StoredVal = DepSI->getOperand(0);
1587
1588 // The store and load are to a must-aliased pointer, but they may not
1589 // actually have the same type. See if we know how to reuse the stored
1590 // value (depending on its type).
1591 const TargetData *TD = 0;
1592 if (StoredVal->getType() != L->getType() &&
1593 (TD = getAnalysisIfAvailable<TargetData>())) {
Chris Lattner7c62d8a2009-09-20 19:31:14 +00001594 StoredVal = CoerceAvailableValueToLoadType(StoredVal, L->getType(), L, *TD);
Chris Lattner1dd48c32009-09-20 19:03:47 +00001595 if (StoredVal == 0)
1596 return false;
1597
1598 DEBUG(errs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
1599 << '\n' << *L << "\n\n\n");
1600 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001601
Chris Lattner0e3d6332008-12-05 21:04:20 +00001602 // Remove it!
Chris Lattner1dd48c32009-09-20 19:03:47 +00001603 L->replaceAllUsesWith(StoredVal);
1604 if (isa<PointerType>(StoredVal->getType()))
1605 MD->invalidateCachedPointerInfo(StoredVal);
Chris Lattner0e3d6332008-12-05 21:04:20 +00001606 toErase.push_back(L);
1607 NumGVNLoad++;
1608 return true;
1609 }
1610
1611 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
Chris Lattner1dd48c32009-09-20 19:03:47 +00001612 Value *AvailableVal = DepLI;
1613
1614 // The loads are of a must-aliased pointer, but they may not actually have
1615 // the same type. See if we know how to reuse the previously loaded value
1616 // (depending on its type).
1617 const TargetData *TD = 0;
1618 if (DepLI->getType() != L->getType() &&
1619 (TD = getAnalysisIfAvailable<TargetData>())) {
Chris Lattner7c62d8a2009-09-20 19:31:14 +00001620 AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(), L, *TD);
Chris Lattner1dd48c32009-09-20 19:03:47 +00001621 if (AvailableVal == 0)
1622 return false;
1623
1624 DEBUG(errs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
1625 << "\n" << *L << "\n\n\n");
1626 }
1627
Chris Lattner0e3d6332008-12-05 21:04:20 +00001628 // Remove it!
Chris Lattner1dd48c32009-09-20 19:03:47 +00001629 L->replaceAllUsesWith(AvailableVal);
Chris Lattnerfa9f99a2008-12-09 22:06:23 +00001630 if (isa<PointerType>(DepLI->getType()))
1631 MD->invalidateCachedPointerInfo(DepLI);
Chris Lattner0e3d6332008-12-05 21:04:20 +00001632 toErase.push_back(L);
1633 NumGVNLoad++;
1634 return true;
1635 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001636
Chris Lattner3ff6d012008-11-30 01:39:32 +00001637 // If this load really doesn't depend on anything, then we must be loading an
1638 // undef value. This can happen when loading for a fresh allocation with no
1639 // intervening stores, for example.
Victor Hernandez5d034492009-09-18 22:35:49 +00001640 if (isa<AllocationInst>(DepInst) || isMalloc(DepInst)) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00001641 L->replaceAllUsesWith(UndefValue::get(L->getType()));
Chris Lattner3ff6d012008-11-30 01:39:32 +00001642 toErase.push_back(L);
Chris Lattner3ff6d012008-11-30 01:39:32 +00001643 NumGVNLoad++;
Chris Lattner0e3d6332008-12-05 21:04:20 +00001644 return true;
Eli Friedman716c10c2008-02-12 12:08:14 +00001645 }
1646
Chris Lattner0e3d6332008-12-05 21:04:20 +00001647 return false;
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001648}
1649
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001650Value *GVN::lookupNumber(BasicBlock *BB, uint32_t num) {
Owen Anderson54e02192008-06-23 17:49:45 +00001651 DenseMap<BasicBlock*, ValueNumberScope*>::iterator I = localAvail.find(BB);
1652 if (I == localAvail.end())
1653 return 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001654
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001655 ValueNumberScope *Locals = I->second;
1656 while (Locals) {
1657 DenseMap<uint32_t, Value*>::iterator I = Locals->table.find(num);
1658 if (I != Locals->table.end())
Owen Anderson1b3ea962008-06-20 01:15:47 +00001659 return I->second;
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001660 Locals = Locals->parent;
Owen Anderson1b3ea962008-06-20 01:15:47 +00001661 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001662
Owen Anderson1b3ea962008-06-20 01:15:47 +00001663 return 0;
1664}
1665
Owen Andersonbfe133e2008-12-15 02:03:00 +00001666/// AttemptRedundancyElimination - If the "fast path" of redundancy elimination
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001667/// by inheritance from the dominator fails, see if we can perform phi
Owen Andersonbfe133e2008-12-15 02:03:00 +00001668/// construction to eliminate the redundancy.
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001669Value *GVN::AttemptRedundancyElimination(Instruction *orig, unsigned valno) {
1670 BasicBlock *BaseBlock = orig->getParent();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001671
Owen Andersonbfe133e2008-12-15 02:03:00 +00001672 SmallPtrSet<BasicBlock*, 4> Visited;
1673 SmallVector<BasicBlock*, 8> Stack;
1674 Stack.push_back(BaseBlock);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001675
Owen Andersonbfe133e2008-12-15 02:03:00 +00001676 DenseMap<BasicBlock*, Value*> Results;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001677
Owen Andersonbfe133e2008-12-15 02:03:00 +00001678 // Walk backwards through our predecessors, looking for instances of the
1679 // value number we're looking for. Instances are recorded in the Results
1680 // map, which is then used to perform phi construction.
1681 while (!Stack.empty()) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001682 BasicBlock *Current = Stack.back();
Owen Andersonbfe133e2008-12-15 02:03:00 +00001683 Stack.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001684
Owen Andersonbfe133e2008-12-15 02:03:00 +00001685 // If we've walked all the way to a proper dominator, then give up. Cases
1686 // where the instance is in the dominator will have been caught by the fast
1687 // path, and any cases that require phi construction further than this are
1688 // probably not worth it anyways. Note that this is a SIGNIFICANT compile
1689 // time improvement.
1690 if (DT->properlyDominates(Current, orig->getParent())) return 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001691
Owen Andersonbfe133e2008-12-15 02:03:00 +00001692 DenseMap<BasicBlock*, ValueNumberScope*>::iterator LA =
1693 localAvail.find(Current);
1694 if (LA == localAvail.end()) return 0;
Chris Lattner73d7fe52009-01-19 22:00:18 +00001695 DenseMap<uint32_t, Value*>::iterator V = LA->second->table.find(valno);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001696
Owen Andersonbfe133e2008-12-15 02:03:00 +00001697 if (V != LA->second->table.end()) {
1698 // Found an instance, record it.
1699 Results.insert(std::make_pair(Current, V->second));
1700 continue;
1701 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001702
Owen Andersonbfe133e2008-12-15 02:03:00 +00001703 // If we reach the beginning of the function, then give up.
1704 if (pred_begin(Current) == pred_end(Current))
1705 return 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001706
Owen Andersonbfe133e2008-12-15 02:03:00 +00001707 for (pred_iterator PI = pred_begin(Current), PE = pred_end(Current);
1708 PI != PE; ++PI)
1709 if (Visited.insert(*PI))
1710 Stack.push_back(*PI);
1711 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001712
Owen Andersonbfe133e2008-12-15 02:03:00 +00001713 // If we didn't find instances, give up. Otherwise, perform phi construction.
1714 if (Results.size() == 0)
1715 return 0;
1716 else
1717 return GetValueForBlock(BaseBlock, orig, Results, true);
1718}
1719
Owen Anderson398602a2007-08-14 18:16:29 +00001720/// processInstruction - When calculating availability, handle an instruction
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001721/// by inserting it into the appropriate sets
Owen Andersonaccdca12008-06-12 19:25:32 +00001722bool GVN::processInstruction(Instruction *I,
Chris Lattner804209d2008-03-21 22:01:16 +00001723 SmallVectorImpl<Instruction*> &toErase) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001724 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1725 bool Changed = processLoad(LI, toErase);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001726
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001727 if (!Changed) {
1728 unsigned Num = VN.lookup_or_add(LI);
1729 localAvail[I->getParent()]->table.insert(std::make_pair(Num, LI));
Owen Anderson6a903bc2008-06-18 21:41:49 +00001730 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001731
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001732 return Changed;
Owen Anderson6a903bc2008-06-18 21:41:49 +00001733 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001734
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001735 uint32_t NextNum = VN.getNextUnusedValueNumber();
1736 unsigned Num = VN.lookup_or_add(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001737
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001738 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1739 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001740
Owen Anderson98f912b2009-04-01 23:53:49 +00001741 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
1742 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001743
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001744 Value *BranchCond = BI->getCondition();
1745 uint32_t CondVN = VN.lookup_or_add(BranchCond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001746
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001747 BasicBlock *TrueSucc = BI->getSuccessor(0);
1748 BasicBlock *FalseSucc = BI->getSuccessor(1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001749
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001750 if (TrueSucc->getSinglePredecessor())
1751 localAvail[TrueSucc]->table[CondVN] =
1752 ConstantInt::getTrue(TrueSucc->getContext());
1753 if (FalseSucc->getSinglePredecessor())
1754 localAvail[FalseSucc]->table[CondVN] =
1755 ConstantInt::getFalse(TrueSucc->getContext());
Owen Anderson98f912b2009-04-01 23:53:49 +00001756
1757 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001758
Owen Anderson0c1e6342008-04-07 09:59:07 +00001759 // Allocations are always uniquely numbered, so we can save time and memory
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001760 // by fast failing them.
Victor Hernandez5d034492009-09-18 22:35:49 +00001761 } else if (isa<AllocationInst>(I) || isMalloc(I) || isa<TerminatorInst>(I)) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001762 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Owen Anderson0c1e6342008-04-07 09:59:07 +00001763 return false;
Owen Anderson6a903bc2008-06-18 21:41:49 +00001764 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001765
Owen Anderson221a4362007-08-16 22:02:55 +00001766 // Collapse PHI nodes
Owen Andersonbc271a02007-08-14 18:33:27 +00001767 if (PHINode* p = dyn_cast<PHINode>(I)) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001768 Value *constVal = CollapsePhi(p);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001769
Owen Andersonbc271a02007-08-14 18:33:27 +00001770 if (constVal) {
Owen Andersonf5023a72007-08-16 22:51:56 +00001771 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1772 PI != PE; ++PI)
Chris Lattner0a5a8d52008-12-09 19:21:47 +00001773 PI->second.erase(p);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001774
Owen Andersonf5023a72007-08-16 22:51:56 +00001775 p->replaceAllUsesWith(constVal);
Chris Lattnerfa9f99a2008-12-09 22:06:23 +00001776 if (isa<PointerType>(constVal->getType()))
1777 MD->invalidateCachedPointerInfo(constVal);
Owen Anderson164274e2008-12-23 00:49:51 +00001778 VN.erase(p);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001779
Owen Andersonf5023a72007-08-16 22:51:56 +00001780 toErase.push_back(p);
Owen Anderson6a903bc2008-06-18 21:41:49 +00001781 } else {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001782 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Owen Andersonbc271a02007-08-14 18:33:27 +00001783 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001784
Owen Anderson3ea90a72008-07-03 17:44:33 +00001785 // If the number we were assigned was a brand new VN, then we don't
1786 // need to do a lookup to see if the number already exists
1787 // somewhere in the domtree: it can't!
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001788 } else if (Num == NextNum) {
1789 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001790
Owen Andersonbfe133e2008-12-15 02:03:00 +00001791 // Perform fast-path value-number based elimination of values inherited from
1792 // dominators.
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001793 } else if (Value *repl = lookupNumber(I->getParent(), Num)) {
Owen Anderson086b2c42007-12-08 01:37:09 +00001794 // Remove it!
Owen Anderson10ffa862007-07-31 23:27:13 +00001795 VN.erase(I);
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001796 I->replaceAllUsesWith(repl);
Chris Lattnerfa9f99a2008-12-09 22:06:23 +00001797 if (isa<PointerType>(repl->getType()))
1798 MD->invalidateCachedPointerInfo(repl);
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001799 toErase.push_back(I);
1800 return true;
Owen Andersonbfe133e2008-12-15 02:03:00 +00001801
1802#if 0
1803 // Perform slow-pathvalue-number based elimination with phi construction.
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001804 } else if (Value *repl = AttemptRedundancyElimination(I, Num)) {
Owen Andersonbfe133e2008-12-15 02:03:00 +00001805 // Remove it!
1806 VN.erase(I);
1807 I->replaceAllUsesWith(repl);
1808 if (isa<PointerType>(repl->getType()))
1809 MD->invalidateCachedPointerInfo(repl);
1810 toErase.push_back(I);
1811 return true;
1812#endif
Owen Anderson3ea90a72008-07-03 17:44:33 +00001813 } else {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001814 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001815 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001816
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001817 return false;
1818}
1819
Bill Wendling456e8852008-12-22 22:32:22 +00001820/// runOnFunction - This is the main transformation entry point for a function.
Owen Anderson676070d2007-08-14 18:04:11 +00001821bool GVN::runOnFunction(Function& F) {
Chris Lattner8541ede2008-12-01 00:40:32 +00001822 MD = &getAnalysis<MemoryDependenceAnalysis>();
1823 DT = &getAnalysis<DominatorTree>();
Owen Andersonf7928602008-05-12 20:15:55 +00001824 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
Chris Lattner8541ede2008-12-01 00:40:32 +00001825 VN.setMemDep(MD);
1826 VN.setDomTree(DT);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001827
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001828 bool Changed = false;
1829 bool ShouldContinue = true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001830
Owen Andersonac310962008-07-16 17:52:31 +00001831 // Merge unconditional branches, allowing PRE to catch more
1832 // optimization opportunities.
1833 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001834 BasicBlock *BB = FI;
Owen Andersonac310962008-07-16 17:52:31 +00001835 ++FI;
Owen Andersonc0623812008-07-17 00:01:40 +00001836 bool removedBlock = MergeBlockIntoPredecessor(BB, this);
1837 if (removedBlock) NumGVNBlocks++;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001838
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001839 Changed |= removedBlock;
Owen Andersonac310962008-07-16 17:52:31 +00001840 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001841
Chris Lattner0a5a8d52008-12-09 19:21:47 +00001842 unsigned Iteration = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001843
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001844 while (ShouldContinue) {
Dan Gohman1ddf98a2009-07-25 01:43:01 +00001845 DEBUG(errs() << "GVN iteration: " << Iteration << "\n");
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001846 ShouldContinue = iterateOnFunction(F);
1847 Changed |= ShouldContinue;
Chris Lattner0a5a8d52008-12-09 19:21:47 +00001848 ++Iteration;
Owen Anderson676070d2007-08-14 18:04:11 +00001849 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001850
Owen Anderson04a6e0b2008-07-18 18:03:38 +00001851 if (EnablePRE) {
Owen Anderson2fbfb702008-09-03 23:06:07 +00001852 bool PREChanged = true;
1853 while (PREChanged) {
1854 PREChanged = performPRE(F);
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001855 Changed |= PREChanged;
Owen Anderson2fbfb702008-09-03 23:06:07 +00001856 }
Owen Anderson04a6e0b2008-07-18 18:03:38 +00001857 }
Chris Lattner0a5a8d52008-12-09 19:21:47 +00001858 // FIXME: Should perform GVN again after PRE does something. PRE can move
1859 // computations into blocks where they become fully redundant. Note that
1860 // we can't do this until PRE's critical edge splitting updates memdep.
1861 // Actually, when this happens, we should just fully integrate PRE into GVN.
Nuno Lopese3127f32008-10-10 16:25:50 +00001862
1863 cleanupGlobalSets();
1864
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001865 return Changed;
Owen Anderson676070d2007-08-14 18:04:11 +00001866}
1867
1868
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001869bool GVN::processBlock(BasicBlock *BB) {
Chris Lattner0a5a8d52008-12-09 19:21:47 +00001870 // FIXME: Kill off toErase by doing erasing eagerly in a helper function (and
1871 // incrementing BI before processing an instruction).
Owen Andersonaccdca12008-06-12 19:25:32 +00001872 SmallVector<Instruction*, 8> toErase;
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001873 bool ChangedFunction = false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001874
Owen Andersonaccdca12008-06-12 19:25:32 +00001875 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1876 BI != BE;) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001877 ChangedFunction |= processInstruction(BI, toErase);
Owen Andersonaccdca12008-06-12 19:25:32 +00001878 if (toErase.empty()) {
1879 ++BI;
1880 continue;
1881 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001882
Owen Andersonaccdca12008-06-12 19:25:32 +00001883 // If we need some instructions deleted, do it now.
1884 NumGVNInstr += toErase.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001885
Owen Andersonaccdca12008-06-12 19:25:32 +00001886 // Avoid iterator invalidation.
1887 bool AtStart = BI == BB->begin();
1888 if (!AtStart)
1889 --BI;
1890
1891 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
Chris Lattner8541ede2008-12-01 00:40:32 +00001892 E = toErase.end(); I != E; ++I) {
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001893 DEBUG(errs() << "GVN removed: " << **I << '\n');
Chris Lattner8541ede2008-12-01 00:40:32 +00001894 MD->removeInstruction(*I);
Owen Andersonaccdca12008-06-12 19:25:32 +00001895 (*I)->eraseFromParent();
Bill Wendlingebb6a542008-12-22 21:57:30 +00001896 DEBUG(verifyRemoved(*I));
Chris Lattner8541ede2008-12-01 00:40:32 +00001897 }
Chris Lattner0a5a8d52008-12-09 19:21:47 +00001898 toErase.clear();
Owen Andersonaccdca12008-06-12 19:25:32 +00001899
1900 if (AtStart)
1901 BI = BB->begin();
1902 else
1903 ++BI;
Owen Andersonaccdca12008-06-12 19:25:32 +00001904 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001905
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001906 return ChangedFunction;
Owen Andersonaccdca12008-06-12 19:25:32 +00001907}
1908
Owen Anderson6a903bc2008-06-18 21:41:49 +00001909/// performPRE - Perform a purely local form of PRE that looks for diamond
1910/// control flow patterns and attempts to perform simple PRE at the join point.
1911bool GVN::performPRE(Function& F) {
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001912 bool Changed = false;
Owen Andersonfdf9f162008-06-19 19:54:19 +00001913 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
Chris Lattnerf00aae42008-12-01 07:29:03 +00001914 DenseMap<BasicBlock*, Value*> predMap;
Owen Anderson6a903bc2008-06-18 21:41:49 +00001915 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
1916 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001917 BasicBlock *CurrentBlock = *DI;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001918
Owen Anderson6a903bc2008-06-18 21:41:49 +00001919 // Nothing to PRE in the entry block.
1920 if (CurrentBlock == &F.getEntryBlock()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001921
Owen Anderson6a903bc2008-06-18 21:41:49 +00001922 for (BasicBlock::iterator BI = CurrentBlock->begin(),
1923 BE = CurrentBlock->end(); BI != BE; ) {
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001924 Instruction *CurInst = BI++;
Duncan Sands1efabaa2009-05-06 06:49:50 +00001925
Victor Hernandez5d034492009-09-18 22:35:49 +00001926 if (isa<AllocationInst>(CurInst) || isMalloc(CurInst) ||
1927 isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
Owen Anderson55f1c092009-08-13 21:58:54 +00001928 (CurInst->getType() == Type::getVoidTy(F.getContext())) ||
Duncan Sands1efabaa2009-05-06 06:49:50 +00001929 CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
John Criswell073e4d12009-03-10 15:04:53 +00001930 isa<DbgInfoIntrinsic>(CurInst))
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001931 continue;
Duncan Sands1efabaa2009-05-06 06:49:50 +00001932
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001933 uint32_t ValNo = VN.lookup(CurInst);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001934
Owen Anderson6a903bc2008-06-18 21:41:49 +00001935 // Look for the predecessors for PRE opportunities. We're
1936 // only trying to solve the basic diamond case, where
1937 // a value is computed in the successor and one predecessor,
1938 // but not the other. We also explicitly disallow cases
1939 // where the successor is its own predecessor, because they're
1940 // more complicated to get right.
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001941 unsigned NumWith = 0;
1942 unsigned NumWithout = 0;
1943 BasicBlock *PREPred = 0;
Chris Lattnerf00aae42008-12-01 07:29:03 +00001944 predMap.clear();
1945
Owen Anderson6a903bc2008-06-18 21:41:49 +00001946 for (pred_iterator PI = pred_begin(CurrentBlock),
1947 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
1948 // We're not interested in PRE where the block is its
Owen Anderson1b3ea962008-06-20 01:15:47 +00001949 // own predecessor, on in blocks with predecessors
1950 // that are not reachable.
1951 if (*PI == CurrentBlock) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001952 NumWithout = 2;
Owen Anderson1b3ea962008-06-20 01:15:47 +00001953 break;
1954 } else if (!localAvail.count(*PI)) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001955 NumWithout = 2;
Owen Anderson1b3ea962008-06-20 01:15:47 +00001956 break;
1957 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001958
1959 DenseMap<uint32_t, Value*>::iterator predV =
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001960 localAvail[*PI]->table.find(ValNo);
Owen Anderson1b3ea962008-06-20 01:15:47 +00001961 if (predV == localAvail[*PI]->table.end()) {
Owen Anderson6a903bc2008-06-18 21:41:49 +00001962 PREPred = *PI;
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001963 NumWithout++;
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001964 } else if (predV->second == CurInst) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001965 NumWithout = 2;
Owen Anderson6a903bc2008-06-18 21:41:49 +00001966 } else {
Owen Anderson1b3ea962008-06-20 01:15:47 +00001967 predMap[*PI] = predV->second;
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001968 NumWith++;
Owen Anderson6a903bc2008-06-18 21:41:49 +00001969 }
1970 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001971
Owen Anderson6a903bc2008-06-18 21:41:49 +00001972 // Don't do PRE when it might increase code size, i.e. when
1973 // we would need to insert instructions in more than one pred.
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001974 if (NumWithout != 1 || NumWith == 0)
Owen Anderson6a903bc2008-06-18 21:41:49 +00001975 continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001976
Owen Andersonfdf9f162008-06-19 19:54:19 +00001977 // We can't do PRE safely on a critical edge, so instead we schedule
1978 // the edge to be split and perform the PRE the next time we iterate
1979 // on the function.
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001980 unsigned SuccNum = 0;
Owen Andersonfdf9f162008-06-19 19:54:19 +00001981 for (unsigned i = 0, e = PREPred->getTerminator()->getNumSuccessors();
1982 i != e; ++i)
Owen Anderson2fbfb702008-09-03 23:06:07 +00001983 if (PREPred->getTerminator()->getSuccessor(i) == CurrentBlock) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001984 SuccNum = i;
Owen Andersonfdf9f162008-06-19 19:54:19 +00001985 break;
1986 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001987
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001988 if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
1989 toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
Owen Andersonfdf9f162008-06-19 19:54:19 +00001990 continue;
1991 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001992
Owen Anderson6a903bc2008-06-18 21:41:49 +00001993 // Instantiate the expression the in predecessor that lacked it.
1994 // Because we are going top-down through the block, all value numbers
1995 // will be available in the predecessor by the time we need them. Any
1996 // that weren't original present will have been instantiated earlier
1997 // in this loop.
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001998 Instruction *PREInstr = CurInst->clone(CurInst->getContext());
Owen Anderson6a903bc2008-06-18 21:41:49 +00001999 bool success = true;
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00002000 for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
2001 Value *Op = PREInstr->getOperand(i);
2002 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
2003 continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002004
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00002005 if (Value *V = lookupNumber(PREPred, VN.lookup(Op))) {
2006 PREInstr->setOperand(i, V);
2007 } else {
2008 success = false;
2009 break;
Owen Anderson8e462e92008-07-11 20:05:13 +00002010 }
Owen Anderson6a903bc2008-06-18 21:41:49 +00002011 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002012
Owen Anderson6a903bc2008-06-18 21:41:49 +00002013 // Fail out if we encounter an operand that is not available in
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002014 // the PRE predecessor. This is typically because of loads which
Owen Anderson6a903bc2008-06-18 21:41:49 +00002015 // are not value numbered precisely.
2016 if (!success) {
2017 delete PREInstr;
Bill Wendling3c793442008-12-22 22:14:07 +00002018 DEBUG(verifyRemoved(PREInstr));
Owen Anderson6a903bc2008-06-18 21:41:49 +00002019 continue;
2020 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002021
Owen Anderson6a903bc2008-06-18 21:41:49 +00002022 PREInstr->insertBefore(PREPred->getTerminator());
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00002023 PREInstr->setName(CurInst->getName() + ".pre");
Owen Anderson1b3ea962008-06-20 01:15:47 +00002024 predMap[PREPred] = PREInstr;
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002025 VN.add(PREInstr, ValNo);
Owen Anderson6a903bc2008-06-18 21:41:49 +00002026 NumGVNPRE++;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002027
Owen Anderson6a903bc2008-06-18 21:41:49 +00002028 // Update the availability map to include the new instruction.
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002029 localAvail[PREPred]->table.insert(std::make_pair(ValNo, PREInstr));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002030
Owen Anderson6a903bc2008-06-18 21:41:49 +00002031 // Create a PHI to make the value available in this block.
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00002032 PHINode* Phi = PHINode::Create(CurInst->getType(),
2033 CurInst->getName() + ".pre-phi",
Owen Anderson6a903bc2008-06-18 21:41:49 +00002034 CurrentBlock->begin());
2035 for (pred_iterator PI = pred_begin(CurrentBlock),
2036 PE = pred_end(CurrentBlock); PI != PE; ++PI)
Owen Anderson1b3ea962008-06-20 01:15:47 +00002037 Phi->addIncoming(predMap[*PI], *PI);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002038
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002039 VN.add(Phi, ValNo);
2040 localAvail[CurrentBlock]->table[ValNo] = Phi;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002041
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00002042 CurInst->replaceAllUsesWith(Phi);
Chris Lattnerfa9f99a2008-12-09 22:06:23 +00002043 if (isa<PointerType>(Phi->getType()))
2044 MD->invalidateCachedPointerInfo(Phi);
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00002045 VN.erase(CurInst);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002046
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00002047 DEBUG(errs() << "GVN PRE removed: " << *CurInst << '\n');
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00002048 MD->removeInstruction(CurInst);
2049 CurInst->eraseFromParent();
Bill Wendlingebb6a542008-12-22 21:57:30 +00002050 DEBUG(verifyRemoved(CurInst));
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00002051 Changed = true;
Owen Anderson6a903bc2008-06-18 21:41:49 +00002052 }
2053 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002054
Owen Andersonfdf9f162008-06-19 19:54:19 +00002055 for (SmallVector<std::pair<TerminatorInst*, unsigned>, 4>::iterator
Anton Korobeynikov24600bf2008-12-05 19:38:49 +00002056 I = toSplit.begin(), E = toSplit.end(); I != E; ++I)
Owen Andersonfdf9f162008-06-19 19:54:19 +00002057 SplitCriticalEdge(I->first, I->second, this);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002058
Anton Korobeynikov24600bf2008-12-05 19:38:49 +00002059 return Changed || toSplit.size();
Owen Anderson6a903bc2008-06-18 21:41:49 +00002060}
2061
Bill Wendling456e8852008-12-22 22:32:22 +00002062/// iterateOnFunction - Executes one iteration of GVN
Owen Anderson676070d2007-08-14 18:04:11 +00002063bool GVN::iterateOnFunction(Function &F) {
Nuno Lopese3127f32008-10-10 16:25:50 +00002064 cleanupGlobalSets();
Chris Lattnerbeb216d2008-03-21 21:33:23 +00002065
Owen Anderson98f912b2009-04-01 23:53:49 +00002066 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
2067 DE = df_end(DT->getRootNode()); DI != DE; ++DI) {
2068 if (DI->getIDom())
2069 localAvail[DI->getBlock()] =
2070 new ValueNumberScope(localAvail[DI->getIDom()->getBlock()]);
2071 else
2072 localAvail[DI->getBlock()] = new ValueNumberScope(0);
2073 }
2074
Owen Andersonab6ec2e2007-07-24 17:55:58 +00002075 // Top-down walk of the dominator tree
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002076 bool Changed = false;
Owen Anderson03aacba2008-12-15 03:52:17 +00002077#if 0
2078 // Needed for value numbering with phi construction to work.
Owen Andersonbfe133e2008-12-15 02:03:00 +00002079 ReversePostOrderTraversal<Function*> RPOT(&F);
2080 for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
2081 RE = RPOT.end(); RI != RE; ++RI)
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002082 Changed |= processBlock(*RI);
Owen Anderson03aacba2008-12-15 03:52:17 +00002083#else
2084 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
2085 DE = df_end(DT->getRootNode()); DI != DE; ++DI)
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002086 Changed |= processBlock(DI->getBlock());
Owen Anderson03aacba2008-12-15 03:52:17 +00002087#endif
2088
Chris Lattner1eefa9c2009-09-21 02:42:51 +00002089 return Changed;
Owen Andersonab6ec2e2007-07-24 17:55:58 +00002090}
Nuno Lopese3127f32008-10-10 16:25:50 +00002091
2092void GVN::cleanupGlobalSets() {
2093 VN.clear();
2094 phiMap.clear();
2095
2096 for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
2097 I = localAvail.begin(), E = localAvail.end(); I != E; ++I)
2098 delete I->second;
2099 localAvail.clear();
2100}
Bill Wendling6b18a392008-12-22 21:36:08 +00002101
2102/// verifyRemoved - Verify that the specified instruction does not occur in our
2103/// internal data structures.
Bill Wendlinge7f08e72008-12-22 22:28:56 +00002104void GVN::verifyRemoved(const Instruction *Inst) const {
2105 VN.verifyRemoved(Inst);
Bill Wendling3c793442008-12-22 22:14:07 +00002106
2107 // Walk through the PHI map to make sure the instruction isn't hiding in there
2108 // somewhere.
2109 for (PhiMapType::iterator
Bill Wendlinge7f08e72008-12-22 22:28:56 +00002110 I = phiMap.begin(), E = phiMap.end(); I != E; ++I) {
2111 assert(I->first != Inst && "Inst is still a key in PHI map!");
Bill Wendling3c793442008-12-22 22:14:07 +00002112
2113 for (SmallPtrSet<Instruction*, 4>::iterator
Bill Wendlinge7f08e72008-12-22 22:28:56 +00002114 II = I->second.begin(), IE = I->second.end(); II != IE; ++II) {
2115 assert(*II != Inst && "Inst is still a value in PHI map!");
2116 }
2117 }
2118
2119 // Walk through the value number scope to make sure the instruction isn't
2120 // ferreted away in it.
2121 for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
2122 I = localAvail.begin(), E = localAvail.end(); I != E; ++I) {
2123 const ValueNumberScope *VNS = I->second;
2124
2125 while (VNS) {
2126 for (DenseMap<uint32_t, Value*>::iterator
2127 II = VNS->table.begin(), IE = VNS->table.end(); II != IE; ++II) {
2128 assert(II->second != Inst && "Inst still in value numbering scope!");
2129 }
2130
2131 VNS = VNS->parent;
Bill Wendling3c793442008-12-22 22:14:07 +00002132 }
2133 }
Bill Wendling6b18a392008-12-22 21:36:08 +00002134}