blob: 33ad4e1059d120252983b557490b4a2a7da1ce0d [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 Hernandezf390e042009-10-27 20:05:49 +000036#include "llvm/Analysis/MemoryBuiltins.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"
Chris Lattnerb6c65fa2009-10-10 23:50:30 +000047#include "llvm/Transforms/Utils/SSAUpdater.h"
Duncan Sands26ff6f92008-10-08 07:23:46 +000048#include <cstdio>
Owen Andersonab6ec2e2007-07-24 17:55:58 +000049using namespace llvm;
50
Bill Wendling3c793442008-12-22 22:14:07 +000051STATISTIC(NumGVNInstr, "Number of instructions deleted");
52STATISTIC(NumGVNLoad, "Number of loads deleted");
53STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
Owen Anderson53d546e2008-07-15 16:28:06 +000054STATISTIC(NumGVNBlocks, "Number of blocks merged");
Bill Wendling3c793442008-12-22 22:14:07 +000055STATISTIC(NumPRELoad, "Number of loads PRE'd");
Chris Lattner168be762008-03-22 04:13:49 +000056
Evan Cheng9598f932008-06-20 01:01:07 +000057static cl::opt<bool> EnablePRE("enable-pre",
Owen Andersonaddbe3e2008-07-17 19:41:00 +000058 cl::init(true), cl::Hidden);
Dan Gohmana8f8a852009-06-15 18:30:15 +000059static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
Owen Andersone780d662008-06-19 19:57:25 +000060
Owen Andersonab6ec2e2007-07-24 17:55:58 +000061//===----------------------------------------------------------------------===//
62// ValueTable Class
63//===----------------------------------------------------------------------===//
64
65/// This class holds the mapping between values and value numbers. It is used
66/// as an efficient mechanism to determine the expression-wise equivalence of
67/// two values.
68namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +000069 struct Expression {
Dan Gohmana5b96452009-06-04 22:49:04 +000070 enum ExpressionOpcode { ADD, FADD, SUB, FSUB, MUL, FMUL,
71 UDIV, SDIV, FDIV, UREM, SREM,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000072 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
73 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
74 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
75 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
76 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
Owen Andersonab6ec2e2007-07-24 17:55:58 +000077 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
78 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000079 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
Owen Anderson69057b82008-05-13 08:17:22 +000080 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
Owen Anderson168ad692009-10-19 22:14:22 +000081 INSERTVALUE, EXTRACTVALUE, EMPTY, TOMBSTONE };
Owen Andersonab6ec2e2007-07-24 17:55:58 +000082
83 ExpressionOpcode opcode;
84 const Type* type;
Owen Andersonab6ec2e2007-07-24 17:55:58 +000085 SmallVector<uint32_t, 4> varargs;
Chris Lattner1eefa9c2009-09-21 02:42:51 +000086 Value *function;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000087
Owen Andersonab6ec2e2007-07-24 17:55:58 +000088 Expression() { }
89 Expression(ExpressionOpcode o) : opcode(o) { }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +000090
Owen Andersonab6ec2e2007-07-24 17:55:58 +000091 bool operator==(const Expression &other) const {
92 if (opcode != other.opcode)
93 return false;
94 else if (opcode == EMPTY || opcode == TOMBSTONE)
95 return true;
96 else if (type != other.type)
97 return false;
Owen Anderson09b83ba2007-10-18 19:39:33 +000098 else if (function != other.function)
99 return false;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000100 else {
101 if (varargs.size() != other.varargs.size())
102 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000103
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000104 for (size_t i = 0; i < varargs.size(); ++i)
105 if (varargs[i] != other.varargs[i])
106 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000107
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000108 return true;
109 }
110 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000111
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000112 bool operator!=(const Expression &other) const {
Bill Wendling86f01cb2008-12-22 22:16:31 +0000113 return !(*this == other);
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000114 }
115 };
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000116
Chris Lattner2dd09db2009-09-02 06:11:42 +0000117 class ValueTable {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000118 private:
119 DenseMap<Value*, uint32_t> valueNumbering;
120 DenseMap<Expression, uint32_t> expressionNumbering;
Owen Andersonf7928602008-05-12 20:15:55 +0000121 AliasAnalysis* AA;
122 MemoryDependenceAnalysis* MD;
123 DominatorTree* DT;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000124
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000125 uint32_t nextValueNumber;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000126
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000127 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
128 Expression::ExpressionOpcode getOpcode(CmpInst* C);
129 Expression::ExpressionOpcode getOpcode(CastInst* C);
130 Expression create_expression(BinaryOperator* BO);
131 Expression create_expression(CmpInst* C);
132 Expression create_expression(ShuffleVectorInst* V);
133 Expression create_expression(ExtractElementInst* C);
134 Expression create_expression(InsertElementInst* V);
135 Expression create_expression(SelectInst* V);
136 Expression create_expression(CastInst* C);
137 Expression create_expression(GetElementPtrInst* G);
Owen Anderson09b83ba2007-10-18 19:39:33 +0000138 Expression create_expression(CallInst* C);
Owen Anderson69057b82008-05-13 08:17:22 +0000139 Expression create_expression(Constant* C);
Owen Anderson168ad692009-10-19 22:14:22 +0000140 Expression create_expression(ExtractValueInst* C);
141 Expression create_expression(InsertValueInst* C);
142
143 uint32_t lookup_or_add_call(CallInst* C);
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000144 public:
Dan Gohmanc4971722009-04-01 16:37:47 +0000145 ValueTable() : nextValueNumber(1) { }
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000146 uint32_t lookup_or_add(Value *V);
147 uint32_t lookup(Value *V) const;
148 void add(Value *V, uint32_t num);
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000149 void clear();
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000150 void erase(Value *v);
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000151 unsigned size();
Owen Andersonf7928602008-05-12 20:15:55 +0000152 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
Chris Lattner8541ede2008-12-01 00:40:32 +0000153 AliasAnalysis *getAliasAnalysis() const { return AA; }
Owen Andersonf7928602008-05-12 20:15:55 +0000154 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
155 void setDomTree(DominatorTree* D) { DT = D; }
Owen Anderson3ea90a72008-07-03 17:44:33 +0000156 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
Bill Wendling6b18a392008-12-22 21:36:08 +0000157 void verifyRemoved(const Value *) const;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000158 };
159}
160
161namespace llvm {
Chris Lattner0625bd62007-09-17 18:34:04 +0000162template <> struct DenseMapInfo<Expression> {
Owen Anderson9699a6e2007-08-02 18:16:06 +0000163 static inline Expression getEmptyKey() {
164 return Expression(Expression::EMPTY);
165 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000166
Owen Anderson9699a6e2007-08-02 18:16:06 +0000167 static inline Expression getTombstoneKey() {
168 return Expression(Expression::TOMBSTONE);
169 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000170
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000171 static unsigned getHashValue(const Expression e) {
172 unsigned hash = e.opcode;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000173
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000174 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
Owen Anderson168ad692009-10-19 22:14:22 +0000175 (unsigned)((uintptr_t)e.type >> 9));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000176
Owen Anderson9699a6e2007-08-02 18:16:06 +0000177 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
178 E = e.varargs.end(); I != E; ++I)
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000179 hash = *I + hash * 37;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000180
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000181 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
182 (unsigned)((uintptr_t)e.function >> 9)) +
183 hash * 37;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000184
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000185 return hash;
186 }
Chris Lattner0625bd62007-09-17 18:34:04 +0000187 static bool isEqual(const Expression &LHS, const Expression &RHS) {
188 return LHS == RHS;
189 }
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000190 static bool isPod() { return true; }
191};
192}
193
194//===----------------------------------------------------------------------===//
195// ValueTable Internal Functions
196//===----------------------------------------------------------------------===//
Chris Lattner2876a642008-03-21 21:14:38 +0000197Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000198 switch(BO->getOpcode()) {
Chris Lattner2876a642008-03-21 21:14:38 +0000199 default: // THIS SHOULD NEVER HAPPEN
Torok Edwinfbcc6632009-07-14 16:55:14 +0000200 llvm_unreachable("Binary operator with unknown opcode?");
Chris Lattner2876a642008-03-21 21:14:38 +0000201 case Instruction::Add: return Expression::ADD;
Dan Gohmana5b96452009-06-04 22:49:04 +0000202 case Instruction::FAdd: return Expression::FADD;
Chris Lattner2876a642008-03-21 21:14:38 +0000203 case Instruction::Sub: return Expression::SUB;
Dan Gohmana5b96452009-06-04 22:49:04 +0000204 case Instruction::FSub: return Expression::FSUB;
Chris Lattner2876a642008-03-21 21:14:38 +0000205 case Instruction::Mul: return Expression::MUL;
Dan Gohmana5b96452009-06-04 22:49:04 +0000206 case Instruction::FMul: return Expression::FMUL;
Chris Lattner2876a642008-03-21 21:14:38 +0000207 case Instruction::UDiv: return Expression::UDIV;
208 case Instruction::SDiv: return Expression::SDIV;
209 case Instruction::FDiv: return Expression::FDIV;
210 case Instruction::URem: return Expression::UREM;
211 case Instruction::SRem: return Expression::SREM;
212 case Instruction::FRem: return Expression::FREM;
213 case Instruction::Shl: return Expression::SHL;
214 case Instruction::LShr: return Expression::LSHR;
215 case Instruction::AShr: return Expression::ASHR;
216 case Instruction::And: return Expression::AND;
217 case Instruction::Or: return Expression::OR;
218 case Instruction::Xor: return Expression::XOR;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000219 }
220}
221
222Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
Nick Lewyckya21d3da2009-07-08 03:04:38 +0000223 if (isa<ICmpInst>(C)) {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000224 switch (C->getPredicate()) {
Chris Lattner2876a642008-03-21 21:14:38 +0000225 default: // THIS SHOULD NEVER HAPPEN
Torok Edwinfbcc6632009-07-14 16:55:14 +0000226 llvm_unreachable("Comparison with unknown predicate?");
Chris Lattner2876a642008-03-21 21:14:38 +0000227 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ;
228 case ICmpInst::ICMP_NE: return Expression::ICMPNE;
229 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
230 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
231 case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
232 case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
233 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
234 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
235 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
236 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000237 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +0000238 } else {
239 switch (C->getPredicate()) {
240 default: // THIS SHOULD NEVER HAPPEN
Torok Edwinfbcc6632009-07-14 16:55:14 +0000241 llvm_unreachable("Comparison with unknown predicate?");
Nick Lewyckya21d3da2009-07-08 03:04:38 +0000242 case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
243 case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
244 case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
245 case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
246 case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
247 case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
248 case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
249 case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
250 case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
251 case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
252 case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
253 case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
254 case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
255 case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
256 }
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000257 }
258}
259
Chris Lattner2876a642008-03-21 21:14:38 +0000260Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000261 switch(C->getOpcode()) {
Chris Lattner2876a642008-03-21 21:14:38 +0000262 default: // THIS SHOULD NEVER HAPPEN
Torok Edwinfbcc6632009-07-14 16:55:14 +0000263 llvm_unreachable("Cast operator with unknown opcode?");
Chris Lattner2876a642008-03-21 21:14:38 +0000264 case Instruction::Trunc: return Expression::TRUNC;
265 case Instruction::ZExt: return Expression::ZEXT;
266 case Instruction::SExt: return Expression::SEXT;
267 case Instruction::FPToUI: return Expression::FPTOUI;
268 case Instruction::FPToSI: return Expression::FPTOSI;
269 case Instruction::UIToFP: return Expression::UITOFP;
270 case Instruction::SIToFP: return Expression::SITOFP;
271 case Instruction::FPTrunc: return Expression::FPTRUNC;
272 case Instruction::FPExt: return Expression::FPEXT;
273 case Instruction::PtrToInt: return Expression::PTRTOINT;
274 case Instruction::IntToPtr: return Expression::INTTOPTR;
275 case Instruction::BitCast: return Expression::BITCAST;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000276 }
277}
278
Owen Anderson09b83ba2007-10-18 19:39:33 +0000279Expression ValueTable::create_expression(CallInst* C) {
280 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000281
Owen Anderson09b83ba2007-10-18 19:39:33 +0000282 e.type = C->getType();
Owen Anderson09b83ba2007-10-18 19:39:33 +0000283 e.function = C->getCalledFunction();
284 e.opcode = Expression::CALL;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000285
Owen Anderson09b83ba2007-10-18 19:39:33 +0000286 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
287 I != E; ++I)
Owen Anderson1e73f292008-04-11 05:11:49 +0000288 e.varargs.push_back(lookup_or_add(*I));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000289
Owen Anderson09b83ba2007-10-18 19:39:33 +0000290 return e;
291}
292
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000293Expression ValueTable::create_expression(BinaryOperator* BO) {
294 Expression e;
Owen Anderson168ad692009-10-19 22:14:22 +0000295 e.varargs.push_back(lookup_or_add(BO->getOperand(0)));
296 e.varargs.push_back(lookup_or_add(BO->getOperand(1)));
Owen Anderson09b83ba2007-10-18 19:39:33 +0000297 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000298 e.type = BO->getType();
299 e.opcode = getOpcode(BO);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000300
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000301 return e;
302}
303
304Expression ValueTable::create_expression(CmpInst* C) {
305 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000306
Owen Anderson168ad692009-10-19 22:14:22 +0000307 e.varargs.push_back(lookup_or_add(C->getOperand(0)));
308 e.varargs.push_back(lookup_or_add(C->getOperand(1)));
Owen Anderson09b83ba2007-10-18 19:39:33 +0000309 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000310 e.type = C->getType();
311 e.opcode = getOpcode(C);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000312
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000313 return e;
314}
315
316Expression ValueTable::create_expression(CastInst* C) {
317 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000318
Owen Anderson168ad692009-10-19 22:14:22 +0000319 e.varargs.push_back(lookup_or_add(C->getOperand(0)));
Owen Anderson09b83ba2007-10-18 19:39:33 +0000320 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000321 e.type = C->getType();
322 e.opcode = getOpcode(C);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000323
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000324 return e;
325}
326
327Expression ValueTable::create_expression(ShuffleVectorInst* S) {
328 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000329
Owen Anderson168ad692009-10-19 22:14:22 +0000330 e.varargs.push_back(lookup_or_add(S->getOperand(0)));
331 e.varargs.push_back(lookup_or_add(S->getOperand(1)));
332 e.varargs.push_back(lookup_or_add(S->getOperand(2)));
Owen Anderson09b83ba2007-10-18 19:39:33 +0000333 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000334 e.type = S->getType();
335 e.opcode = Expression::SHUFFLE;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000336
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000337 return e;
338}
339
340Expression ValueTable::create_expression(ExtractElementInst* E) {
341 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000342
Owen Anderson168ad692009-10-19 22:14:22 +0000343 e.varargs.push_back(lookup_or_add(E->getOperand(0)));
344 e.varargs.push_back(lookup_or_add(E->getOperand(1)));
Owen Anderson09b83ba2007-10-18 19:39:33 +0000345 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000346 e.type = E->getType();
347 e.opcode = Expression::EXTRACT;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000348
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000349 return e;
350}
351
352Expression ValueTable::create_expression(InsertElementInst* I) {
353 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000354
Owen Anderson168ad692009-10-19 22:14:22 +0000355 e.varargs.push_back(lookup_or_add(I->getOperand(0)));
356 e.varargs.push_back(lookup_or_add(I->getOperand(1)));
357 e.varargs.push_back(lookup_or_add(I->getOperand(2)));
Owen Anderson09b83ba2007-10-18 19:39:33 +0000358 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000359 e.type = I->getType();
360 e.opcode = Expression::INSERT;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000361
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000362 return e;
363}
364
365Expression ValueTable::create_expression(SelectInst* I) {
366 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000367
Owen Anderson168ad692009-10-19 22:14:22 +0000368 e.varargs.push_back(lookup_or_add(I->getCondition()));
369 e.varargs.push_back(lookup_or_add(I->getTrueValue()));
370 e.varargs.push_back(lookup_or_add(I->getFalseValue()));
Owen Anderson09b83ba2007-10-18 19:39:33 +0000371 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000372 e.type = I->getType();
373 e.opcode = Expression::SELECT;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000374
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000375 return e;
376}
377
378Expression ValueTable::create_expression(GetElementPtrInst* G) {
379 Expression e;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000380
Owen Anderson168ad692009-10-19 22:14:22 +0000381 e.varargs.push_back(lookup_or_add(G->getPointerOperand()));
Owen Anderson09b83ba2007-10-18 19:39:33 +0000382 e.function = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000383 e.type = G->getType();
384 e.opcode = Expression::GEP;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000385
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000386 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
387 I != E; ++I)
Owen Anderson1e73f292008-04-11 05:11:49 +0000388 e.varargs.push_back(lookup_or_add(*I));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000389
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000390 return e;
391}
392
Owen Anderson168ad692009-10-19 22:14:22 +0000393Expression ValueTable::create_expression(ExtractValueInst* E) {
394 Expression e;
395
396 e.varargs.push_back(lookup_or_add(E->getAggregateOperand()));
397 for (ExtractValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
398 II != IE; ++II)
399 e.varargs.push_back(*II);
400 e.function = 0;
401 e.type = E->getType();
402 e.opcode = Expression::EXTRACTVALUE;
403
404 return e;
405}
406
407Expression ValueTable::create_expression(InsertValueInst* E) {
408 Expression e;
409
410 e.varargs.push_back(lookup_or_add(E->getAggregateOperand()));
411 e.varargs.push_back(lookup_or_add(E->getInsertedValueOperand()));
412 for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
413 II != IE; ++II)
414 e.varargs.push_back(*II);
415 e.function = 0;
416 e.type = E->getType();
417 e.opcode = Expression::INSERTVALUE;
418
419 return e;
420}
421
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000422//===----------------------------------------------------------------------===//
423// ValueTable External Functions
424//===----------------------------------------------------------------------===//
425
Owen Anderson6a903bc2008-06-18 21:41:49 +0000426/// add - Insert a value into the table with a specified value number.
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000427void ValueTable::add(Value *V, uint32_t num) {
Owen Anderson6a903bc2008-06-18 21:41:49 +0000428 valueNumbering.insert(std::make_pair(V, num));
429}
430
Owen Anderson168ad692009-10-19 22:14:22 +0000431uint32_t ValueTable::lookup_or_add_call(CallInst* C) {
432 if (AA->doesNotAccessMemory(C)) {
433 Expression exp = create_expression(C);
434 uint32_t& e = expressionNumbering[exp];
435 if (!e) e = nextValueNumber++;
436 valueNumbering[C] = e;
437 return e;
438 } else if (AA->onlyReadsMemory(C)) {
439 Expression exp = create_expression(C);
440 uint32_t& e = expressionNumbering[exp];
441 if (!e) {
442 e = nextValueNumber++;
443 valueNumbering[C] = e;
444 return e;
445 }
446
447 MemDepResult local_dep = MD->getDependency(C);
448
449 if (!local_dep.isDef() && !local_dep.isNonLocal()) {
450 valueNumbering[C] = nextValueNumber;
451 return nextValueNumber++;
452 }
453
454 if (local_dep.isDef()) {
455 CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
456
457 if (local_cdep->getNumOperands() != C->getNumOperands()) {
458 valueNumbering[C] = nextValueNumber;
459 return nextValueNumber++;
460 }
461
462 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
463 uint32_t c_vn = lookup_or_add(C->getOperand(i));
464 uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
465 if (c_vn != cd_vn) {
466 valueNumbering[C] = nextValueNumber;
467 return nextValueNumber++;
468 }
469 }
470
471 uint32_t v = lookup_or_add(local_cdep);
472 valueNumbering[C] = v;
473 return v;
474 }
475
476 // Non-local case.
477 const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
478 MD->getNonLocalCallDependency(CallSite(C));
479 // FIXME: call/call dependencies for readonly calls should return def, not
480 // clobber! Move the checking logic to MemDep!
481 CallInst* cdep = 0;
482
483 // Check to see if we have a single dominating call instruction that is
484 // identical to C.
485 for (unsigned i = 0, e = deps.size(); i != e; ++i) {
486 const MemoryDependenceAnalysis::NonLocalDepEntry *I = &deps[i];
487 // Ignore non-local dependencies.
488 if (I->second.isNonLocal())
489 continue;
490
491 // We don't handle non-depedencies. If we already have a call, reject
492 // instruction dependencies.
493 if (I->second.isClobber() || cdep != 0) {
494 cdep = 0;
495 break;
496 }
497
498 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->second.getInst());
499 // FIXME: All duplicated with non-local case.
500 if (NonLocalDepCall && DT->properlyDominates(I->first, C->getParent())){
501 cdep = NonLocalDepCall;
502 continue;
503 }
504
505 cdep = 0;
506 break;
507 }
508
509 if (!cdep) {
510 valueNumbering[C] = nextValueNumber;
511 return nextValueNumber++;
512 }
513
514 if (cdep->getNumOperands() != C->getNumOperands()) {
515 valueNumbering[C] = nextValueNumber;
516 return nextValueNumber++;
517 }
518 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
519 uint32_t c_vn = lookup_or_add(C->getOperand(i));
520 uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
521 if (c_vn != cd_vn) {
522 valueNumbering[C] = nextValueNumber;
523 return nextValueNumber++;
524 }
525 }
526
527 uint32_t v = lookup_or_add(cdep);
528 valueNumbering[C] = v;
529 return v;
530
531 } else {
532 valueNumbering[C] = nextValueNumber;
533 return nextValueNumber++;
534 }
535}
536
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000537/// lookup_or_add - Returns the value number for the specified value, assigning
538/// it a new number if it did not have one before.
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000539uint32_t ValueTable::lookup_or_add(Value *V) {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000540 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
541 if (VI != valueNumbering.end())
542 return VI->second;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000543
Owen Anderson168ad692009-10-19 22:14:22 +0000544 if (!isa<Instruction>(V)) {
Owen Anderson1059b5b2009-10-19 21:14:57 +0000545 valueNumbering[V] = nextValueNumber;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000546 return nextValueNumber++;
547 }
Owen Anderson168ad692009-10-19 22:14:22 +0000548
549 Instruction* I = cast<Instruction>(V);
550 Expression exp;
551 switch (I->getOpcode()) {
552 case Instruction::Call:
553 return lookup_or_add_call(cast<CallInst>(I));
554 case Instruction::Add:
555 case Instruction::FAdd:
556 case Instruction::Sub:
557 case Instruction::FSub:
558 case Instruction::Mul:
559 case Instruction::FMul:
560 case Instruction::UDiv:
561 case Instruction::SDiv:
562 case Instruction::FDiv:
563 case Instruction::URem:
564 case Instruction::SRem:
565 case Instruction::FRem:
566 case Instruction::Shl:
567 case Instruction::LShr:
568 case Instruction::AShr:
569 case Instruction::And:
570 case Instruction::Or :
571 case Instruction::Xor:
572 exp = create_expression(cast<BinaryOperator>(I));
573 break;
574 case Instruction::ICmp:
575 case Instruction::FCmp:
576 exp = create_expression(cast<CmpInst>(I));
577 break;
578 case Instruction::Trunc:
579 case Instruction::ZExt:
580 case Instruction::SExt:
581 case Instruction::FPToUI:
582 case Instruction::FPToSI:
583 case Instruction::UIToFP:
584 case Instruction::SIToFP:
585 case Instruction::FPTrunc:
586 case Instruction::FPExt:
587 case Instruction::PtrToInt:
588 case Instruction::IntToPtr:
589 case Instruction::BitCast:
590 exp = create_expression(cast<CastInst>(I));
591 break;
592 case Instruction::Select:
593 exp = create_expression(cast<SelectInst>(I));
594 break;
595 case Instruction::ExtractElement:
596 exp = create_expression(cast<ExtractElementInst>(I));
597 break;
598 case Instruction::InsertElement:
599 exp = create_expression(cast<InsertElementInst>(I));
600 break;
601 case Instruction::ShuffleVector:
602 exp = create_expression(cast<ShuffleVectorInst>(I));
603 break;
604 case Instruction::ExtractValue:
605 exp = create_expression(cast<ExtractValueInst>(I));
606 break;
607 case Instruction::InsertValue:
608 exp = create_expression(cast<InsertValueInst>(I));
609 break;
610 case Instruction::GetElementPtr:
611 exp = create_expression(cast<GetElementPtrInst>(I));
612 break;
613 default:
614 valueNumbering[V] = nextValueNumber;
615 return nextValueNumber++;
616 }
617
618 uint32_t& e = expressionNumbering[exp];
619 if (!e) e = nextValueNumber++;
620 valueNumbering[V] = e;
621 return e;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000622}
623
624/// lookup - Returns the value number of the specified value. Fails if
625/// the value has not yet been numbered.
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000626uint32_t ValueTable::lookup(Value *V) const {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000627 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
Chris Lattner2876a642008-03-21 21:14:38 +0000628 assert(VI != valueNumbering.end() && "Value not numbered?");
629 return VI->second;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000630}
631
632/// clear - Remove all entries from the ValueTable
633void ValueTable::clear() {
634 valueNumbering.clear();
635 expressionNumbering.clear();
636 nextValueNumber = 1;
637}
638
Owen Anderson10ffa862007-07-31 23:27:13 +0000639/// erase - Remove a value from the value numbering
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000640void ValueTable::erase(Value *V) {
Owen Anderson10ffa862007-07-31 23:27:13 +0000641 valueNumbering.erase(V);
642}
643
Bill Wendling6b18a392008-12-22 21:36:08 +0000644/// verifyRemoved - Verify that the value is removed from all internal data
645/// structures.
646void ValueTable::verifyRemoved(const Value *V) const {
647 for (DenseMap<Value*, uint32_t>::iterator
648 I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
649 assert(I->first != V && "Inst still occurs in value numbering map!");
650 }
651}
652
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000653//===----------------------------------------------------------------------===//
Bill Wendling456e8852008-12-22 22:32:22 +0000654// GVN Pass
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000655//===----------------------------------------------------------------------===//
656
657namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +0000658 struct ValueNumberScope {
Owen Anderson1b3ea962008-06-20 01:15:47 +0000659 ValueNumberScope* parent;
660 DenseMap<uint32_t, Value*> table;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000661
Owen Anderson1b3ea962008-06-20 01:15:47 +0000662 ValueNumberScope(ValueNumberScope* p) : parent(p) { }
663 };
664}
665
666namespace {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000667
Chris Lattner2dd09db2009-09-02 06:11:42 +0000668 class GVN : public FunctionPass {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000669 bool runOnFunction(Function &F);
670 public:
671 static char ID; // Pass identification, replacement for typeid
Evan Cheng5a6b9c42009-10-30 20:12:24 +0000672 GVN(bool nopre = false) : FunctionPass(&ID), NoPRE(nopre) { }
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000673
674 private:
Evan Cheng5a6b9c42009-10-30 20:12:24 +0000675 bool NoPRE;
Chris Lattner8541ede2008-12-01 00:40:32 +0000676 MemoryDependenceAnalysis *MD;
677 DominatorTree *DT;
678
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000679 ValueTable VN;
Owen Anderson1b3ea962008-06-20 01:15:47 +0000680 DenseMap<BasicBlock*, ValueNumberScope*> localAvail;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000681
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000682 // This transformation requires dominator postdominator info
683 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000684 AU.addRequired<DominatorTree>();
685 AU.addRequired<MemoryDependenceAnalysis>();
Owen Anderson09b83ba2007-10-18 19:39:33 +0000686 AU.addRequired<AliasAnalysis>();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000687
Owen Anderson54e02192008-06-23 17:49:45 +0000688 AU.addPreserved<DominatorTree>();
Owen Anderson09b83ba2007-10-18 19:39:33 +0000689 AU.addPreserved<AliasAnalysis>();
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000690 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000691
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000692 // Helper fuctions
693 // FIXME: eliminate or document these better
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000694 bool processLoad(LoadInst* L,
Chris Lattner804209d2008-03-21 22:01:16 +0000695 SmallVectorImpl<Instruction*> &toErase);
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000696 bool processInstruction(Instruction *I,
Chris Lattner804209d2008-03-21 22:01:16 +0000697 SmallVectorImpl<Instruction*> &toErase);
Owen Anderson9699a6e2007-08-02 18:16:06 +0000698 bool processNonLocalLoad(LoadInst* L,
Chris Lattner804209d2008-03-21 22:01:16 +0000699 SmallVectorImpl<Instruction*> &toErase);
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000700 bool processBlock(BasicBlock *BB);
Owen Anderson6a903bc2008-06-18 21:41:49 +0000701 void dump(DenseMap<uint32_t, Value*>& d);
Owen Anderson676070d2007-08-14 18:04:11 +0000702 bool iterateOnFunction(Function &F);
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000703 Value *CollapsePhi(PHINode* p);
Owen Anderson6a903bc2008-06-18 21:41:49 +0000704 bool performPRE(Function& F);
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000705 Value *lookupNumber(BasicBlock *BB, uint32_t num);
Nuno Lopese3127f32008-10-10 16:25:50 +0000706 void cleanupGlobalSets();
Bill Wendling6b18a392008-12-22 21:36:08 +0000707 void verifyRemoved(const Instruction *I) const;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000708 };
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000709
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000710 char GVN::ID = 0;
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000711}
712
713// createGVNPass - The public interface to this file...
Evan Cheng5a6b9c42009-10-30 20:12:24 +0000714FunctionPass *llvm::createGVNPass(bool NoPRE) { return new GVN(NoPRE); }
Owen Andersonab6ec2e2007-07-24 17:55:58 +0000715
716static RegisterPass<GVN> X("gvn",
717 "Global Value Numbering");
718
Owen Anderson6a903bc2008-06-18 21:41:49 +0000719void GVN::dump(DenseMap<uint32_t, Value*>& d) {
Owen Anderson5e5599b2007-07-25 19:57:03 +0000720 printf("{\n");
Owen Anderson6a903bc2008-06-18 21:41:49 +0000721 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
Owen Anderson5e5599b2007-07-25 19:57:03 +0000722 E = d.end(); I != E; ++I) {
Owen Anderson6a903bc2008-06-18 21:41:49 +0000723 printf("%d\n", I->first);
Owen Anderson5e5599b2007-07-25 19:57:03 +0000724 I->second->dump();
725 }
726 printf("}\n");
727}
728
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000729static bool isSafeReplacement(PHINode* p, Instruction *inst) {
Owen Anderson109ca5a2009-08-26 22:55:11 +0000730 if (!isa<PHINode>(inst))
731 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000732
Owen Anderson109ca5a2009-08-26 22:55:11 +0000733 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
734 UI != E; ++UI)
735 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
736 if (use_phi->getParent() == inst->getParent())
737 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000738
Owen Anderson109ca5a2009-08-26 22:55:11 +0000739 return true;
740}
741
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000742Value *GVN::CollapsePhi(PHINode *PN) {
743 Value *ConstVal = PN->hasConstantValue(DT);
744 if (!ConstVal) return 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000745
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000746 Instruction *Inst = dyn_cast<Instruction>(ConstVal);
747 if (!Inst)
748 return ConstVal;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000749
Chris Lattner1eefa9c2009-09-21 02:42:51 +0000750 if (DT->dominates(Inst, PN))
751 if (isSafeReplacement(PN, Inst))
752 return Inst;
Owen Andersonf5023a72007-08-16 22:51:56 +0000753 return 0;
754}
Owen Anderson5e5599b2007-07-25 19:57:03 +0000755
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000756/// IsValueFullyAvailableInBlock - Return true if we can prove that the value
757/// we're analyzing is fully available in the specified block. As we go, keep
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000758/// track of which blocks we know are fully alive in FullyAvailableBlocks. This
759/// map is actually a tri-state map with the following values:
760/// 0) we know the block *is not* fully available.
761/// 1) we know the block *is* fully available.
762/// 2) we do not know whether the block is fully available or not, but we are
763/// currently speculating that it will be.
764/// 3) we are speculating for this block and have used that to speculate for
765/// other blocks.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000766static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000767 DenseMap<BasicBlock*, char> &FullyAvailableBlocks) {
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000768 // Optimistically assume that the block is fully available and check to see
769 // if we already know about this block in one lookup.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000770 std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000771 FullyAvailableBlocks.insert(std::make_pair(BB, 2));
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000772
773 // If the entry already existed for this block, return the precomputed value.
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000774 if (!IV.second) {
775 // If this is a speculative "available" value, mark it as being used for
776 // speculation of other blocks.
777 if (IV.first->second == 2)
778 IV.first->second = 3;
779 return IV.first->second != 0;
780 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000781
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000782 // Otherwise, see if it is fully available in all predecessors.
783 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000784
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000785 // If this block has no predecessors, it isn't live-in here.
786 if (PI == PE)
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000787 goto SpeculationFailure;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000788
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000789 for (; PI != PE; ++PI)
790 // If the value isn't fully available in one of our predecessors, then it
791 // isn't fully available in this block either. Undo our previous
792 // optimistic assumption and bail out.
793 if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000794 goto SpeculationFailure;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000795
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000796 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000797
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000798// SpeculationFailure - If we get here, we found out that this is not, after
799// all, a fully-available block. We have a problem if we speculated on this and
800// used the speculation to mark other blocks as available.
801SpeculationFailure:
802 char &BBVal = FullyAvailableBlocks[BB];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000803
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000804 // If we didn't speculate on this, just return with it set to false.
805 if (BBVal == 2) {
806 BBVal = 0;
807 return false;
808 }
809
810 // If we did speculate on this value, we could have blocks set to 1 that are
811 // incorrect. Walk the (transitive) successors of this block and mark them as
812 // 0 if set to one.
813 SmallVector<BasicBlock*, 32> BBWorklist;
814 BBWorklist.push_back(BB);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000815
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000816 while (!BBWorklist.empty()) {
817 BasicBlock *Entry = BBWorklist.pop_back_val();
818 // Note that this sets blocks to 0 (unavailable) if they happen to not
819 // already be in FullyAvailableBlocks. This is safe.
820 char &EntryVal = FullyAvailableBlocks[Entry];
821 if (EntryVal == 0) continue; // Already unavailable.
822
823 // Mark as unavailable.
824 EntryVal = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000825
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000826 for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I)
827 BBWorklist.push_back(*I);
828 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000829
Chris Lattnerd2a653a2008-12-05 07:49:08 +0000830 return false;
Chris Lattner1db9bbe2008-12-02 08:16:11 +0000831}
832
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000833
Chris Lattner9045f232009-09-21 17:24:04 +0000834/// CanCoerceMustAliasedValueToLoad - Return true if
835/// CoerceAvailableValueToLoadType will succeed.
836static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
837 const Type *LoadTy,
838 const TargetData &TD) {
839 // If the loaded or stored value is an first class array or struct, don't try
840 // to transform them. We need to be able to bitcast to integer.
841 if (isa<StructType>(LoadTy) || isa<ArrayType>(LoadTy) ||
842 isa<StructType>(StoredVal->getType()) ||
843 isa<ArrayType>(StoredVal->getType()))
844 return false;
845
846 // The store has to be at least as big as the load.
847 if (TD.getTypeSizeInBits(StoredVal->getType()) <
848 TD.getTypeSizeInBits(LoadTy))
849 return false;
850
851 return true;
852}
853
854
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000855/// CoerceAvailableValueToLoadType - If we saw a store of a value to memory, and
856/// then a load from a must-aliased pointer of a different type, try to coerce
857/// the stored value. LoadedTy is the type of the load we want to replace and
858/// InsertPt is the place to insert new instructions.
859///
860/// If we can't do it, return null.
861static Value *CoerceAvailableValueToLoadType(Value *StoredVal,
862 const Type *LoadedTy,
863 Instruction *InsertPt,
864 const TargetData &TD) {
Chris Lattner9045f232009-09-21 17:24:04 +0000865 if (!CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, TD))
866 return 0;
867
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000868 const Type *StoredValTy = StoredVal->getType();
869
870 uint64_t StoreSize = TD.getTypeSizeInBits(StoredValTy);
871 uint64_t LoadSize = TD.getTypeSizeInBits(LoadedTy);
872
873 // If the store and reload are the same size, we can always reuse it.
874 if (StoreSize == LoadSize) {
875 if (isa<PointerType>(StoredValTy) && isa<PointerType>(LoadedTy)) {
876 // Pointer to Pointer -> use bitcast.
877 return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
878 }
879
880 // Convert source pointers to integers, which can be bitcast.
881 if (isa<PointerType>(StoredValTy)) {
882 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
883 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
884 }
885
886 const Type *TypeToCastTo = LoadedTy;
887 if (isa<PointerType>(TypeToCastTo))
888 TypeToCastTo = TD.getIntPtrType(StoredValTy->getContext());
889
890 if (StoredValTy != TypeToCastTo)
891 StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
892
893 // Cast to pointer if the load needs a pointer type.
894 if (isa<PointerType>(LoadedTy))
895 StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
896
897 return StoredVal;
898 }
899
900 // If the loaded value is smaller than the available value, then we can
901 // extract out a piece from it. If the available value is too small, then we
902 // can't do anything.
Chris Lattner9045f232009-09-21 17:24:04 +0000903 assert(StoreSize >= LoadSize && "CanCoerceMustAliasedValueToLoad fail");
Chris Lattnera0aa8fb2009-09-20 20:09:34 +0000904
905 // Convert source pointers to integers, which can be manipulated.
906 if (isa<PointerType>(StoredValTy)) {
907 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
908 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
909 }
910
911 // Convert vectors and fp to integer, which can be manipulated.
912 if (!isa<IntegerType>(StoredValTy)) {
913 StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
914 StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
915 }
916
917 // If this is a big-endian system, we need to shift the value down to the low
918 // bits so that a truncate will work.
919 if (TD.isBigEndian()) {
920 Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
921 StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
922 }
923
924 // Truncate the integer to the right size now.
925 const Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
926 StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
927
928 if (LoadedTy == NewIntTy)
929 return StoredVal;
930
931 // If the result is a pointer, inttoptr.
932 if (isa<PointerType>(LoadedTy))
933 return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
934
935 // Otherwise, bitcast.
936 return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
937}
938
Chris Lattnerd28f9082009-09-21 06:24:16 +0000939/// GetBaseWithConstantOffset - Analyze the specified pointer to see if it can
940/// be expressed as a base pointer plus a constant offset. Return the base and
941/// offset to the caller.
942static Value *GetBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
Chris Lattner4d8af2f2009-09-21 06:48:08 +0000943 const TargetData &TD) {
Chris Lattnerd28f9082009-09-21 06:24:16 +0000944 Operator *PtrOp = dyn_cast<Operator>(Ptr);
945 if (PtrOp == 0) return Ptr;
946
947 // Just look through bitcasts.
948 if (PtrOp->getOpcode() == Instruction::BitCast)
949 return GetBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
950
951 // If this is a GEP with constant indices, we can look through it.
952 GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
953 if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
954
955 gep_type_iterator GTI = gep_type_begin(GEP);
956 for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
957 ++I, ++GTI) {
958 ConstantInt *OpC = cast<ConstantInt>(*I);
959 if (OpC->isZero()) continue;
960
961 // Handle a struct and array indices which add their offset to the pointer.
962 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner4d8af2f2009-09-21 06:48:08 +0000963 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
Chris Lattnerd28f9082009-09-21 06:24:16 +0000964 } else {
Chris Lattner4d8af2f2009-09-21 06:48:08 +0000965 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnerd28f9082009-09-21 06:24:16 +0000966 Offset += OpC->getSExtValue()*Size;
967 }
968 }
969
970 // Re-sign extend from the pointer size if needed to get overflow edge cases
971 // right.
Chris Lattner4d8af2f2009-09-21 06:48:08 +0000972 unsigned PtrSize = TD.getPointerSizeInBits();
Chris Lattnerd28f9082009-09-21 06:24:16 +0000973 if (PtrSize < 64)
974 Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
975
976 return GetBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
977}
978
979
980/// AnalyzeLoadFromClobberingStore - This function is called when we have a
981/// memdep query of a load that ends up being a clobbering store. This means
982/// that the store *may* provide bits used by the load but we can't be sure
983/// because the pointers don't mustalias. Check this case to see if there is
984/// anything more we can do before we give up. This returns -1 if we have to
985/// give up, or a byte number in the stored value of the piece that feeds the
986/// load.
987static int AnalyzeLoadFromClobberingStore(LoadInst *L, StoreInst *DepSI,
Chris Lattner4d8af2f2009-09-21 06:48:08 +0000988 const TargetData &TD) {
Chris Lattner9045f232009-09-21 17:24:04 +0000989 // If the loaded or stored value is an first class array or struct, don't try
990 // to transform them. We need to be able to bitcast to integer.
991 if (isa<StructType>(L->getType()) || isa<ArrayType>(L->getType()) ||
992 isa<StructType>(DepSI->getOperand(0)->getType()) ||
993 isa<ArrayType>(DepSI->getOperand(0)->getType()))
994 return -1;
995
Chris Lattnerd28f9082009-09-21 06:24:16 +0000996 int64_t StoreOffset = 0, LoadOffset = 0;
997 Value *StoreBase =
Chris Lattner4d8af2f2009-09-21 06:48:08 +0000998 GetBaseWithConstantOffset(DepSI->getPointerOperand(), StoreOffset, TD);
Chris Lattnerd28f9082009-09-21 06:24:16 +0000999 Value *LoadBase =
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001000 GetBaseWithConstantOffset(L->getPointerOperand(), LoadOffset, TD);
Chris Lattnerd28f9082009-09-21 06:24:16 +00001001 if (StoreBase != LoadBase)
1002 return -1;
1003
1004 // If the load and store are to the exact same address, they should have been
1005 // a must alias. AA must have gotten confused.
1006 // FIXME: Study to see if/when this happens.
1007 if (LoadOffset == StoreOffset) {
1008#if 0
1009 errs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
1010 << "Base = " << *StoreBase << "\n"
1011 << "Store Ptr = " << *DepSI->getPointerOperand() << "\n"
1012 << "Store Offs = " << StoreOffset << " - " << *DepSI << "\n"
1013 << "Load Ptr = " << *L->getPointerOperand() << "\n"
1014 << "Load Offs = " << LoadOffset << " - " << *L << "\n\n";
1015 errs() << "'" << L->getParent()->getParent()->getName() << "'"
1016 << *L->getParent();
1017#endif
1018 return -1;
1019 }
1020
1021 // If the load and store don't overlap at all, the store doesn't provide
1022 // anything to the load. In this case, they really don't alias at all, AA
1023 // must have gotten confused.
1024 // FIXME: Investigate cases where this bails out, e.g. rdar://7238614. Then
1025 // remove this check, as it is duplicated with what we have below.
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001026 uint64_t StoreSize = TD.getTypeSizeInBits(DepSI->getOperand(0)->getType());
1027 uint64_t LoadSize = TD.getTypeSizeInBits(L->getType());
Chris Lattnerd28f9082009-09-21 06:24:16 +00001028
1029 if ((StoreSize & 7) | (LoadSize & 7))
1030 return -1;
1031 StoreSize >>= 3; // Convert to bytes.
1032 LoadSize >>= 3;
1033
1034
1035 bool isAAFailure = false;
1036 if (StoreOffset < LoadOffset) {
1037 isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
1038 } else {
1039 isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
1040 }
1041 if (isAAFailure) {
1042#if 0
1043 errs() << "STORE LOAD DEP WITH COMMON BASE:\n"
1044 << "Base = " << *StoreBase << "\n"
1045 << "Store Ptr = " << *DepSI->getPointerOperand() << "\n"
1046 << "Store Offs = " << StoreOffset << " - " << *DepSI << "\n"
1047 << "Load Ptr = " << *L->getPointerOperand() << "\n"
1048 << "Load Offs = " << LoadOffset << " - " << *L << "\n\n";
1049 errs() << "'" << L->getParent()->getParent()->getName() << "'"
1050 << *L->getParent();
1051#endif
1052 return -1;
1053 }
1054
1055 // If the Load isn't completely contained within the stored bits, we don't
1056 // have all the bits to feed it. We could do something crazy in the future
1057 // (issue a smaller load then merge the bits in) but this seems unlikely to be
1058 // valuable.
1059 if (StoreOffset > LoadOffset ||
1060 StoreOffset+StoreSize < LoadOffset+LoadSize)
1061 return -1;
1062
1063 // Okay, we can do this transformation. Return the number of bytes into the
1064 // store that the load is.
1065 return LoadOffset-StoreOffset;
1066}
1067
1068
1069/// GetStoreValueForLoad - This function is called when we have a
1070/// memdep query of a load that ends up being a clobbering store. This means
1071/// that the store *may* provide bits used by the load but we can't be sure
1072/// because the pointers don't mustalias. Check this case to see if there is
1073/// anything more we can do before we give up.
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001074static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
1075 const Type *LoadTy,
1076 Instruction *InsertPt, const TargetData &TD){
Chris Lattnerd28f9082009-09-21 06:24:16 +00001077 LLVMContext &Ctx = SrcVal->getType()->getContext();
1078
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001079 uint64_t StoreSize = TD.getTypeSizeInBits(SrcVal->getType())/8;
1080 uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy)/8;
Chris Lattnerd28f9082009-09-21 06:24:16 +00001081
1082
1083 // Compute which bits of the stored value are being used by the load. Convert
1084 // to an integer type to start with.
1085 if (isa<PointerType>(SrcVal->getType()))
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001086 SrcVal = new PtrToIntInst(SrcVal, TD.getIntPtrType(Ctx), "tmp", InsertPt);
Chris Lattnerd28f9082009-09-21 06:24:16 +00001087 if (!isa<IntegerType>(SrcVal->getType()))
1088 SrcVal = new BitCastInst(SrcVal, IntegerType::get(Ctx, StoreSize*8),
1089 "tmp", InsertPt);
1090
1091 // Shift the bits to the least significant depending on endianness.
1092 unsigned ShiftAmt;
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001093 if (TD.isLittleEndian()) {
Chris Lattnerd28f9082009-09-21 06:24:16 +00001094 ShiftAmt = Offset*8;
1095 } else {
Chris Lattner24705382009-09-21 17:55:47 +00001096 ShiftAmt = (StoreSize-LoadSize-Offset)*8;
Chris Lattnerd28f9082009-09-21 06:24:16 +00001097 }
1098
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001099 if (ShiftAmt)
1100 SrcVal = BinaryOperator::CreateLShr(SrcVal,
1101 ConstantInt::get(SrcVal->getType(), ShiftAmt), "tmp", InsertPt);
Chris Lattnerd28f9082009-09-21 06:24:16 +00001102
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001103 if (LoadSize != StoreSize)
1104 SrcVal = new TruncInst(SrcVal, IntegerType::get(Ctx, LoadSize*8),
1105 "tmp", InsertPt);
Chris Lattnerd28f9082009-09-21 06:24:16 +00001106
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001107 return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, TD);
Chris Lattnerd28f9082009-09-21 06:24:16 +00001108}
1109
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001110struct AvailableValueInBlock {
1111 /// BB - The basic block in question.
1112 BasicBlock *BB;
1113 /// V - The value that is live out of the block.
1114 Value *V;
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001115 /// Offset - The byte offset in V that is interesting for the load query.
1116 unsigned Offset;
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001117
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001118 static AvailableValueInBlock get(BasicBlock *BB, Value *V,
1119 unsigned Offset = 0) {
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001120 AvailableValueInBlock Res;
1121 Res.BB = BB;
1122 Res.V = V;
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001123 Res.Offset = Offset;
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001124 return Res;
1125 }
1126};
1127
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001128/// ConstructSSAForLoadSet - Given a set of loads specified by ValuesPerBlock,
1129/// construct SSA form, allowing us to eliminate LI. This returns the value
1130/// that should be used at LI's definition site.
1131static Value *ConstructSSAForLoadSet(LoadInst *LI,
1132 SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
1133 const TargetData *TD,
1134 AliasAnalysis *AA) {
1135 SmallVector<PHINode*, 8> NewPHIs;
1136 SSAUpdater SSAUpdate(&NewPHIs);
1137 SSAUpdate.Initialize(LI);
1138
1139 const Type *LoadTy = LI->getType();
1140
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001141 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001142 BasicBlock *BB = ValuesPerBlock[i].BB;
1143 Value *AvailableVal = ValuesPerBlock[i].V;
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001144 unsigned Offset = ValuesPerBlock[i].Offset;
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001145
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001146 if (SSAUpdate.HasValueForBlock(BB))
1147 continue;
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001148
1149 if (AvailableVal->getType() != LoadTy) {
1150 assert(TD && "Need target data to handle type mismatch case");
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001151 AvailableVal = GetStoreValueForLoad(AvailableVal, Offset, LoadTy,
1152 BB->getTerminator(), *TD);
1153
1154 if (Offset) {
1155 DEBUG(errs() << "GVN COERCED NONLOCAL VAL:\n"
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001156 << *ValuesPerBlock[i].V << '\n'
1157 << *AvailableVal << '\n' << "\n\n\n");
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001158 }
1159
1160
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001161 DEBUG(errs() << "GVN COERCED NONLOCAL VAL:\n"
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001162 << *ValuesPerBlock[i].V << '\n'
1163 << *AvailableVal << '\n' << "\n\n\n");
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001164 }
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001165
1166 SSAUpdate.AddAvailableValue(BB, AvailableVal);
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001167 }
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001168
1169 // Perform PHI construction.
1170 Value *V = SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
1171
1172 // If new PHI nodes were created, notify alias analysis.
1173 if (isa<PointerType>(V->getType()))
1174 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
1175 AA->copyValue(LI, NewPHIs[i]);
1176
1177 return V;
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001178}
1179
Owen Anderson221a4362007-08-16 22:02:55 +00001180/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
1181/// non-local by performing PHI construction.
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001182bool GVN::processNonLocalLoad(LoadInst *LI,
Chris Lattner804209d2008-03-21 22:01:16 +00001183 SmallVectorImpl<Instruction*> &toErase) {
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001184 // Find the non-local dependencies of the load.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001185 SmallVector<MemoryDependenceAnalysis::NonLocalDepEntry, 64> Deps;
Chris Lattnerb6fc4b82008-12-09 19:25:07 +00001186 MD->getNonLocalPointerDependency(LI->getOperand(0), true, LI->getParent(),
1187 Deps);
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001188 //DEBUG(errs() << "INVESTIGATING NONLOCAL LOAD: "
1189 // << Deps.size() << *LI << '\n');
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001190
Owen Andersonb39e0de2008-08-26 22:07:42 +00001191 // If we had to process more than one hundred blocks to find the
1192 // dependencies, this load isn't worth worrying about. Optimizing
1193 // it will be too expensive.
Chris Lattnerb6fc4b82008-12-09 19:25:07 +00001194 if (Deps.size() > 100)
Owen Andersonb39e0de2008-08-26 22:07:42 +00001195 return false;
Chris Lattnerb6372932008-12-18 00:51:32 +00001196
1197 // If we had a phi translation failure, we'll have a single entry which is a
1198 // clobber in the current block. Reject this early.
Torok Edwinba93ea72009-06-17 18:48:18 +00001199 if (Deps.size() == 1 && Deps[0].second.isClobber()) {
1200 DEBUG(
Dan Gohman1ddf98a2009-07-25 01:43:01 +00001201 errs() << "GVN: non-local load ";
1202 WriteAsOperand(errs(), LI);
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001203 errs() << " is clobbered by " << *Deps[0].second.getInst() << '\n';
Torok Edwinba93ea72009-06-17 18:48:18 +00001204 );
Chris Lattnerb6372932008-12-18 00:51:32 +00001205 return false;
Torok Edwinba93ea72009-06-17 18:48:18 +00001206 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001207
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001208 // Filter out useless results (non-locals, etc). Keep track of the blocks
1209 // where we have a value available in repl, also keep track of whether we see
1210 // dependencies that produce an unknown value for the load (such as a call
1211 // that could potentially clobber the load).
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001212 SmallVector<AvailableValueInBlock, 16> ValuesPerBlock;
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001213 SmallVector<BasicBlock*, 16> UnavailableBlocks;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001214
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001215 const TargetData *TD = 0;
1216
Chris Lattnerb6fc4b82008-12-09 19:25:07 +00001217 for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
1218 BasicBlock *DepBB = Deps[i].first;
1219 MemDepResult DepInfo = Deps[i].second;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001220
Chris Lattner0e3d6332008-12-05 21:04:20 +00001221 if (DepInfo.isClobber()) {
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001222 // If the dependence is to a store that writes to a superset of the bits
1223 // read by the load, we can extract the bits we need for the load from the
1224 // stored value.
1225 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
1226 if (TD == 0)
1227 TD = getAnalysisIfAvailable<TargetData>();
1228 if (TD) {
1229 int Offset = AnalyzeLoadFromClobberingStore(LI, DepSI, *TD);
1230 if (Offset != -1) {
1231 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1232 DepSI->getOperand(0),
1233 Offset));
1234 continue;
1235 }
1236 }
1237 }
1238
1239 // FIXME: Handle memset/memcpy.
Chris Lattner0e3d6332008-12-05 21:04:20 +00001240 UnavailableBlocks.push_back(DepBB);
1241 continue;
1242 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001243
Chris Lattner0e3d6332008-12-05 21:04:20 +00001244 Instruction *DepInst = DepInfo.getInst();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001245
Chris Lattner0e3d6332008-12-05 21:04:20 +00001246 // Loading the allocation -> undef.
Victor Hernandez8acf2952009-10-23 21:09:37 +00001247 if (isa<AllocaInst>(DepInst) || isMalloc(DepInst)) {
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001248 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1249 UndefValue::get(LI->getType())));
Chris Lattner7e61daf2008-12-01 01:15:42 +00001250 continue;
1251 }
Owen Anderson2b2bd282009-10-28 07:05:35 +00001252
1253 // Loading immediately after lifetime begin or end -> undef.
1254 if (IntrinsicInst* II = dyn_cast<IntrinsicInst>(DepInst)) {
1255 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
1256 II->getIntrinsicID() == Intrinsic::lifetime_end) {
1257 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1258 UndefValue::get(LI->getType())));
1259 }
1260 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001261
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001262 if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001263 // Reject loads and stores that are to the same address but are of
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001264 // different types if we have to.
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001265 if (S->getOperand(0)->getType() != LI->getType()) {
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001266 if (TD == 0)
1267 TD = getAnalysisIfAvailable<TargetData>();
1268
1269 // If the stored value is larger or equal to the loaded value, we can
1270 // reuse it.
Chris Lattner9045f232009-09-21 17:24:04 +00001271 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(S->getOperand(0),
1272 LI->getType(), *TD)) {
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001273 UnavailableBlocks.push_back(DepBB);
1274 continue;
1275 }
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001276 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001277
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001278 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1279 S->getOperand(0)));
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001280 continue;
1281 }
1282
1283 if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001284 // If the types mismatch and we can't handle it, reject reuse of the load.
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001285 if (LD->getType() != LI->getType()) {
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001286 if (TD == 0)
1287 TD = getAnalysisIfAvailable<TargetData>();
1288
1289 // If the stored value is larger or equal to the loaded value, we can
1290 // reuse it.
Chris Lattner9045f232009-09-21 17:24:04 +00001291 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(LD, LI->getType(),*TD)){
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001292 UnavailableBlocks.push_back(DepBB);
1293 continue;
1294 }
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001295 }
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001296 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB, LD));
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001297 continue;
Owen Anderson5e5599b2007-07-25 19:57:03 +00001298 }
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001299
1300 UnavailableBlocks.push_back(DepBB);
1301 continue;
Chris Lattner2876a642008-03-21 21:14:38 +00001302 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001303
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001304 // If we have no predecessors that produce a known value for this load, exit
1305 // early.
1306 if (ValuesPerBlock.empty()) return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001307
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001308 // If all of the instructions we depend on produce a known value for this
1309 // load, then it is fully redundant and we can use PHI insertion to compute
1310 // its value. Insert PHIs and remove the fully redundant value now.
1311 if (UnavailableBlocks.empty()) {
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001312 DEBUG(errs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001313
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001314 // Perform PHI construction.
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001315 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, TD,
1316 VN.getAliasAnalysis());
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001317 LI->replaceAllUsesWith(V);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001318
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001319 if (isa<PHINode>(V))
1320 V->takeName(LI);
1321 if (isa<PointerType>(V->getType()))
1322 MD->invalidateCachedPointerInfo(V);
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001323 toErase.push_back(LI);
1324 NumGVNLoad++;
1325 return true;
1326 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001327
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001328 if (!EnablePRE || !EnableLoadPRE)
1329 return false;
1330
1331 // Okay, we have *some* definitions of the value. This means that the value
1332 // is available in some of our (transitive) predecessors. Lets think about
1333 // doing PRE of this load. This will involve inserting a new load into the
1334 // predecessor when it's not available. We could do this in general, but
1335 // prefer to not increase code size. As such, we only do this when we know
1336 // that we only have to insert *one* load (which means we're basically moving
1337 // the load, not inserting a new one).
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001338
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001339 SmallPtrSet<BasicBlock *, 4> Blockers;
1340 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1341 Blockers.insert(UnavailableBlocks[i]);
1342
1343 // Lets find first basic block with more than one predecessor. Walk backwards
1344 // through predecessors if needed.
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001345 BasicBlock *LoadBB = LI->getParent();
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001346 BasicBlock *TmpBB = LoadBB;
1347
1348 bool isSinglePred = false;
Dale Johannesen81b64632009-06-17 20:48:23 +00001349 bool allSingleSucc = true;
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001350 while (TmpBB->getSinglePredecessor()) {
1351 isSinglePred = true;
1352 TmpBB = TmpBB->getSinglePredecessor();
1353 if (!TmpBB) // If haven't found any, bail now.
1354 return false;
1355 if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1356 return false;
1357 if (Blockers.count(TmpBB))
1358 return false;
Dale Johannesen81b64632009-06-17 20:48:23 +00001359 if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1360 allSingleSucc = false;
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001361 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001362
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001363 assert(TmpBB);
1364 LoadBB = TmpBB;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001365
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001366 // If we have a repl set with LI itself in it, this means we have a loop where
1367 // at least one of the values is LI. Since this means that we won't be able
1368 // to eliminate LI even if we insert uses in the other predecessors, we will
1369 // end up increasing code size. Reject this by scanning for LI.
1370 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001371 if (ValuesPerBlock[i].V == LI)
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001372 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001373
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001374 if (isSinglePred) {
1375 bool isHot = false;
1376 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001377 if (Instruction *I = dyn_cast<Instruction>(ValuesPerBlock[i].V))
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001378 // "Hot" Instruction is in some loop (because it dominates its dep.
1379 // instruction).
1380 if (DT->dominates(LI, I)) {
1381 isHot = true;
1382 break;
1383 }
Owen Andersoncc0c75c2009-05-31 09:03:40 +00001384
1385 // We are interested only in "hot" instructions. We don't want to do any
1386 // mis-optimizations here.
1387 if (!isHot)
1388 return false;
1389 }
1390
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001391 // Okay, we have some hope :). Check to see if the loaded value is fully
1392 // available in all but one predecessor.
1393 // FIXME: If we could restructure the CFG, we could make a common pred with
1394 // all the preds that don't have an available LI and insert a new load into
1395 // that one block.
1396 BasicBlock *UnavailablePred = 0;
1397
Chris Lattnerd2a653a2008-12-05 07:49:08 +00001398 DenseMap<BasicBlock*, char> FullyAvailableBlocks;
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001399 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
Chris Lattner0cdc17e2009-09-21 06:30:24 +00001400 FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001401 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1402 FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1403
1404 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1405 PI != E; ++PI) {
1406 if (IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
1407 continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001408
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001409 // If this load is not available in multiple predecessors, reject it.
1410 if (UnavailablePred && UnavailablePred != *PI)
1411 return false;
1412 UnavailablePred = *PI;
1413 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001414
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001415 assert(UnavailablePred != 0 &&
1416 "Fully available value should be eliminated above!");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001417
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001418 // If the loaded pointer is PHI node defined in this block, do PHI translation
1419 // to get its value in the predecessor.
1420 Value *LoadPtr = LI->getOperand(0)->DoPHITranslation(LoadBB, UnavailablePred);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001421
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001422 // Make sure the value is live in the predecessor. If it was defined by a
1423 // non-PHI instruction in this block, we don't know how to recompute it above.
1424 if (Instruction *LPInst = dyn_cast<Instruction>(LoadPtr))
1425 if (!DT->dominates(LPInst->getParent(), UnavailablePred)) {
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +00001426 DEBUG(errs() << "COULDN'T PRE LOAD BECAUSE PTR IS UNAVAILABLE IN PRED: "
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001427 << *LPInst << '\n' << *LI << "\n");
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001428 return false;
1429 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001430
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001431 // We don't currently handle critical edges :(
1432 if (UnavailablePred->getTerminator()->getNumSuccessors() != 1) {
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +00001433 DEBUG(errs() << "COULD NOT PRE LOAD BECAUSE OF CRITICAL EDGE '"
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001434 << UnavailablePred->getName() << "': " << *LI << '\n');
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001435 return false;
Owen Anderson0cc1a762007-08-07 23:12:31 +00001436 }
Dale Johannesen81b64632009-06-17 20:48:23 +00001437
1438 // Make sure it is valid to move this load here. We have to watch out for:
1439 // @1 = getelementptr (i8* p, ...
1440 // test p and branch if == 0
1441 // load @1
1442 // It is valid to have the getelementptr before the test, even if p can be 0,
1443 // as getelementptr only does address arithmetic.
1444 // If we are not pushing the value through any multiple-successor blocks
1445 // we do not have this case. Otherwise, check that the load is safe to
1446 // put anywhere; this can be improved, but should be conservatively safe.
1447 if (!allSingleSucc &&
1448 !isSafeToLoadUnconditionally(LoadPtr, UnavailablePred->getTerminator()))
1449 return false;
1450
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001451 // Okay, we can eliminate this load by inserting a reload in the predecessor
1452 // and using PHI construction to get the value in the other predecessors, do
1453 // it.
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001454 DEBUG(errs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001455
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001456 Value *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1457 LI->getAlignment(),
1458 UnavailablePred->getTerminator());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001459
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001460 // Add the newly created load.
1461 ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,NewLoad));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001462
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001463 // Perform PHI construction.
Chris Lattnerb6c65fa2009-10-10 23:50:30 +00001464 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, TD,
1465 VN.getAliasAnalysis());
Chris Lattnera0aa8fb2009-09-20 20:09:34 +00001466 LI->replaceAllUsesWith(V);
1467 if (isa<PHINode>(V))
1468 V->takeName(LI);
1469 if (isa<PointerType>(V->getType()))
1470 MD->invalidateCachedPointerInfo(V);
Chris Lattner1db9bbe2008-12-02 08:16:11 +00001471 toErase.push_back(LI);
1472 NumPRELoad++;
Owen Anderson5e5599b2007-07-25 19:57:03 +00001473 return true;
1474}
1475
Owen Anderson221a4362007-08-16 22:02:55 +00001476/// processLoad - Attempt to eliminate a load, first by eliminating it
1477/// locally, and then attempting non-local elimination if that fails.
Chris Lattner0e3d6332008-12-05 21:04:20 +00001478bool GVN::processLoad(LoadInst *L, SmallVectorImpl<Instruction*> &toErase) {
1479 if (L->isVolatile())
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001480 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001481
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001482 // ... to a pointer that has been loaded from before...
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001483 MemDepResult Dep = MD->getDependency(L);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001484
Chris Lattner0e3d6332008-12-05 21:04:20 +00001485 // If the value isn't available, don't do anything!
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001486 if (Dep.isClobber()) {
Chris Lattner0a9616d2009-09-21 05:57:11 +00001487 // FIXME: We should handle memset/memcpy/memmove as dependent instructions
1488 // to forward the value if available.
1489 //if (isa<MemIntrinsic>(Dep.getInst()))
1490 //errs() << "LOAD DEPENDS ON MEM: " << *L << "\n" << *Dep.getInst()<<"\n\n";
1491
1492 // Check to see if we have something like this:
Chris Lattner1dd48c32009-09-20 19:03:47 +00001493 // store i32 123, i32* %P
1494 // %A = bitcast i32* %P to i8*
1495 // %B = gep i8* %A, i32 1
1496 // %C = load i8* %B
1497 //
1498 // We could do that by recognizing if the clobber instructions are obviously
1499 // a common base + constant offset, and if the previous store (or memset)
1500 // completely covers this load. This sort of thing can happen in bitfield
1501 // access code.
Chris Lattner0a9616d2009-09-21 05:57:11 +00001502 if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst()))
Chris Lattner9d7fb292009-09-21 06:22:46 +00001503 if (const TargetData *TD = getAnalysisIfAvailable<TargetData>()) {
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001504 int Offset = AnalyzeLoadFromClobberingStore(L, DepSI, *TD);
Chris Lattner9d7fb292009-09-21 06:22:46 +00001505 if (Offset != -1) {
1506 Value *AvailVal = GetStoreValueForLoad(DepSI->getOperand(0), Offset,
Chris Lattner4d8af2f2009-09-21 06:48:08 +00001507 L->getType(), L, *TD);
Chris Lattner0a9616d2009-09-21 05:57:11 +00001508 DEBUG(errs() << "GVN COERCED STORE BITS:\n" << *DepSI << '\n'
1509 << *AvailVal << '\n' << *L << "\n\n\n");
1510
1511 // Replace the load!
1512 L->replaceAllUsesWith(AvailVal);
1513 if (isa<PointerType>(AvailVal->getType()))
1514 MD->invalidateCachedPointerInfo(AvailVal);
1515 toErase.push_back(L);
1516 NumGVNLoad++;
1517 return true;
1518 }
Chris Lattner9d7fb292009-09-21 06:22:46 +00001519 }
Chris Lattner0a9616d2009-09-21 05:57:11 +00001520
Torok Edwin72070282009-05-29 09:46:03 +00001521 DEBUG(
1522 // fast print dep, using operator<< on instruction would be too slow
Dan Gohman1ddf98a2009-07-25 01:43:01 +00001523 errs() << "GVN: load ";
1524 WriteAsOperand(errs(), L);
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001525 Instruction *I = Dep.getInst();
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001526 errs() << " is clobbered by " << *I << '\n';
Torok Edwin72070282009-05-29 09:46:03 +00001527 );
Chris Lattner0e3d6332008-12-05 21:04:20 +00001528 return false;
Torok Edwin72070282009-05-29 09:46:03 +00001529 }
Chris Lattner0e3d6332008-12-05 21:04:20 +00001530
1531 // If it is defined in another block, try harder.
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001532 if (Dep.isNonLocal())
Chris Lattner0e3d6332008-12-05 21:04:20 +00001533 return processNonLocalLoad(L, toErase);
Eli Friedman716c10c2008-02-12 12:08:14 +00001534
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001535 Instruction *DepInst = Dep.getInst();
Chris Lattner0e3d6332008-12-05 21:04:20 +00001536 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
Chris Lattner1dd48c32009-09-20 19:03:47 +00001537 Value *StoredVal = DepSI->getOperand(0);
1538
1539 // The store and load are to a must-aliased pointer, but they may not
1540 // actually have the same type. See if we know how to reuse the stored
1541 // value (depending on its type).
1542 const TargetData *TD = 0;
Chris Lattner8ed7bef2009-10-21 04:11:19 +00001543 if (StoredVal->getType() != L->getType()) {
1544 if ((TD = getAnalysisIfAvailable<TargetData>())) {
1545 StoredVal = CoerceAvailableValueToLoadType(StoredVal, L->getType(),
1546 L, *TD);
1547 if (StoredVal == 0)
1548 return false;
1549
1550 DEBUG(errs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
1551 << '\n' << *L << "\n\n\n");
1552 }
1553 else
Chris Lattner1dd48c32009-09-20 19:03:47 +00001554 return false;
Chris Lattner1dd48c32009-09-20 19:03:47 +00001555 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001556
Chris Lattner0e3d6332008-12-05 21:04:20 +00001557 // Remove it!
Chris Lattner1dd48c32009-09-20 19:03:47 +00001558 L->replaceAllUsesWith(StoredVal);
1559 if (isa<PointerType>(StoredVal->getType()))
1560 MD->invalidateCachedPointerInfo(StoredVal);
Chris Lattner0e3d6332008-12-05 21:04:20 +00001561 toErase.push_back(L);
1562 NumGVNLoad++;
1563 return true;
1564 }
1565
1566 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
Chris Lattner1dd48c32009-09-20 19:03:47 +00001567 Value *AvailableVal = DepLI;
1568
1569 // The loads are of a must-aliased pointer, but they may not actually have
1570 // the same type. See if we know how to reuse the previously loaded value
1571 // (depending on its type).
1572 const TargetData *TD = 0;
Chris Lattner8ed7bef2009-10-21 04:11:19 +00001573 if (DepLI->getType() != L->getType()) {
1574 if ((TD = getAnalysisIfAvailable<TargetData>())) {
1575 AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(), L,*TD);
1576 if (AvailableVal == 0)
1577 return false;
Chris Lattner1dd48c32009-09-20 19:03:47 +00001578
Chris Lattner8ed7bef2009-10-21 04:11:19 +00001579 DEBUG(errs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
1580 << "\n" << *L << "\n\n\n");
1581 }
1582 else
1583 return false;
Chris Lattner1dd48c32009-09-20 19:03:47 +00001584 }
1585
Chris Lattner0e3d6332008-12-05 21:04:20 +00001586 // Remove it!
Chris Lattner1dd48c32009-09-20 19:03:47 +00001587 L->replaceAllUsesWith(AvailableVal);
Chris Lattnerfa9f99a2008-12-09 22:06:23 +00001588 if (isa<PointerType>(DepLI->getType()))
1589 MD->invalidateCachedPointerInfo(DepLI);
Chris Lattner0e3d6332008-12-05 21:04:20 +00001590 toErase.push_back(L);
1591 NumGVNLoad++;
1592 return true;
1593 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001594
Chris Lattner3ff6d012008-11-30 01:39:32 +00001595 // If this load really doesn't depend on anything, then we must be loading an
1596 // undef value. This can happen when loading for a fresh allocation with no
1597 // intervening stores, for example.
Victor Hernandez8acf2952009-10-23 21:09:37 +00001598 if (isa<AllocaInst>(DepInst) || isMalloc(DepInst)) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00001599 L->replaceAllUsesWith(UndefValue::get(L->getType()));
Chris Lattner3ff6d012008-11-30 01:39:32 +00001600 toErase.push_back(L);
Chris Lattner3ff6d012008-11-30 01:39:32 +00001601 NumGVNLoad++;
Chris Lattner0e3d6332008-12-05 21:04:20 +00001602 return true;
Eli Friedman716c10c2008-02-12 12:08:14 +00001603 }
Owen Anderson2b2bd282009-10-28 07:05:35 +00001604
1605 // If this load occurs either right after a lifetime begin or a lifetime end,
1606 // then the loaded value is undefined.
1607 if (IntrinsicInst* II = dyn_cast<IntrinsicInst>(DepInst)) {
1608 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
1609 II->getIntrinsicID() == Intrinsic::lifetime_end) {
1610 L->replaceAllUsesWith(UndefValue::get(L->getType()));
1611 toErase.push_back(L);
1612 NumGVNLoad++;
1613 return true;
1614 }
1615 }
Eli Friedman716c10c2008-02-12 12:08:14 +00001616
Chris Lattner0e3d6332008-12-05 21:04:20 +00001617 return false;
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001618}
1619
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001620Value *GVN::lookupNumber(BasicBlock *BB, uint32_t num) {
Owen Anderson54e02192008-06-23 17:49:45 +00001621 DenseMap<BasicBlock*, ValueNumberScope*>::iterator I = localAvail.find(BB);
1622 if (I == localAvail.end())
1623 return 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001624
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001625 ValueNumberScope *Locals = I->second;
1626 while (Locals) {
1627 DenseMap<uint32_t, Value*>::iterator I = Locals->table.find(num);
1628 if (I != Locals->table.end())
Owen Anderson1b3ea962008-06-20 01:15:47 +00001629 return I->second;
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001630 Locals = Locals->parent;
Owen Anderson1b3ea962008-06-20 01:15:47 +00001631 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001632
Owen Anderson1b3ea962008-06-20 01:15:47 +00001633 return 0;
1634}
1635
Owen Andersonbfe133e2008-12-15 02:03:00 +00001636
Owen Anderson398602a2007-08-14 18:16:29 +00001637/// processInstruction - When calculating availability, handle an instruction
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001638/// by inserting it into the appropriate sets
Owen Andersonaccdca12008-06-12 19:25:32 +00001639bool GVN::processInstruction(Instruction *I,
Chris Lattner804209d2008-03-21 22:01:16 +00001640 SmallVectorImpl<Instruction*> &toErase) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001641 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1642 bool Changed = processLoad(LI, toErase);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001643
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001644 if (!Changed) {
1645 unsigned Num = VN.lookup_or_add(LI);
1646 localAvail[I->getParent()]->table.insert(std::make_pair(Num, LI));
Owen Anderson6a903bc2008-06-18 21:41:49 +00001647 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001648
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001649 return Changed;
Owen Anderson6a903bc2008-06-18 21:41:49 +00001650 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001651
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001652 uint32_t NextNum = VN.getNextUnusedValueNumber();
1653 unsigned Num = VN.lookup_or_add(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001654
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001655 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1656 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001657
Owen Anderson98f912b2009-04-01 23:53:49 +00001658 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
1659 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001660
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001661 Value *BranchCond = BI->getCondition();
1662 uint32_t CondVN = VN.lookup_or_add(BranchCond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001663
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001664 BasicBlock *TrueSucc = BI->getSuccessor(0);
1665 BasicBlock *FalseSucc = BI->getSuccessor(1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001666
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001667 if (TrueSucc->getSinglePredecessor())
1668 localAvail[TrueSucc]->table[CondVN] =
1669 ConstantInt::getTrue(TrueSucc->getContext());
1670 if (FalseSucc->getSinglePredecessor())
1671 localAvail[FalseSucc]->table[CondVN] =
1672 ConstantInt::getFalse(TrueSucc->getContext());
Owen Anderson98f912b2009-04-01 23:53:49 +00001673
1674 return false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001675
Owen Anderson0c1e6342008-04-07 09:59:07 +00001676 // Allocations are always uniquely numbered, so we can save time and memory
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001677 // by fast failing them.
Victor Hernandez8acf2952009-10-23 21:09:37 +00001678 } else if (isa<AllocaInst>(I) || isa<TerminatorInst>(I)) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001679 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Owen Anderson0c1e6342008-04-07 09:59:07 +00001680 return false;
Owen Anderson6a903bc2008-06-18 21:41:49 +00001681 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001682
Owen Anderson221a4362007-08-16 22:02:55 +00001683 // Collapse PHI nodes
Owen Andersonbc271a02007-08-14 18:33:27 +00001684 if (PHINode* p = dyn_cast<PHINode>(I)) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001685 Value *constVal = CollapsePhi(p);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001686
Owen Andersonbc271a02007-08-14 18:33:27 +00001687 if (constVal) {
Owen Andersonf5023a72007-08-16 22:51:56 +00001688 p->replaceAllUsesWith(constVal);
Chris Lattnerfa9f99a2008-12-09 22:06:23 +00001689 if (isa<PointerType>(constVal->getType()))
1690 MD->invalidateCachedPointerInfo(constVal);
Owen Anderson164274e2008-12-23 00:49:51 +00001691 VN.erase(p);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001692
Owen Andersonf5023a72007-08-16 22:51:56 +00001693 toErase.push_back(p);
Owen Anderson6a903bc2008-06-18 21:41:49 +00001694 } else {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001695 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Owen Andersonbc271a02007-08-14 18:33:27 +00001696 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001697
Owen Anderson3ea90a72008-07-03 17:44:33 +00001698 // If the number we were assigned was a brand new VN, then we don't
1699 // need to do a lookup to see if the number already exists
1700 // somewhere in the domtree: it can't!
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001701 } else if (Num == NextNum) {
1702 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001703
Owen Andersonbfe133e2008-12-15 02:03:00 +00001704 // Perform fast-path value-number based elimination of values inherited from
1705 // dominators.
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001706 } else if (Value *repl = lookupNumber(I->getParent(), Num)) {
Owen Anderson086b2c42007-12-08 01:37:09 +00001707 // Remove it!
Owen Anderson10ffa862007-07-31 23:27:13 +00001708 VN.erase(I);
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001709 I->replaceAllUsesWith(repl);
Chris Lattnerfa9f99a2008-12-09 22:06:23 +00001710 if (isa<PointerType>(repl->getType()))
1711 MD->invalidateCachedPointerInfo(repl);
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001712 toErase.push_back(I);
1713 return true;
Owen Andersonbfe133e2008-12-15 02:03:00 +00001714
Owen Anderson3ea90a72008-07-03 17:44:33 +00001715 } else {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001716 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001717 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001718
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001719 return false;
1720}
1721
Bill Wendling456e8852008-12-22 22:32:22 +00001722/// runOnFunction - This is the main transformation entry point for a function.
Owen Anderson676070d2007-08-14 18:04:11 +00001723bool GVN::runOnFunction(Function& F) {
Chris Lattner8541ede2008-12-01 00:40:32 +00001724 MD = &getAnalysis<MemoryDependenceAnalysis>();
1725 DT = &getAnalysis<DominatorTree>();
Owen Andersonf7928602008-05-12 20:15:55 +00001726 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
Chris Lattner8541ede2008-12-01 00:40:32 +00001727 VN.setMemDep(MD);
1728 VN.setDomTree(DT);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001729
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001730 bool Changed = false;
1731 bool ShouldContinue = true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001732
Owen Andersonac310962008-07-16 17:52:31 +00001733 // Merge unconditional branches, allowing PRE to catch more
1734 // optimization opportunities.
1735 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001736 BasicBlock *BB = FI;
Owen Andersonac310962008-07-16 17:52:31 +00001737 ++FI;
Owen Andersonc0623812008-07-17 00:01:40 +00001738 bool removedBlock = MergeBlockIntoPredecessor(BB, this);
1739 if (removedBlock) NumGVNBlocks++;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001740
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001741 Changed |= removedBlock;
Owen Andersonac310962008-07-16 17:52:31 +00001742 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001743
Chris Lattner0a5a8d52008-12-09 19:21:47 +00001744 unsigned Iteration = 0;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001745
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001746 while (ShouldContinue) {
Dan Gohman1ddf98a2009-07-25 01:43:01 +00001747 DEBUG(errs() << "GVN iteration: " << Iteration << "\n");
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001748 ShouldContinue = iterateOnFunction(F);
1749 Changed |= ShouldContinue;
Chris Lattner0a5a8d52008-12-09 19:21:47 +00001750 ++Iteration;
Owen Anderson676070d2007-08-14 18:04:11 +00001751 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001752
Owen Anderson04a6e0b2008-07-18 18:03:38 +00001753 if (EnablePRE) {
Owen Anderson2fbfb702008-09-03 23:06:07 +00001754 bool PREChanged = true;
1755 while (PREChanged) {
1756 PREChanged = performPRE(F);
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001757 Changed |= PREChanged;
Owen Anderson2fbfb702008-09-03 23:06:07 +00001758 }
Owen Anderson04a6e0b2008-07-18 18:03:38 +00001759 }
Chris Lattner0a5a8d52008-12-09 19:21:47 +00001760 // FIXME: Should perform GVN again after PRE does something. PRE can move
1761 // computations into blocks where they become fully redundant. Note that
1762 // we can't do this until PRE's critical edge splitting updates memdep.
1763 // Actually, when this happens, we should just fully integrate PRE into GVN.
Nuno Lopese3127f32008-10-10 16:25:50 +00001764
1765 cleanupGlobalSets();
1766
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001767 return Changed;
Owen Anderson676070d2007-08-14 18:04:11 +00001768}
1769
1770
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001771bool GVN::processBlock(BasicBlock *BB) {
Chris Lattner0a5a8d52008-12-09 19:21:47 +00001772 // FIXME: Kill off toErase by doing erasing eagerly in a helper function (and
1773 // incrementing BI before processing an instruction).
Owen Andersonaccdca12008-06-12 19:25:32 +00001774 SmallVector<Instruction*, 8> toErase;
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001775 bool ChangedFunction = false;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001776
Owen Andersonaccdca12008-06-12 19:25:32 +00001777 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1778 BI != BE;) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001779 ChangedFunction |= processInstruction(BI, toErase);
Owen Andersonaccdca12008-06-12 19:25:32 +00001780 if (toErase.empty()) {
1781 ++BI;
1782 continue;
1783 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001784
Owen Andersonaccdca12008-06-12 19:25:32 +00001785 // If we need some instructions deleted, do it now.
1786 NumGVNInstr += toErase.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001787
Owen Andersonaccdca12008-06-12 19:25:32 +00001788 // Avoid iterator invalidation.
1789 bool AtStart = BI == BB->begin();
1790 if (!AtStart)
1791 --BI;
1792
1793 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
Chris Lattner8541ede2008-12-01 00:40:32 +00001794 E = toErase.end(); I != E; ++I) {
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001795 DEBUG(errs() << "GVN removed: " << **I << '\n');
Chris Lattner8541ede2008-12-01 00:40:32 +00001796 MD->removeInstruction(*I);
Owen Andersonaccdca12008-06-12 19:25:32 +00001797 (*I)->eraseFromParent();
Bill Wendlingebb6a542008-12-22 21:57:30 +00001798 DEBUG(verifyRemoved(*I));
Chris Lattner8541ede2008-12-01 00:40:32 +00001799 }
Chris Lattner0a5a8d52008-12-09 19:21:47 +00001800 toErase.clear();
Owen Andersonaccdca12008-06-12 19:25:32 +00001801
1802 if (AtStart)
1803 BI = BB->begin();
1804 else
1805 ++BI;
Owen Andersonaccdca12008-06-12 19:25:32 +00001806 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001807
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001808 return ChangedFunction;
Owen Andersonaccdca12008-06-12 19:25:32 +00001809}
1810
Owen Anderson6a903bc2008-06-18 21:41:49 +00001811/// performPRE - Perform a purely local form of PRE that looks for diamond
1812/// control flow patterns and attempts to perform simple PRE at the join point.
1813bool GVN::performPRE(Function& F) {
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001814 bool Changed = false;
Owen Andersonfdf9f162008-06-19 19:54:19 +00001815 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
Chris Lattnerf00aae42008-12-01 07:29:03 +00001816 DenseMap<BasicBlock*, Value*> predMap;
Owen Anderson6a903bc2008-06-18 21:41:49 +00001817 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
1818 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001819 BasicBlock *CurrentBlock = *DI;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001820
Owen Anderson6a903bc2008-06-18 21:41:49 +00001821 // Nothing to PRE in the entry block.
1822 if (CurrentBlock == &F.getEntryBlock()) continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001823
Owen Anderson6a903bc2008-06-18 21:41:49 +00001824 for (BasicBlock::iterator BI = CurrentBlock->begin(),
1825 BE = CurrentBlock->end(); BI != BE; ) {
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001826 Instruction *CurInst = BI++;
Duncan Sands1efabaa2009-05-06 06:49:50 +00001827
Victor Hernandez8acf2952009-10-23 21:09:37 +00001828 if (isa<AllocaInst>(CurInst) ||
Victor Hernandez5d034492009-09-18 22:35:49 +00001829 isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
Devang Patel92f86192009-10-14 17:29:00 +00001830 CurInst->getType()->isVoidTy() ||
Duncan Sands1efabaa2009-05-06 06:49:50 +00001831 CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
John Criswell073e4d12009-03-10 15:04:53 +00001832 isa<DbgInfoIntrinsic>(CurInst))
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001833 continue;
Duncan Sands1efabaa2009-05-06 06:49:50 +00001834
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001835 uint32_t ValNo = VN.lookup(CurInst);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001836
Owen Anderson6a903bc2008-06-18 21:41:49 +00001837 // Look for the predecessors for PRE opportunities. We're
1838 // only trying to solve the basic diamond case, where
1839 // a value is computed in the successor and one predecessor,
1840 // but not the other. We also explicitly disallow cases
1841 // where the successor is its own predecessor, because they're
1842 // more complicated to get right.
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001843 unsigned NumWith = 0;
1844 unsigned NumWithout = 0;
1845 BasicBlock *PREPred = 0;
Chris Lattnerf00aae42008-12-01 07:29:03 +00001846 predMap.clear();
1847
Owen Anderson6a903bc2008-06-18 21:41:49 +00001848 for (pred_iterator PI = pred_begin(CurrentBlock),
1849 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
1850 // We're not interested in PRE where the block is its
Owen Anderson1b3ea962008-06-20 01:15:47 +00001851 // own predecessor, on in blocks with predecessors
1852 // that are not reachable.
1853 if (*PI == CurrentBlock) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001854 NumWithout = 2;
Owen Anderson1b3ea962008-06-20 01:15:47 +00001855 break;
1856 } else if (!localAvail.count(*PI)) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001857 NumWithout = 2;
Owen Anderson1b3ea962008-06-20 01:15:47 +00001858 break;
1859 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001860
1861 DenseMap<uint32_t, Value*>::iterator predV =
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001862 localAvail[*PI]->table.find(ValNo);
Owen Anderson1b3ea962008-06-20 01:15:47 +00001863 if (predV == localAvail[*PI]->table.end()) {
Owen Anderson6a903bc2008-06-18 21:41:49 +00001864 PREPred = *PI;
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001865 NumWithout++;
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001866 } else if (predV->second == CurInst) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001867 NumWithout = 2;
Owen Anderson6a903bc2008-06-18 21:41:49 +00001868 } else {
Owen Anderson1b3ea962008-06-20 01:15:47 +00001869 predMap[*PI] = predV->second;
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001870 NumWith++;
Owen Anderson6a903bc2008-06-18 21:41:49 +00001871 }
1872 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001873
Owen Anderson6a903bc2008-06-18 21:41:49 +00001874 // Don't do PRE when it might increase code size, i.e. when
1875 // we would need to insert instructions in more than one pred.
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001876 if (NumWithout != 1 || NumWith == 0)
Owen Anderson6a903bc2008-06-18 21:41:49 +00001877 continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001878
Owen Andersonfdf9f162008-06-19 19:54:19 +00001879 // We can't do PRE safely on a critical edge, so instead we schedule
1880 // the edge to be split and perform the PRE the next time we iterate
1881 // on the function.
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001882 unsigned SuccNum = 0;
Owen Andersonfdf9f162008-06-19 19:54:19 +00001883 for (unsigned i = 0, e = PREPred->getTerminator()->getNumSuccessors();
1884 i != e; ++i)
Owen Anderson2fbfb702008-09-03 23:06:07 +00001885 if (PREPred->getTerminator()->getSuccessor(i) == CurrentBlock) {
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001886 SuccNum = i;
Owen Andersonfdf9f162008-06-19 19:54:19 +00001887 break;
1888 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001889
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001890 if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
1891 toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
Owen Andersonfdf9f162008-06-19 19:54:19 +00001892 continue;
1893 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001894
Owen Anderson6a903bc2008-06-18 21:41:49 +00001895 // Instantiate the expression the in predecessor that lacked it.
1896 // Because we are going top-down through the block, all value numbers
1897 // will be available in the predecessor by the time we need them. Any
1898 // that weren't original present will have been instantiated earlier
1899 // in this loop.
Nick Lewycky42fb7452009-09-27 07:38:41 +00001900 Instruction *PREInstr = CurInst->clone();
Owen Anderson6a903bc2008-06-18 21:41:49 +00001901 bool success = true;
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001902 for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
1903 Value *Op = PREInstr->getOperand(i);
1904 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
1905 continue;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001906
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001907 if (Value *V = lookupNumber(PREPred, VN.lookup(Op))) {
1908 PREInstr->setOperand(i, V);
1909 } else {
1910 success = false;
1911 break;
Owen Anderson8e462e92008-07-11 20:05:13 +00001912 }
Owen Anderson6a903bc2008-06-18 21:41:49 +00001913 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001914
Owen Anderson6a903bc2008-06-18 21:41:49 +00001915 // Fail out if we encounter an operand that is not available in
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001916 // the PRE predecessor. This is typically because of loads which
Owen Anderson6a903bc2008-06-18 21:41:49 +00001917 // are not value numbered precisely.
1918 if (!success) {
1919 delete PREInstr;
Bill Wendling3c793442008-12-22 22:14:07 +00001920 DEBUG(verifyRemoved(PREInstr));
Owen Anderson6a903bc2008-06-18 21:41:49 +00001921 continue;
1922 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001923
Owen Anderson6a903bc2008-06-18 21:41:49 +00001924 PREInstr->insertBefore(PREPred->getTerminator());
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001925 PREInstr->setName(CurInst->getName() + ".pre");
Owen Anderson1b3ea962008-06-20 01:15:47 +00001926 predMap[PREPred] = PREInstr;
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001927 VN.add(PREInstr, ValNo);
Owen Anderson6a903bc2008-06-18 21:41:49 +00001928 NumGVNPRE++;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001929
Owen Anderson6a903bc2008-06-18 21:41:49 +00001930 // Update the availability map to include the new instruction.
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001931 localAvail[PREPred]->table.insert(std::make_pair(ValNo, PREInstr));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001932
Owen Anderson6a903bc2008-06-18 21:41:49 +00001933 // Create a PHI to make the value available in this block.
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001934 PHINode* Phi = PHINode::Create(CurInst->getType(),
1935 CurInst->getName() + ".pre-phi",
Owen Anderson6a903bc2008-06-18 21:41:49 +00001936 CurrentBlock->begin());
1937 for (pred_iterator PI = pred_begin(CurrentBlock),
1938 PE = pred_end(CurrentBlock); PI != PE; ++PI)
Owen Anderson1b3ea962008-06-20 01:15:47 +00001939 Phi->addIncoming(predMap[*PI], *PI);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001940
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001941 VN.add(Phi, ValNo);
1942 localAvail[CurrentBlock]->table[ValNo] = Phi;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001943
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001944 CurInst->replaceAllUsesWith(Phi);
Chris Lattnerfa9f99a2008-12-09 22:06:23 +00001945 if (isa<PointerType>(Phi->getType()))
1946 MD->invalidateCachedPointerInfo(Phi);
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001947 VN.erase(CurInst);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001948
Dan Gohmanef3ef7f2009-07-31 20:24:18 +00001949 DEBUG(errs() << "GVN PRE removed: " << *CurInst << '\n');
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001950 MD->removeInstruction(CurInst);
1951 CurInst->eraseFromParent();
Bill Wendlingebb6a542008-12-22 21:57:30 +00001952 DEBUG(verifyRemoved(CurInst));
Chris Lattner6f5bf6a2008-12-01 07:35:54 +00001953 Changed = true;
Owen Anderson6a903bc2008-06-18 21:41:49 +00001954 }
1955 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001956
Owen Andersonfdf9f162008-06-19 19:54:19 +00001957 for (SmallVector<std::pair<TerminatorInst*, unsigned>, 4>::iterator
Anton Korobeynikov24600bf2008-12-05 19:38:49 +00001958 I = toSplit.begin(), E = toSplit.end(); I != E; ++I)
Owen Andersonfdf9f162008-06-19 19:54:19 +00001959 SplitCriticalEdge(I->first, I->second, this);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001960
Anton Korobeynikov24600bf2008-12-05 19:38:49 +00001961 return Changed || toSplit.size();
Owen Anderson6a903bc2008-06-18 21:41:49 +00001962}
1963
Bill Wendling456e8852008-12-22 22:32:22 +00001964/// iterateOnFunction - Executes one iteration of GVN
Owen Anderson676070d2007-08-14 18:04:11 +00001965bool GVN::iterateOnFunction(Function &F) {
Nuno Lopese3127f32008-10-10 16:25:50 +00001966 cleanupGlobalSets();
Chris Lattnerbeb216d2008-03-21 21:33:23 +00001967
Owen Anderson98f912b2009-04-01 23:53:49 +00001968 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
1969 DE = df_end(DT->getRootNode()); DI != DE; ++DI) {
1970 if (DI->getIDom())
1971 localAvail[DI->getBlock()] =
1972 new ValueNumberScope(localAvail[DI->getIDom()->getBlock()]);
1973 else
1974 localAvail[DI->getBlock()] = new ValueNumberScope(0);
1975 }
1976
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001977 // Top-down walk of the dominator tree
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001978 bool Changed = false;
Owen Anderson03aacba2008-12-15 03:52:17 +00001979#if 0
1980 // Needed for value numbering with phi construction to work.
Owen Andersonbfe133e2008-12-15 02:03:00 +00001981 ReversePostOrderTraversal<Function*> RPOT(&F);
1982 for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
1983 RE = RPOT.end(); RI != RE; ++RI)
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001984 Changed |= processBlock(*RI);
Owen Anderson03aacba2008-12-15 03:52:17 +00001985#else
1986 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
1987 DE = df_end(DT->getRootNode()); DI != DE; ++DI)
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001988 Changed |= processBlock(DI->getBlock());
Owen Anderson03aacba2008-12-15 03:52:17 +00001989#endif
1990
Chris Lattner1eefa9c2009-09-21 02:42:51 +00001991 return Changed;
Owen Andersonab6ec2e2007-07-24 17:55:58 +00001992}
Nuno Lopese3127f32008-10-10 16:25:50 +00001993
1994void GVN::cleanupGlobalSets() {
1995 VN.clear();
Nuno Lopese3127f32008-10-10 16:25:50 +00001996
1997 for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
1998 I = localAvail.begin(), E = localAvail.end(); I != E; ++I)
1999 delete I->second;
2000 localAvail.clear();
2001}
Bill Wendling6b18a392008-12-22 21:36:08 +00002002
2003/// verifyRemoved - Verify that the specified instruction does not occur in our
2004/// internal data structures.
Bill Wendlinge7f08e72008-12-22 22:28:56 +00002005void GVN::verifyRemoved(const Instruction *Inst) const {
2006 VN.verifyRemoved(Inst);
Bill Wendling3c793442008-12-22 22:14:07 +00002007
Bill Wendlinge7f08e72008-12-22 22:28:56 +00002008 // Walk through the value number scope to make sure the instruction isn't
2009 // ferreted away in it.
2010 for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
2011 I = localAvail.begin(), E = localAvail.end(); I != E; ++I) {
2012 const ValueNumberScope *VNS = I->second;
2013
2014 while (VNS) {
2015 for (DenseMap<uint32_t, Value*>::iterator
2016 II = VNS->table.begin(), IE = VNS->table.end(); II != IE; ++II) {
2017 assert(II->second != Inst && "Inst still in value numbering scope!");
2018 }
2019
2020 VNS = VNS->parent;
Bill Wendling3c793442008-12-22 22:14:07 +00002021 }
2022 }
Bill Wendling6b18a392008-12-22 21:36:08 +00002023}