blob: d5f0b5c82154ca4f5911838570a4a2c735000089 [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"
Chris Lattner16976522009-11-11 22:48:44 +000023#include "llvm/Support/CFG.h"
Owen Anderson5be2e782010-08-05 22:59:19 +000024#include "llvm/Support/ConstantRange.h"
Chris Lattnerb8c124c2009-11-12 01:22:16 +000025#include "llvm/Support/Debug.h"
Chris Lattner16976522009-11-11 22:48:44 +000026#include "llvm/Support/raw_ostream.h"
Owen Anderson7f9cb742010-07-30 23:59:40 +000027#include "llvm/Support/ValueHandle.h"
Chris Lattner16976522009-11-11 22:48:44 +000028#include "llvm/ADT/DenseMap.h"
Owen Anderson9a65dc92010-07-27 23:58:11 +000029#include "llvm/ADT/DenseSet.h"
Chris Lattnere5642812009-11-15 20:00:52 +000030#include "llvm/ADT/STLExtras.h"
Owen Anderson6bcd3a02010-09-07 19:16:25 +000031#include <map>
Nick Lewycky90862ee2010-12-18 01:00:40 +000032#include <stack>
Chris Lattner10f2d132009-11-11 00:22:30 +000033using namespace llvm;
34
35char LazyValueInfo::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000036INITIALIZE_PASS(LazyValueInfo, "lazy-value-info",
Owen Andersonce665bd2010-10-07 22:25:06 +000037 "Lazy Value Information Analysis", false, true)
Chris Lattner10f2d132009-11-11 00:22:30 +000038
39namespace llvm {
40 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
41}
42
Chris Lattnercc4d3b22009-11-11 02:08:33 +000043
44//===----------------------------------------------------------------------===//
45// LVILatticeVal
46//===----------------------------------------------------------------------===//
47
48/// LVILatticeVal - This is the information tracked by LazyValueInfo for each
49/// value.
50///
51/// FIXME: This is basically just for bringup, this can be made a lot more rich
52/// in the future.
53///
54namespace {
55class LVILatticeVal {
56 enum LatticeValueTy {
Nick Lewycky69bfdf52010-12-15 18:57:18 +000057 /// undefined - This Value has no known value yet.
Chris Lattnercc4d3b22009-11-11 02:08:33 +000058 undefined,
Owen Anderson5be2e782010-08-05 22:59:19 +000059
Nick Lewycky69bfdf52010-12-15 18:57:18 +000060 /// constant - This Value has a specific constant value.
Chris Lattnercc4d3b22009-11-11 02:08:33 +000061 constant,
Nick Lewycky69bfdf52010-12-15 18:57:18 +000062 /// notconstant - This Value is known to not have the specified value.
Chris Lattnerb52675b2009-11-12 04:36:58 +000063 notconstant,
64
Nick Lewycky69bfdf52010-12-15 18:57:18 +000065 /// constantrange - The Value falls within this range.
Owen Anderson5be2e782010-08-05 22:59:19 +000066 constantrange,
67
Nick Lewycky69bfdf52010-12-15 18:57:18 +000068 /// overdefined - This value is not known to be constant, and we know that
Chris Lattnercc4d3b22009-11-11 02:08:33 +000069 /// it has a value.
70 overdefined
71 };
72
73 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattnerb52675b2009-11-12 04:36:58 +000074 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersondb78d732010-08-05 22:10:46 +000075 LatticeValueTy Tag;
76 Constant *Val;
Owen Anderson5be2e782010-08-05 22:59:19 +000077 ConstantRange Range;
Chris Lattnercc4d3b22009-11-11 02:08:33 +000078
79public:
Owen Anderson5be2e782010-08-05 22:59:19 +000080 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
Chris Lattnercc4d3b22009-11-11 02:08:33 +000081
Chris Lattner16976522009-11-11 22:48:44 +000082 static LVILatticeVal get(Constant *C) {
83 LVILatticeVal Res;
Nick Lewycky69bfdf52010-12-15 18:57:18 +000084 if (!isa<UndefValue>(C))
Owen Anderson9f014062010-08-10 20:03:09 +000085 Res.markConstant(C);
Chris Lattner16976522009-11-11 22:48:44 +000086 return Res;
87 }
Chris Lattnerb52675b2009-11-12 04:36:58 +000088 static LVILatticeVal getNot(Constant *C) {
89 LVILatticeVal Res;
Nick Lewycky69bfdf52010-12-15 18:57:18 +000090 if (!isa<UndefValue>(C))
Owen Anderson9f014062010-08-10 20:03:09 +000091 Res.markNotConstant(C);
Chris Lattnerb52675b2009-11-12 04:36:58 +000092 return Res;
93 }
Owen Anderson625051b2010-08-10 23:20:01 +000094 static LVILatticeVal getRange(ConstantRange CR) {
95 LVILatticeVal Res;
96 Res.markConstantRange(CR);
97 return Res;
98 }
Chris Lattner16976522009-11-11 22:48:44 +000099
Owen Anderson5be2e782010-08-05 22:59:19 +0000100 bool isUndefined() const { return Tag == undefined; }
101 bool isConstant() const { return Tag == constant; }
102 bool isNotConstant() const { return Tag == notconstant; }
103 bool isConstantRange() const { return Tag == constantrange; }
104 bool isOverdefined() const { return Tag == overdefined; }
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000105
106 Constant *getConstant() const {
107 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000108 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000109 }
110
Chris Lattnerb52675b2009-11-12 04:36:58 +0000111 Constant *getNotConstant() const {
112 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000113 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000114 }
115
Owen Anderson5be2e782010-08-05 22:59:19 +0000116 ConstantRange getConstantRange() const {
117 assert(isConstantRange() &&
118 "Cannot get the constant-range of a non-constant-range!");
119 return Range;
120 }
121
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000122 /// markOverdefined - Return true if this is a change in status.
123 bool markOverdefined() {
124 if (isOverdefined())
125 return false;
Owen Andersondb78d732010-08-05 22:10:46 +0000126 Tag = overdefined;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000127 return true;
128 }
129
130 /// markConstant - Return true if this is a change in status.
131 bool markConstant(Constant *V) {
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000132 assert(V && "Marking constant with NULL");
133 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
134 return markConstantRange(ConstantRange(CI->getValue()));
135 if (isa<UndefValue>(V))
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000136 return false;
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000137
138 assert((!isConstant() || getConstant() == V) &&
139 "Marking constant with different value");
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000140 assert(isUndefined());
Owen Andersondb78d732010-08-05 22:10:46 +0000141 Tag = constant;
Owen Andersondb78d732010-08-05 22:10:46 +0000142 Val = V;
Chris Lattner16976522009-11-11 22:48:44 +0000143 return true;
144 }
145
Chris Lattnerb52675b2009-11-12 04:36:58 +0000146 /// markNotConstant - Return true if this is a change in status.
147 bool markNotConstant(Constant *V) {
Chris Lattnerb52675b2009-11-12 04:36:58 +0000148 assert(V && "Marking constant with NULL");
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000149 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
150 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
151 if (isa<UndefValue>(V))
152 return false;
153
154 assert((!isConstant() || getConstant() != V) &&
155 "Marking constant !constant with same value");
156 assert((!isNotConstant() || getNotConstant() == V) &&
157 "Marking !constant with different value");
158 assert(isUndefined() || isConstant());
159 Tag = notconstant;
Owen Andersondb78d732010-08-05 22:10:46 +0000160 Val = V;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000161 return true;
162 }
163
Owen Anderson5be2e782010-08-05 22:59:19 +0000164 /// markConstantRange - Return true if this is a change in status.
165 bool markConstantRange(const ConstantRange NewR) {
166 if (isConstantRange()) {
167 if (NewR.isEmptySet())
168 return markOverdefined();
169
Owen Anderson5be2e782010-08-05 22:59:19 +0000170 bool changed = Range == NewR;
171 Range = NewR;
172 return changed;
173 }
174
175 assert(isUndefined());
176 if (NewR.isEmptySet())
177 return markOverdefined();
Owen Anderson5be2e782010-08-05 22:59:19 +0000178
179 Tag = constantrange;
180 Range = NewR;
181 return true;
182 }
183
Chris Lattner16976522009-11-11 22:48:44 +0000184 /// mergeIn - Merge the specified lattice value into this one, updating this
185 /// one and returning true if anything changed.
186 bool mergeIn(const LVILatticeVal &RHS) {
187 if (RHS.isUndefined() || isOverdefined()) return false;
188 if (RHS.isOverdefined()) return markOverdefined();
189
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000190 if (isUndefined()) {
191 Tag = RHS.Tag;
192 Val = RHS.Val;
193 Range = RHS.Range;
194 return true;
Chris Lattnerf496e792009-11-12 04:57:13 +0000195 }
196
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000197 if (isConstant()) {
198 if (RHS.isConstant()) {
199 if (Val == RHS.Val)
200 return false;
201 return markOverdefined();
202 }
203
204 if (RHS.isNotConstant()) {
205 if (Val == RHS.Val)
206 return markOverdefined();
207
208 // Unless we can prove that the two Constants are different, we must
209 // move to overdefined.
210 // FIXME: use TargetData for smarter constant folding.
211 if (ConstantInt *Res = dyn_cast<ConstantInt>(
212 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
213 getConstant(),
214 RHS.getNotConstant())))
215 if (Res->isOne())
216 return markNotConstant(RHS.getNotConstant());
217
218 return markOverdefined();
219 }
220
221 // RHS is a ConstantRange, LHS is a non-integer Constant.
222
223 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
224 // a function. The correct result is to pick up RHS.
225
Chris Lattner16976522009-11-11 22:48:44 +0000226 return markOverdefined();
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000227 }
228
229 if (isNotConstant()) {
230 if (RHS.isConstant()) {
231 if (Val == RHS.Val)
232 return markOverdefined();
233
234 // Unless we can prove that the two Constants are different, we must
235 // move to overdefined.
236 // FIXME: use TargetData for smarter constant folding.
237 if (ConstantInt *Res = dyn_cast<ConstantInt>(
238 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
239 getNotConstant(),
240 RHS.getConstant())))
241 if (Res->isOne())
242 return false;
243
244 return markOverdefined();
245 }
246
247 if (RHS.isNotConstant()) {
248 if (Val == RHS.Val)
249 return false;
250 return markOverdefined();
251 }
252
253 return markOverdefined();
254 }
255
256 assert(isConstantRange() && "New LVILattice type?");
257 if (!RHS.isConstantRange())
258 return markOverdefined();
259
260 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
261 if (NewR.isFullSet())
262 return markOverdefined();
263 return markConstantRange(NewR);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000264 }
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000265};
266
267} // end anonymous namespace.
268
Chris Lattner16976522009-11-11 22:48:44 +0000269namespace llvm {
Chandler Carruth3b55a372011-04-18 18:49:44 +0000270raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
271 LLVM_ATTRIBUTE_USED;
Chris Lattner16976522009-11-11 22:48:44 +0000272raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
273 if (Val.isUndefined())
274 return OS << "undefined";
275 if (Val.isOverdefined())
276 return OS << "overdefined";
Chris Lattnerb52675b2009-11-12 04:36:58 +0000277
278 if (Val.isNotConstant())
279 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Owen Anderson2f3ffb82010-08-09 20:50:46 +0000280 else if (Val.isConstantRange())
281 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
282 << Val.getConstantRange().getUpper() << '>';
Chris Lattner16976522009-11-11 22:48:44 +0000283 return OS << "constant<" << *Val.getConstant() << '>';
284}
285}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000286
287//===----------------------------------------------------------------------===//
Chris Lattner2c5adf82009-11-15 19:59:49 +0000288// LazyValueInfoCache Decl
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000289//===----------------------------------------------------------------------===//
290
Chris Lattner2c5adf82009-11-15 19:59:49 +0000291namespace {
Owen Anderson89778462011-01-05 21:15:29 +0000292 /// LVIValueHandle - A callback value handle update the cache when
293 /// values are erased.
294 class LazyValueInfoCache;
295 struct LVIValueHandle : public CallbackVH {
296 LazyValueInfoCache *Parent;
297
298 LVIValueHandle(Value *V, LazyValueInfoCache *P)
299 : CallbackVH(V), Parent(P) { }
300
301 void deleted();
302 void allUsesReplacedWith(Value *V) {
303 deleted();
304 }
305 };
306}
307
308namespace llvm {
309 template<>
310 struct DenseMapInfo<LVIValueHandle> {
311 typedef DenseMapInfo<Value*> PointerInfo;
312 static inline LVIValueHandle getEmptyKey() {
313 return LVIValueHandle(PointerInfo::getEmptyKey(),
314 static_cast<LazyValueInfoCache*>(0));
315 }
316 static inline LVIValueHandle getTombstoneKey() {
317 return LVIValueHandle(PointerInfo::getTombstoneKey(),
318 static_cast<LazyValueInfoCache*>(0));
319 }
320 static unsigned getHashValue(const LVIValueHandle &Val) {
321 return PointerInfo::getHashValue(Val);
322 }
323 static bool isEqual(const LVIValueHandle &LHS, const LVIValueHandle &RHS) {
324 return LHS == RHS;
325 }
326 };
327
328 template<>
329 struct DenseMapInfo<std::pair<AssertingVH<BasicBlock>, Value*> > {
330 typedef std::pair<AssertingVH<BasicBlock>, Value*> PairTy;
331 typedef DenseMapInfo<AssertingVH<BasicBlock> > APointerInfo;
332 typedef DenseMapInfo<Value*> BPointerInfo;
333 static inline PairTy getEmptyKey() {
334 return std::make_pair(APointerInfo::getEmptyKey(),
335 BPointerInfo::getEmptyKey());
336 }
337 static inline PairTy getTombstoneKey() {
338 return std::make_pair(APointerInfo::getTombstoneKey(),
339 BPointerInfo::getTombstoneKey());
340 }
341 static unsigned getHashValue( const PairTy &Val) {
342 return APointerInfo::getHashValue(Val.first) ^
343 BPointerInfo::getHashValue(Val.second);
344 }
345 static bool isEqual(const PairTy &LHS, const PairTy &RHS) {
346 return APointerInfo::isEqual(LHS.first, RHS.first) &&
347 BPointerInfo::isEqual(LHS.second, RHS.second);
348 }
349 };
350}
351
352namespace {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000353 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
354 /// maintains information about queries across the clients' queries.
355 class LazyValueInfoCache {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000356 /// ValueCacheEntryTy - This is all of the cached block information for
357 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
358 /// entries, allowing us to do a lookup with a binary search.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000359 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000360
Owen Andersone68713a2011-01-05 23:26:22 +0000361 /// ValueCache - This is all of the cached information for all values,
362 /// mapped from Value* to key information.
363 DenseMap<LVIValueHandle, ValueCacheEntryTy> ValueCache;
364
365 /// OverDefinedCache - This tracks, on a per-block basis, the set of
366 /// values that are over-defined at the end of that block. This is required
367 /// for cache updating.
368 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
369 DenseSet<OverDefinedPairTy> OverDefinedCache;
370
371 /// BlockValueStack - This stack holds the state of the value solver
372 /// during a query. It basically emulates the callstack of the naive
373 /// recursive value lookup process.
374 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
375
Owen Anderson89778462011-01-05 21:15:29 +0000376 friend struct LVIValueHandle;
Owen Anderson87790ab2010-12-20 19:33:41 +0000377
378 /// OverDefinedCacheUpdater - A helper object that ensures that the
379 /// OverDefinedCache is updated whenever solveBlockValue returns.
380 struct OverDefinedCacheUpdater {
381 LazyValueInfoCache *Parent;
382 Value *Val;
383 BasicBlock *BB;
384 LVILatticeVal &BBLV;
385
386 OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV,
387 LazyValueInfoCache *P)
388 : Parent(P), Val(V), BB(B), BBLV(LV) { }
389
390 bool markResult(bool changed) {
391 if (changed && BBLV.isOverdefined())
392 Parent->OverDefinedCache.insert(std::make_pair(BB, Val));
393 return changed;
394 }
395 };
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000396
Owen Andersone68713a2011-01-05 23:26:22 +0000397
Owen Anderson7f9cb742010-07-30 23:59:40 +0000398
Owen Andersonf33b3022010-12-09 06:14:58 +0000399 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000400 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
401 LVILatticeVal &Result);
402 bool hasBlockValue(Value *Val, BasicBlock *BB);
403
404 // These methods process one work item and may add more. A false value
405 // returned means that the work item was not completely processed and must
406 // be revisited after going through the new items.
407 bool solveBlockValue(Value *Val, BasicBlock *BB);
Owen Anderson61863942010-12-20 18:18:16 +0000408 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
409 Value *Val, BasicBlock *BB);
410 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
411 PHINode *PN, BasicBlock *BB);
412 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
413 Instruction *BBI, BasicBlock *BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000414
415 void solve();
Owen Andersonf33b3022010-12-09 06:14:58 +0000416
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000417 ValueCacheEntryTy &lookup(Value *V) {
Owen Andersonf33b3022010-12-09 06:14:58 +0000418 return ValueCache[LVIValueHandle(V, this)];
419 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000420
Chris Lattner2c5adf82009-11-15 19:59:49 +0000421 public:
Chris Lattner2c5adf82009-11-15 19:59:49 +0000422 /// getValueInBlock - This is the query interface to determine the lattice
423 /// value for the specified Value* at the end of the specified block.
424 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
425
426 /// getValueOnEdge - This is the query interface to determine the lattice
427 /// value for the specified Value* that is true on the specified edge.
428 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000429
430 /// threadEdge - This is the update interface to inform the cache that an
431 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
432 /// NewSucc.
433 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000434
435 /// eraseBlock - This is part of the update interface to inform the cache
436 /// that a block has been deleted.
437 void eraseBlock(BasicBlock *BB);
438
439 /// clear - Empty the cache.
440 void clear() {
441 ValueCache.clear();
442 OverDefinedCache.clear();
443 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000444 };
445} // end anonymous namespace
446
Owen Anderson89778462011-01-05 21:15:29 +0000447void LVIValueHandle::deleted() {
448 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
449
450 SmallVector<OverDefinedPairTy, 4> ToErase;
451 for (DenseSet<OverDefinedPairTy>::iterator
Owen Anderson7f9cb742010-07-30 23:59:40 +0000452 I = Parent->OverDefinedCache.begin(),
453 E = Parent->OverDefinedCache.end();
Owen Anderson89778462011-01-05 21:15:29 +0000454 I != E; ++I) {
455 if (I->second == getValPtr())
456 ToErase.push_back(*I);
Owen Anderson7f9cb742010-07-30 23:59:40 +0000457 }
Owen Andersoncf6abd22010-08-11 22:36:04 +0000458
Owen Anderson89778462011-01-05 21:15:29 +0000459 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
460 E = ToErase.end(); I != E; ++I)
461 Parent->OverDefinedCache.erase(*I);
462
Owen Andersoncf6abd22010-08-11 22:36:04 +0000463 // This erasure deallocates *this, so it MUST happen after we're done
464 // using any and all members of *this.
465 Parent->ValueCache.erase(*this);
Owen Anderson7f9cb742010-07-30 23:59:40 +0000466}
467
Owen Anderson00ac77e2010-08-18 18:39:01 +0000468void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
Owen Anderson89778462011-01-05 21:15:29 +0000469 SmallVector<OverDefinedPairTy, 4> ToErase;
470 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
471 E = OverDefinedCache.end(); I != E; ++I) {
472 if (I->first == BB)
473 ToErase.push_back(*I);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000474 }
Owen Anderson89778462011-01-05 21:15:29 +0000475
476 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
477 E = ToErase.end(); I != E; ++I)
478 OverDefinedCache.erase(*I);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000479
Owen Anderson89778462011-01-05 21:15:29 +0000480 for (DenseMap<LVIValueHandle, ValueCacheEntryTy>::iterator
Owen Anderson00ac77e2010-08-18 18:39:01 +0000481 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
482 I->second.erase(BB);
483}
Owen Anderson7f9cb742010-07-30 23:59:40 +0000484
Nick Lewycky90862ee2010-12-18 01:00:40 +0000485void LazyValueInfoCache::solve() {
Owen Andersone68713a2011-01-05 23:26:22 +0000486 while (!BlockValueStack.empty()) {
487 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
Owen Anderson87790ab2010-12-20 19:33:41 +0000488 if (solveBlockValue(e.second, e.first))
Owen Andersone68713a2011-01-05 23:26:22 +0000489 BlockValueStack.pop();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000490 }
491}
492
493bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
494 // If already a constant, there is nothing to compute.
495 if (isa<Constant>(Val))
496 return true;
497
Owen Anderson89778462011-01-05 21:15:29 +0000498 LVIValueHandle ValHandle(Val, this);
499 if (!ValueCache.count(ValHandle)) return false;
500 return ValueCache[ValHandle].count(BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000501}
502
Owen Andersonf33b3022010-12-09 06:14:58 +0000503LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000504 // If already a constant, there is nothing to compute.
505 if (Constant *VC = dyn_cast<Constant>(Val))
506 return LVILatticeVal::get(VC);
507
508 return lookup(Val)[BB];
509}
510
511bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
512 if (isa<Constant>(Val))
513 return true;
514
Owen Andersonf33b3022010-12-09 06:14:58 +0000515 ValueCacheEntryTy &Cache = lookup(Val);
516 LVILatticeVal &BBLV = Cache[BB];
Owen Anderson87790ab2010-12-20 19:33:41 +0000517
518 // OverDefinedCacheUpdater is a helper object that will update
519 // the OverDefinedCache for us when this method exits. Make sure to
520 // call markResult on it as we exist, passing a bool to indicate if the
521 // cache needs updating, i.e. if we have solve a new value or not.
522 OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000523
Chris Lattner2c5adf82009-11-15 19:59:49 +0000524 // If we've already computed this block's value, return it.
Chris Lattnere5642812009-11-15 20:00:52 +0000525 if (!BBLV.isUndefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000526 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
Owen Anderson87790ab2010-12-20 19:33:41 +0000527
528 // Since we're reusing a cached value here, we don't need to update the
529 // OverDefinedCahce. The cache will have been properly updated
530 // whenever the cached value was inserted.
531 ODCacheUpdater.markResult(false);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000532 return true;
Chris Lattnere5642812009-11-15 20:00:52 +0000533 }
534
Chris Lattner2c5adf82009-11-15 19:59:49 +0000535 // Otherwise, this is the first time we're seeing this block. Reset the
536 // lattice value to overdefined, so that cycles will terminate and be
537 // conservatively correct.
538 BBLV.markOverdefined();
539
Chris Lattner2c5adf82009-11-15 19:59:49 +0000540 Instruction *BBI = dyn_cast<Instruction>(Val);
541 if (BBI == 0 || BBI->getParent() != BB) {
Owen Anderson87790ab2010-12-20 19:33:41 +0000542 return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
Chris Lattner2c5adf82009-11-15 19:59:49 +0000543 }
Chris Lattnere5642812009-11-15 20:00:52 +0000544
Nick Lewycky90862ee2010-12-18 01:00:40 +0000545 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Owen Anderson87790ab2010-12-20 19:33:41 +0000546 return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000547 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000548
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000549 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
550 BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
551 return ODCacheUpdater.markResult(true);
552 }
553
Owen Andersonb81fd622010-08-18 21:11:37 +0000554 // We can only analyze the definitions of certain classes of instructions
555 // (integral binops and casts at the moment), so bail if this isn't one.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000556 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000557 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
558 !BBI->getType()->isIntegerTy()) {
559 DEBUG(dbgs() << " compute BB '" << BB->getName()
560 << "' - overdefined because inst def found.\n");
Owen Anderson61863942010-12-20 18:18:16 +0000561 BBLV.markOverdefined();
Owen Anderson87790ab2010-12-20 19:33:41 +0000562 return ODCacheUpdater.markResult(true);
Owen Andersonb81fd622010-08-18 21:11:37 +0000563 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000564
Owen Andersonb81fd622010-08-18 21:11:37 +0000565 // FIXME: We're currently limited to binops with a constant RHS. This should
566 // be improved.
567 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
568 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
569 DEBUG(dbgs() << " compute BB '" << BB->getName()
570 << "' - overdefined because inst def found.\n");
571
Owen Anderson61863942010-12-20 18:18:16 +0000572 BBLV.markOverdefined();
Owen Anderson87790ab2010-12-20 19:33:41 +0000573 return ODCacheUpdater.markResult(true);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000574 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000575
Owen Anderson87790ab2010-12-20 19:33:41 +0000576 return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000577}
578
579static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
580 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
581 return L->getPointerAddressSpace() == 0 &&
582 GetUnderlyingObject(L->getPointerOperand()) ==
583 GetUnderlyingObject(Ptr);
584 }
585 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
586 return S->getPointerAddressSpace() == 0 &&
587 GetUnderlyingObject(S->getPointerOperand()) ==
588 GetUnderlyingObject(Ptr);
589 }
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000590 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
591 if (MI->isVolatile()) return false;
592 if (MI->getAddressSpace() != 0) return false;
593
594 // FIXME: check whether it has a valuerange that excludes zero?
595 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
596 if (!Len || Len->isZero()) return false;
597
598 if (MI->getRawDest() == Ptr || MI->getDest() == Ptr)
599 return true;
600 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
601 return MTI->getRawSource() == Ptr || MTI->getSource() == Ptr;
602 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000603 return false;
604}
605
Owen Anderson61863942010-12-20 18:18:16 +0000606bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
607 Value *Val, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000608 LVILatticeVal Result; // Start Undefined.
609
610 // If this is a pointer, and there's a load from that pointer in this BB,
611 // then we know that the pointer can't be NULL.
612 bool NotNull = false;
613 if (Val->getType()->isPointerTy()) {
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000614 if (isa<AllocaInst>(Val)) {
615 NotNull = true;
616 } else {
617 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
618 if (InstructionDereferencesPointer(BI, Val)) {
619 NotNull = true;
620 break;
621 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000622 }
623 }
624 }
625
626 // If this is the entry block, we must be asking about an argument. The
627 // value is overdefined.
628 if (BB == &BB->getParent()->getEntryBlock()) {
629 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
630 if (NotNull) {
631 const PointerType *PTy = cast<PointerType>(Val->getType());
632 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
633 } else {
634 Result.markOverdefined();
635 }
Owen Anderson61863942010-12-20 18:18:16 +0000636 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000637 return true;
638 }
639
640 // Loop over all of our predecessors, merging what we know from them into
641 // result.
642 bool EdgesMissing = false;
643 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
644 LVILatticeVal EdgeResult;
645 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
646 if (EdgesMissing)
647 continue;
648
649 Result.mergeIn(EdgeResult);
650
651 // If we hit overdefined, exit early. The BlockVals entry is already set
652 // to overdefined.
653 if (Result.isOverdefined()) {
654 DEBUG(dbgs() << " compute BB '" << BB->getName()
655 << "' - overdefined because of pred.\n");
656 // If we previously determined that this is a pointer that can't be null
657 // then return that rather than giving up entirely.
658 if (NotNull) {
659 const PointerType *PTy = cast<PointerType>(Val->getType());
660 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
661 }
Owen Anderson61863942010-12-20 18:18:16 +0000662
663 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000664 return true;
665 }
666 }
667 if (EdgesMissing)
668 return false;
669
670 // Return the merged value, which is more precise than 'overdefined'.
671 assert(!Result.isOverdefined());
Owen Anderson61863942010-12-20 18:18:16 +0000672 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000673 return true;
674}
675
Owen Anderson61863942010-12-20 18:18:16 +0000676bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
677 PHINode *PN, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000678 LVILatticeVal Result; // Start Undefined.
679
680 // Loop over all of our predecessors, merging what we know from them into
681 // result.
682 bool EdgesMissing = false;
683 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
684 BasicBlock *PhiBB = PN->getIncomingBlock(i);
685 Value *PhiVal = PN->getIncomingValue(i);
686 LVILatticeVal EdgeResult;
687 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
688 if (EdgesMissing)
689 continue;
690
691 Result.mergeIn(EdgeResult);
692
693 // If we hit overdefined, exit early. The BlockVals entry is already set
694 // to overdefined.
695 if (Result.isOverdefined()) {
696 DEBUG(dbgs() << " compute BB '" << BB->getName()
697 << "' - overdefined because of pred.\n");
Owen Anderson61863942010-12-20 18:18:16 +0000698
699 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000700 return true;
701 }
702 }
703 if (EdgesMissing)
704 return false;
705
706 // Return the merged value, which is more precise than 'overdefined'.
707 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson61863942010-12-20 18:18:16 +0000708 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000709 return true;
710}
711
Owen Anderson61863942010-12-20 18:18:16 +0000712bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
713 Instruction *BBI,
Nick Lewycky90862ee2010-12-18 01:00:40 +0000714 BasicBlock *BB) {
Owen Andersonb81fd622010-08-18 21:11:37 +0000715 // Figure out the range of the LHS. If that fails, bail.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000716 if (!hasBlockValue(BBI->getOperand(0), BB)) {
Owen Andersone68713a2011-01-05 23:26:22 +0000717 BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0)));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000718 return false;
719 }
720
Nick Lewycky90862ee2010-12-18 01:00:40 +0000721 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Owen Andersonb81fd622010-08-18 21:11:37 +0000722 if (!LHSVal.isConstantRange()) {
Owen Anderson61863942010-12-20 18:18:16 +0000723 BBLV.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000724 return true;
Owen Andersonb81fd622010-08-18 21:11:37 +0000725 }
726
Owen Andersonb81fd622010-08-18 21:11:37 +0000727 ConstantRange LHSRange = LHSVal.getConstantRange();
728 ConstantRange RHSRange(1);
729 const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
730 if (isa<BinaryOperator>(BBI)) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000731 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
732 RHSRange = ConstantRange(RHS->getValue());
733 } else {
Owen Anderson61863942010-12-20 18:18:16 +0000734 BBLV.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000735 return true;
Owen Anderson59b06dc2010-08-24 07:55:44 +0000736 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000737 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000738
Owen Andersonb81fd622010-08-18 21:11:37 +0000739 // NOTE: We're currently limited by the set of operations that ConstantRange
740 // can evaluate symbolically. Enhancing that set will allows us to analyze
741 // more definitions.
Owen Anderson61863942010-12-20 18:18:16 +0000742 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000743 switch (BBI->getOpcode()) {
744 case Instruction::Add:
745 Result.markConstantRange(LHSRange.add(RHSRange));
746 break;
747 case Instruction::Sub:
748 Result.markConstantRange(LHSRange.sub(RHSRange));
749 break;
750 case Instruction::Mul:
751 Result.markConstantRange(LHSRange.multiply(RHSRange));
752 break;
753 case Instruction::UDiv:
754 Result.markConstantRange(LHSRange.udiv(RHSRange));
755 break;
756 case Instruction::Shl:
757 Result.markConstantRange(LHSRange.shl(RHSRange));
758 break;
759 case Instruction::LShr:
760 Result.markConstantRange(LHSRange.lshr(RHSRange));
761 break;
762 case Instruction::Trunc:
763 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
764 break;
765 case Instruction::SExt:
766 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
767 break;
768 case Instruction::ZExt:
769 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
770 break;
771 case Instruction::BitCast:
772 Result.markConstantRange(LHSRange);
773 break;
Nick Lewycky198381e2010-09-07 05:39:02 +0000774 case Instruction::And:
775 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
776 break;
777 case Instruction::Or:
778 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
779 break;
Owen Andersonb81fd622010-08-18 21:11:37 +0000780
781 // Unhandled instructions are overdefined.
782 default:
783 DEBUG(dbgs() << " compute BB '" << BB->getName()
784 << "' - overdefined because inst def found.\n");
785 Result.markOverdefined();
786 break;
787 }
788
Owen Anderson61863942010-12-20 18:18:16 +0000789 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000790 return true;
Chris Lattner10f2d132009-11-11 00:22:30 +0000791}
792
Chris Lattner800c47e2009-11-15 20:02:12 +0000793/// getEdgeValue - This method attempts to infer more complex
Nick Lewycky90862ee2010-12-18 01:00:40 +0000794bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
795 BasicBlock *BBTo, LVILatticeVal &Result) {
796 // If already a constant, there is nothing to compute.
797 if (Constant *VC = dyn_cast<Constant>(Val)) {
798 Result = LVILatticeVal::get(VC);
799 return true;
800 }
801
Chris Lattner800c47e2009-11-15 20:02:12 +0000802 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
803 // know that v != 0.
Chris Lattner16976522009-11-11 22:48:44 +0000804 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
805 // If this is a conditional branch and only one successor goes to BBTo, then
806 // we maybe able to infer something from the condition.
807 if (BI->isConditional() &&
808 BI->getSuccessor(0) != BI->getSuccessor(1)) {
809 bool isTrueDest = BI->getSuccessor(0) == BBTo;
810 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
811 "BBTo isn't a successor of BBFrom");
812
813 // If V is the condition of the branch itself, then we know exactly what
814 // it is.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000815 if (BI->getCondition() == Val) {
816 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson9f014062010-08-10 20:03:09 +0000817 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000818 return true;
819 }
Chris Lattner16976522009-11-11 22:48:44 +0000820
821 // If the condition of the branch is an equality comparison, we may be
822 // able to infer the value.
Owen Anderson2d0f2472010-08-11 04:24:25 +0000823 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
824 if (ICI && ICI->getOperand(0) == Val &&
825 isa<Constant>(ICI->getOperand(1))) {
826 if (ICI->isEquality()) {
827 // We know that V has the RHS constant if this is a true SETEQ or
828 // false SETNE.
829 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
Nick Lewycky90862ee2010-12-18 01:00:40 +0000830 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
831 else
832 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
833 return true;
Chris Lattner16976522009-11-11 22:48:44 +0000834 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000835
Owen Anderson2d0f2472010-08-11 04:24:25 +0000836 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
837 // Calculate the range of values that would satisfy the comparison.
838 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
839 ConstantRange TrueValues =
840 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000841
Owen Anderson2d0f2472010-08-11 04:24:25 +0000842 // If we're interested in the false dest, invert the condition.
843 if (!isTrueDest) TrueValues = TrueValues.inverse();
844
845 // Figure out the possible values of the query BEFORE this branch.
Owen Andersonbe419012011-01-05 21:37:18 +0000846 if (!hasBlockValue(Val, BBFrom)) {
Owen Andersone68713a2011-01-05 23:26:22 +0000847 BlockValueStack.push(std::make_pair(BBFrom, Val));
Owen Andersonbe419012011-01-05 21:37:18 +0000848 return false;
849 }
850
Owen Andersonf33b3022010-12-09 06:14:58 +0000851 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000852 if (!InBlock.isConstantRange()) {
853 Result = LVILatticeVal::getRange(TrueValues);
854 return true;
855 }
856
Owen Anderson2d0f2472010-08-11 04:24:25 +0000857 // Find all potential values that satisfy both the input and output
858 // conditions.
859 ConstantRange PossibleValues =
860 TrueValues.intersectWith(InBlock.getConstantRange());
Nick Lewycky90862ee2010-12-18 01:00:40 +0000861
862 Result = LVILatticeVal::getRange(PossibleValues);
863 return true;
Owen Anderson2d0f2472010-08-11 04:24:25 +0000864 }
865 }
Chris Lattner16976522009-11-11 22:48:44 +0000866 }
867 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000868
869 // If the edge was formed by a switch on the value, then we may know exactly
870 // what it is.
871 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Owen Andersondae90c62010-08-24 21:59:42 +0000872 if (SI->getCondition() == Val) {
Owen Anderson4caef602010-09-02 22:16:52 +0000873 // We don't know anything in the default case.
Owen Andersondae90c62010-08-24 21:59:42 +0000874 if (SI->getDefaultDest() == BBTo) {
Owen Anderson4caef602010-09-02 22:16:52 +0000875 Result.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000876 return true;
Owen Andersondae90c62010-08-24 21:59:42 +0000877 }
878
Chris Lattner800c47e2009-11-15 20:02:12 +0000879 // We only know something if there is exactly one value that goes from
880 // BBFrom to BBTo.
881 unsigned NumEdges = 0;
882 ConstantInt *EdgeVal = 0;
883 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
884 if (SI->getSuccessor(i) != BBTo) continue;
885 if (NumEdges++) break;
886 EdgeVal = SI->getCaseValue(i);
887 }
888 assert(EdgeVal && "Missing successor?");
Nick Lewycky90862ee2010-12-18 01:00:40 +0000889 if (NumEdges == 1) {
890 Result = LVILatticeVal::get(EdgeVal);
891 return true;
892 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000893 }
894 }
Chris Lattner16976522009-11-11 22:48:44 +0000895
896 // Otherwise see if the value is known in the block.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000897 if (hasBlockValue(Val, BBFrom)) {
898 Result = getBlockValue(Val, BBFrom);
899 return true;
900 }
Owen Andersone68713a2011-01-05 23:26:22 +0000901 BlockValueStack.push(std::make_pair(BBFrom, Val));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000902 return false;
Chris Lattner16976522009-11-11 22:48:44 +0000903}
904
Chris Lattner2c5adf82009-11-15 19:59:49 +0000905LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
David Greene5d93a1f2009-12-23 20:43:58 +0000906 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000907 << BB->getName() << "'\n");
908
Owen Andersone68713a2011-01-05 23:26:22 +0000909 BlockValueStack.push(std::make_pair(BB, V));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000910 solve();
Owen Andersonf33b3022010-12-09 06:14:58 +0000911 LVILatticeVal Result = getBlockValue(V, BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000912
David Greene5d93a1f2009-12-23 20:43:58 +0000913 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000914 return Result;
915}
Chris Lattner16976522009-11-11 22:48:44 +0000916
Chris Lattner2c5adf82009-11-15 19:59:49 +0000917LVILatticeVal LazyValueInfoCache::
918getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
David Greene5d93a1f2009-12-23 20:43:58 +0000919 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000920 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000921
Nick Lewycky90862ee2010-12-18 01:00:40 +0000922 LVILatticeVal Result;
923 if (!getEdgeValue(V, FromBB, ToBB, Result)) {
924 solve();
925 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
926 (void)WasFastQuery;
927 assert(WasFastQuery && "More work to do after problem solved?");
928 }
929
David Greene5d93a1f2009-12-23 20:43:58 +0000930 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000931 return Result;
932}
933
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000934void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
935 BasicBlock *NewSucc) {
936 // When an edge in the graph has been threaded, values that we could not
937 // determine a value for before (i.e. were marked overdefined) may be possible
938 // to solve now. We do NOT try to proactively update these values. Instead,
939 // we clear their entries from the cache, and allow lazy updating to recompute
940 // them when needed.
941
942 // The updating process is fairly simple: we need to dropped cached info
943 // for all values that were marked overdefined in OldSucc, and for those same
944 // values in any successor of OldSucc (except NewSucc) in which they were
945 // also marked overdefined.
946 std::vector<BasicBlock*> worklist;
947 worklist.push_back(OldSucc);
948
Owen Anderson9a65dc92010-07-27 23:58:11 +0000949 DenseSet<Value*> ClearSet;
Owen Anderson89778462011-01-05 21:15:29 +0000950 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
951 E = OverDefinedCache.end(); I != E; ++I) {
Owen Anderson9a65dc92010-07-27 23:58:11 +0000952 if (I->first == OldSucc)
953 ClearSet.insert(I->second);
954 }
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000955
956 // Use a worklist to perform a depth-first search of OldSucc's successors.
957 // NOTE: We do not need a visited list since any blocks we have already
958 // visited will have had their overdefined markers cleared already, and we
959 // thus won't loop to their successors.
960 while (!worklist.empty()) {
961 BasicBlock *ToUpdate = worklist.back();
962 worklist.pop_back();
963
964 // Skip blocks only accessible through NewSucc.
965 if (ToUpdate == NewSucc) continue;
966
967 bool changed = false;
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000968 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000969 I != E; ++I) {
970 // If a value was marked overdefined in OldSucc, and is here too...
Owen Anderson89778462011-01-05 21:15:29 +0000971 DenseSet<OverDefinedPairTy>::iterator OI =
Owen Anderson9a65dc92010-07-27 23:58:11 +0000972 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
973 if (OI == OverDefinedCache.end()) continue;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000974
Owen Anderson9a65dc92010-07-27 23:58:11 +0000975 // Remove it from the caches.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000976 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
Owen Anderson9a65dc92010-07-27 23:58:11 +0000977 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000978
Owen Anderson9a65dc92010-07-27 23:58:11 +0000979 assert(CI != Entry.end() && "Couldn't find entry to update?");
980 Entry.erase(CI);
981 OverDefinedCache.erase(OI);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000982
Owen Anderson9a65dc92010-07-27 23:58:11 +0000983 // If we removed anything, then we potentially need to update
984 // blocks successors too.
985 changed = true;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000986 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000987
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000988 if (!changed) continue;
989
990 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
991 }
992}
993
Chris Lattner2c5adf82009-11-15 19:59:49 +0000994//===----------------------------------------------------------------------===//
995// LazyValueInfo Impl
996//===----------------------------------------------------------------------===//
997
Chris Lattner2c5adf82009-11-15 19:59:49 +0000998/// getCache - This lazily constructs the LazyValueInfoCache.
999static LazyValueInfoCache &getCache(void *&PImpl) {
1000 if (!PImpl)
1001 PImpl = new LazyValueInfoCache();
1002 return *static_cast<LazyValueInfoCache*>(PImpl);
1003}
1004
Owen Anderson00ac77e2010-08-18 18:39:01 +00001005bool LazyValueInfo::runOnFunction(Function &F) {
1006 if (PImpl)
1007 getCache(PImpl).clear();
1008
1009 TD = getAnalysisIfAvailable<TargetData>();
1010 // Fully lazy.
1011 return false;
1012}
1013
Chris Lattner2c5adf82009-11-15 19:59:49 +00001014void LazyValueInfo::releaseMemory() {
1015 // If the cache was allocated, free it.
1016 if (PImpl) {
1017 delete &getCache(PImpl);
1018 PImpl = 0;
1019 }
1020}
1021
1022Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
1023 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
1024
Chris Lattner16976522009-11-11 22:48:44 +00001025 if (Result.isConstant())
1026 return Result.getConstant();
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001027 if (Result.isConstantRange()) {
Owen Andersonee61fcf2010-08-27 23:29:38 +00001028 ConstantRange CR = Result.getConstantRange();
1029 if (const APInt *SingleVal = CR.getSingleElement())
1030 return ConstantInt::get(V->getContext(), *SingleVal);
1031 }
Chris Lattner16976522009-11-11 22:48:44 +00001032 return 0;
1033}
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001034
Chris Lattner38392bb2009-11-12 01:29:10 +00001035/// getConstantOnEdge - Determine whether the specified value is known to be a
1036/// constant on the specified edge. Return null if not.
1037Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1038 BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +00001039 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattner38392bb2009-11-12 01:29:10 +00001040
1041 if (Result.isConstant())
1042 return Result.getConstant();
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001043 if (Result.isConstantRange()) {
Owen Anderson9f014062010-08-10 20:03:09 +00001044 ConstantRange CR = Result.getConstantRange();
1045 if (const APInt *SingleVal = CR.getSingleElement())
1046 return ConstantInt::get(V->getContext(), *SingleVal);
1047 }
Chris Lattner38392bb2009-11-12 01:29:10 +00001048 return 0;
1049}
1050
Chris Lattnerb52675b2009-11-12 04:36:58 +00001051/// getPredicateOnEdge - Determine whether the specified value comparison
1052/// with a constant is known to be true or false on the specified CFG edge.
1053/// Pred is a CmpInst predicate.
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001054LazyValueInfo::Tristate
Chris Lattnerb52675b2009-11-12 04:36:58 +00001055LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1056 BasicBlock *FromBB, BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +00001057 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001058
Chris Lattnerb52675b2009-11-12 04:36:58 +00001059 // If we know the value is a constant, evaluate the conditional.
1060 Constant *Res = 0;
1061 if (Result.isConstant()) {
1062 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001063 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Chris Lattnerb52675b2009-11-12 04:36:58 +00001064 return ResCI->isZero() ? False : True;
Chris Lattner2c5adf82009-11-15 19:59:49 +00001065 return Unknown;
1066 }
1067
Owen Anderson9f014062010-08-10 20:03:09 +00001068 if (Result.isConstantRange()) {
Owen Anderson59b06dc2010-08-24 07:55:44 +00001069 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1070 if (!CI) return Unknown;
1071
Owen Anderson9f014062010-08-10 20:03:09 +00001072 ConstantRange CR = Result.getConstantRange();
1073 if (Pred == ICmpInst::ICMP_EQ) {
1074 if (!CR.contains(CI->getValue()))
1075 return False;
1076
1077 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1078 return True;
1079 } else if (Pred == ICmpInst::ICMP_NE) {
1080 if (!CR.contains(CI->getValue()))
1081 return True;
1082
1083 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1084 return False;
1085 }
1086
1087 // Handle more complex predicates.
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001088 ConstantRange TrueValues =
1089 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1090 if (TrueValues.contains(CR))
Owen Anderson9f014062010-08-10 20:03:09 +00001091 return True;
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001092 if (TrueValues.inverse().contains(CR))
1093 return False;
Owen Anderson9f014062010-08-10 20:03:09 +00001094 return Unknown;
1095 }
1096
Chris Lattner2c5adf82009-11-15 19:59:49 +00001097 if (Result.isNotConstant()) {
Chris Lattnerb52675b2009-11-12 04:36:58 +00001098 // If this is an equality comparison, we can try to fold it knowing that
1099 // "V != C1".
1100 if (Pred == ICmpInst::ICMP_EQ) {
1101 // !C1 == C -> false iff C1 == C.
1102 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1103 Result.getNotConstant(), C, TD);
1104 if (Res->isNullValue())
1105 return False;
1106 } else if (Pred == ICmpInst::ICMP_NE) {
1107 // !C1 != C -> true iff C1 == C.
Chris Lattner5553a3a2009-11-15 20:01:24 +00001108 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chris Lattnerb52675b2009-11-12 04:36:58 +00001109 Result.getNotConstant(), C, TD);
1110 if (Res->isNullValue())
1111 return True;
1112 }
Chris Lattner2c5adf82009-11-15 19:59:49 +00001113 return Unknown;
Chris Lattnerb52675b2009-11-12 04:36:58 +00001114 }
1115
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001116 return Unknown;
1117}
1118
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001119void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001120 BasicBlock *NewSucc) {
Owen Anderson00ac77e2010-08-18 18:39:01 +00001121 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1122}
1123
1124void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1125 if (PImpl) getCache(PImpl).eraseBlock(BB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001126}