blob: 991fb82b4449b4393e1533b72dba16136907b3cf [file] [log] [blame]
Chris Lattner10f2d132009-11-11 00:22:30 +00001//===- LazyValueInfo.cpp - Value constraint analysis ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interface for lazy computation of value constraint
11// information.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattnerb8c124c2009-11-12 01:22:16 +000015#define DEBUG_TYPE "lazy-value-info"
Chris Lattner10f2d132009-11-11 00:22:30 +000016#include "llvm/Analysis/LazyValueInfo.h"
Dan Gohman5034dd32010-12-15 20:02:24 +000017#include "llvm/Analysis/ValueTracking.h"
Chris Lattnercc4d3b22009-11-11 02:08:33 +000018#include "llvm/Constants.h"
19#include "llvm/Instructions.h"
Nick Lewycky786c7cd2011-01-15 09:16:12 +000020#include "llvm/IntrinsicInst.h"
Chris Lattnercc4d3b22009-11-11 02:08:33 +000021#include "llvm/Analysis/ConstantFolding.h"
22#include "llvm/Target/TargetData.h"
Chad Rosieraab8e282011-12-02 01:26:24 +000023#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattner16976522009-11-11 22:48:44 +000024#include "llvm/Support/CFG.h"
Owen Anderson5be2e782010-08-05 22:59:19 +000025#include "llvm/Support/ConstantRange.h"
Chris Lattnerb8c124c2009-11-12 01:22:16 +000026#include "llvm/Support/Debug.h"
Chris Lattner16976522009-11-11 22:48:44 +000027#include "llvm/Support/raw_ostream.h"
Owen Anderson7f9cb742010-07-30 23:59:40 +000028#include "llvm/Support/ValueHandle.h"
Chris Lattner16976522009-11-11 22:48:44 +000029#include "llvm/ADT/DenseMap.h"
Owen Anderson9a65dc92010-07-27 23:58:11 +000030#include "llvm/ADT/DenseSet.h"
Chris Lattnere5642812009-11-15 20:00:52 +000031#include "llvm/ADT/STLExtras.h"
Owen Anderson6bcd3a02010-09-07 19:16:25 +000032#include <map>
Nick Lewycky90862ee2010-12-18 01:00:40 +000033#include <stack>
Chris Lattner10f2d132009-11-11 00:22:30 +000034using namespace llvm;
35
36char LazyValueInfo::ID = 0;
Chad Rosieraab8e282011-12-02 01:26:24 +000037INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
38 "Lazy Value Information Analysis", false, true)
39INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
40INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
Owen Andersonce665bd2010-10-07 22:25:06 +000041 "Lazy Value Information Analysis", false, true)
Chris Lattner10f2d132009-11-11 00:22:30 +000042
43namespace llvm {
44 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
45}
46
Chris Lattnercc4d3b22009-11-11 02:08:33 +000047
48//===----------------------------------------------------------------------===//
49// LVILatticeVal
50//===----------------------------------------------------------------------===//
51
52/// LVILatticeVal - This is the information tracked by LazyValueInfo for each
53/// value.
54///
55/// FIXME: This is basically just for bringup, this can be made a lot more rich
56/// in the future.
57///
58namespace {
59class LVILatticeVal {
60 enum LatticeValueTy {
Nick Lewycky69bfdf52010-12-15 18:57:18 +000061 /// undefined - This Value has no known value yet.
Chris Lattnercc4d3b22009-11-11 02:08:33 +000062 undefined,
Owen Anderson5be2e782010-08-05 22:59:19 +000063
Nick Lewycky69bfdf52010-12-15 18:57:18 +000064 /// constant - This Value has a specific constant value.
Chris Lattnercc4d3b22009-11-11 02:08:33 +000065 constant,
Nick Lewycky69bfdf52010-12-15 18:57:18 +000066 /// notconstant - This Value is known to not have the specified value.
Chris Lattnerb52675b2009-11-12 04:36:58 +000067 notconstant,
Chad Rosieraab8e282011-12-02 01:26:24 +000068
Nick Lewycky69bfdf52010-12-15 18:57:18 +000069 /// constantrange - The Value falls within this range.
Owen Anderson5be2e782010-08-05 22:59:19 +000070 constantrange,
Chad Rosieraab8e282011-12-02 01:26:24 +000071
Nick Lewycky69bfdf52010-12-15 18:57:18 +000072 /// overdefined - This value is not known to be constant, and we know that
Chris Lattnercc4d3b22009-11-11 02:08:33 +000073 /// it has a value.
74 overdefined
75 };
76
77 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattnerb52675b2009-11-12 04:36:58 +000078 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersondb78d732010-08-05 22:10:46 +000079 LatticeValueTy Tag;
80 Constant *Val;
Owen Anderson5be2e782010-08-05 22:59:19 +000081 ConstantRange Range;
Chris Lattnercc4d3b22009-11-11 02:08:33 +000082
83public:
Owen Anderson5be2e782010-08-05 22:59:19 +000084 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
Chris Lattnercc4d3b22009-11-11 02:08:33 +000085
Chris Lattner16976522009-11-11 22:48:44 +000086 static LVILatticeVal get(Constant *C) {
87 LVILatticeVal Res;
Nick Lewycky69bfdf52010-12-15 18:57:18 +000088 if (!isa<UndefValue>(C))
Owen Anderson9f014062010-08-10 20:03:09 +000089 Res.markConstant(C);
Chris Lattner16976522009-11-11 22:48:44 +000090 return Res;
91 }
Chris Lattnerb52675b2009-11-12 04:36:58 +000092 static LVILatticeVal getNot(Constant *C) {
93 LVILatticeVal Res;
Nick Lewycky69bfdf52010-12-15 18:57:18 +000094 if (!isa<UndefValue>(C))
Owen Anderson9f014062010-08-10 20:03:09 +000095 Res.markNotConstant(C);
Chris Lattnerb52675b2009-11-12 04:36:58 +000096 return Res;
97 }
Owen Anderson625051b2010-08-10 23:20:01 +000098 static LVILatticeVal getRange(ConstantRange CR) {
99 LVILatticeVal Res;
100 Res.markConstantRange(CR);
101 return Res;
102 }
Chris Lattner16976522009-11-11 22:48:44 +0000103
Owen Anderson5be2e782010-08-05 22:59:19 +0000104 bool isUndefined() const { return Tag == undefined; }
105 bool isConstant() const { return Tag == constant; }
106 bool isNotConstant() const { return Tag == notconstant; }
107 bool isConstantRange() const { return Tag == constantrange; }
108 bool isOverdefined() const { return Tag == overdefined; }
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000109
110 Constant *getConstant() const {
111 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000112 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000113 }
114
Chris Lattnerb52675b2009-11-12 04:36:58 +0000115 Constant *getNotConstant() const {
116 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000117 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000118 }
119
Owen Anderson5be2e782010-08-05 22:59:19 +0000120 ConstantRange getConstantRange() const {
121 assert(isConstantRange() &&
122 "Cannot get the constant-range of a non-constant-range!");
123 return Range;
124 }
125
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000126 /// markOverdefined - Return true if this is a change in status.
127 bool markOverdefined() {
128 if (isOverdefined())
129 return false;
Owen Andersondb78d732010-08-05 22:10:46 +0000130 Tag = overdefined;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000131 return true;
132 }
133
134 /// markConstant - Return true if this is a change in status.
135 bool markConstant(Constant *V) {
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000136 assert(V && "Marking constant with NULL");
137 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
138 return markConstantRange(ConstantRange(CI->getValue()));
139 if (isa<UndefValue>(V))
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000140 return false;
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000141
142 assert((!isConstant() || getConstant() == V) &&
143 "Marking constant with different value");
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000144 assert(isUndefined());
Owen Andersondb78d732010-08-05 22:10:46 +0000145 Tag = constant;
Owen Andersondb78d732010-08-05 22:10:46 +0000146 Val = V;
Chris Lattner16976522009-11-11 22:48:44 +0000147 return true;
148 }
149
Chris Lattnerb52675b2009-11-12 04:36:58 +0000150 /// markNotConstant - Return true if this is a change in status.
151 bool markNotConstant(Constant *V) {
Chris Lattnerb52675b2009-11-12 04:36:58 +0000152 assert(V && "Marking constant with NULL");
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000153 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
154 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
155 if (isa<UndefValue>(V))
156 return false;
157
158 assert((!isConstant() || getConstant() != V) &&
159 "Marking constant !constant with same value");
160 assert((!isNotConstant() || getNotConstant() == V) &&
161 "Marking !constant with different value");
162 assert(isUndefined() || isConstant());
163 Tag = notconstant;
Owen Andersondb78d732010-08-05 22:10:46 +0000164 Val = V;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000165 return true;
166 }
167
Owen Anderson5be2e782010-08-05 22:59:19 +0000168 /// markConstantRange - Return true if this is a change in status.
169 bool markConstantRange(const ConstantRange NewR) {
170 if (isConstantRange()) {
171 if (NewR.isEmptySet())
172 return markOverdefined();
173
Owen Anderson5be2e782010-08-05 22:59:19 +0000174 bool changed = Range == NewR;
175 Range = NewR;
176 return changed;
177 }
178
179 assert(isUndefined());
180 if (NewR.isEmptySet())
181 return markOverdefined();
Owen Anderson5be2e782010-08-05 22:59:19 +0000182
183 Tag = constantrange;
184 Range = NewR;
185 return true;
186 }
187
Chris Lattner16976522009-11-11 22:48:44 +0000188 /// mergeIn - Merge the specified lattice value into this one, updating this
189 /// one and returning true if anything changed.
190 bool mergeIn(const LVILatticeVal &RHS) {
191 if (RHS.isUndefined() || isOverdefined()) return false;
192 if (RHS.isOverdefined()) return markOverdefined();
193
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000194 if (isUndefined()) {
195 Tag = RHS.Tag;
196 Val = RHS.Val;
197 Range = RHS.Range;
198 return true;
Chris Lattnerf496e792009-11-12 04:57:13 +0000199 }
200
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000201 if (isConstant()) {
202 if (RHS.isConstant()) {
203 if (Val == RHS.Val)
204 return false;
205 return markOverdefined();
206 }
207
208 if (RHS.isNotConstant()) {
209 if (Val == RHS.Val)
210 return markOverdefined();
211
212 // Unless we can prove that the two Constants are different, we must
213 // move to overdefined.
Chad Rosieraab8e282011-12-02 01:26:24 +0000214 // FIXME: use TargetData/TargetLibraryInfo for smarter constant folding.
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000215 if (ConstantInt *Res = dyn_cast<ConstantInt>(
216 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
217 getConstant(),
218 RHS.getNotConstant())))
219 if (Res->isOne())
220 return markNotConstant(RHS.getNotConstant());
221
222 return markOverdefined();
223 }
224
225 // RHS is a ConstantRange, LHS is a non-integer Constant.
226
227 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
228 // a function. The correct result is to pick up RHS.
229
Chris Lattner16976522009-11-11 22:48:44 +0000230 return markOverdefined();
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000231 }
232
233 if (isNotConstant()) {
234 if (RHS.isConstant()) {
235 if (Val == RHS.Val)
236 return markOverdefined();
237
238 // Unless we can prove that the two Constants are different, we must
239 // move to overdefined.
Chad Rosieraab8e282011-12-02 01:26:24 +0000240 // FIXME: use TargetData/TargetLibraryInfo for smarter constant folding.
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000241 if (ConstantInt *Res = dyn_cast<ConstantInt>(
242 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
243 getNotConstant(),
244 RHS.getConstant())))
245 if (Res->isOne())
246 return false;
247
248 return markOverdefined();
249 }
250
251 if (RHS.isNotConstant()) {
252 if (Val == RHS.Val)
253 return false;
254 return markOverdefined();
255 }
256
257 return markOverdefined();
258 }
259
260 assert(isConstantRange() && "New LVILattice type?");
261 if (!RHS.isConstantRange())
262 return markOverdefined();
263
264 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
265 if (NewR.isFullSet())
266 return markOverdefined();
267 return markConstantRange(NewR);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000268 }
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000269};
270
271} // end anonymous namespace.
272
Chris Lattner16976522009-11-11 22:48:44 +0000273namespace llvm {
Chandler Carruth3b55a372011-04-18 18:49:44 +0000274raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
275 LLVM_ATTRIBUTE_USED;
Chris Lattner16976522009-11-11 22:48:44 +0000276raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
277 if (Val.isUndefined())
278 return OS << "undefined";
279 if (Val.isOverdefined())
280 return OS << "overdefined";
Chris Lattnerb52675b2009-11-12 04:36:58 +0000281
282 if (Val.isNotConstant())
283 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Owen Anderson2f3ffb82010-08-09 20:50:46 +0000284 else if (Val.isConstantRange())
285 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
286 << Val.getConstantRange().getUpper() << '>';
Chris Lattner16976522009-11-11 22:48:44 +0000287 return OS << "constant<" << *Val.getConstant() << '>';
288}
289}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000290
291//===----------------------------------------------------------------------===//
Chris Lattner2c5adf82009-11-15 19:59:49 +0000292// LazyValueInfoCache Decl
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000293//===----------------------------------------------------------------------===//
294
Chris Lattner2c5adf82009-11-15 19:59:49 +0000295namespace {
Owen Anderson89778462011-01-05 21:15:29 +0000296 /// LVIValueHandle - A callback value handle update the cache when
297 /// values are erased.
298 class LazyValueInfoCache;
299 struct LVIValueHandle : public CallbackVH {
300 LazyValueInfoCache *Parent;
301
302 LVIValueHandle(Value *V, LazyValueInfoCache *P)
303 : CallbackVH(V), Parent(P) { }
304
305 void deleted();
306 void allUsesReplacedWith(Value *V) {
307 deleted();
308 }
309 };
310}
311
312namespace llvm {
313 template<>
314 struct DenseMapInfo<LVIValueHandle> {
315 typedef DenseMapInfo<Value*> PointerInfo;
316 static inline LVIValueHandle getEmptyKey() {
317 return LVIValueHandle(PointerInfo::getEmptyKey(),
318 static_cast<LazyValueInfoCache*>(0));
319 }
320 static inline LVIValueHandle getTombstoneKey() {
321 return LVIValueHandle(PointerInfo::getTombstoneKey(),
322 static_cast<LazyValueInfoCache*>(0));
323 }
324 static unsigned getHashValue(const LVIValueHandle &Val) {
325 return PointerInfo::getHashValue(Val);
326 }
327 static bool isEqual(const LVIValueHandle &LHS, const LVIValueHandle &RHS) {
328 return LHS == RHS;
329 }
330 };
331
332 template<>
333 struct DenseMapInfo<std::pair<AssertingVH<BasicBlock>, Value*> > {
334 typedef std::pair<AssertingVH<BasicBlock>, Value*> PairTy;
335 typedef DenseMapInfo<AssertingVH<BasicBlock> > APointerInfo;
336 typedef DenseMapInfo<Value*> BPointerInfo;
337 static inline PairTy getEmptyKey() {
338 return std::make_pair(APointerInfo::getEmptyKey(),
339 BPointerInfo::getEmptyKey());
340 }
341 static inline PairTy getTombstoneKey() {
342 return std::make_pair(APointerInfo::getTombstoneKey(),
343 BPointerInfo::getTombstoneKey());
344 }
345 static unsigned getHashValue( const PairTy &Val) {
346 return APointerInfo::getHashValue(Val.first) ^
347 BPointerInfo::getHashValue(Val.second);
348 }
349 static bool isEqual(const PairTy &LHS, const PairTy &RHS) {
350 return APointerInfo::isEqual(LHS.first, RHS.first) &&
351 BPointerInfo::isEqual(LHS.second, RHS.second);
352 }
353 };
354}
355
356namespace {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000357 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
358 /// maintains information about queries across the clients' queries.
359 class LazyValueInfoCache {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000360 /// ValueCacheEntryTy - This is all of the cached block information for
361 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
362 /// entries, allowing us to do a lookup with a binary search.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000363 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000364
Owen Andersone68713a2011-01-05 23:26:22 +0000365 /// ValueCache - This is all of the cached information for all values,
366 /// mapped from Value* to key information.
367 DenseMap<LVIValueHandle, ValueCacheEntryTy> ValueCache;
368
369 /// OverDefinedCache - This tracks, on a per-block basis, the set of
370 /// values that are over-defined at the end of that block. This is required
371 /// for cache updating.
372 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
373 DenseSet<OverDefinedPairTy> OverDefinedCache;
374
375 /// BlockValueStack - This stack holds the state of the value solver
376 /// during a query. It basically emulates the callstack of the naive
377 /// recursive value lookup process.
378 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
379
Owen Anderson89778462011-01-05 21:15:29 +0000380 friend struct LVIValueHandle;
Owen Anderson87790ab2010-12-20 19:33:41 +0000381
382 /// OverDefinedCacheUpdater - A helper object that ensures that the
383 /// OverDefinedCache is updated whenever solveBlockValue returns.
384 struct OverDefinedCacheUpdater {
385 LazyValueInfoCache *Parent;
386 Value *Val;
387 BasicBlock *BB;
388 LVILatticeVal &BBLV;
389
390 OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV,
391 LazyValueInfoCache *P)
392 : Parent(P), Val(V), BB(B), BBLV(LV) { }
393
394 bool markResult(bool changed) {
395 if (changed && BBLV.isOverdefined())
396 Parent->OverDefinedCache.insert(std::make_pair(BB, Val));
397 return changed;
398 }
399 };
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000400
Owen Andersone68713a2011-01-05 23:26:22 +0000401
Owen Anderson7f9cb742010-07-30 23:59:40 +0000402
Owen Andersonf33b3022010-12-09 06:14:58 +0000403 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000404 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
405 LVILatticeVal &Result);
406 bool hasBlockValue(Value *Val, BasicBlock *BB);
407
408 // These methods process one work item and may add more. A false value
409 // returned means that the work item was not completely processed and must
410 // be revisited after going through the new items.
411 bool solveBlockValue(Value *Val, BasicBlock *BB);
Owen Anderson61863942010-12-20 18:18:16 +0000412 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
413 Value *Val, BasicBlock *BB);
414 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
415 PHINode *PN, BasicBlock *BB);
416 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
417 Instruction *BBI, BasicBlock *BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000418
419 void solve();
Owen Andersonf33b3022010-12-09 06:14:58 +0000420
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000421 ValueCacheEntryTy &lookup(Value *V) {
Owen Andersonf33b3022010-12-09 06:14:58 +0000422 return ValueCache[LVIValueHandle(V, this)];
423 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000424
Chris Lattner2c5adf82009-11-15 19:59:49 +0000425 public:
Chris Lattner2c5adf82009-11-15 19:59:49 +0000426 /// getValueInBlock - This is the query interface to determine the lattice
427 /// value for the specified Value* at the end of the specified block.
428 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
429
430 /// getValueOnEdge - This is the query interface to determine the lattice
431 /// value for the specified Value* that is true on the specified edge.
432 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000433
434 /// threadEdge - This is the update interface to inform the cache that an
435 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
436 /// NewSucc.
437 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000438
439 /// eraseBlock - This is part of the update interface to inform the cache
440 /// that a block has been deleted.
441 void eraseBlock(BasicBlock *BB);
442
443 /// clear - Empty the cache.
444 void clear() {
445 ValueCache.clear();
446 OverDefinedCache.clear();
447 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000448 };
449} // end anonymous namespace
450
Owen Anderson89778462011-01-05 21:15:29 +0000451void LVIValueHandle::deleted() {
452 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
453
454 SmallVector<OverDefinedPairTy, 4> ToErase;
455 for (DenseSet<OverDefinedPairTy>::iterator
Owen Anderson7f9cb742010-07-30 23:59:40 +0000456 I = Parent->OverDefinedCache.begin(),
457 E = Parent->OverDefinedCache.end();
Owen Anderson89778462011-01-05 21:15:29 +0000458 I != E; ++I) {
459 if (I->second == getValPtr())
460 ToErase.push_back(*I);
Owen Anderson7f9cb742010-07-30 23:59:40 +0000461 }
Owen Andersoncf6abd22010-08-11 22:36:04 +0000462
Owen Anderson89778462011-01-05 21:15:29 +0000463 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
464 E = ToErase.end(); I != E; ++I)
465 Parent->OverDefinedCache.erase(*I);
466
Owen Andersoncf6abd22010-08-11 22:36:04 +0000467 // This erasure deallocates *this, so it MUST happen after we're done
468 // using any and all members of *this.
469 Parent->ValueCache.erase(*this);
Owen Anderson7f9cb742010-07-30 23:59:40 +0000470}
471
Owen Anderson00ac77e2010-08-18 18:39:01 +0000472void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
Owen Anderson89778462011-01-05 21:15:29 +0000473 SmallVector<OverDefinedPairTy, 4> ToErase;
474 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
475 E = OverDefinedCache.end(); I != E; ++I) {
476 if (I->first == BB)
477 ToErase.push_back(*I);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000478 }
Owen Anderson89778462011-01-05 21:15:29 +0000479
480 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
481 E = ToErase.end(); I != E; ++I)
482 OverDefinedCache.erase(*I);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000483
Owen Anderson89778462011-01-05 21:15:29 +0000484 for (DenseMap<LVIValueHandle, ValueCacheEntryTy>::iterator
Owen Anderson00ac77e2010-08-18 18:39:01 +0000485 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
486 I->second.erase(BB);
487}
Owen Anderson7f9cb742010-07-30 23:59:40 +0000488
Nick Lewycky90862ee2010-12-18 01:00:40 +0000489void LazyValueInfoCache::solve() {
Owen Andersone68713a2011-01-05 23:26:22 +0000490 while (!BlockValueStack.empty()) {
491 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
Owen Anderson87790ab2010-12-20 19:33:41 +0000492 if (solveBlockValue(e.second, e.first))
Owen Andersone68713a2011-01-05 23:26:22 +0000493 BlockValueStack.pop();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000494 }
495}
496
497bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
498 // If already a constant, there is nothing to compute.
499 if (isa<Constant>(Val))
500 return true;
501
Owen Anderson89778462011-01-05 21:15:29 +0000502 LVIValueHandle ValHandle(Val, this);
503 if (!ValueCache.count(ValHandle)) return false;
504 return ValueCache[ValHandle].count(BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000505}
506
Owen Andersonf33b3022010-12-09 06:14:58 +0000507LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000508 // If already a constant, there is nothing to compute.
509 if (Constant *VC = dyn_cast<Constant>(Val))
510 return LVILatticeVal::get(VC);
511
512 return lookup(Val)[BB];
513}
514
515bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
516 if (isa<Constant>(Val))
517 return true;
518
Owen Andersonf33b3022010-12-09 06:14:58 +0000519 ValueCacheEntryTy &Cache = lookup(Val);
520 LVILatticeVal &BBLV = Cache[BB];
Owen Anderson87790ab2010-12-20 19:33:41 +0000521
522 // OverDefinedCacheUpdater is a helper object that will update
523 // the OverDefinedCache for us when this method exits. Make sure to
524 // call markResult on it as we exist, passing a bool to indicate if the
525 // cache needs updating, i.e. if we have solve a new value or not.
526 OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000527
Chris Lattner2c5adf82009-11-15 19:59:49 +0000528 // If we've already computed this block's value, return it.
Chris Lattnere5642812009-11-15 20:00:52 +0000529 if (!BBLV.isUndefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000530 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
Owen Anderson87790ab2010-12-20 19:33:41 +0000531
532 // Since we're reusing a cached value here, we don't need to update the
533 // OverDefinedCahce. The cache will have been properly updated
534 // whenever the cached value was inserted.
535 ODCacheUpdater.markResult(false);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000536 return true;
Chris Lattnere5642812009-11-15 20:00:52 +0000537 }
538
Chris Lattner2c5adf82009-11-15 19:59:49 +0000539 // Otherwise, this is the first time we're seeing this block. Reset the
540 // lattice value to overdefined, so that cycles will terminate and be
541 // conservatively correct.
542 BBLV.markOverdefined();
543
Chris Lattner2c5adf82009-11-15 19:59:49 +0000544 Instruction *BBI = dyn_cast<Instruction>(Val);
545 if (BBI == 0 || BBI->getParent() != BB) {
Owen Anderson87790ab2010-12-20 19:33:41 +0000546 return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
Chris Lattner2c5adf82009-11-15 19:59:49 +0000547 }
Chris Lattnere5642812009-11-15 20:00:52 +0000548
Nick Lewycky90862ee2010-12-18 01:00:40 +0000549 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Owen Anderson87790ab2010-12-20 19:33:41 +0000550 return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000551 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000552
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000553 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
554 BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
555 return ODCacheUpdater.markResult(true);
556 }
557
Owen Andersonb81fd622010-08-18 21:11:37 +0000558 // We can only analyze the definitions of certain classes of instructions
559 // (integral binops and casts at the moment), so bail if this isn't one.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000560 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000561 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
562 !BBI->getType()->isIntegerTy()) {
563 DEBUG(dbgs() << " compute BB '" << BB->getName()
564 << "' - overdefined because inst def found.\n");
Owen Anderson61863942010-12-20 18:18:16 +0000565 BBLV.markOverdefined();
Owen Anderson87790ab2010-12-20 19:33:41 +0000566 return ODCacheUpdater.markResult(true);
Owen Andersonb81fd622010-08-18 21:11:37 +0000567 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000568
Owen Andersonb81fd622010-08-18 21:11:37 +0000569 // FIXME: We're currently limited to binops with a constant RHS. This should
570 // be improved.
571 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
572 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
573 DEBUG(dbgs() << " compute BB '" << BB->getName()
574 << "' - overdefined because inst def found.\n");
575
Owen Anderson61863942010-12-20 18:18:16 +0000576 BBLV.markOverdefined();
Owen Anderson87790ab2010-12-20 19:33:41 +0000577 return ODCacheUpdater.markResult(true);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000578 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000579
Owen Anderson87790ab2010-12-20 19:33:41 +0000580 return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000581}
582
583static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
584 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
585 return L->getPointerAddressSpace() == 0 &&
586 GetUnderlyingObject(L->getPointerOperand()) ==
587 GetUnderlyingObject(Ptr);
588 }
589 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
590 return S->getPointerAddressSpace() == 0 &&
591 GetUnderlyingObject(S->getPointerOperand()) ==
592 GetUnderlyingObject(Ptr);
593 }
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000594 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
595 if (MI->isVolatile()) return false;
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000596
597 // FIXME: check whether it has a valuerange that excludes zero?
598 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
599 if (!Len || Len->isZero()) return false;
600
Eli Friedman69388e52011-05-31 20:40:16 +0000601 if (MI->getDestAddressSpace() == 0)
602 if (MI->getRawDest() == Ptr || MI->getDest() == Ptr)
603 return true;
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000604 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman69388e52011-05-31 20:40:16 +0000605 if (MTI->getSourceAddressSpace() == 0)
606 if (MTI->getRawSource() == Ptr || MTI->getSource() == Ptr)
607 return true;
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000608 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000609 return false;
610}
611
Owen Anderson61863942010-12-20 18:18:16 +0000612bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
613 Value *Val, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000614 LVILatticeVal Result; // Start Undefined.
615
616 // If this is a pointer, and there's a load from that pointer in this BB,
617 // then we know that the pointer can't be NULL.
618 bool NotNull = false;
619 if (Val->getType()->isPointerTy()) {
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000620 if (isa<AllocaInst>(Val)) {
621 NotNull = true;
622 } else {
623 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
624 if (InstructionDereferencesPointer(BI, Val)) {
625 NotNull = true;
626 break;
627 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000628 }
629 }
630 }
631
632 // If this is the entry block, we must be asking about an argument. The
633 // value is overdefined.
634 if (BB == &BB->getParent()->getEntryBlock()) {
635 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
636 if (NotNull) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000637 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky90862ee2010-12-18 01:00:40 +0000638 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
639 } else {
640 Result.markOverdefined();
641 }
Owen Anderson61863942010-12-20 18:18:16 +0000642 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000643 return true;
644 }
645
646 // Loop over all of our predecessors, merging what we know from them into
647 // result.
648 bool EdgesMissing = false;
649 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
650 LVILatticeVal EdgeResult;
651 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
652 if (EdgesMissing)
653 continue;
654
655 Result.mergeIn(EdgeResult);
656
657 // If we hit overdefined, exit early. The BlockVals entry is already set
658 // to overdefined.
659 if (Result.isOverdefined()) {
660 DEBUG(dbgs() << " compute BB '" << BB->getName()
661 << "' - overdefined because of pred.\n");
662 // If we previously determined that this is a pointer that can't be null
663 // then return that rather than giving up entirely.
664 if (NotNull) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000665 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky90862ee2010-12-18 01:00:40 +0000666 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
667 }
Owen Anderson61863942010-12-20 18:18:16 +0000668
669 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000670 return true;
671 }
672 }
673 if (EdgesMissing)
674 return false;
675
676 // Return the merged value, which is more precise than 'overdefined'.
677 assert(!Result.isOverdefined());
Owen Anderson61863942010-12-20 18:18:16 +0000678 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000679 return true;
680}
681
Owen Anderson61863942010-12-20 18:18:16 +0000682bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
683 PHINode *PN, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000684 LVILatticeVal Result; // Start Undefined.
685
686 // Loop over all of our predecessors, merging what we know from them into
687 // result.
688 bool EdgesMissing = false;
689 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
690 BasicBlock *PhiBB = PN->getIncomingBlock(i);
691 Value *PhiVal = PN->getIncomingValue(i);
692 LVILatticeVal EdgeResult;
693 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
694 if (EdgesMissing)
695 continue;
696
697 Result.mergeIn(EdgeResult);
698
699 // If we hit overdefined, exit early. The BlockVals entry is already set
700 // to overdefined.
701 if (Result.isOverdefined()) {
702 DEBUG(dbgs() << " compute BB '" << BB->getName()
703 << "' - overdefined because of pred.\n");
Owen Anderson61863942010-12-20 18:18:16 +0000704
705 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000706 return true;
707 }
708 }
709 if (EdgesMissing)
710 return false;
711
712 // Return the merged value, which is more precise than 'overdefined'.
713 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson61863942010-12-20 18:18:16 +0000714 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000715 return true;
716}
717
Owen Anderson61863942010-12-20 18:18:16 +0000718bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
719 Instruction *BBI,
Nick Lewycky90862ee2010-12-18 01:00:40 +0000720 BasicBlock *BB) {
Owen Andersonb81fd622010-08-18 21:11:37 +0000721 // Figure out the range of the LHS. If that fails, bail.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000722 if (!hasBlockValue(BBI->getOperand(0), BB)) {
Owen Andersone68713a2011-01-05 23:26:22 +0000723 BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0)));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000724 return false;
725 }
726
Nick Lewycky90862ee2010-12-18 01:00:40 +0000727 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Owen Andersonb81fd622010-08-18 21:11:37 +0000728 if (!LHSVal.isConstantRange()) {
Owen Anderson61863942010-12-20 18:18:16 +0000729 BBLV.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000730 return true;
Owen Andersonb81fd622010-08-18 21:11:37 +0000731 }
732
Owen Andersonb81fd622010-08-18 21:11:37 +0000733 ConstantRange LHSRange = LHSVal.getConstantRange();
734 ConstantRange RHSRange(1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000735 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
Owen Andersonb81fd622010-08-18 21:11:37 +0000736 if (isa<BinaryOperator>(BBI)) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000737 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
738 RHSRange = ConstantRange(RHS->getValue());
739 } else {
Owen Anderson61863942010-12-20 18:18:16 +0000740 BBLV.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000741 return true;
Owen Anderson59b06dc2010-08-24 07:55:44 +0000742 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000743 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000744
Owen Andersonb81fd622010-08-18 21:11:37 +0000745 // NOTE: We're currently limited by the set of operations that ConstantRange
746 // can evaluate symbolically. Enhancing that set will allows us to analyze
747 // more definitions.
Owen Anderson61863942010-12-20 18:18:16 +0000748 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000749 switch (BBI->getOpcode()) {
750 case Instruction::Add:
751 Result.markConstantRange(LHSRange.add(RHSRange));
752 break;
753 case Instruction::Sub:
754 Result.markConstantRange(LHSRange.sub(RHSRange));
755 break;
756 case Instruction::Mul:
757 Result.markConstantRange(LHSRange.multiply(RHSRange));
758 break;
759 case Instruction::UDiv:
760 Result.markConstantRange(LHSRange.udiv(RHSRange));
761 break;
762 case Instruction::Shl:
763 Result.markConstantRange(LHSRange.shl(RHSRange));
764 break;
765 case Instruction::LShr:
766 Result.markConstantRange(LHSRange.lshr(RHSRange));
767 break;
768 case Instruction::Trunc:
769 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
770 break;
771 case Instruction::SExt:
772 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
773 break;
774 case Instruction::ZExt:
775 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
776 break;
777 case Instruction::BitCast:
778 Result.markConstantRange(LHSRange);
779 break;
Nick Lewycky198381e2010-09-07 05:39:02 +0000780 case Instruction::And:
781 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
782 break;
783 case Instruction::Or:
784 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
785 break;
Owen Andersonb81fd622010-08-18 21:11:37 +0000786
787 // Unhandled instructions are overdefined.
788 default:
789 DEBUG(dbgs() << " compute BB '" << BB->getName()
790 << "' - overdefined because inst def found.\n");
791 Result.markOverdefined();
792 break;
793 }
794
Owen Anderson61863942010-12-20 18:18:16 +0000795 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000796 return true;
Chris Lattner10f2d132009-11-11 00:22:30 +0000797}
798
Chris Lattner800c47e2009-11-15 20:02:12 +0000799/// getEdgeValue - This method attempts to infer more complex
Nick Lewycky90862ee2010-12-18 01:00:40 +0000800bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
801 BasicBlock *BBTo, LVILatticeVal &Result) {
802 // If already a constant, there is nothing to compute.
803 if (Constant *VC = dyn_cast<Constant>(Val)) {
804 Result = LVILatticeVal::get(VC);
805 return true;
806 }
807
Chris Lattner800c47e2009-11-15 20:02:12 +0000808 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
809 // know that v != 0.
Chris Lattner16976522009-11-11 22:48:44 +0000810 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
811 // If this is a conditional branch and only one successor goes to BBTo, then
812 // we maybe able to infer something from the condition.
813 if (BI->isConditional() &&
814 BI->getSuccessor(0) != BI->getSuccessor(1)) {
815 bool isTrueDest = BI->getSuccessor(0) == BBTo;
816 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
817 "BBTo isn't a successor of BBFrom");
818
819 // If V is the condition of the branch itself, then we know exactly what
820 // it is.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000821 if (BI->getCondition() == Val) {
822 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson9f014062010-08-10 20:03:09 +0000823 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000824 return true;
825 }
Chris Lattner16976522009-11-11 22:48:44 +0000826
827 // If the condition of the branch is an equality comparison, we may be
828 // able to infer the value.
Owen Anderson2d0f2472010-08-11 04:24:25 +0000829 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
830 if (ICI && ICI->getOperand(0) == Val &&
831 isa<Constant>(ICI->getOperand(1))) {
832 if (ICI->isEquality()) {
833 // We know that V has the RHS constant if this is a true SETEQ or
834 // false SETNE.
835 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
Nick Lewycky90862ee2010-12-18 01:00:40 +0000836 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
837 else
838 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
839 return true;
Chris Lattner16976522009-11-11 22:48:44 +0000840 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000841
Owen Anderson2d0f2472010-08-11 04:24:25 +0000842 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
843 // Calculate the range of values that would satisfy the comparison.
844 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
845 ConstantRange TrueValues =
846 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000847
Owen Anderson2d0f2472010-08-11 04:24:25 +0000848 // If we're interested in the false dest, invert the condition.
849 if (!isTrueDest) TrueValues = TrueValues.inverse();
850
851 // Figure out the possible values of the query BEFORE this branch.
Owen Andersonbe419012011-01-05 21:37:18 +0000852 if (!hasBlockValue(Val, BBFrom)) {
Owen Andersone68713a2011-01-05 23:26:22 +0000853 BlockValueStack.push(std::make_pair(BBFrom, Val));
Owen Andersonbe419012011-01-05 21:37:18 +0000854 return false;
855 }
856
Owen Andersonf33b3022010-12-09 06:14:58 +0000857 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000858 if (!InBlock.isConstantRange()) {
859 Result = LVILatticeVal::getRange(TrueValues);
860 return true;
861 }
862
Owen Anderson2d0f2472010-08-11 04:24:25 +0000863 // Find all potential values that satisfy both the input and output
864 // conditions.
865 ConstantRange PossibleValues =
866 TrueValues.intersectWith(InBlock.getConstantRange());
Nick Lewycky90862ee2010-12-18 01:00:40 +0000867
868 Result = LVILatticeVal::getRange(PossibleValues);
869 return true;
Owen Anderson2d0f2472010-08-11 04:24:25 +0000870 }
871 }
Chris Lattner16976522009-11-11 22:48:44 +0000872 }
873 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000874
875 // If the edge was formed by a switch on the value, then we may know exactly
876 // what it is.
877 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Owen Andersondae90c62010-08-24 21:59:42 +0000878 if (SI->getCondition() == Val) {
Owen Anderson4caef602010-09-02 22:16:52 +0000879 // We don't know anything in the default case.
Owen Andersondae90c62010-08-24 21:59:42 +0000880 if (SI->getDefaultDest() == BBTo) {
Owen Anderson4caef602010-09-02 22:16:52 +0000881 Result.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000882 return true;
Owen Andersondae90c62010-08-24 21:59:42 +0000883 }
884
Chris Lattner800c47e2009-11-15 20:02:12 +0000885 // We only know something if there is exactly one value that goes from
886 // BBFrom to BBTo.
887 unsigned NumEdges = 0;
888 ConstantInt *EdgeVal = 0;
889 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
890 if (SI->getSuccessor(i) != BBTo) continue;
891 if (NumEdges++) break;
892 EdgeVal = SI->getCaseValue(i);
893 }
894 assert(EdgeVal && "Missing successor?");
Nick Lewycky90862ee2010-12-18 01:00:40 +0000895 if (NumEdges == 1) {
896 Result = LVILatticeVal::get(EdgeVal);
897 return true;
898 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000899 }
900 }
Chris Lattner16976522009-11-11 22:48:44 +0000901
902 // Otherwise see if the value is known in the block.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000903 if (hasBlockValue(Val, BBFrom)) {
904 Result = getBlockValue(Val, BBFrom);
905 return true;
906 }
Owen Andersone68713a2011-01-05 23:26:22 +0000907 BlockValueStack.push(std::make_pair(BBFrom, Val));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000908 return false;
Chris Lattner16976522009-11-11 22:48:44 +0000909}
910
Chris Lattner2c5adf82009-11-15 19:59:49 +0000911LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
David Greene5d93a1f2009-12-23 20:43:58 +0000912 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000913 << BB->getName() << "'\n");
914
Owen Andersone68713a2011-01-05 23:26:22 +0000915 BlockValueStack.push(std::make_pair(BB, V));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000916 solve();
Owen Andersonf33b3022010-12-09 06:14:58 +0000917 LVILatticeVal Result = getBlockValue(V, BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000918
David Greene5d93a1f2009-12-23 20:43:58 +0000919 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000920 return Result;
921}
Chris Lattner16976522009-11-11 22:48:44 +0000922
Chris Lattner2c5adf82009-11-15 19:59:49 +0000923LVILatticeVal LazyValueInfoCache::
924getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
David Greene5d93a1f2009-12-23 20:43:58 +0000925 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000926 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000927
Nick Lewycky90862ee2010-12-18 01:00:40 +0000928 LVILatticeVal Result;
929 if (!getEdgeValue(V, FromBB, ToBB, Result)) {
930 solve();
931 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
932 (void)WasFastQuery;
933 assert(WasFastQuery && "More work to do after problem solved?");
934 }
935
David Greene5d93a1f2009-12-23 20:43:58 +0000936 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000937 return Result;
938}
939
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000940void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
941 BasicBlock *NewSucc) {
942 // When an edge in the graph has been threaded, values that we could not
943 // determine a value for before (i.e. were marked overdefined) may be possible
944 // to solve now. We do NOT try to proactively update these values. Instead,
945 // we clear their entries from the cache, and allow lazy updating to recompute
946 // them when needed.
947
948 // The updating process is fairly simple: we need to dropped cached info
949 // for all values that were marked overdefined in OldSucc, and for those same
950 // values in any successor of OldSucc (except NewSucc) in which they were
951 // also marked overdefined.
952 std::vector<BasicBlock*> worklist;
953 worklist.push_back(OldSucc);
954
Owen Anderson9a65dc92010-07-27 23:58:11 +0000955 DenseSet<Value*> ClearSet;
Owen Anderson89778462011-01-05 21:15:29 +0000956 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
957 E = OverDefinedCache.end(); I != E; ++I) {
Owen Anderson9a65dc92010-07-27 23:58:11 +0000958 if (I->first == OldSucc)
959 ClearSet.insert(I->second);
960 }
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000961
962 // Use a worklist to perform a depth-first search of OldSucc's successors.
963 // NOTE: We do not need a visited list since any blocks we have already
964 // visited will have had their overdefined markers cleared already, and we
965 // thus won't loop to their successors.
966 while (!worklist.empty()) {
967 BasicBlock *ToUpdate = worklist.back();
968 worklist.pop_back();
969
970 // Skip blocks only accessible through NewSucc.
971 if (ToUpdate == NewSucc) continue;
972
973 bool changed = false;
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000974 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000975 I != E; ++I) {
976 // If a value was marked overdefined in OldSucc, and is here too...
Owen Anderson89778462011-01-05 21:15:29 +0000977 DenseSet<OverDefinedPairTy>::iterator OI =
Owen Anderson9a65dc92010-07-27 23:58:11 +0000978 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
979 if (OI == OverDefinedCache.end()) continue;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000980
Owen Anderson9a65dc92010-07-27 23:58:11 +0000981 // Remove it from the caches.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000982 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
Owen Anderson9a65dc92010-07-27 23:58:11 +0000983 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000984
Owen Anderson9a65dc92010-07-27 23:58:11 +0000985 assert(CI != Entry.end() && "Couldn't find entry to update?");
986 Entry.erase(CI);
987 OverDefinedCache.erase(OI);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000988
Owen Anderson9a65dc92010-07-27 23:58:11 +0000989 // If we removed anything, then we potentially need to update
990 // blocks successors too.
991 changed = true;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000992 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000993
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000994 if (!changed) continue;
995
996 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
997 }
998}
999
Chris Lattner2c5adf82009-11-15 19:59:49 +00001000//===----------------------------------------------------------------------===//
1001// LazyValueInfo Impl
1002//===----------------------------------------------------------------------===//
1003
Chris Lattner2c5adf82009-11-15 19:59:49 +00001004/// getCache - This lazily constructs the LazyValueInfoCache.
1005static LazyValueInfoCache &getCache(void *&PImpl) {
1006 if (!PImpl)
1007 PImpl = new LazyValueInfoCache();
1008 return *static_cast<LazyValueInfoCache*>(PImpl);
1009}
1010
Owen Anderson00ac77e2010-08-18 18:39:01 +00001011bool LazyValueInfo::runOnFunction(Function &F) {
1012 if (PImpl)
1013 getCache(PImpl).clear();
Chad Rosieraab8e282011-12-02 01:26:24 +00001014
Owen Anderson00ac77e2010-08-18 18:39:01 +00001015 TD = getAnalysisIfAvailable<TargetData>();
Chad Rosieraab8e282011-12-02 01:26:24 +00001016 TLI = &getAnalysis<TargetLibraryInfo>();
1017
Owen Anderson00ac77e2010-08-18 18:39:01 +00001018 // Fully lazy.
1019 return false;
1020}
1021
Chad Rosieraab8e282011-12-02 01:26:24 +00001022void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1023 AU.setPreservesAll();
1024 AU.addRequired<TargetLibraryInfo>();
1025}
1026
Chris Lattner2c5adf82009-11-15 19:59:49 +00001027void LazyValueInfo::releaseMemory() {
1028 // If the cache was allocated, free it.
1029 if (PImpl) {
1030 delete &getCache(PImpl);
1031 PImpl = 0;
1032 }
1033}
1034
1035Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
1036 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
1037
Chris Lattner16976522009-11-11 22:48:44 +00001038 if (Result.isConstant())
1039 return Result.getConstant();
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001040 if (Result.isConstantRange()) {
Owen Andersonee61fcf2010-08-27 23:29:38 +00001041 ConstantRange CR = Result.getConstantRange();
1042 if (const APInt *SingleVal = CR.getSingleElement())
1043 return ConstantInt::get(V->getContext(), *SingleVal);
1044 }
Chris Lattner16976522009-11-11 22:48:44 +00001045 return 0;
1046}
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001047
Chris Lattner38392bb2009-11-12 01:29:10 +00001048/// getConstantOnEdge - Determine whether the specified value is known to be a
1049/// constant on the specified edge. Return null if not.
1050Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1051 BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +00001052 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattner38392bb2009-11-12 01:29:10 +00001053
1054 if (Result.isConstant())
1055 return Result.getConstant();
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001056 if (Result.isConstantRange()) {
Owen Anderson9f014062010-08-10 20:03:09 +00001057 ConstantRange CR = Result.getConstantRange();
1058 if (const APInt *SingleVal = CR.getSingleElement())
1059 return ConstantInt::get(V->getContext(), *SingleVal);
1060 }
Chris Lattner38392bb2009-11-12 01:29:10 +00001061 return 0;
1062}
1063
Chris Lattnerb52675b2009-11-12 04:36:58 +00001064/// getPredicateOnEdge - Determine whether the specified value comparison
1065/// with a constant is known to be true or false on the specified CFG edge.
1066/// Pred is a CmpInst predicate.
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001067LazyValueInfo::Tristate
Chris Lattnerb52675b2009-11-12 04:36:58 +00001068LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1069 BasicBlock *FromBB, BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +00001070 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001071
Chris Lattnerb52675b2009-11-12 04:36:58 +00001072 // If we know the value is a constant, evaluate the conditional.
1073 Constant *Res = 0;
1074 if (Result.isConstant()) {
Chad Rosieraab8e282011-12-02 01:26:24 +00001075 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD,
1076 TLI);
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001077 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Chris Lattnerb52675b2009-11-12 04:36:58 +00001078 return ResCI->isZero() ? False : True;
Chris Lattner2c5adf82009-11-15 19:59:49 +00001079 return Unknown;
1080 }
1081
Owen Anderson9f014062010-08-10 20:03:09 +00001082 if (Result.isConstantRange()) {
Owen Anderson59b06dc2010-08-24 07:55:44 +00001083 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1084 if (!CI) return Unknown;
1085
Owen Anderson9f014062010-08-10 20:03:09 +00001086 ConstantRange CR = Result.getConstantRange();
1087 if (Pred == ICmpInst::ICMP_EQ) {
1088 if (!CR.contains(CI->getValue()))
1089 return False;
1090
1091 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1092 return True;
1093 } else if (Pred == ICmpInst::ICMP_NE) {
1094 if (!CR.contains(CI->getValue()))
1095 return True;
1096
1097 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1098 return False;
1099 }
1100
1101 // Handle more complex predicates.
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001102 ConstantRange TrueValues =
1103 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1104 if (TrueValues.contains(CR))
Owen Anderson9f014062010-08-10 20:03:09 +00001105 return True;
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001106 if (TrueValues.inverse().contains(CR))
1107 return False;
Owen Anderson9f014062010-08-10 20:03:09 +00001108 return Unknown;
1109 }
1110
Chris Lattner2c5adf82009-11-15 19:59:49 +00001111 if (Result.isNotConstant()) {
Chris Lattnerb52675b2009-11-12 04:36:58 +00001112 // If this is an equality comparison, we can try to fold it knowing that
1113 // "V != C1".
1114 if (Pred == ICmpInst::ICMP_EQ) {
1115 // !C1 == C -> false iff C1 == C.
1116 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chad Rosieraab8e282011-12-02 01:26:24 +00001117 Result.getNotConstant(), C, TD,
1118 TLI);
Chris Lattnerb52675b2009-11-12 04:36:58 +00001119 if (Res->isNullValue())
1120 return False;
1121 } else if (Pred == ICmpInst::ICMP_NE) {
1122 // !C1 != C -> true iff C1 == C.
Chris Lattner5553a3a2009-11-15 20:01:24 +00001123 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chad Rosieraab8e282011-12-02 01:26:24 +00001124 Result.getNotConstant(), C, TD,
1125 TLI);
Chris Lattnerb52675b2009-11-12 04:36:58 +00001126 if (Res->isNullValue())
1127 return True;
1128 }
Chris Lattner2c5adf82009-11-15 19:59:49 +00001129 return Unknown;
Chris Lattnerb52675b2009-11-12 04:36:58 +00001130 }
1131
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001132 return Unknown;
1133}
1134
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001135void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001136 BasicBlock *NewSucc) {
Owen Anderson00ac77e2010-08-18 18:39:01 +00001137 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1138}
1139
1140void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1141 if (PImpl) getCache(PImpl).eraseBlock(BB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001142}