blob: 1b42c6b9592bb550c85875ff304af2c968d92ac0 [file] [log] [blame]
Chris Lattner72bc70d2008-12-05 07:49:08 +00001//===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
Owen Anderson1ad2cb72007-07-24 17:55:58 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Anderson1ad2cb72007-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 Criswell090c0a22009-03-10 15:04:53 +000013// Note that this pass does the value numbering itself; it does not use the
Matthijs Kooijman845f5242008-06-05 07:55:49 +000014// ValueNumbering analysis passes.
15//
Owen Anderson1ad2cb72007-07-24 17:55:58 +000016//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "gvn"
Owen Anderson1ad2cb72007-07-24 17:55:58 +000019#include "llvm/Transforms/Scalar.h"
Owen Anderson0cd32032007-07-25 19:57:03 +000020#include "llvm/BasicBlock.h"
Owen Anderson45537912007-07-26 18:26:51 +000021#include "llvm/Constants.h"
Owen Anderson1ad2cb72007-07-24 17:55:58 +000022#include "llvm/DerivedTypes.h"
Owen Anderson45537912007-07-26 18:26:51 +000023#include "llvm/Function.h"
Devang Patelc64bc162009-03-06 02:59:27 +000024#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000025#include "llvm/LLVMContext.h"
Chris Lattnereed919b2009-09-21 05:57:11 +000026#include "llvm/Operator.h"
Owen Anderson45537912007-07-26 18:26:51 +000027#include "llvm/Value.h"
Owen Anderson1ad2cb72007-07-24 17:55:58 +000028#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/DepthFirstIterator.h"
Owen Anderson255dafc2008-12-15 02:03:00 +000030#include "llvm/ADT/PostOrderIterator.h"
Owen Anderson1ad2cb72007-07-24 17:55:58 +000031#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/Statistic.h"
Owen Andersonb388ca92007-10-18 19:39:33 +000034#include "llvm/Analysis/Dominators.h"
35#include "llvm/Analysis/AliasAnalysis.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000036#include "llvm/Analysis/MemoryBuiltins.h"
Owen Anderson1ad2cb72007-07-24 17:55:58 +000037#include "llvm/Analysis/MemoryDependenceAnalysis.h"
38#include "llvm/Support/CFG.h"
Owen Andersonaa0b6342008-06-19 19:57:25 +000039#include "llvm/Support/CommandLine.h"
Chris Lattner9f8a6a72008-03-29 04:36:18 +000040#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000041#include "llvm/Support/ErrorHandling.h"
Chris Lattnereed919b2009-09-21 05:57:11 +000042#include "llvm/Support/GetElementPtrTypeIterator.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000043#include "llvm/Support/raw_ostream.h"
Chris Lattnerbb6495c2009-09-20 19:03:47 +000044#include "llvm/Target/TargetData.h"
Owen Anderson5c274ee2008-06-19 19:54:19 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dale Johannesen42c3f552009-06-17 20:48:23 +000046#include "llvm/Transforms/Utils/Local.h"
Chris Lattnera09fbf02009-10-10 23:50:30 +000047#include "llvm/Transforms/Utils/SSAUpdater.h"
Duncan Sands4520dd22008-10-08 07:23:46 +000048#include <cstdio>
Owen Anderson1ad2cb72007-07-24 17:55:58 +000049using namespace llvm;
50
Bill Wendling70ded192008-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 Anderson961edc82008-07-15 16:28:06 +000054STATISTIC(NumGVNBlocks, "Number of blocks merged");
Bill Wendling70ded192008-12-22 22:14:07 +000055STATISTIC(NumPRELoad, "Number of loads PRE'd");
Chris Lattnerd27290d2008-03-22 04:13:49 +000056
Evan Cheng88d11c02008-06-20 01:01:07 +000057static cl::opt<bool> EnablePRE("enable-pre",
Owen Andersonc2b856e2008-07-17 19:41:00 +000058 cl::init(true), cl::Hidden);
Dan Gohmanc915c952009-06-15 18:30:15 +000059static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
Owen Andersonaa0b6342008-06-19 19:57:25 +000060
Owen Anderson1ad2cb72007-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 Lattner3e8b6632009-09-02 06:11:42 +000069 struct Expression {
Dan Gohmanae3a0be2009-06-04 22:49:04 +000070 enum ExpressionOpcode { ADD, FADD, SUB, FSUB, MUL, FMUL,
71 UDIV, SDIV, FDIV, UREM, SREM,
Daniel Dunbara279bc32009-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 Anderson1ad2cb72007-07-24 17:55:58 +000077 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
78 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
Daniel Dunbara279bc32009-09-20 02:20:51 +000079 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
Owen Anderson3b3f58c2008-05-13 08:17:22 +000080 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
Owen Andersond41ed4e2009-10-19 22:14:22 +000081 INSERTVALUE, EXTRACTVALUE, EMPTY, TOMBSTONE };
Owen Anderson1ad2cb72007-07-24 17:55:58 +000082
83 ExpressionOpcode opcode;
84 const Type* type;
Owen Anderson1ad2cb72007-07-24 17:55:58 +000085 SmallVector<uint32_t, 4> varargs;
Chris Lattnerb2412a82009-09-21 02:42:51 +000086 Value *function;
Daniel Dunbara279bc32009-09-20 02:20:51 +000087
Owen Anderson1ad2cb72007-07-24 17:55:58 +000088 Expression() { }
89 Expression(ExpressionOpcode o) : opcode(o) { }
Daniel Dunbara279bc32009-09-20 02:20:51 +000090
Owen Anderson1ad2cb72007-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 Andersonb388ca92007-10-18 19:39:33 +000098 else if (function != other.function)
99 return false;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000100 else {
101 if (varargs.size() != other.varargs.size())
102 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000103
Owen Anderson1ad2cb72007-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 Dunbara279bc32009-09-20 02:20:51 +0000107
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000108 return true;
109 }
110 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000111
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000112 bool operator!=(const Expression &other) const {
Bill Wendling75f02ee2008-12-22 22:16:31 +0000113 return !(*this == other);
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000114 }
115 };
Daniel Dunbara279bc32009-09-20 02:20:51 +0000116
Chris Lattner3e8b6632009-09-02 06:11:42 +0000117 class ValueTable {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000118 private:
119 DenseMap<Value*, uint32_t> valueNumbering;
120 DenseMap<Expression, uint32_t> expressionNumbering;
Owen Andersona472c4a2008-05-12 20:15:55 +0000121 AliasAnalysis* AA;
122 MemoryDependenceAnalysis* MD;
123 DominatorTree* DT;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000124
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000125 uint32_t nextValueNumber;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000126
Owen Anderson1ad2cb72007-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 Andersonb388ca92007-10-18 19:39:33 +0000138 Expression create_expression(CallInst* C);
Owen Anderson3b3f58c2008-05-13 08:17:22 +0000139 Expression create_expression(Constant* C);
Owen Andersond41ed4e2009-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 Anderson1ad2cb72007-07-24 17:55:58 +0000144 public:
Dan Gohmane63c4a22009-04-01 16:37:47 +0000145 ValueTable() : nextValueNumber(1) { }
Chris Lattnerb2412a82009-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 Anderson1ad2cb72007-07-24 17:55:58 +0000149 void clear();
Chris Lattnerb2412a82009-09-21 02:42:51 +0000150 void erase(Value *v);
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000151 unsigned size();
Owen Andersona472c4a2008-05-12 20:15:55 +0000152 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
Chris Lattner663e4412008-12-01 00:40:32 +0000153 AliasAnalysis *getAliasAnalysis() const { return AA; }
Owen Andersona472c4a2008-05-12 20:15:55 +0000154 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
155 void setDomTree(DominatorTree* D) { DT = D; }
Owen Anderson0ae33ef2008-07-03 17:44:33 +0000156 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
Bill Wendling246dbbb2008-12-22 21:36:08 +0000157 void verifyRemoved(const Value *) const;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000158 };
159}
160
161namespace llvm {
Chris Lattner76c1b972007-09-17 18:34:04 +0000162template <> struct DenseMapInfo<Expression> {
Owen Anderson830db6a2007-08-02 18:16:06 +0000163 static inline Expression getEmptyKey() {
164 return Expression(Expression::EMPTY);
165 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000166
Owen Anderson830db6a2007-08-02 18:16:06 +0000167 static inline Expression getTombstoneKey() {
168 return Expression(Expression::TOMBSTONE);
169 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000170
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000171 static unsigned getHashValue(const Expression e) {
172 unsigned hash = e.opcode;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000173
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000174 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
Owen Andersond41ed4e2009-10-19 22:14:22 +0000175 (unsigned)((uintptr_t)e.type >> 9));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000176
Owen Anderson830db6a2007-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 Anderson1ad2cb72007-07-24 17:55:58 +0000179 hash = *I + hash * 37;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000180
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000181 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
182 (unsigned)((uintptr_t)e.function >> 9)) +
183 hash * 37;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000184
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000185 return hash;
186 }
Chris Lattner76c1b972007-09-17 18:34:04 +0000187 static bool isEqual(const Expression &LHS, const Expression &RHS) {
188 return LHS == RHS;
189 }
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000190 static bool isPod() { return true; }
191};
192}
193
194//===----------------------------------------------------------------------===//
195// ValueTable Internal Functions
196//===----------------------------------------------------------------------===//
Chris Lattner88365bb2008-03-21 21:14:38 +0000197Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000198 switch(BO->getOpcode()) {
Chris Lattner88365bb2008-03-21 21:14:38 +0000199 default: // THIS SHOULD NEVER HAPPEN
Torok Edwinc23197a2009-07-14 16:55:14 +0000200 llvm_unreachable("Binary operator with unknown opcode?");
Chris Lattner88365bb2008-03-21 21:14:38 +0000201 case Instruction::Add: return Expression::ADD;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000202 case Instruction::FAdd: return Expression::FADD;
Chris Lattner88365bb2008-03-21 21:14:38 +0000203 case Instruction::Sub: return Expression::SUB;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000204 case Instruction::FSub: return Expression::FSUB;
Chris Lattner88365bb2008-03-21 21:14:38 +0000205 case Instruction::Mul: return Expression::MUL;
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000206 case Instruction::FMul: return Expression::FMUL;
Chris Lattner88365bb2008-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 Anderson1ad2cb72007-07-24 17:55:58 +0000219 }
220}
221
222Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +0000223 if (isa<ICmpInst>(C)) {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000224 switch (C->getPredicate()) {
Chris Lattner88365bb2008-03-21 21:14:38 +0000225 default: // THIS SHOULD NEVER HAPPEN
Torok Edwinc23197a2009-07-14 16:55:14 +0000226 llvm_unreachable("Comparison with unknown predicate?");
Chris Lattner88365bb2008-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 Anderson1ad2cb72007-07-24 17:55:58 +0000237 }
Nick Lewycky7f6aa2b2009-07-08 03:04:38 +0000238 } else {
239 switch (C->getPredicate()) {
240 default: // THIS SHOULD NEVER HAPPEN
Torok Edwinc23197a2009-07-14 16:55:14 +0000241 llvm_unreachable("Comparison with unknown predicate?");
Nick Lewycky7f6aa2b2009-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 Anderson1ad2cb72007-07-24 17:55:58 +0000257 }
258}
259
Chris Lattner88365bb2008-03-21 21:14:38 +0000260Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000261 switch(C->getOpcode()) {
Chris Lattner88365bb2008-03-21 21:14:38 +0000262 default: // THIS SHOULD NEVER HAPPEN
Torok Edwinc23197a2009-07-14 16:55:14 +0000263 llvm_unreachable("Cast operator with unknown opcode?");
Chris Lattner88365bb2008-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 Anderson1ad2cb72007-07-24 17:55:58 +0000276 }
277}
278
Owen Andersonb388ca92007-10-18 19:39:33 +0000279Expression ValueTable::create_expression(CallInst* C) {
280 Expression e;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000281
Owen Andersonb388ca92007-10-18 19:39:33 +0000282 e.type = C->getType();
Owen Andersonb388ca92007-10-18 19:39:33 +0000283 e.function = C->getCalledFunction();
284 e.opcode = Expression::CALL;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000285
Owen Andersonb388ca92007-10-18 19:39:33 +0000286 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
287 I != E; ++I)
Owen Anderson8f46c782008-04-11 05:11:49 +0000288 e.varargs.push_back(lookup_or_add(*I));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000289
Owen Andersonb388ca92007-10-18 19:39:33 +0000290 return e;
291}
292
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000293Expression ValueTable::create_expression(BinaryOperator* BO) {
294 Expression e;
Owen Andersond41ed4e2009-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 Andersonb388ca92007-10-18 19:39:33 +0000297 e.function = 0;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000298 e.type = BO->getType();
299 e.opcode = getOpcode(BO);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000300
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000301 return e;
302}
303
304Expression ValueTable::create_expression(CmpInst* C) {
305 Expression e;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000306
Owen Andersond41ed4e2009-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 Andersonb388ca92007-10-18 19:39:33 +0000309 e.function = 0;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000310 e.type = C->getType();
311 e.opcode = getOpcode(C);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000312
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000313 return e;
314}
315
316Expression ValueTable::create_expression(CastInst* C) {
317 Expression e;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000318
Owen Andersond41ed4e2009-10-19 22:14:22 +0000319 e.varargs.push_back(lookup_or_add(C->getOperand(0)));
Owen Andersonb388ca92007-10-18 19:39:33 +0000320 e.function = 0;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000321 e.type = C->getType();
322 e.opcode = getOpcode(C);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000323
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000324 return e;
325}
326
327Expression ValueTable::create_expression(ShuffleVectorInst* S) {
328 Expression e;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000329
Owen Andersond41ed4e2009-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 Andersonb388ca92007-10-18 19:39:33 +0000333 e.function = 0;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000334 e.type = S->getType();
335 e.opcode = Expression::SHUFFLE;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000336
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000337 return e;
338}
339
340Expression ValueTable::create_expression(ExtractElementInst* E) {
341 Expression e;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000342
Owen Andersond41ed4e2009-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 Andersonb388ca92007-10-18 19:39:33 +0000345 e.function = 0;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000346 e.type = E->getType();
347 e.opcode = Expression::EXTRACT;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000348
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000349 return e;
350}
351
352Expression ValueTable::create_expression(InsertElementInst* I) {
353 Expression e;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000354
Owen Andersond41ed4e2009-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 Andersonb388ca92007-10-18 19:39:33 +0000358 e.function = 0;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000359 e.type = I->getType();
360 e.opcode = Expression::INSERT;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000361
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000362 return e;
363}
364
365Expression ValueTable::create_expression(SelectInst* I) {
366 Expression e;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000367
Owen Andersond41ed4e2009-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 Andersonb388ca92007-10-18 19:39:33 +0000371 e.function = 0;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000372 e.type = I->getType();
373 e.opcode = Expression::SELECT;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000374
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000375 return e;
376}
377
378Expression ValueTable::create_expression(GetElementPtrInst* G) {
379 Expression e;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000380
Owen Andersond41ed4e2009-10-19 22:14:22 +0000381 e.varargs.push_back(lookup_or_add(G->getPointerOperand()));
Owen Andersonb388ca92007-10-18 19:39:33 +0000382 e.function = 0;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000383 e.type = G->getType();
384 e.opcode = Expression::GEP;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000385
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000386 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
387 I != E; ++I)
Owen Anderson8f46c782008-04-11 05:11:49 +0000388 e.varargs.push_back(lookup_or_add(*I));
Daniel Dunbara279bc32009-09-20 02:20:51 +0000389
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000390 return e;
391}
392
Owen Andersond41ed4e2009-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 Anderson1ad2cb72007-07-24 17:55:58 +0000422//===----------------------------------------------------------------------===//
423// ValueTable External Functions
424//===----------------------------------------------------------------------===//
425
Owen Andersonb2303722008-06-18 21:41:49 +0000426/// add - Insert a value into the table with a specified value number.
Chris Lattnerb2412a82009-09-21 02:42:51 +0000427void ValueTable::add(Value *V, uint32_t num) {
Owen Andersonb2303722008-06-18 21:41:49 +0000428 valueNumbering.insert(std::make_pair(V, num));
429}
430
Owen Andersond41ed4e2009-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 }
Dan Gohman4ec01b22009-11-14 02:27:51 +0000446 if (!MD) {
447 e = nextValueNumber++;
448 valueNumbering[C] = e;
449 return e;
450 }
Owen Andersond41ed4e2009-10-19 22:14:22 +0000451
452 MemDepResult local_dep = MD->getDependency(C);
453
454 if (!local_dep.isDef() && !local_dep.isNonLocal()) {
455 valueNumbering[C] = nextValueNumber;
456 return nextValueNumber++;
457 }
458
459 if (local_dep.isDef()) {
460 CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
461
462 if (local_cdep->getNumOperands() != C->getNumOperands()) {
463 valueNumbering[C] = nextValueNumber;
464 return nextValueNumber++;
465 }
466
467 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
468 uint32_t c_vn = lookup_or_add(C->getOperand(i));
469 uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
470 if (c_vn != cd_vn) {
471 valueNumbering[C] = nextValueNumber;
472 return nextValueNumber++;
473 }
474 }
475
476 uint32_t v = lookup_or_add(local_cdep);
477 valueNumbering[C] = v;
478 return v;
479 }
480
481 // Non-local case.
482 const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
483 MD->getNonLocalCallDependency(CallSite(C));
484 // FIXME: call/call dependencies for readonly calls should return def, not
485 // clobber! Move the checking logic to MemDep!
486 CallInst* cdep = 0;
487
488 // Check to see if we have a single dominating call instruction that is
489 // identical to C.
490 for (unsigned i = 0, e = deps.size(); i != e; ++i) {
491 const MemoryDependenceAnalysis::NonLocalDepEntry *I = &deps[i];
492 // Ignore non-local dependencies.
493 if (I->second.isNonLocal())
494 continue;
495
496 // We don't handle non-depedencies. If we already have a call, reject
497 // instruction dependencies.
498 if (I->second.isClobber() || cdep != 0) {
499 cdep = 0;
500 break;
501 }
502
503 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->second.getInst());
504 // FIXME: All duplicated with non-local case.
505 if (NonLocalDepCall && DT->properlyDominates(I->first, C->getParent())){
506 cdep = NonLocalDepCall;
507 continue;
508 }
509
510 cdep = 0;
511 break;
512 }
513
514 if (!cdep) {
515 valueNumbering[C] = nextValueNumber;
516 return nextValueNumber++;
517 }
518
519 if (cdep->getNumOperands() != C->getNumOperands()) {
520 valueNumbering[C] = nextValueNumber;
521 return nextValueNumber++;
522 }
523 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
524 uint32_t c_vn = lookup_or_add(C->getOperand(i));
525 uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
526 if (c_vn != cd_vn) {
527 valueNumbering[C] = nextValueNumber;
528 return nextValueNumber++;
529 }
530 }
531
532 uint32_t v = lookup_or_add(cdep);
533 valueNumbering[C] = v;
534 return v;
535
536 } else {
537 valueNumbering[C] = nextValueNumber;
538 return nextValueNumber++;
539 }
540}
541
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000542/// lookup_or_add - Returns the value number for the specified value, assigning
543/// it a new number if it did not have one before.
Chris Lattnerb2412a82009-09-21 02:42:51 +0000544uint32_t ValueTable::lookup_or_add(Value *V) {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000545 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
546 if (VI != valueNumbering.end())
547 return VI->second;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000548
Owen Andersond41ed4e2009-10-19 22:14:22 +0000549 if (!isa<Instruction>(V)) {
Owen Anderson158d86e2009-10-19 21:14:57 +0000550 valueNumbering[V] = nextValueNumber;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000551 return nextValueNumber++;
552 }
Owen Andersond41ed4e2009-10-19 22:14:22 +0000553
554 Instruction* I = cast<Instruction>(V);
555 Expression exp;
556 switch (I->getOpcode()) {
557 case Instruction::Call:
558 return lookup_or_add_call(cast<CallInst>(I));
559 case Instruction::Add:
560 case Instruction::FAdd:
561 case Instruction::Sub:
562 case Instruction::FSub:
563 case Instruction::Mul:
564 case Instruction::FMul:
565 case Instruction::UDiv:
566 case Instruction::SDiv:
567 case Instruction::FDiv:
568 case Instruction::URem:
569 case Instruction::SRem:
570 case Instruction::FRem:
571 case Instruction::Shl:
572 case Instruction::LShr:
573 case Instruction::AShr:
574 case Instruction::And:
575 case Instruction::Or :
576 case Instruction::Xor:
577 exp = create_expression(cast<BinaryOperator>(I));
578 break;
579 case Instruction::ICmp:
580 case Instruction::FCmp:
581 exp = create_expression(cast<CmpInst>(I));
582 break;
583 case Instruction::Trunc:
584 case Instruction::ZExt:
585 case Instruction::SExt:
586 case Instruction::FPToUI:
587 case Instruction::FPToSI:
588 case Instruction::UIToFP:
589 case Instruction::SIToFP:
590 case Instruction::FPTrunc:
591 case Instruction::FPExt:
592 case Instruction::PtrToInt:
593 case Instruction::IntToPtr:
594 case Instruction::BitCast:
595 exp = create_expression(cast<CastInst>(I));
596 break;
597 case Instruction::Select:
598 exp = create_expression(cast<SelectInst>(I));
599 break;
600 case Instruction::ExtractElement:
601 exp = create_expression(cast<ExtractElementInst>(I));
602 break;
603 case Instruction::InsertElement:
604 exp = create_expression(cast<InsertElementInst>(I));
605 break;
606 case Instruction::ShuffleVector:
607 exp = create_expression(cast<ShuffleVectorInst>(I));
608 break;
609 case Instruction::ExtractValue:
610 exp = create_expression(cast<ExtractValueInst>(I));
611 break;
612 case Instruction::InsertValue:
613 exp = create_expression(cast<InsertValueInst>(I));
614 break;
615 case Instruction::GetElementPtr:
616 exp = create_expression(cast<GetElementPtrInst>(I));
617 break;
618 default:
619 valueNumbering[V] = nextValueNumber;
620 return nextValueNumber++;
621 }
622
623 uint32_t& e = expressionNumbering[exp];
624 if (!e) e = nextValueNumber++;
625 valueNumbering[V] = e;
626 return e;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000627}
628
629/// lookup - Returns the value number of the specified value. Fails if
630/// the value has not yet been numbered.
Chris Lattnerb2412a82009-09-21 02:42:51 +0000631uint32_t ValueTable::lookup(Value *V) const {
Jeffrey Yasskin81cf4322009-11-10 01:02:17 +0000632 DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
Chris Lattner88365bb2008-03-21 21:14:38 +0000633 assert(VI != valueNumbering.end() && "Value not numbered?");
634 return VI->second;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000635}
636
637/// clear - Remove all entries from the ValueTable
638void ValueTable::clear() {
639 valueNumbering.clear();
640 expressionNumbering.clear();
641 nextValueNumber = 1;
642}
643
Owen Andersonbf7d0bc2007-07-31 23:27:13 +0000644/// erase - Remove a value from the value numbering
Chris Lattnerb2412a82009-09-21 02:42:51 +0000645void ValueTable::erase(Value *V) {
Owen Andersonbf7d0bc2007-07-31 23:27:13 +0000646 valueNumbering.erase(V);
647}
648
Bill Wendling246dbbb2008-12-22 21:36:08 +0000649/// verifyRemoved - Verify that the value is removed from all internal data
650/// structures.
651void ValueTable::verifyRemoved(const Value *V) const {
Jeffrey Yasskin81cf4322009-11-10 01:02:17 +0000652 for (DenseMap<Value*, uint32_t>::const_iterator
Bill Wendling246dbbb2008-12-22 21:36:08 +0000653 I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
654 assert(I->first != V && "Inst still occurs in value numbering map!");
655 }
656}
657
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000658//===----------------------------------------------------------------------===//
Bill Wendling30788b82008-12-22 22:32:22 +0000659// GVN Pass
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000660//===----------------------------------------------------------------------===//
661
662namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000663 struct ValueNumberScope {
Owen Anderson6fafe842008-06-20 01:15:47 +0000664 ValueNumberScope* parent;
665 DenseMap<uint32_t, Value*> table;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000666
Owen Anderson6fafe842008-06-20 01:15:47 +0000667 ValueNumberScope(ValueNumberScope* p) : parent(p) { }
668 };
669}
670
671namespace {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000672
Chris Lattner3e8b6632009-09-02 06:11:42 +0000673 class GVN : public FunctionPass {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000674 bool runOnFunction(Function &F);
675 public:
676 static char ID; // Pass identification, replacement for typeid
Dan Gohman4ec01b22009-11-14 02:27:51 +0000677 explicit GVN(bool nopre = false, bool noloads = false)
678 : FunctionPass(&ID), NoPRE(nopre), NoLoads(noloads), MD(0) { }
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000679
680 private:
Evan Cheng2f192c22009-10-30 20:12:24 +0000681 bool NoPRE;
Dan Gohman4ec01b22009-11-14 02:27:51 +0000682 bool NoLoads;
Chris Lattner663e4412008-12-01 00:40:32 +0000683 MemoryDependenceAnalysis *MD;
684 DominatorTree *DT;
685
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000686 ValueTable VN;
Owen Anderson6fafe842008-06-20 01:15:47 +0000687 DenseMap<BasicBlock*, ValueNumberScope*> localAvail;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000688
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000689 // This transformation requires dominator postdominator info
690 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000691 AU.addRequired<DominatorTree>();
Dan Gohman4ec01b22009-11-14 02:27:51 +0000692 if (!NoLoads)
693 AU.addRequired<MemoryDependenceAnalysis>();
Owen Andersonb388ca92007-10-18 19:39:33 +0000694 AU.addRequired<AliasAnalysis>();
Daniel Dunbara279bc32009-09-20 02:20:51 +0000695
Owen Andersonb70a5712008-06-23 17:49:45 +0000696 AU.addPreserved<DominatorTree>();
Owen Andersonb388ca92007-10-18 19:39:33 +0000697 AU.addPreserved<AliasAnalysis>();
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000698 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000699
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000700 // Helper fuctions
701 // FIXME: eliminate or document these better
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000702 bool processLoad(LoadInst* L,
Chris Lattner8e1e95c2008-03-21 22:01:16 +0000703 SmallVectorImpl<Instruction*> &toErase);
Chris Lattnerb2412a82009-09-21 02:42:51 +0000704 bool processInstruction(Instruction *I,
Chris Lattner8e1e95c2008-03-21 22:01:16 +0000705 SmallVectorImpl<Instruction*> &toErase);
Owen Anderson830db6a2007-08-02 18:16:06 +0000706 bool processNonLocalLoad(LoadInst* L,
Chris Lattner8e1e95c2008-03-21 22:01:16 +0000707 SmallVectorImpl<Instruction*> &toErase);
Chris Lattnerb2412a82009-09-21 02:42:51 +0000708 bool processBlock(BasicBlock *BB);
Owen Andersonb2303722008-06-18 21:41:49 +0000709 void dump(DenseMap<uint32_t, Value*>& d);
Owen Anderson3e75a422007-08-14 18:04:11 +0000710 bool iterateOnFunction(Function &F);
Chris Lattnerb2412a82009-09-21 02:42:51 +0000711 Value *CollapsePhi(PHINode* p);
Owen Andersonb2303722008-06-18 21:41:49 +0000712 bool performPRE(Function& F);
Chris Lattnerb2412a82009-09-21 02:42:51 +0000713 Value *lookupNumber(BasicBlock *BB, uint32_t num);
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +0000714 void cleanupGlobalSets();
Bill Wendling246dbbb2008-12-22 21:36:08 +0000715 void verifyRemoved(const Instruction *I) const;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000716 };
Daniel Dunbara279bc32009-09-20 02:20:51 +0000717
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000718 char GVN::ID = 0;
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000719}
720
721// createGVNPass - The public interface to this file...
Dan Gohman4ec01b22009-11-14 02:27:51 +0000722FunctionPass *llvm::createGVNPass(bool NoPRE, bool NoLoads) {
723 return new GVN(NoPRE, NoLoads);
724}
Owen Anderson1ad2cb72007-07-24 17:55:58 +0000725
726static RegisterPass<GVN> X("gvn",
727 "Global Value Numbering");
728
Owen Andersonb2303722008-06-18 21:41:49 +0000729void GVN::dump(DenseMap<uint32_t, Value*>& d) {
Owen Anderson0cd32032007-07-25 19:57:03 +0000730 printf("{\n");
Owen Andersonb2303722008-06-18 21:41:49 +0000731 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
Owen Anderson0cd32032007-07-25 19:57:03 +0000732 E = d.end(); I != E; ++I) {
Owen Andersonb2303722008-06-18 21:41:49 +0000733 printf("%d\n", I->first);
Owen Anderson0cd32032007-07-25 19:57:03 +0000734 I->second->dump();
735 }
736 printf("}\n");
737}
738
Chris Lattnerb2412a82009-09-21 02:42:51 +0000739static bool isSafeReplacement(PHINode* p, Instruction *inst) {
Owen Anderson4eebf0b2009-08-26 22:55:11 +0000740 if (!isa<PHINode>(inst))
741 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000742
Owen Anderson4eebf0b2009-08-26 22:55:11 +0000743 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
744 UI != E; ++UI)
745 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
746 if (use_phi->getParent() == inst->getParent())
747 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000748
Owen Anderson4eebf0b2009-08-26 22:55:11 +0000749 return true;
750}
751
Chris Lattnerb2412a82009-09-21 02:42:51 +0000752Value *GVN::CollapsePhi(PHINode *PN) {
753 Value *ConstVal = PN->hasConstantValue(DT);
754 if (!ConstVal) return 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000755
Chris Lattnerb2412a82009-09-21 02:42:51 +0000756 Instruction *Inst = dyn_cast<Instruction>(ConstVal);
757 if (!Inst)
758 return ConstVal;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000759
Chris Lattnerb2412a82009-09-21 02:42:51 +0000760 if (DT->dominates(Inst, PN))
761 if (isSafeReplacement(PN, Inst))
762 return Inst;
Owen Anderson1defe2d2007-08-16 22:51:56 +0000763 return 0;
764}
Owen Anderson0cd32032007-07-25 19:57:03 +0000765
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000766/// IsValueFullyAvailableInBlock - Return true if we can prove that the value
767/// we're analyzing is fully available in the specified block. As we go, keep
Chris Lattner72bc70d2008-12-05 07:49:08 +0000768/// track of which blocks we know are fully alive in FullyAvailableBlocks. This
769/// map is actually a tri-state map with the following values:
770/// 0) we know the block *is not* fully available.
771/// 1) we know the block *is* fully available.
772/// 2) we do not know whether the block is fully available or not, but we are
773/// currently speculating that it will be.
774/// 3) we are speculating for this block and have used that to speculate for
775/// other blocks.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000776static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
Chris Lattner72bc70d2008-12-05 07:49:08 +0000777 DenseMap<BasicBlock*, char> &FullyAvailableBlocks) {
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000778 // Optimistically assume that the block is fully available and check to see
779 // if we already know about this block in one lookup.
Daniel Dunbara279bc32009-09-20 02:20:51 +0000780 std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
Chris Lattner72bc70d2008-12-05 07:49:08 +0000781 FullyAvailableBlocks.insert(std::make_pair(BB, 2));
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000782
783 // If the entry already existed for this block, return the precomputed value.
Chris Lattner72bc70d2008-12-05 07:49:08 +0000784 if (!IV.second) {
785 // If this is a speculative "available" value, mark it as being used for
786 // speculation of other blocks.
787 if (IV.first->second == 2)
788 IV.first->second = 3;
789 return IV.first->second != 0;
790 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000791
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000792 // Otherwise, see if it is fully available in all predecessors.
793 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000794
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000795 // If this block has no predecessors, it isn't live-in here.
796 if (PI == PE)
Chris Lattner72bc70d2008-12-05 07:49:08 +0000797 goto SpeculationFailure;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000798
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000799 for (; PI != PE; ++PI)
800 // If the value isn't fully available in one of our predecessors, then it
801 // isn't fully available in this block either. Undo our previous
802 // optimistic assumption and bail out.
803 if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
Chris Lattner72bc70d2008-12-05 07:49:08 +0000804 goto SpeculationFailure;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000805
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000806 return true;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000807
Chris Lattner72bc70d2008-12-05 07:49:08 +0000808// SpeculationFailure - If we get here, we found out that this is not, after
809// all, a fully-available block. We have a problem if we speculated on this and
810// used the speculation to mark other blocks as available.
811SpeculationFailure:
812 char &BBVal = FullyAvailableBlocks[BB];
Daniel Dunbara279bc32009-09-20 02:20:51 +0000813
Chris Lattner72bc70d2008-12-05 07:49:08 +0000814 // If we didn't speculate on this, just return with it set to false.
815 if (BBVal == 2) {
816 BBVal = 0;
817 return false;
818 }
819
820 // If we did speculate on this value, we could have blocks set to 1 that are
821 // incorrect. Walk the (transitive) successors of this block and mark them as
822 // 0 if set to one.
823 SmallVector<BasicBlock*, 32> BBWorklist;
824 BBWorklist.push_back(BB);
Daniel Dunbara279bc32009-09-20 02:20:51 +0000825
Chris Lattner72bc70d2008-12-05 07:49:08 +0000826 while (!BBWorklist.empty()) {
827 BasicBlock *Entry = BBWorklist.pop_back_val();
828 // Note that this sets blocks to 0 (unavailable) if they happen to not
829 // already be in FullyAvailableBlocks. This is safe.
830 char &EntryVal = FullyAvailableBlocks[Entry];
831 if (EntryVal == 0) continue; // Already unavailable.
832
833 // Mark as unavailable.
834 EntryVal = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +0000835
Chris Lattner72bc70d2008-12-05 07:49:08 +0000836 for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I)
837 BBWorklist.push_back(*I);
838 }
Daniel Dunbara279bc32009-09-20 02:20:51 +0000839
Chris Lattner72bc70d2008-12-05 07:49:08 +0000840 return false;
Chris Lattnerc89c6a92008-12-02 08:16:11 +0000841}
842
Chris Lattner771a5422009-09-20 20:09:34 +0000843
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000844/// CanCoerceMustAliasedValueToLoad - Return true if
845/// CoerceAvailableValueToLoadType will succeed.
846static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
847 const Type *LoadTy,
848 const TargetData &TD) {
849 // If the loaded or stored value is an first class array or struct, don't try
850 // to transform them. We need to be able to bitcast to integer.
851 if (isa<StructType>(LoadTy) || isa<ArrayType>(LoadTy) ||
852 isa<StructType>(StoredVal->getType()) ||
853 isa<ArrayType>(StoredVal->getType()))
854 return false;
855
856 // The store has to be at least as big as the load.
857 if (TD.getTypeSizeInBits(StoredVal->getType()) <
858 TD.getTypeSizeInBits(LoadTy))
859 return false;
860
861 return true;
862}
863
864
Chris Lattner771a5422009-09-20 20:09:34 +0000865/// CoerceAvailableValueToLoadType - If we saw a store of a value to memory, and
866/// then a load from a must-aliased pointer of a different type, try to coerce
867/// the stored value. LoadedTy is the type of the load we want to replace and
868/// InsertPt is the place to insert new instructions.
869///
870/// If we can't do it, return null.
871static Value *CoerceAvailableValueToLoadType(Value *StoredVal,
872 const Type *LoadedTy,
873 Instruction *InsertPt,
874 const TargetData &TD) {
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000875 if (!CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, TD))
876 return 0;
877
Chris Lattner771a5422009-09-20 20:09:34 +0000878 const Type *StoredValTy = StoredVal->getType();
879
880 uint64_t StoreSize = TD.getTypeSizeInBits(StoredValTy);
881 uint64_t LoadSize = TD.getTypeSizeInBits(LoadedTy);
882
883 // If the store and reload are the same size, we can always reuse it.
884 if (StoreSize == LoadSize) {
885 if (isa<PointerType>(StoredValTy) && isa<PointerType>(LoadedTy)) {
886 // Pointer to Pointer -> use bitcast.
887 return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
888 }
889
890 // Convert source pointers to integers, which can be bitcast.
891 if (isa<PointerType>(StoredValTy)) {
892 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
893 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
894 }
895
896 const Type *TypeToCastTo = LoadedTy;
897 if (isa<PointerType>(TypeToCastTo))
898 TypeToCastTo = TD.getIntPtrType(StoredValTy->getContext());
899
900 if (StoredValTy != TypeToCastTo)
901 StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
902
903 // Cast to pointer if the load needs a pointer type.
904 if (isa<PointerType>(LoadedTy))
905 StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
906
907 return StoredVal;
908 }
909
910 // If the loaded value is smaller than the available value, then we can
911 // extract out a piece from it. If the available value is too small, then we
912 // can't do anything.
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000913 assert(StoreSize >= LoadSize && "CanCoerceMustAliasedValueToLoad fail");
Chris Lattner771a5422009-09-20 20:09:34 +0000914
915 // Convert source pointers to integers, which can be manipulated.
916 if (isa<PointerType>(StoredValTy)) {
917 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
918 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
919 }
920
921 // Convert vectors and fp to integer, which can be manipulated.
922 if (!isa<IntegerType>(StoredValTy)) {
923 StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
924 StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
925 }
926
927 // If this is a big-endian system, we need to shift the value down to the low
928 // bits so that a truncate will work.
929 if (TD.isBigEndian()) {
930 Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
931 StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
932 }
933
934 // Truncate the integer to the right size now.
935 const Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
936 StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
937
938 if (LoadedTy == NewIntTy)
939 return StoredVal;
940
941 // If the result is a pointer, inttoptr.
942 if (isa<PointerType>(LoadedTy))
943 return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
944
945 // Otherwise, bitcast.
946 return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
947}
948
Chris Lattnerca749402009-09-21 06:24:16 +0000949/// GetBaseWithConstantOffset - Analyze the specified pointer to see if it can
950/// be expressed as a base pointer plus a constant offset. Return the base and
951/// offset to the caller.
952static Value *GetBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
Chris Lattner4fbd14e2009-09-21 06:48:08 +0000953 const TargetData &TD) {
Chris Lattnerca749402009-09-21 06:24:16 +0000954 Operator *PtrOp = dyn_cast<Operator>(Ptr);
955 if (PtrOp == 0) return Ptr;
956
957 // Just look through bitcasts.
958 if (PtrOp->getOpcode() == Instruction::BitCast)
959 return GetBaseWithConstantOffset(PtrOp->getOperand(0), Offset, TD);
960
961 // If this is a GEP with constant indices, we can look through it.
962 GEPOperator *GEP = dyn_cast<GEPOperator>(PtrOp);
963 if (GEP == 0 || !GEP->hasAllConstantIndices()) return Ptr;
964
965 gep_type_iterator GTI = gep_type_begin(GEP);
966 for (User::op_iterator I = GEP->idx_begin(), E = GEP->idx_end(); I != E;
967 ++I, ++GTI) {
968 ConstantInt *OpC = cast<ConstantInt>(*I);
969 if (OpC->isZero()) continue;
970
971 // Handle a struct and array indices which add their offset to the pointer.
972 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner4fbd14e2009-09-21 06:48:08 +0000973 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
Chris Lattnerca749402009-09-21 06:24:16 +0000974 } else {
Chris Lattner4fbd14e2009-09-21 06:48:08 +0000975 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnerca749402009-09-21 06:24:16 +0000976 Offset += OpC->getSExtValue()*Size;
977 }
978 }
979
980 // Re-sign extend from the pointer size if needed to get overflow edge cases
981 // right.
Chris Lattner4fbd14e2009-09-21 06:48:08 +0000982 unsigned PtrSize = TD.getPointerSizeInBits();
Chris Lattnerca749402009-09-21 06:24:16 +0000983 if (PtrSize < 64)
984 Offset = (Offset << (64-PtrSize)) >> (64-PtrSize);
985
986 return GetBaseWithConstantOffset(GEP->getPointerOperand(), Offset, TD);
987}
988
989
990/// AnalyzeLoadFromClobberingStore - This function is called when we have a
991/// memdep query of a load that ends up being a clobbering store. This means
992/// that the store *may* provide bits used by the load but we can't be sure
993/// because the pointers don't mustalias. Check this case to see if there is
994/// anything more we can do before we give up. This returns -1 if we have to
995/// give up, or a byte number in the stored value of the piece that feeds the
996/// load.
997static int AnalyzeLoadFromClobberingStore(LoadInst *L, StoreInst *DepSI,
Chris Lattner4fbd14e2009-09-21 06:48:08 +0000998 const TargetData &TD) {
Chris Lattner8b2bc3d2009-09-21 17:24:04 +0000999 // If the loaded or stored value is an first class array or struct, don't try
1000 // to transform them. We need to be able to bitcast to integer.
1001 if (isa<StructType>(L->getType()) || isa<ArrayType>(L->getType()) ||
1002 isa<StructType>(DepSI->getOperand(0)->getType()) ||
1003 isa<ArrayType>(DepSI->getOperand(0)->getType()))
1004 return -1;
1005
Chris Lattnerca749402009-09-21 06:24:16 +00001006 int64_t StoreOffset = 0, LoadOffset = 0;
1007 Value *StoreBase =
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001008 GetBaseWithConstantOffset(DepSI->getPointerOperand(), StoreOffset, TD);
Chris Lattnerca749402009-09-21 06:24:16 +00001009 Value *LoadBase =
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001010 GetBaseWithConstantOffset(L->getPointerOperand(), LoadOffset, TD);
Chris Lattnerca749402009-09-21 06:24:16 +00001011 if (StoreBase != LoadBase)
1012 return -1;
1013
1014 // If the load and store are to the exact same address, they should have been
1015 // a must alias. AA must have gotten confused.
1016 // FIXME: Study to see if/when this happens.
1017 if (LoadOffset == StoreOffset) {
1018#if 0
1019 errs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
1020 << "Base = " << *StoreBase << "\n"
1021 << "Store Ptr = " << *DepSI->getPointerOperand() << "\n"
1022 << "Store Offs = " << StoreOffset << " - " << *DepSI << "\n"
1023 << "Load Ptr = " << *L->getPointerOperand() << "\n"
1024 << "Load Offs = " << LoadOffset << " - " << *L << "\n\n";
1025 errs() << "'" << L->getParent()->getParent()->getName() << "'"
1026 << *L->getParent();
1027#endif
1028 return -1;
1029 }
1030
1031 // If the load and store don't overlap at all, the store doesn't provide
1032 // anything to the load. In this case, they really don't alias at all, AA
1033 // must have gotten confused.
1034 // FIXME: Investigate cases where this bails out, e.g. rdar://7238614. Then
1035 // remove this check, as it is duplicated with what we have below.
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001036 uint64_t StoreSize = TD.getTypeSizeInBits(DepSI->getOperand(0)->getType());
1037 uint64_t LoadSize = TD.getTypeSizeInBits(L->getType());
Chris Lattnerca749402009-09-21 06:24:16 +00001038
1039 if ((StoreSize & 7) | (LoadSize & 7))
1040 return -1;
1041 StoreSize >>= 3; // Convert to bytes.
1042 LoadSize >>= 3;
1043
1044
1045 bool isAAFailure = false;
1046 if (StoreOffset < LoadOffset) {
1047 isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
1048 } else {
1049 isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
1050 }
1051 if (isAAFailure) {
1052#if 0
1053 errs() << "STORE LOAD DEP WITH COMMON BASE:\n"
1054 << "Base = " << *StoreBase << "\n"
1055 << "Store Ptr = " << *DepSI->getPointerOperand() << "\n"
1056 << "Store Offs = " << StoreOffset << " - " << *DepSI << "\n"
1057 << "Load Ptr = " << *L->getPointerOperand() << "\n"
1058 << "Load Offs = " << LoadOffset << " - " << *L << "\n\n";
1059 errs() << "'" << L->getParent()->getParent()->getName() << "'"
1060 << *L->getParent();
1061#endif
1062 return -1;
1063 }
1064
1065 // If the Load isn't completely contained within the stored bits, we don't
1066 // have all the bits to feed it. We could do something crazy in the future
1067 // (issue a smaller load then merge the bits in) but this seems unlikely to be
1068 // valuable.
1069 if (StoreOffset > LoadOffset ||
1070 StoreOffset+StoreSize < LoadOffset+LoadSize)
1071 return -1;
1072
1073 // Okay, we can do this transformation. Return the number of bytes into the
1074 // store that the load is.
1075 return LoadOffset-StoreOffset;
1076}
1077
1078
1079/// GetStoreValueForLoad - This function is called when we have a
1080/// memdep query of a load that ends up being a clobbering store. This means
1081/// that the store *may* provide bits used by the load but we can't be sure
1082/// because the pointers don't mustalias. Check this case to see if there is
1083/// anything more we can do before we give up.
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001084static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
1085 const Type *LoadTy,
1086 Instruction *InsertPt, const TargetData &TD){
Chris Lattnerca749402009-09-21 06:24:16 +00001087 LLVMContext &Ctx = SrcVal->getType()->getContext();
1088
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001089 uint64_t StoreSize = TD.getTypeSizeInBits(SrcVal->getType())/8;
1090 uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy)/8;
Chris Lattnerca749402009-09-21 06:24:16 +00001091
1092
1093 // Compute which bits of the stored value are being used by the load. Convert
1094 // to an integer type to start with.
1095 if (isa<PointerType>(SrcVal->getType()))
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001096 SrcVal = new PtrToIntInst(SrcVal, TD.getIntPtrType(Ctx), "tmp", InsertPt);
Chris Lattnerca749402009-09-21 06:24:16 +00001097 if (!isa<IntegerType>(SrcVal->getType()))
1098 SrcVal = new BitCastInst(SrcVal, IntegerType::get(Ctx, StoreSize*8),
1099 "tmp", InsertPt);
1100
1101 // Shift the bits to the least significant depending on endianness.
1102 unsigned ShiftAmt;
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001103 if (TD.isLittleEndian()) {
Chris Lattnerca749402009-09-21 06:24:16 +00001104 ShiftAmt = Offset*8;
1105 } else {
Chris Lattner19ad7842009-09-21 17:55:47 +00001106 ShiftAmt = (StoreSize-LoadSize-Offset)*8;
Chris Lattnerca749402009-09-21 06:24:16 +00001107 }
1108
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001109 if (ShiftAmt)
1110 SrcVal = BinaryOperator::CreateLShr(SrcVal,
1111 ConstantInt::get(SrcVal->getType(), ShiftAmt), "tmp", InsertPt);
Chris Lattnerca749402009-09-21 06:24:16 +00001112
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001113 if (LoadSize != StoreSize)
1114 SrcVal = new TruncInst(SrcVal, IntegerType::get(Ctx, LoadSize*8),
1115 "tmp", InsertPt);
Chris Lattnerca749402009-09-21 06:24:16 +00001116
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001117 return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, TD);
Chris Lattnerca749402009-09-21 06:24:16 +00001118}
1119
Chris Lattner87913512009-09-21 06:30:24 +00001120struct AvailableValueInBlock {
1121 /// BB - The basic block in question.
1122 BasicBlock *BB;
1123 /// V - The value that is live out of the block.
1124 Value *V;
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001125 /// Offset - The byte offset in V that is interesting for the load query.
1126 unsigned Offset;
Chris Lattner87913512009-09-21 06:30:24 +00001127
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001128 static AvailableValueInBlock get(BasicBlock *BB, Value *V,
1129 unsigned Offset = 0) {
Chris Lattner87913512009-09-21 06:30:24 +00001130 AvailableValueInBlock Res;
1131 Res.BB = BB;
1132 Res.V = V;
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001133 Res.Offset = Offset;
Chris Lattner87913512009-09-21 06:30:24 +00001134 return Res;
1135 }
1136};
1137
Chris Lattnera09fbf02009-10-10 23:50:30 +00001138/// ConstructSSAForLoadSet - Given a set of loads specified by ValuesPerBlock,
1139/// construct SSA form, allowing us to eliminate LI. This returns the value
1140/// that should be used at LI's definition site.
1141static Value *ConstructSSAForLoadSet(LoadInst *LI,
1142 SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
1143 const TargetData *TD,
1144 AliasAnalysis *AA) {
1145 SmallVector<PHINode*, 8> NewPHIs;
1146 SSAUpdater SSAUpdate(&NewPHIs);
1147 SSAUpdate.Initialize(LI);
1148
1149 const Type *LoadTy = LI->getType();
1150
Chris Lattner771a5422009-09-20 20:09:34 +00001151 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
Chris Lattner87913512009-09-21 06:30:24 +00001152 BasicBlock *BB = ValuesPerBlock[i].BB;
1153 Value *AvailableVal = ValuesPerBlock[i].V;
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001154 unsigned Offset = ValuesPerBlock[i].Offset;
Chris Lattner771a5422009-09-20 20:09:34 +00001155
Chris Lattnera09fbf02009-10-10 23:50:30 +00001156 if (SSAUpdate.HasValueForBlock(BB))
1157 continue;
Chris Lattner771a5422009-09-20 20:09:34 +00001158
1159 if (AvailableVal->getType() != LoadTy) {
1160 assert(TD && "Need target data to handle type mismatch case");
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001161 AvailableVal = GetStoreValueForLoad(AvailableVal, Offset, LoadTy,
1162 BB->getTerminator(), *TD);
1163
1164 if (Offset) {
1165 DEBUG(errs() << "GVN COERCED NONLOCAL VAL:\n"
Chris Lattnera09fbf02009-10-10 23:50:30 +00001166 << *ValuesPerBlock[i].V << '\n'
1167 << *AvailableVal << '\n' << "\n\n\n");
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001168 }
1169
1170
Chris Lattner771a5422009-09-20 20:09:34 +00001171 DEBUG(errs() << "GVN COERCED NONLOCAL VAL:\n"
Chris Lattnera09fbf02009-10-10 23:50:30 +00001172 << *ValuesPerBlock[i].V << '\n'
1173 << *AvailableVal << '\n' << "\n\n\n");
Chris Lattner771a5422009-09-20 20:09:34 +00001174 }
Chris Lattnera09fbf02009-10-10 23:50:30 +00001175
1176 SSAUpdate.AddAvailableValue(BB, AvailableVal);
Chris Lattner771a5422009-09-20 20:09:34 +00001177 }
Chris Lattnera09fbf02009-10-10 23:50:30 +00001178
1179 // Perform PHI construction.
1180 Value *V = SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
1181
1182 // If new PHI nodes were created, notify alias analysis.
1183 if (isa<PointerType>(V->getType()))
1184 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
1185 AA->copyValue(LI, NewPHIs[i]);
1186
1187 return V;
Chris Lattner771a5422009-09-20 20:09:34 +00001188}
1189
Chris Lattner720e7902009-12-02 06:44:58 +00001190static bool isLifetimeStartOrEnd(Instruction *Inst) {
1191 if (IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
1192 return II->getIntrinsicID() == Intrinsic::lifetime_start ||
1193 II->getIntrinsicID() == Intrinsic::lifetime_end;
1194 return false;
1195}
1196
Owen Anderson62bc33c2007-08-16 22:02:55 +00001197/// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
1198/// non-local by performing PHI construction.
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001199bool GVN::processNonLocalLoad(LoadInst *LI,
Chris Lattner8e1e95c2008-03-21 22:01:16 +00001200 SmallVectorImpl<Instruction*> &toErase) {
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001201 // Find the non-local dependencies of the load.
Daniel Dunbara279bc32009-09-20 02:20:51 +00001202 SmallVector<MemoryDependenceAnalysis::NonLocalDepEntry, 64> Deps;
Chris Lattner91bcf642008-12-09 19:25:07 +00001203 MD->getNonLocalPointerDependency(LI->getOperand(0), true, LI->getParent(),
1204 Deps);
Dan Gohman2a298992009-07-31 20:24:18 +00001205 //DEBUG(errs() << "INVESTIGATING NONLOCAL LOAD: "
1206 // << Deps.size() << *LI << '\n');
Daniel Dunbara279bc32009-09-20 02:20:51 +00001207
Owen Anderson516eb1c2008-08-26 22:07:42 +00001208 // If we had to process more than one hundred blocks to find the
1209 // dependencies, this load isn't worth worrying about. Optimizing
1210 // it will be too expensive.
Chris Lattner91bcf642008-12-09 19:25:07 +00001211 if (Deps.size() > 100)
Owen Anderson516eb1c2008-08-26 22:07:42 +00001212 return false;
Chris Lattner5f4f84b2008-12-18 00:51:32 +00001213
1214 // If we had a phi translation failure, we'll have a single entry which is a
1215 // clobber in the current block. Reject this early.
Torok Edwin4306b1a2009-06-17 18:48:18 +00001216 if (Deps.size() == 1 && Deps[0].second.isClobber()) {
1217 DEBUG(
Dan Gohmanfd87a542009-07-25 01:43:01 +00001218 errs() << "GVN: non-local load ";
1219 WriteAsOperand(errs(), LI);
Dan Gohman2a298992009-07-31 20:24:18 +00001220 errs() << " is clobbered by " << *Deps[0].second.getInst() << '\n';
Torok Edwin4306b1a2009-06-17 18:48:18 +00001221 );
Chris Lattner5f4f84b2008-12-18 00:51:32 +00001222 return false;
Torok Edwin4306b1a2009-06-17 18:48:18 +00001223 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001224
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001225 // Filter out useless results (non-locals, etc). Keep track of the blocks
1226 // where we have a value available in repl, also keep track of whether we see
1227 // dependencies that produce an unknown value for the load (such as a call
1228 // that could potentially clobber the load).
Chris Lattner87913512009-09-21 06:30:24 +00001229 SmallVector<AvailableValueInBlock, 16> ValuesPerBlock;
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001230 SmallVector<BasicBlock*, 16> UnavailableBlocks;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001231
Chris Lattner771a5422009-09-20 20:09:34 +00001232 const TargetData *TD = 0;
1233
Chris Lattner91bcf642008-12-09 19:25:07 +00001234 for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
1235 BasicBlock *DepBB = Deps[i].first;
1236 MemDepResult DepInfo = Deps[i].second;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001237
Chris Lattnerb51deb92008-12-05 21:04:20 +00001238 if (DepInfo.isClobber()) {
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001239 // If the dependence is to a store that writes to a superset of the bits
1240 // read by the load, we can extract the bits we need for the load from the
1241 // stored value.
1242 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
1243 if (TD == 0)
1244 TD = getAnalysisIfAvailable<TargetData>();
1245 if (TD) {
1246 int Offset = AnalyzeLoadFromClobberingStore(LI, DepSI, *TD);
1247 if (Offset != -1) {
1248 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1249 DepSI->getOperand(0),
1250 Offset));
1251 continue;
1252 }
1253 }
1254 }
1255
1256 // FIXME: Handle memset/memcpy.
Chris Lattnerb51deb92008-12-05 21:04:20 +00001257 UnavailableBlocks.push_back(DepBB);
1258 continue;
1259 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001260
Chris Lattnerb51deb92008-12-05 21:04:20 +00001261 Instruction *DepInst = DepInfo.getInst();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001262
Chris Lattnerb51deb92008-12-05 21:04:20 +00001263 // Loading the allocation -> undef.
Chris Lattner720e7902009-12-02 06:44:58 +00001264 if (isa<AllocaInst>(DepInst) || isMalloc(DepInst) ||
1265 // Loading immediately after lifetime begin or end -> undef.
1266 isLifetimeStartOrEnd(DepInst)) {
Chris Lattner87913512009-09-21 06:30:24 +00001267 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1268 UndefValue::get(LI->getType())));
Chris Lattnerbf145d62008-12-01 01:15:42 +00001269 continue;
1270 }
Owen Andersonb62f7922009-10-28 07:05:35 +00001271
Chris Lattner87913512009-09-21 06:30:24 +00001272 if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
Daniel Dunbara279bc32009-09-20 02:20:51 +00001273 // Reject loads and stores that are to the same address but are of
Chris Lattner771a5422009-09-20 20:09:34 +00001274 // different types if we have to.
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001275 if (S->getOperand(0)->getType() != LI->getType()) {
Chris Lattner771a5422009-09-20 20:09:34 +00001276 if (TD == 0)
1277 TD = getAnalysisIfAvailable<TargetData>();
1278
1279 // If the stored value is larger or equal to the loaded value, we can
1280 // reuse it.
Chris Lattner8b2bc3d2009-09-21 17:24:04 +00001281 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(S->getOperand(0),
1282 LI->getType(), *TD)) {
Chris Lattner771a5422009-09-20 20:09:34 +00001283 UnavailableBlocks.push_back(DepBB);
1284 continue;
1285 }
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001286 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001287
Chris Lattner87913512009-09-21 06:30:24 +00001288 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1289 S->getOperand(0)));
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001290 continue;
1291 }
1292
1293 if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
Chris Lattner771a5422009-09-20 20:09:34 +00001294 // If the types mismatch and we can't handle it, reject reuse of the load.
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001295 if (LD->getType() != LI->getType()) {
Chris Lattner771a5422009-09-20 20:09:34 +00001296 if (TD == 0)
1297 TD = getAnalysisIfAvailable<TargetData>();
1298
1299 // If the stored value is larger or equal to the loaded value, we can
1300 // reuse it.
Chris Lattner8b2bc3d2009-09-21 17:24:04 +00001301 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(LD, LI->getType(),*TD)){
Chris Lattner771a5422009-09-20 20:09:34 +00001302 UnavailableBlocks.push_back(DepBB);
1303 continue;
1304 }
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001305 }
Chris Lattner87913512009-09-21 06:30:24 +00001306 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB, LD));
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001307 continue;
Owen Anderson0cd32032007-07-25 19:57:03 +00001308 }
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001309
1310 UnavailableBlocks.push_back(DepBB);
1311 continue;
Chris Lattner88365bb2008-03-21 21:14:38 +00001312 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001313
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001314 // If we have no predecessors that produce a known value for this load, exit
1315 // early.
1316 if (ValuesPerBlock.empty()) return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001317
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001318 // If all of the instructions we depend on produce a known value for this
1319 // load, then it is fully redundant and we can use PHI insertion to compute
1320 // its value. Insert PHIs and remove the fully redundant value now.
1321 if (UnavailableBlocks.empty()) {
Dan Gohman2a298992009-07-31 20:24:18 +00001322 DEBUG(errs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
Chris Lattner771a5422009-09-20 20:09:34 +00001323
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001324 // Perform PHI construction.
Chris Lattnera09fbf02009-10-10 23:50:30 +00001325 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, TD,
1326 VN.getAliasAnalysis());
Chris Lattner771a5422009-09-20 20:09:34 +00001327 LI->replaceAllUsesWith(V);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001328
Chris Lattner771a5422009-09-20 20:09:34 +00001329 if (isa<PHINode>(V))
1330 V->takeName(LI);
1331 if (isa<PointerType>(V->getType()))
1332 MD->invalidateCachedPointerInfo(V);
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001333 toErase.push_back(LI);
1334 NumGVNLoad++;
1335 return true;
1336 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001337
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001338 if (!EnablePRE || !EnableLoadPRE)
1339 return false;
1340
1341 // Okay, we have *some* definitions of the value. This means that the value
1342 // is available in some of our (transitive) predecessors. Lets think about
1343 // doing PRE of this load. This will involve inserting a new load into the
1344 // predecessor when it's not available. We could do this in general, but
1345 // prefer to not increase code size. As such, we only do this when we know
1346 // that we only have to insert *one* load (which means we're basically moving
1347 // the load, not inserting a new one).
Daniel Dunbara279bc32009-09-20 02:20:51 +00001348
Owen Anderson88554df2009-05-31 09:03:40 +00001349 SmallPtrSet<BasicBlock *, 4> Blockers;
1350 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1351 Blockers.insert(UnavailableBlocks[i]);
1352
1353 // Lets find first basic block with more than one predecessor. Walk backwards
1354 // through predecessors if needed.
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001355 BasicBlock *LoadBB = LI->getParent();
Owen Anderson88554df2009-05-31 09:03:40 +00001356 BasicBlock *TmpBB = LoadBB;
1357
1358 bool isSinglePred = false;
Dale Johannesen42c3f552009-06-17 20:48:23 +00001359 bool allSingleSucc = true;
Owen Anderson88554df2009-05-31 09:03:40 +00001360 while (TmpBB->getSinglePredecessor()) {
1361 isSinglePred = true;
1362 TmpBB = TmpBB->getSinglePredecessor();
1363 if (!TmpBB) // If haven't found any, bail now.
1364 return false;
1365 if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1366 return false;
1367 if (Blockers.count(TmpBB))
1368 return false;
Dale Johannesen42c3f552009-06-17 20:48:23 +00001369 if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1370 allSingleSucc = false;
Owen Anderson88554df2009-05-31 09:03:40 +00001371 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001372
Owen Anderson88554df2009-05-31 09:03:40 +00001373 assert(TmpBB);
1374 LoadBB = TmpBB;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001375
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001376 // If we have a repl set with LI itself in it, this means we have a loop where
1377 // at least one of the values is LI. Since this means that we won't be able
1378 // to eliminate LI even if we insert uses in the other predecessors, we will
1379 // end up increasing code size. Reject this by scanning for LI.
1380 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
Chris Lattner87913512009-09-21 06:30:24 +00001381 if (ValuesPerBlock[i].V == LI)
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001382 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001383
Owen Anderson88554df2009-05-31 09:03:40 +00001384 if (isSinglePred) {
1385 bool isHot = false;
1386 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
Chris Lattner87913512009-09-21 06:30:24 +00001387 if (Instruction *I = dyn_cast<Instruction>(ValuesPerBlock[i].V))
Daniel Dunbara279bc32009-09-20 02:20:51 +00001388 // "Hot" Instruction is in some loop (because it dominates its dep.
1389 // instruction).
1390 if (DT->dominates(LI, I)) {
1391 isHot = true;
1392 break;
1393 }
Owen Anderson88554df2009-05-31 09:03:40 +00001394
1395 // We are interested only in "hot" instructions. We don't want to do any
1396 // mis-optimizations here.
1397 if (!isHot)
1398 return false;
1399 }
1400
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001401 // Okay, we have some hope :). Check to see if the loaded value is fully
1402 // available in all but one predecessor.
1403 // FIXME: If we could restructure the CFG, we could make a common pred with
1404 // all the preds that don't have an available LI and insert a new load into
1405 // that one block.
1406 BasicBlock *UnavailablePred = 0;
1407
Chris Lattner72bc70d2008-12-05 07:49:08 +00001408 DenseMap<BasicBlock*, char> FullyAvailableBlocks;
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001409 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
Chris Lattner87913512009-09-21 06:30:24 +00001410 FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001411 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1412 FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1413
1414 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1415 PI != E; ++PI) {
1416 if (IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
1417 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001418
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001419 // If this load is not available in multiple predecessors, reject it.
1420 if (UnavailablePred && UnavailablePred != *PI)
1421 return false;
1422 UnavailablePred = *PI;
1423 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001424
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001425 assert(UnavailablePred != 0 &&
1426 "Fully available value should be eliminated above!");
Daniel Dunbara279bc32009-09-20 02:20:51 +00001427
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001428 // We don't currently handle critical edges :(
1429 if (UnavailablePred->getTerminator()->getNumSuccessors() != 1) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001430 DEBUG(errs() << "COULD NOT PRE LOAD BECAUSE OF CRITICAL EDGE '"
Dan Gohman2a298992009-07-31 20:24:18 +00001431 << UnavailablePred->getName() << "': " << *LI << '\n');
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001432 return false;
Owen Andersona37226a2007-08-07 23:12:31 +00001433 }
Chris Lattner616613d2009-11-27 08:25:10 +00001434
Chris Lattner6f7b2102009-11-27 22:05:15 +00001435 // Do PHI translation to get its value in the predecessor if necessary. The
1436 // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
1437 //
1438 // FIXME: This may insert a computation, but we don't tell scalar GVN
1439 // optimization stuff about it. How do we do this?
Chris Lattnerdd696052009-11-28 15:39:14 +00001440 SmallVector<Instruction*, 8> NewInsts;
Chris Lattner0c264b12009-11-28 16:08:18 +00001441 Value *LoadPtr = 0;
Chris Lattner971fd572009-11-27 22:50:07 +00001442
Chris Lattner0c264b12009-11-28 16:08:18 +00001443 // If all preds have a single successor, then we know it is safe to insert the
1444 // load on the pred (?!?), so we can insert code to materialize the pointer if
1445 // it is not available.
1446 if (allSingleSucc) {
1447 LoadPtr = MD->InsertPHITranslatedPointer(LI->getOperand(0), LoadBB,
1448 UnavailablePred, TD, *DT,NewInsts);
1449 } else {
1450 LoadPtr = MD->GetAvailablePHITranslatedValue(LI->getOperand(0), LoadBB,
1451 UnavailablePred, TD, *DT);
1452 }
1453
Chris Lattner6f7b2102009-11-27 22:05:15 +00001454 // If we couldn't find or insert a computation of this phi translated value,
1455 // we fail PRE.
Chris Lattner616613d2009-11-27 08:25:10 +00001456 if (LoadPtr == 0) {
Chris Lattner6f7b2102009-11-27 22:05:15 +00001457 DEBUG(errs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
1458 << *LI->getOperand(0) << "\n");
1459 return false;
Chris Lattner616613d2009-11-27 08:25:10 +00001460 }
1461
Dale Johannesen42c3f552009-06-17 20:48:23 +00001462 // Make sure it is valid to move this load here. We have to watch out for:
1463 // @1 = getelementptr (i8* p, ...
1464 // test p and branch if == 0
1465 // load @1
1466 // It is valid to have the getelementptr before the test, even if p can be 0,
1467 // as getelementptr only does address arithmetic.
1468 // If we are not pushing the value through any multiple-successor blocks
1469 // we do not have this case. Otherwise, check that the load is safe to
1470 // put anywhere; this can be improved, but should be conservatively safe.
1471 if (!allSingleSucc &&
Chris Lattnerdd696052009-11-28 15:39:14 +00001472 // FIXME: REEVALUTE THIS.
Chris Lattner0c264b12009-11-28 16:08:18 +00001473 !isSafeToLoadUnconditionally(LoadPtr, UnavailablePred->getTerminator())) {
1474 assert(NewInsts.empty() && "Should not have inserted instructions");
Dale Johannesen42c3f552009-06-17 20:48:23 +00001475 return false;
Chris Lattner0c264b12009-11-28 16:08:18 +00001476 }
Dale Johannesen42c3f552009-06-17 20:48:23 +00001477
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001478 // Okay, we can eliminate this load by inserting a reload in the predecessor
1479 // and using PHI construction to get the value in the other predecessors, do
1480 // it.
Dan Gohman2a298992009-07-31 20:24:18 +00001481 DEBUG(errs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
Chris Lattner0c264b12009-11-28 16:08:18 +00001482 DEBUG(if (!NewInsts.empty())
1483 errs() << "INSERTED " << NewInsts.size() << " INSTS: "
1484 << *NewInsts.back() << '\n');
1485
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001486 Value *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1487 LI->getAlignment(),
1488 UnavailablePred->getTerminator());
Daniel Dunbara279bc32009-09-20 02:20:51 +00001489
Chris Lattnera09fbf02009-10-10 23:50:30 +00001490 // Add the newly created load.
1491 ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,NewLoad));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001492
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001493 // Perform PHI construction.
Chris Lattnera09fbf02009-10-10 23:50:30 +00001494 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, TD,
1495 VN.getAliasAnalysis());
Chris Lattner771a5422009-09-20 20:09:34 +00001496 LI->replaceAllUsesWith(V);
1497 if (isa<PHINode>(V))
1498 V->takeName(LI);
1499 if (isa<PointerType>(V->getType()))
1500 MD->invalidateCachedPointerInfo(V);
Chris Lattnerc89c6a92008-12-02 08:16:11 +00001501 toErase.push_back(LI);
1502 NumPRELoad++;
Owen Anderson0cd32032007-07-25 19:57:03 +00001503 return true;
1504}
1505
Owen Anderson62bc33c2007-08-16 22:02:55 +00001506/// processLoad - Attempt to eliminate a load, first by eliminating it
1507/// locally, and then attempting non-local elimination if that fails.
Chris Lattnerb51deb92008-12-05 21:04:20 +00001508bool GVN::processLoad(LoadInst *L, SmallVectorImpl<Instruction*> &toErase) {
Dan Gohman4ec01b22009-11-14 02:27:51 +00001509 if (!MD)
1510 return false;
1511
Chris Lattnerb51deb92008-12-05 21:04:20 +00001512 if (L->isVolatile())
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001513 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001514
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001515 // ... to a pointer that has been loaded from before...
Chris Lattnerb2412a82009-09-21 02:42:51 +00001516 MemDepResult Dep = MD->getDependency(L);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001517
Chris Lattnerb51deb92008-12-05 21:04:20 +00001518 // If the value isn't available, don't do anything!
Chris Lattnerb2412a82009-09-21 02:42:51 +00001519 if (Dep.isClobber()) {
Chris Lattnereed919b2009-09-21 05:57:11 +00001520 // FIXME: We should handle memset/memcpy/memmove as dependent instructions
1521 // to forward the value if available.
1522 //if (isa<MemIntrinsic>(Dep.getInst()))
1523 //errs() << "LOAD DEPENDS ON MEM: " << *L << "\n" << *Dep.getInst()<<"\n\n";
1524
1525 // Check to see if we have something like this:
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001526 // store i32 123, i32* %P
1527 // %A = bitcast i32* %P to i8*
1528 // %B = gep i8* %A, i32 1
1529 // %C = load i8* %B
1530 //
1531 // We could do that by recognizing if the clobber instructions are obviously
1532 // a common base + constant offset, and if the previous store (or memset)
1533 // completely covers this load. This sort of thing can happen in bitfield
1534 // access code.
Chris Lattnereed919b2009-09-21 05:57:11 +00001535 if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst()))
Chris Lattner1ce08292009-09-21 06:22:46 +00001536 if (const TargetData *TD = getAnalysisIfAvailable<TargetData>()) {
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001537 int Offset = AnalyzeLoadFromClobberingStore(L, DepSI, *TD);
Chris Lattner1ce08292009-09-21 06:22:46 +00001538 if (Offset != -1) {
1539 Value *AvailVal = GetStoreValueForLoad(DepSI->getOperand(0), Offset,
Chris Lattner4fbd14e2009-09-21 06:48:08 +00001540 L->getType(), L, *TD);
Chris Lattnereed919b2009-09-21 05:57:11 +00001541 DEBUG(errs() << "GVN COERCED STORE BITS:\n" << *DepSI << '\n'
1542 << *AvailVal << '\n' << *L << "\n\n\n");
1543
1544 // Replace the load!
1545 L->replaceAllUsesWith(AvailVal);
1546 if (isa<PointerType>(AvailVal->getType()))
1547 MD->invalidateCachedPointerInfo(AvailVal);
1548 toErase.push_back(L);
1549 NumGVNLoad++;
1550 return true;
1551 }
Chris Lattner1ce08292009-09-21 06:22:46 +00001552 }
Chris Lattnereed919b2009-09-21 05:57:11 +00001553
Torok Edwin3f3c6d42009-05-29 09:46:03 +00001554 DEBUG(
1555 // fast print dep, using operator<< on instruction would be too slow
Dan Gohmanfd87a542009-07-25 01:43:01 +00001556 errs() << "GVN: load ";
1557 WriteAsOperand(errs(), L);
Chris Lattnerb2412a82009-09-21 02:42:51 +00001558 Instruction *I = Dep.getInst();
Dan Gohman2a298992009-07-31 20:24:18 +00001559 errs() << " is clobbered by " << *I << '\n';
Torok Edwin3f3c6d42009-05-29 09:46:03 +00001560 );
Chris Lattnerb51deb92008-12-05 21:04:20 +00001561 return false;
Torok Edwin3f3c6d42009-05-29 09:46:03 +00001562 }
Chris Lattnerb51deb92008-12-05 21:04:20 +00001563
1564 // If it is defined in another block, try harder.
Chris Lattnerb2412a82009-09-21 02:42:51 +00001565 if (Dep.isNonLocal())
Chris Lattnerb51deb92008-12-05 21:04:20 +00001566 return processNonLocalLoad(L, toErase);
Eli Friedmanb6c36e42008-02-12 12:08:14 +00001567
Chris Lattnerb2412a82009-09-21 02:42:51 +00001568 Instruction *DepInst = Dep.getInst();
Chris Lattnerb51deb92008-12-05 21:04:20 +00001569 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001570 Value *StoredVal = DepSI->getOperand(0);
1571
1572 // The store and load are to a must-aliased pointer, but they may not
1573 // actually have the same type. See if we know how to reuse the stored
1574 // value (depending on its type).
1575 const TargetData *TD = 0;
Chris Lattnera52fce42009-10-21 04:11:19 +00001576 if (StoredVal->getType() != L->getType()) {
1577 if ((TD = getAnalysisIfAvailable<TargetData>())) {
1578 StoredVal = CoerceAvailableValueToLoadType(StoredVal, L->getType(),
1579 L, *TD);
1580 if (StoredVal == 0)
1581 return false;
1582
1583 DEBUG(errs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
1584 << '\n' << *L << "\n\n\n");
1585 }
1586 else
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001587 return false;
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001588 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001589
Chris Lattnerb51deb92008-12-05 21:04:20 +00001590 // Remove it!
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001591 L->replaceAllUsesWith(StoredVal);
1592 if (isa<PointerType>(StoredVal->getType()))
1593 MD->invalidateCachedPointerInfo(StoredVal);
Chris Lattnerb51deb92008-12-05 21:04:20 +00001594 toErase.push_back(L);
1595 NumGVNLoad++;
1596 return true;
1597 }
1598
1599 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001600 Value *AvailableVal = DepLI;
1601
1602 // The loads are of a must-aliased pointer, but they may not actually have
1603 // the same type. See if we know how to reuse the previously loaded value
1604 // (depending on its type).
1605 const TargetData *TD = 0;
Chris Lattnera52fce42009-10-21 04:11:19 +00001606 if (DepLI->getType() != L->getType()) {
1607 if ((TD = getAnalysisIfAvailable<TargetData>())) {
1608 AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(), L,*TD);
1609 if (AvailableVal == 0)
1610 return false;
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001611
Chris Lattnera52fce42009-10-21 04:11:19 +00001612 DEBUG(errs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
1613 << "\n" << *L << "\n\n\n");
1614 }
1615 else
1616 return false;
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001617 }
1618
Chris Lattnerb51deb92008-12-05 21:04:20 +00001619 // Remove it!
Chris Lattnerbb6495c2009-09-20 19:03:47 +00001620 L->replaceAllUsesWith(AvailableVal);
Chris Lattnerbc99be12008-12-09 22:06:23 +00001621 if (isa<PointerType>(DepLI->getType()))
1622 MD->invalidateCachedPointerInfo(DepLI);
Chris Lattnerb51deb92008-12-05 21:04:20 +00001623 toErase.push_back(L);
1624 NumGVNLoad++;
1625 return true;
1626 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001627
Chris Lattner237a8282008-11-30 01:39:32 +00001628 // If this load really doesn't depend on anything, then we must be loading an
1629 // undef value. This can happen when loading for a fresh allocation with no
1630 // intervening stores, for example.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001631 if (isa<AllocaInst>(DepInst) || isMalloc(DepInst)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001632 L->replaceAllUsesWith(UndefValue::get(L->getType()));
Chris Lattner237a8282008-11-30 01:39:32 +00001633 toErase.push_back(L);
Chris Lattner237a8282008-11-30 01:39:32 +00001634 NumGVNLoad++;
Chris Lattnerb51deb92008-12-05 21:04:20 +00001635 return true;
Eli Friedmanb6c36e42008-02-12 12:08:14 +00001636 }
Owen Andersonb62f7922009-10-28 07:05:35 +00001637
1638 // If this load occurs either right after a lifetime begin or a lifetime end,
1639 // then the loaded value is undefined.
1640 if (IntrinsicInst* II = dyn_cast<IntrinsicInst>(DepInst)) {
1641 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
1642 II->getIntrinsicID() == Intrinsic::lifetime_end) {
1643 L->replaceAllUsesWith(UndefValue::get(L->getType()));
1644 toErase.push_back(L);
1645 NumGVNLoad++;
1646 return true;
1647 }
1648 }
Eli Friedmanb6c36e42008-02-12 12:08:14 +00001649
Chris Lattnerb51deb92008-12-05 21:04:20 +00001650 return false;
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001651}
1652
Chris Lattnerb2412a82009-09-21 02:42:51 +00001653Value *GVN::lookupNumber(BasicBlock *BB, uint32_t num) {
Owen Andersonb70a5712008-06-23 17:49:45 +00001654 DenseMap<BasicBlock*, ValueNumberScope*>::iterator I = localAvail.find(BB);
1655 if (I == localAvail.end())
1656 return 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001657
Chris Lattnerb2412a82009-09-21 02:42:51 +00001658 ValueNumberScope *Locals = I->second;
1659 while (Locals) {
1660 DenseMap<uint32_t, Value*>::iterator I = Locals->table.find(num);
1661 if (I != Locals->table.end())
Owen Anderson6fafe842008-06-20 01:15:47 +00001662 return I->second;
Chris Lattnerb2412a82009-09-21 02:42:51 +00001663 Locals = Locals->parent;
Owen Anderson6fafe842008-06-20 01:15:47 +00001664 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001665
Owen Anderson6fafe842008-06-20 01:15:47 +00001666 return 0;
1667}
1668
Owen Anderson255dafc2008-12-15 02:03:00 +00001669
Owen Anderson36057c72007-08-14 18:16:29 +00001670/// processInstruction - When calculating availability, handle an instruction
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001671/// by inserting it into the appropriate sets
Owen Andersonaf4240a2008-06-12 19:25:32 +00001672bool GVN::processInstruction(Instruction *I,
Chris Lattner8e1e95c2008-03-21 22:01:16 +00001673 SmallVectorImpl<Instruction*> &toErase) {
Chris Lattnerb2412a82009-09-21 02:42:51 +00001674 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1675 bool Changed = processLoad(LI, toErase);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001676
Chris Lattnerb2412a82009-09-21 02:42:51 +00001677 if (!Changed) {
1678 unsigned Num = VN.lookup_or_add(LI);
1679 localAvail[I->getParent()]->table.insert(std::make_pair(Num, LI));
Owen Andersonb2303722008-06-18 21:41:49 +00001680 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001681
Chris Lattnerb2412a82009-09-21 02:42:51 +00001682 return Changed;
Owen Andersonb2303722008-06-18 21:41:49 +00001683 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001684
Chris Lattnerb2412a82009-09-21 02:42:51 +00001685 uint32_t NextNum = VN.getNextUnusedValueNumber();
1686 unsigned Num = VN.lookup_or_add(I);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001687
Chris Lattnerb2412a82009-09-21 02:42:51 +00001688 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1689 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001690
Owen Andersone8a290f2009-04-01 23:53:49 +00001691 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
1692 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001693
Chris Lattnerb2412a82009-09-21 02:42:51 +00001694 Value *BranchCond = BI->getCondition();
1695 uint32_t CondVN = VN.lookup_or_add(BranchCond);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001696
Chris Lattnerb2412a82009-09-21 02:42:51 +00001697 BasicBlock *TrueSucc = BI->getSuccessor(0);
1698 BasicBlock *FalseSucc = BI->getSuccessor(1);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001699
Chris Lattnerb2412a82009-09-21 02:42:51 +00001700 if (TrueSucc->getSinglePredecessor())
1701 localAvail[TrueSucc]->table[CondVN] =
1702 ConstantInt::getTrue(TrueSucc->getContext());
1703 if (FalseSucc->getSinglePredecessor())
1704 localAvail[FalseSucc]->table[CondVN] =
1705 ConstantInt::getFalse(TrueSucc->getContext());
Owen Andersone8a290f2009-04-01 23:53:49 +00001706
1707 return false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001708
Owen Andersone5ffa902008-04-07 09:59:07 +00001709 // Allocations are always uniquely numbered, so we can save time and memory
Daniel Dunbara279bc32009-09-20 02:20:51 +00001710 // by fast failing them.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001711 } else if (isa<AllocaInst>(I) || isa<TerminatorInst>(I)) {
Chris Lattnerb2412a82009-09-21 02:42:51 +00001712 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Owen Andersone5ffa902008-04-07 09:59:07 +00001713 return false;
Owen Andersonb2303722008-06-18 21:41:49 +00001714 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001715
Owen Anderson62bc33c2007-08-16 22:02:55 +00001716 // Collapse PHI nodes
Owen Anderson31f49672007-08-14 18:33:27 +00001717 if (PHINode* p = dyn_cast<PHINode>(I)) {
Chris Lattnerb2412a82009-09-21 02:42:51 +00001718 Value *constVal = CollapsePhi(p);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001719
Owen Anderson31f49672007-08-14 18:33:27 +00001720 if (constVal) {
Owen Anderson1defe2d2007-08-16 22:51:56 +00001721 p->replaceAllUsesWith(constVal);
Dan Gohman4ec01b22009-11-14 02:27:51 +00001722 if (MD && isa<PointerType>(constVal->getType()))
Chris Lattnerbc99be12008-12-09 22:06:23 +00001723 MD->invalidateCachedPointerInfo(constVal);
Owen Andersonae53c932008-12-23 00:49:51 +00001724 VN.erase(p);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001725
Owen Anderson1defe2d2007-08-16 22:51:56 +00001726 toErase.push_back(p);
Owen Andersonb2303722008-06-18 21:41:49 +00001727 } else {
Chris Lattnerb2412a82009-09-21 02:42:51 +00001728 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Owen Anderson31f49672007-08-14 18:33:27 +00001729 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001730
Owen Anderson0ae33ef2008-07-03 17:44:33 +00001731 // If the number we were assigned was a brand new VN, then we don't
1732 // need to do a lookup to see if the number already exists
1733 // somewhere in the domtree: it can't!
Chris Lattnerb2412a82009-09-21 02:42:51 +00001734 } else if (Num == NextNum) {
1735 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001736
Owen Anderson255dafc2008-12-15 02:03:00 +00001737 // Perform fast-path value-number based elimination of values inherited from
1738 // dominators.
Chris Lattnerb2412a82009-09-21 02:42:51 +00001739 } else if (Value *repl = lookupNumber(I->getParent(), Num)) {
Owen Anderson5fc4aba2007-12-08 01:37:09 +00001740 // Remove it!
Owen Andersonbf7d0bc2007-07-31 23:27:13 +00001741 VN.erase(I);
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001742 I->replaceAllUsesWith(repl);
Dan Gohman4ec01b22009-11-14 02:27:51 +00001743 if (MD && isa<PointerType>(repl->getType()))
Chris Lattnerbc99be12008-12-09 22:06:23 +00001744 MD->invalidateCachedPointerInfo(repl);
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001745 toErase.push_back(I);
1746 return true;
Owen Anderson255dafc2008-12-15 02:03:00 +00001747
Owen Anderson0ae33ef2008-07-03 17:44:33 +00001748 } else {
Chris Lattnerb2412a82009-09-21 02:42:51 +00001749 localAvail[I->getParent()]->table.insert(std::make_pair(Num, I));
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001750 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001751
Owen Anderson1ad2cb72007-07-24 17:55:58 +00001752 return false;
1753}
1754
Bill Wendling30788b82008-12-22 22:32:22 +00001755/// runOnFunction - This is the main transformation entry point for a function.
Owen Anderson3e75a422007-08-14 18:04:11 +00001756bool GVN::runOnFunction(Function& F) {
Dan Gohman4ec01b22009-11-14 02:27:51 +00001757 if (!NoLoads)
1758 MD = &getAnalysis<MemoryDependenceAnalysis>();
Chris Lattner663e4412008-12-01 00:40:32 +00001759 DT = &getAnalysis<DominatorTree>();
Owen Andersona472c4a2008-05-12 20:15:55 +00001760 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
Chris Lattner663e4412008-12-01 00:40:32 +00001761 VN.setMemDep(MD);
1762 VN.setDomTree(DT);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001763
Chris Lattnerb2412a82009-09-21 02:42:51 +00001764 bool Changed = false;
1765 bool ShouldContinue = true;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001766
Owen Anderson5d0af032008-07-16 17:52:31 +00001767 // Merge unconditional branches, allowing PRE to catch more
1768 // optimization opportunities.
1769 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
Chris Lattnerb2412a82009-09-21 02:42:51 +00001770 BasicBlock *BB = FI;
Owen Anderson5d0af032008-07-16 17:52:31 +00001771 ++FI;
Owen Andersonb31b06d2008-07-17 00:01:40 +00001772 bool removedBlock = MergeBlockIntoPredecessor(BB, this);
1773 if (removedBlock) NumGVNBlocks++;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001774
Chris Lattnerb2412a82009-09-21 02:42:51 +00001775 Changed |= removedBlock;
Owen Anderson5d0af032008-07-16 17:52:31 +00001776 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001777
Chris Lattnerae199312008-12-09 19:21:47 +00001778 unsigned Iteration = 0;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001779
Chris Lattnerb2412a82009-09-21 02:42:51 +00001780 while (ShouldContinue) {
Dan Gohmanfd87a542009-07-25 01:43:01 +00001781 DEBUG(errs() << "GVN iteration: " << Iteration << "\n");
Chris Lattnerb2412a82009-09-21 02:42:51 +00001782 ShouldContinue = iterateOnFunction(F);
1783 Changed |= ShouldContinue;
Chris Lattnerae199312008-12-09 19:21:47 +00001784 ++Iteration;
Owen Anderson3e75a422007-08-14 18:04:11 +00001785 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001786
Owen Andersone98c54c2008-07-18 18:03:38 +00001787 if (EnablePRE) {
Owen Anderson0c7f91c2008-09-03 23:06:07 +00001788 bool PREChanged = true;
1789 while (PREChanged) {
1790 PREChanged = performPRE(F);
Chris Lattnerb2412a82009-09-21 02:42:51 +00001791 Changed |= PREChanged;
Owen Anderson0c7f91c2008-09-03 23:06:07 +00001792 }
Owen Andersone98c54c2008-07-18 18:03:38 +00001793 }
Chris Lattnerae199312008-12-09 19:21:47 +00001794 // FIXME: Should perform GVN again after PRE does something. PRE can move
1795 // computations into blocks where they become fully redundant. Note that
1796 // we can't do this until PRE's critical edge splitting updates memdep.
1797 // Actually, when this happens, we should just fully integrate PRE into GVN.
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +00001798
1799 cleanupGlobalSets();
1800
Chris Lattnerb2412a82009-09-21 02:42:51 +00001801 return Changed;
Owen Anderson3e75a422007-08-14 18:04:11 +00001802}
1803
1804
Chris Lattnerb2412a82009-09-21 02:42:51 +00001805bool GVN::processBlock(BasicBlock *BB) {
Chris Lattnerae199312008-12-09 19:21:47 +00001806 // FIXME: Kill off toErase by doing erasing eagerly in a helper function (and
1807 // incrementing BI before processing an instruction).
Owen Andersonaf4240a2008-06-12 19:25:32 +00001808 SmallVector<Instruction*, 8> toErase;
Chris Lattnerb2412a82009-09-21 02:42:51 +00001809 bool ChangedFunction = false;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001810
Owen Andersonaf4240a2008-06-12 19:25:32 +00001811 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1812 BI != BE;) {
Chris Lattnerb2412a82009-09-21 02:42:51 +00001813 ChangedFunction |= processInstruction(BI, toErase);
Owen Andersonaf4240a2008-06-12 19:25:32 +00001814 if (toErase.empty()) {
1815 ++BI;
1816 continue;
1817 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001818
Owen Andersonaf4240a2008-06-12 19:25:32 +00001819 // If we need some instructions deleted, do it now.
1820 NumGVNInstr += toErase.size();
Daniel Dunbara279bc32009-09-20 02:20:51 +00001821
Owen Andersonaf4240a2008-06-12 19:25:32 +00001822 // Avoid iterator invalidation.
1823 bool AtStart = BI == BB->begin();
1824 if (!AtStart)
1825 --BI;
1826
1827 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
Chris Lattner663e4412008-12-01 00:40:32 +00001828 E = toErase.end(); I != E; ++I) {
Dan Gohman2a298992009-07-31 20:24:18 +00001829 DEBUG(errs() << "GVN removed: " << **I << '\n');
Dan Gohman4ec01b22009-11-14 02:27:51 +00001830 if (MD) MD->removeInstruction(*I);
Owen Andersonaf4240a2008-06-12 19:25:32 +00001831 (*I)->eraseFromParent();
Bill Wendlingec40d502008-12-22 21:57:30 +00001832 DEBUG(verifyRemoved(*I));
Chris Lattner663e4412008-12-01 00:40:32 +00001833 }
Chris Lattnerae199312008-12-09 19:21:47 +00001834 toErase.clear();
Owen Andersonaf4240a2008-06-12 19:25:32 +00001835
1836 if (AtStart)
1837 BI = BB->begin();
1838 else
1839 ++BI;
Owen Andersonaf4240a2008-06-12 19:25:32 +00001840 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001841
Chris Lattnerb2412a82009-09-21 02:42:51 +00001842 return ChangedFunction;
Owen Andersonaf4240a2008-06-12 19:25:32 +00001843}
1844
Owen Andersonb2303722008-06-18 21:41:49 +00001845/// performPRE - Perform a purely local form of PRE that looks for diamond
1846/// control flow patterns and attempts to perform simple PRE at the join point.
Chris Lattnerfb6e7012009-10-31 22:11:15 +00001847bool GVN::performPRE(Function &F) {
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00001848 bool Changed = false;
Owen Anderson5c274ee2008-06-19 19:54:19 +00001849 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
Chris Lattner09713792008-12-01 07:29:03 +00001850 DenseMap<BasicBlock*, Value*> predMap;
Owen Andersonb2303722008-06-18 21:41:49 +00001851 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
1852 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
Chris Lattnerb2412a82009-09-21 02:42:51 +00001853 BasicBlock *CurrentBlock = *DI;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001854
Owen Andersonb2303722008-06-18 21:41:49 +00001855 // Nothing to PRE in the entry block.
1856 if (CurrentBlock == &F.getEntryBlock()) continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001857
Owen Andersonb2303722008-06-18 21:41:49 +00001858 for (BasicBlock::iterator BI = CurrentBlock->begin(),
1859 BE = CurrentBlock->end(); BI != BE; ) {
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00001860 Instruction *CurInst = BI++;
Duncan Sands7af1c782009-05-06 06:49:50 +00001861
Victor Hernandez7b929da2009-10-23 21:09:37 +00001862 if (isa<AllocaInst>(CurInst) ||
Victor Hernandez83d63912009-09-18 22:35:49 +00001863 isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
Devang Patel9674d152009-10-14 17:29:00 +00001864 CurInst->getType()->isVoidTy() ||
Duncan Sands7af1c782009-05-06 06:49:50 +00001865 CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
John Criswell090c0a22009-03-10 15:04:53 +00001866 isa<DbgInfoIntrinsic>(CurInst))
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00001867 continue;
Duncan Sands7af1c782009-05-06 06:49:50 +00001868
Chris Lattnerb2412a82009-09-21 02:42:51 +00001869 uint32_t ValNo = VN.lookup(CurInst);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001870
Owen Andersonb2303722008-06-18 21:41:49 +00001871 // Look for the predecessors for PRE opportunities. We're
1872 // only trying to solve the basic diamond case, where
1873 // a value is computed in the successor and one predecessor,
1874 // but not the other. We also explicitly disallow cases
1875 // where the successor is its own predecessor, because they're
1876 // more complicated to get right.
Chris Lattnerb2412a82009-09-21 02:42:51 +00001877 unsigned NumWith = 0;
1878 unsigned NumWithout = 0;
1879 BasicBlock *PREPred = 0;
Chris Lattner09713792008-12-01 07:29:03 +00001880 predMap.clear();
1881
Owen Andersonb2303722008-06-18 21:41:49 +00001882 for (pred_iterator PI = pred_begin(CurrentBlock),
1883 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
1884 // We're not interested in PRE where the block is its
Owen Anderson6fafe842008-06-20 01:15:47 +00001885 // own predecessor, on in blocks with predecessors
1886 // that are not reachable.
1887 if (*PI == CurrentBlock) {
Chris Lattnerb2412a82009-09-21 02:42:51 +00001888 NumWithout = 2;
Owen Anderson6fafe842008-06-20 01:15:47 +00001889 break;
1890 } else if (!localAvail.count(*PI)) {
Chris Lattnerb2412a82009-09-21 02:42:51 +00001891 NumWithout = 2;
Owen Anderson6fafe842008-06-20 01:15:47 +00001892 break;
1893 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001894
1895 DenseMap<uint32_t, Value*>::iterator predV =
Chris Lattnerb2412a82009-09-21 02:42:51 +00001896 localAvail[*PI]->table.find(ValNo);
Owen Anderson6fafe842008-06-20 01:15:47 +00001897 if (predV == localAvail[*PI]->table.end()) {
Owen Andersonb2303722008-06-18 21:41:49 +00001898 PREPred = *PI;
Chris Lattnerb2412a82009-09-21 02:42:51 +00001899 NumWithout++;
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00001900 } else if (predV->second == CurInst) {
Chris Lattnerb2412a82009-09-21 02:42:51 +00001901 NumWithout = 2;
Owen Andersonb2303722008-06-18 21:41:49 +00001902 } else {
Owen Anderson6fafe842008-06-20 01:15:47 +00001903 predMap[*PI] = predV->second;
Chris Lattnerb2412a82009-09-21 02:42:51 +00001904 NumWith++;
Owen Andersonb2303722008-06-18 21:41:49 +00001905 }
1906 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001907
Owen Andersonb2303722008-06-18 21:41:49 +00001908 // Don't do PRE when it might increase code size, i.e. when
1909 // we would need to insert instructions in more than one pred.
Chris Lattnerb2412a82009-09-21 02:42:51 +00001910 if (NumWithout != 1 || NumWith == 0)
Owen Andersonb2303722008-06-18 21:41:49 +00001911 continue;
Chris Lattnerfb6e7012009-10-31 22:11:15 +00001912
1913 // Don't do PRE across indirect branch.
1914 if (isa<IndirectBrInst>(PREPred->getTerminator()))
1915 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001916
Owen Anderson5c274ee2008-06-19 19:54:19 +00001917 // We can't do PRE safely on a critical edge, so instead we schedule
1918 // the edge to be split and perform the PRE the next time we iterate
1919 // on the function.
Chris Lattnerb2412a82009-09-21 02:42:51 +00001920 unsigned SuccNum = 0;
Owen Anderson5c274ee2008-06-19 19:54:19 +00001921 for (unsigned i = 0, e = PREPred->getTerminator()->getNumSuccessors();
1922 i != e; ++i)
Owen Anderson0c7f91c2008-09-03 23:06:07 +00001923 if (PREPred->getTerminator()->getSuccessor(i) == CurrentBlock) {
Chris Lattnerb2412a82009-09-21 02:42:51 +00001924 SuccNum = i;
Owen Anderson5c274ee2008-06-19 19:54:19 +00001925 break;
1926 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001927
Chris Lattnerb2412a82009-09-21 02:42:51 +00001928 if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
1929 toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
Owen Anderson5c274ee2008-06-19 19:54:19 +00001930 continue;
1931 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001932
Owen Andersonb2303722008-06-18 21:41:49 +00001933 // Instantiate the expression the in predecessor that lacked it.
1934 // Because we are going top-down through the block, all value numbers
1935 // will be available in the predecessor by the time we need them. Any
1936 // that weren't original present will have been instantiated earlier
1937 // in this loop.
Nick Lewycky67760642009-09-27 07:38:41 +00001938 Instruction *PREInstr = CurInst->clone();
Owen Andersonb2303722008-06-18 21:41:49 +00001939 bool success = true;
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00001940 for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
1941 Value *Op = PREInstr->getOperand(i);
1942 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
1943 continue;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001944
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00001945 if (Value *V = lookupNumber(PREPred, VN.lookup(Op))) {
1946 PREInstr->setOperand(i, V);
1947 } else {
1948 success = false;
1949 break;
Owen Andersonc45996b2008-07-11 20:05:13 +00001950 }
Owen Andersonb2303722008-06-18 21:41:49 +00001951 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001952
Owen Andersonb2303722008-06-18 21:41:49 +00001953 // Fail out if we encounter an operand that is not available in
Daniel Dunbara279bc32009-09-20 02:20:51 +00001954 // the PRE predecessor. This is typically because of loads which
Owen Andersonb2303722008-06-18 21:41:49 +00001955 // are not value numbered precisely.
1956 if (!success) {
1957 delete PREInstr;
Bill Wendling70ded192008-12-22 22:14:07 +00001958 DEBUG(verifyRemoved(PREInstr));
Owen Andersonb2303722008-06-18 21:41:49 +00001959 continue;
1960 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001961
Owen Andersonb2303722008-06-18 21:41:49 +00001962 PREInstr->insertBefore(PREPred->getTerminator());
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00001963 PREInstr->setName(CurInst->getName() + ".pre");
Owen Anderson6fafe842008-06-20 01:15:47 +00001964 predMap[PREPred] = PREInstr;
Chris Lattnerb2412a82009-09-21 02:42:51 +00001965 VN.add(PREInstr, ValNo);
Owen Andersonb2303722008-06-18 21:41:49 +00001966 NumGVNPRE++;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001967
Owen Andersonb2303722008-06-18 21:41:49 +00001968 // Update the availability map to include the new instruction.
Chris Lattnerb2412a82009-09-21 02:42:51 +00001969 localAvail[PREPred]->table.insert(std::make_pair(ValNo, PREInstr));
Daniel Dunbara279bc32009-09-20 02:20:51 +00001970
Owen Andersonb2303722008-06-18 21:41:49 +00001971 // Create a PHI to make the value available in this block.
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00001972 PHINode* Phi = PHINode::Create(CurInst->getType(),
1973 CurInst->getName() + ".pre-phi",
Owen Andersonb2303722008-06-18 21:41:49 +00001974 CurrentBlock->begin());
1975 for (pred_iterator PI = pred_begin(CurrentBlock),
1976 PE = pred_end(CurrentBlock); PI != PE; ++PI)
Owen Anderson6fafe842008-06-20 01:15:47 +00001977 Phi->addIncoming(predMap[*PI], *PI);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001978
Chris Lattnerb2412a82009-09-21 02:42:51 +00001979 VN.add(Phi, ValNo);
1980 localAvail[CurrentBlock]->table[ValNo] = Phi;
Daniel Dunbara279bc32009-09-20 02:20:51 +00001981
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00001982 CurInst->replaceAllUsesWith(Phi);
Dan Gohman4ec01b22009-11-14 02:27:51 +00001983 if (MD && isa<PointerType>(Phi->getType()))
Chris Lattnerbc99be12008-12-09 22:06:23 +00001984 MD->invalidateCachedPointerInfo(Phi);
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00001985 VN.erase(CurInst);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001986
Dan Gohman2a298992009-07-31 20:24:18 +00001987 DEBUG(errs() << "GVN PRE removed: " << *CurInst << '\n');
Dan Gohman4ec01b22009-11-14 02:27:51 +00001988 if (MD) MD->removeInstruction(CurInst);
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00001989 CurInst->eraseFromParent();
Bill Wendlingec40d502008-12-22 21:57:30 +00001990 DEBUG(verifyRemoved(CurInst));
Chris Lattnerd0f5bfc2008-12-01 07:35:54 +00001991 Changed = true;
Owen Andersonb2303722008-06-18 21:41:49 +00001992 }
1993 }
Daniel Dunbara279bc32009-09-20 02:20:51 +00001994
Owen Anderson5c274ee2008-06-19 19:54:19 +00001995 for (SmallVector<std::pair<TerminatorInst*, unsigned>, 4>::iterator
Anton Korobeynikov64b53562008-12-05 19:38:49 +00001996 I = toSplit.begin(), E = toSplit.end(); I != E; ++I)
Owen Anderson5c274ee2008-06-19 19:54:19 +00001997 SplitCriticalEdge(I->first, I->second, this);
Daniel Dunbara279bc32009-09-20 02:20:51 +00001998
Anton Korobeynikov64b53562008-12-05 19:38:49 +00001999 return Changed || toSplit.size();
Owen Andersonb2303722008-06-18 21:41:49 +00002000}
2001
Bill Wendling30788b82008-12-22 22:32:22 +00002002/// iterateOnFunction - Executes one iteration of GVN
Owen Anderson3e75a422007-08-14 18:04:11 +00002003bool GVN::iterateOnFunction(Function &F) {
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +00002004 cleanupGlobalSets();
Chris Lattner2e607012008-03-21 21:33:23 +00002005
Owen Andersone8a290f2009-04-01 23:53:49 +00002006 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
2007 DE = df_end(DT->getRootNode()); DI != DE; ++DI) {
2008 if (DI->getIDom())
2009 localAvail[DI->getBlock()] =
2010 new ValueNumberScope(localAvail[DI->getIDom()->getBlock()]);
2011 else
2012 localAvail[DI->getBlock()] = new ValueNumberScope(0);
2013 }
2014
Owen Anderson1ad2cb72007-07-24 17:55:58 +00002015 // Top-down walk of the dominator tree
Chris Lattnerb2412a82009-09-21 02:42:51 +00002016 bool Changed = false;
Owen Andersonc34d1122008-12-15 03:52:17 +00002017#if 0
2018 // Needed for value numbering with phi construction to work.
Owen Anderson255dafc2008-12-15 02:03:00 +00002019 ReversePostOrderTraversal<Function*> RPOT(&F);
2020 for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
2021 RE = RPOT.end(); RI != RE; ++RI)
Chris Lattnerb2412a82009-09-21 02:42:51 +00002022 Changed |= processBlock(*RI);
Owen Andersonc34d1122008-12-15 03:52:17 +00002023#else
2024 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
2025 DE = df_end(DT->getRootNode()); DI != DE; ++DI)
Chris Lattnerb2412a82009-09-21 02:42:51 +00002026 Changed |= processBlock(DI->getBlock());
Owen Andersonc34d1122008-12-15 03:52:17 +00002027#endif
2028
Chris Lattnerb2412a82009-09-21 02:42:51 +00002029 return Changed;
Owen Anderson1ad2cb72007-07-24 17:55:58 +00002030}
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +00002031
2032void GVN::cleanupGlobalSets() {
2033 VN.clear();
Nuno Lopes7cdd9ee2008-10-10 16:25:50 +00002034
2035 for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
2036 I = localAvail.begin(), E = localAvail.end(); I != E; ++I)
2037 delete I->second;
2038 localAvail.clear();
2039}
Bill Wendling246dbbb2008-12-22 21:36:08 +00002040
2041/// verifyRemoved - Verify that the specified instruction does not occur in our
2042/// internal data structures.
Bill Wendling6d463f22008-12-22 22:28:56 +00002043void GVN::verifyRemoved(const Instruction *Inst) const {
2044 VN.verifyRemoved(Inst);
Bill Wendling70ded192008-12-22 22:14:07 +00002045
Bill Wendling6d463f22008-12-22 22:28:56 +00002046 // Walk through the value number scope to make sure the instruction isn't
2047 // ferreted away in it.
Jeffrey Yasskin81cf4322009-11-10 01:02:17 +00002048 for (DenseMap<BasicBlock*, ValueNumberScope*>::const_iterator
Bill Wendling6d463f22008-12-22 22:28:56 +00002049 I = localAvail.begin(), E = localAvail.end(); I != E; ++I) {
2050 const ValueNumberScope *VNS = I->second;
2051
2052 while (VNS) {
Jeffrey Yasskin81cf4322009-11-10 01:02:17 +00002053 for (DenseMap<uint32_t, Value*>::const_iterator
Bill Wendling6d463f22008-12-22 22:28:56 +00002054 II = VNS->table.begin(), IE = VNS->table.end(); II != IE; ++II) {
2055 assert(II->second != Inst && "Inst still in value numbering scope!");
2056 }
2057
2058 VNS = VNS->parent;
Bill Wendling70ded192008-12-22 22:14:07 +00002059 }
2060 }
Bill Wendling246dbbb2008-12-22 21:36:08 +00002061}