blob: 9e7da6ce2de9e212d58cb06264928bc0538a0237 [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>
32#include <set>
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;
Owen Andersond13db2c2010-07-21 22:09:45 +000037INITIALIZE_PASS(LazyValueInfo, "lazy-value-info",
Owen Andersonce665bd2010-10-07 22:25:06 +000038 "Lazy Value Information Analysis", false, true)
Chris Lattner10f2d132009-11-11 00:22:30 +000039
40namespace llvm {
41 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
42}
43
Chris Lattnercc4d3b22009-11-11 02:08:33 +000044
45//===----------------------------------------------------------------------===//
46// LVILatticeVal
47//===----------------------------------------------------------------------===//
48
49/// LVILatticeVal - This is the information tracked by LazyValueInfo for each
50/// value.
51///
52/// FIXME: This is basically just for bringup, this can be made a lot more rich
53/// in the future.
54///
55namespace {
56class LVILatticeVal {
57 enum LatticeValueTy {
Nick Lewycky69bfdf52010-12-15 18:57:18 +000058 /// undefined - This Value has no known value yet.
Chris Lattnercc4d3b22009-11-11 02:08:33 +000059 undefined,
Owen Anderson5be2e782010-08-05 22:59:19 +000060
Nick Lewycky69bfdf52010-12-15 18:57:18 +000061 /// constant - This Value has a specific constant value.
Chris Lattnercc4d3b22009-11-11 02:08:33 +000062 constant,
Nick Lewycky69bfdf52010-12-15 18:57:18 +000063 /// notconstant - This Value is known to not have the specified value.
Chris Lattnerb52675b2009-11-12 04:36:58 +000064 notconstant,
65
Nick Lewycky69bfdf52010-12-15 18:57:18 +000066 /// constantrange - The Value falls within this range.
Owen Anderson5be2e782010-08-05 22:59:19 +000067 constantrange,
68
Nick Lewycky69bfdf52010-12-15 18:57:18 +000069 /// overdefined - This value is not known to be constant, and we know that
Chris Lattnercc4d3b22009-11-11 02:08:33 +000070 /// it has a value.
71 overdefined
72 };
73
74 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattnerb52675b2009-11-12 04:36:58 +000075 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersondb78d732010-08-05 22:10:46 +000076 LatticeValueTy Tag;
77 Constant *Val;
Owen Anderson5be2e782010-08-05 22:59:19 +000078 ConstantRange Range;
Chris Lattnercc4d3b22009-11-11 02:08:33 +000079
80public:
Owen Anderson5be2e782010-08-05 22:59:19 +000081 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
Chris Lattnercc4d3b22009-11-11 02:08:33 +000082
Chris Lattner16976522009-11-11 22:48:44 +000083 static LVILatticeVal get(Constant *C) {
84 LVILatticeVal Res;
Nick Lewycky69bfdf52010-12-15 18:57:18 +000085 if (!isa<UndefValue>(C))
Owen Anderson9f014062010-08-10 20:03:09 +000086 Res.markConstant(C);
Chris Lattner16976522009-11-11 22:48:44 +000087 return Res;
88 }
Chris Lattnerb52675b2009-11-12 04:36:58 +000089 static LVILatticeVal getNot(Constant *C) {
90 LVILatticeVal Res;
Nick Lewycky69bfdf52010-12-15 18:57:18 +000091 if (!isa<UndefValue>(C))
Owen Anderson9f014062010-08-10 20:03:09 +000092 Res.markNotConstant(C);
Chris Lattnerb52675b2009-11-12 04:36:58 +000093 return Res;
94 }
Owen Anderson625051b2010-08-10 23:20:01 +000095 static LVILatticeVal getRange(ConstantRange CR) {
96 LVILatticeVal Res;
97 Res.markConstantRange(CR);
98 return Res;
99 }
Chris Lattner16976522009-11-11 22:48:44 +0000100
Owen Anderson5be2e782010-08-05 22:59:19 +0000101 bool isUndefined() const { return Tag == undefined; }
102 bool isConstant() const { return Tag == constant; }
103 bool isNotConstant() const { return Tag == notconstant; }
104 bool isConstantRange() const { return Tag == constantrange; }
105 bool isOverdefined() const { return Tag == overdefined; }
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000106
107 Constant *getConstant() const {
108 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000109 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000110 }
111
Chris Lattnerb52675b2009-11-12 04:36:58 +0000112 Constant *getNotConstant() const {
113 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000114 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000115 }
116
Owen Anderson5be2e782010-08-05 22:59:19 +0000117 ConstantRange getConstantRange() const {
118 assert(isConstantRange() &&
119 "Cannot get the constant-range of a non-constant-range!");
120 return Range;
121 }
122
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000123 /// markOverdefined - Return true if this is a change in status.
124 bool markOverdefined() {
125 if (isOverdefined())
126 return false;
Owen Andersondb78d732010-08-05 22:10:46 +0000127 Tag = overdefined;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000128 return true;
129 }
130
131 /// markConstant - Return true if this is a change in status.
132 bool markConstant(Constant *V) {
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000133 assert(V && "Marking constant with NULL");
134 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
135 return markConstantRange(ConstantRange(CI->getValue()));
136 if (isa<UndefValue>(V))
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000137 return false;
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000138
139 assert((!isConstant() || getConstant() == V) &&
140 "Marking constant with different value");
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000141 assert(isUndefined());
Owen Andersondb78d732010-08-05 22:10:46 +0000142 Tag = constant;
Owen Andersondb78d732010-08-05 22:10:46 +0000143 Val = V;
Chris Lattner16976522009-11-11 22:48:44 +0000144 return true;
145 }
146
Chris Lattnerb52675b2009-11-12 04:36:58 +0000147 /// markNotConstant - Return true if this is a change in status.
148 bool markNotConstant(Constant *V) {
Chris Lattnerb52675b2009-11-12 04:36:58 +0000149 assert(V && "Marking constant with NULL");
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000150 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
151 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
152 if (isa<UndefValue>(V))
153 return false;
154
155 assert((!isConstant() || getConstant() != V) &&
156 "Marking constant !constant with same value");
157 assert((!isNotConstant() || getNotConstant() == V) &&
158 "Marking !constant with different value");
159 assert(isUndefined() || isConstant());
160 Tag = notconstant;
Owen Andersondb78d732010-08-05 22:10:46 +0000161 Val = V;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000162 return true;
163 }
164
Owen Anderson5be2e782010-08-05 22:59:19 +0000165 /// markConstantRange - Return true if this is a change in status.
166 bool markConstantRange(const ConstantRange NewR) {
167 if (isConstantRange()) {
168 if (NewR.isEmptySet())
169 return markOverdefined();
170
Owen Anderson5be2e782010-08-05 22:59:19 +0000171 bool changed = Range == NewR;
172 Range = NewR;
173 return changed;
174 }
175
176 assert(isUndefined());
177 if (NewR.isEmptySet())
178 return markOverdefined();
Owen Anderson5be2e782010-08-05 22:59:19 +0000179
180 Tag = constantrange;
181 Range = NewR;
182 return true;
183 }
184
Chris Lattner16976522009-11-11 22:48:44 +0000185 /// mergeIn - Merge the specified lattice value into this one, updating this
186 /// one and returning true if anything changed.
187 bool mergeIn(const LVILatticeVal &RHS) {
188 if (RHS.isUndefined() || isOverdefined()) return false;
189 if (RHS.isOverdefined()) return markOverdefined();
190
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000191 if (isUndefined()) {
192 Tag = RHS.Tag;
193 Val = RHS.Val;
194 Range = RHS.Range;
195 return true;
Chris Lattnerf496e792009-11-12 04:57:13 +0000196 }
197
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000198 if (isConstant()) {
199 if (RHS.isConstant()) {
200 if (Val == RHS.Val)
201 return false;
202 return markOverdefined();
203 }
204
205 if (RHS.isNotConstant()) {
206 if (Val == RHS.Val)
207 return markOverdefined();
208
209 // Unless we can prove that the two Constants are different, we must
210 // move to overdefined.
211 // FIXME: use TargetData for smarter constant folding.
212 if (ConstantInt *Res = dyn_cast<ConstantInt>(
213 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
214 getConstant(),
215 RHS.getNotConstant())))
216 if (Res->isOne())
217 return markNotConstant(RHS.getNotConstant());
218
219 return markOverdefined();
220 }
221
222 // RHS is a ConstantRange, LHS is a non-integer Constant.
223
224 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
225 // a function. The correct result is to pick up RHS.
226
Chris Lattner16976522009-11-11 22:48:44 +0000227 return markOverdefined();
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000228 }
229
230 if (isNotConstant()) {
231 if (RHS.isConstant()) {
232 if (Val == RHS.Val)
233 return markOverdefined();
234
235 // Unless we can prove that the two Constants are different, we must
236 // move to overdefined.
237 // FIXME: use TargetData for smarter constant folding.
238 if (ConstantInt *Res = dyn_cast<ConstantInt>(
239 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
240 getNotConstant(),
241 RHS.getConstant())))
242 if (Res->isOne())
243 return false;
244
245 return markOverdefined();
246 }
247
248 if (RHS.isNotConstant()) {
249 if (Val == RHS.Val)
250 return false;
251 return markOverdefined();
252 }
253
254 return markOverdefined();
255 }
256
257 assert(isConstantRange() && "New LVILattice type?");
258 if (!RHS.isConstantRange())
259 return markOverdefined();
260
261 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
262 if (NewR.isFullSet())
263 return markOverdefined();
264 return markConstantRange(NewR);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000265 }
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000266};
267
268} // end anonymous namespace.
269
Chris Lattner16976522009-11-11 22:48:44 +0000270namespace llvm {
271raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
272 if (Val.isUndefined())
273 return OS << "undefined";
274 if (Val.isOverdefined())
275 return OS << "overdefined";
Chris Lattnerb52675b2009-11-12 04:36:58 +0000276
277 if (Val.isNotConstant())
278 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Owen Anderson2f3ffb82010-08-09 20:50:46 +0000279 else if (Val.isConstantRange())
280 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
281 << Val.getConstantRange().getUpper() << '>';
Chris Lattner16976522009-11-11 22:48:44 +0000282 return OS << "constant<" << *Val.getConstant() << '>';
283}
284}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000285
286//===----------------------------------------------------------------------===//
Chris Lattner2c5adf82009-11-15 19:59:49 +0000287// LazyValueInfoCache Decl
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000288//===----------------------------------------------------------------------===//
289
Chris Lattner2c5adf82009-11-15 19:59:49 +0000290namespace {
Owen Anderson89778462011-01-05 21:15:29 +0000291 /// LVIValueHandle - A callback value handle update the cache when
292 /// values are erased.
293 class LazyValueInfoCache;
294 struct LVIValueHandle : public CallbackVH {
295 LazyValueInfoCache *Parent;
296
297 LVIValueHandle(Value *V, LazyValueInfoCache *P)
298 : CallbackVH(V), Parent(P) { }
299
300 void deleted();
301 void allUsesReplacedWith(Value *V) {
302 deleted();
303 }
304 };
305}
306
307namespace llvm {
308 template<>
309 struct DenseMapInfo<LVIValueHandle> {
310 typedef DenseMapInfo<Value*> PointerInfo;
311 static inline LVIValueHandle getEmptyKey() {
312 return LVIValueHandle(PointerInfo::getEmptyKey(),
313 static_cast<LazyValueInfoCache*>(0));
314 }
315 static inline LVIValueHandle getTombstoneKey() {
316 return LVIValueHandle(PointerInfo::getTombstoneKey(),
317 static_cast<LazyValueInfoCache*>(0));
318 }
319 static unsigned getHashValue(const LVIValueHandle &Val) {
320 return PointerInfo::getHashValue(Val);
321 }
322 static bool isEqual(const LVIValueHandle &LHS, const LVIValueHandle &RHS) {
323 return LHS == RHS;
324 }
325 };
326
327 template<>
328 struct DenseMapInfo<std::pair<AssertingVH<BasicBlock>, Value*> > {
329 typedef std::pair<AssertingVH<BasicBlock>, Value*> PairTy;
330 typedef DenseMapInfo<AssertingVH<BasicBlock> > APointerInfo;
331 typedef DenseMapInfo<Value*> BPointerInfo;
332 static inline PairTy getEmptyKey() {
333 return std::make_pair(APointerInfo::getEmptyKey(),
334 BPointerInfo::getEmptyKey());
335 }
336 static inline PairTy getTombstoneKey() {
337 return std::make_pair(APointerInfo::getTombstoneKey(),
338 BPointerInfo::getTombstoneKey());
339 }
340 static unsigned getHashValue( const PairTy &Val) {
341 return APointerInfo::getHashValue(Val.first) ^
342 BPointerInfo::getHashValue(Val.second);
343 }
344 static bool isEqual(const PairTy &LHS, const PairTy &RHS) {
345 return APointerInfo::isEqual(LHS.first, RHS.first) &&
346 BPointerInfo::isEqual(LHS.second, RHS.second);
347 }
348 };
349}
350
351namespace {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000352 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
353 /// maintains information about queries across the clients' queries.
354 class LazyValueInfoCache {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000355 /// ValueCacheEntryTy - This is all of the cached block information for
356 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
357 /// entries, allowing us to do a lookup with a binary search.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000358 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000359
Owen Andersone68713a2011-01-05 23:26:22 +0000360 /// ValueCache - This is all of the cached information for all values,
361 /// mapped from Value* to key information.
362 DenseMap<LVIValueHandle, ValueCacheEntryTy> ValueCache;
363
364 /// OverDefinedCache - This tracks, on a per-block basis, the set of
365 /// values that are over-defined at the end of that block. This is required
366 /// for cache updating.
367 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
368 DenseSet<OverDefinedPairTy> OverDefinedCache;
369
370 /// BlockValueStack - This stack holds the state of the value solver
371 /// during a query. It basically emulates the callstack of the naive
372 /// recursive value lookup process.
373 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
374
Owen Anderson89778462011-01-05 21:15:29 +0000375 friend struct LVIValueHandle;
Owen Anderson87790ab2010-12-20 19:33:41 +0000376
377 /// OverDefinedCacheUpdater - A helper object that ensures that the
378 /// OverDefinedCache is updated whenever solveBlockValue returns.
379 struct OverDefinedCacheUpdater {
380 LazyValueInfoCache *Parent;
381 Value *Val;
382 BasicBlock *BB;
383 LVILatticeVal &BBLV;
384
385 OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV,
386 LazyValueInfoCache *P)
387 : Parent(P), Val(V), BB(B), BBLV(LV) { }
388
389 bool markResult(bool changed) {
390 if (changed && BBLV.isOverdefined())
391 Parent->OverDefinedCache.insert(std::make_pair(BB, Val));
392 return changed;
393 }
394 };
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000395
Owen Andersone68713a2011-01-05 23:26:22 +0000396
Owen Anderson7f9cb742010-07-30 23:59:40 +0000397
Owen Andersonf33b3022010-12-09 06:14:58 +0000398 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000399 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
400 LVILatticeVal &Result);
401 bool hasBlockValue(Value *Val, BasicBlock *BB);
402
403 // These methods process one work item and may add more. A false value
404 // returned means that the work item was not completely processed and must
405 // be revisited after going through the new items.
406 bool solveBlockValue(Value *Val, BasicBlock *BB);
Owen Anderson61863942010-12-20 18:18:16 +0000407 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
408 Value *Val, BasicBlock *BB);
409 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
410 PHINode *PN, BasicBlock *BB);
411 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
412 Instruction *BBI, BasicBlock *BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000413
414 void solve();
Owen Andersonf33b3022010-12-09 06:14:58 +0000415
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000416 ValueCacheEntryTy &lookup(Value *V) {
Owen Andersonf33b3022010-12-09 06:14:58 +0000417 return ValueCache[LVIValueHandle(V, this)];
418 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000419
Chris Lattner2c5adf82009-11-15 19:59:49 +0000420 public:
Chris Lattner2c5adf82009-11-15 19:59:49 +0000421 /// getValueInBlock - This is the query interface to determine the lattice
422 /// value for the specified Value* at the end of the specified block.
423 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
424
425 /// getValueOnEdge - This is the query interface to determine the lattice
426 /// value for the specified Value* that is true on the specified edge.
427 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000428
429 /// threadEdge - This is the update interface to inform the cache that an
430 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
431 /// NewSucc.
432 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000433
434 /// eraseBlock - This is part of the update interface to inform the cache
435 /// that a block has been deleted.
436 void eraseBlock(BasicBlock *BB);
437
438 /// clear - Empty the cache.
439 void clear() {
440 ValueCache.clear();
441 OverDefinedCache.clear();
442 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000443 };
444} // end anonymous namespace
445
Owen Anderson89778462011-01-05 21:15:29 +0000446void LVIValueHandle::deleted() {
447 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
448
449 SmallVector<OverDefinedPairTy, 4> ToErase;
450 for (DenseSet<OverDefinedPairTy>::iterator
Owen Anderson7f9cb742010-07-30 23:59:40 +0000451 I = Parent->OverDefinedCache.begin(),
452 E = Parent->OverDefinedCache.end();
Owen Anderson89778462011-01-05 21:15:29 +0000453 I != E; ++I) {
454 if (I->second == getValPtr())
455 ToErase.push_back(*I);
Owen Anderson7f9cb742010-07-30 23:59:40 +0000456 }
Owen Andersoncf6abd22010-08-11 22:36:04 +0000457
Owen Anderson89778462011-01-05 21:15:29 +0000458 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
459 E = ToErase.end(); I != E; ++I)
460 Parent->OverDefinedCache.erase(*I);
461
Owen Andersoncf6abd22010-08-11 22:36:04 +0000462 // This erasure deallocates *this, so it MUST happen after we're done
463 // using any and all members of *this.
464 Parent->ValueCache.erase(*this);
Owen Anderson7f9cb742010-07-30 23:59:40 +0000465}
466
Owen Anderson00ac77e2010-08-18 18:39:01 +0000467void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
Owen Anderson89778462011-01-05 21:15:29 +0000468 SmallVector<OverDefinedPairTy, 4> ToErase;
469 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
470 E = OverDefinedCache.end(); I != E; ++I) {
471 if (I->first == BB)
472 ToErase.push_back(*I);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000473 }
Owen Anderson89778462011-01-05 21:15:29 +0000474
475 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
476 E = ToErase.end(); I != E; ++I)
477 OverDefinedCache.erase(*I);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000478
Owen Anderson89778462011-01-05 21:15:29 +0000479 for (DenseMap<LVIValueHandle, ValueCacheEntryTy>::iterator
Owen Anderson00ac77e2010-08-18 18:39:01 +0000480 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
481 I->second.erase(BB);
482}
Owen Anderson7f9cb742010-07-30 23:59:40 +0000483
Nick Lewycky90862ee2010-12-18 01:00:40 +0000484void LazyValueInfoCache::solve() {
Owen Andersone68713a2011-01-05 23:26:22 +0000485 while (!BlockValueStack.empty()) {
486 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
Owen Anderson87790ab2010-12-20 19:33:41 +0000487 if (solveBlockValue(e.second, e.first))
Owen Andersone68713a2011-01-05 23:26:22 +0000488 BlockValueStack.pop();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000489 }
490}
491
492bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
493 // If already a constant, there is nothing to compute.
494 if (isa<Constant>(Val))
495 return true;
496
Owen Anderson89778462011-01-05 21:15:29 +0000497 LVIValueHandle ValHandle(Val, this);
498 if (!ValueCache.count(ValHandle)) return false;
499 return ValueCache[ValHandle].count(BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000500}
501
Owen Andersonf33b3022010-12-09 06:14:58 +0000502LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000503 // If already a constant, there is nothing to compute.
504 if (Constant *VC = dyn_cast<Constant>(Val))
505 return LVILatticeVal::get(VC);
506
507 return lookup(Val)[BB];
508}
509
510bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
511 if (isa<Constant>(Val))
512 return true;
513
Owen Andersonf33b3022010-12-09 06:14:58 +0000514 ValueCacheEntryTy &Cache = lookup(Val);
515 LVILatticeVal &BBLV = Cache[BB];
Owen Anderson87790ab2010-12-20 19:33:41 +0000516
517 // OverDefinedCacheUpdater is a helper object that will update
518 // the OverDefinedCache for us when this method exits. Make sure to
519 // call markResult on it as we exist, passing a bool to indicate if the
520 // cache needs updating, i.e. if we have solve a new value or not.
521 OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000522
Chris Lattner2c5adf82009-11-15 19:59:49 +0000523 // If we've already computed this block's value, return it.
Chris Lattnere5642812009-11-15 20:00:52 +0000524 if (!BBLV.isUndefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000525 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
Owen Anderson87790ab2010-12-20 19:33:41 +0000526
527 // Since we're reusing a cached value here, we don't need to update the
528 // OverDefinedCahce. The cache will have been properly updated
529 // whenever the cached value was inserted.
530 ODCacheUpdater.markResult(false);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000531 return true;
Chris Lattnere5642812009-11-15 20:00:52 +0000532 }
533
Chris Lattner2c5adf82009-11-15 19:59:49 +0000534 // Otherwise, this is the first time we're seeing this block. Reset the
535 // lattice value to overdefined, so that cycles will terminate and be
536 // conservatively correct.
537 BBLV.markOverdefined();
538
Chris Lattner2c5adf82009-11-15 19:59:49 +0000539 Instruction *BBI = dyn_cast<Instruction>(Val);
540 if (BBI == 0 || BBI->getParent() != BB) {
Owen Anderson87790ab2010-12-20 19:33:41 +0000541 return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
Chris Lattner2c5adf82009-11-15 19:59:49 +0000542 }
Chris Lattnere5642812009-11-15 20:00:52 +0000543
Nick Lewycky90862ee2010-12-18 01:00:40 +0000544 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Owen Anderson87790ab2010-12-20 19:33:41 +0000545 return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000546 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000547
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000548 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
549 BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
550 return ODCacheUpdater.markResult(true);
551 }
552
Owen Andersonb81fd622010-08-18 21:11:37 +0000553 // We can only analyze the definitions of certain classes of instructions
554 // (integral binops and casts at the moment), so bail if this isn't one.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000555 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000556 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
557 !BBI->getType()->isIntegerTy()) {
558 DEBUG(dbgs() << " compute BB '" << BB->getName()
559 << "' - overdefined because inst def found.\n");
Owen Anderson61863942010-12-20 18:18:16 +0000560 BBLV.markOverdefined();
Owen Anderson87790ab2010-12-20 19:33:41 +0000561 return ODCacheUpdater.markResult(true);
Owen Andersonb81fd622010-08-18 21:11:37 +0000562 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000563
Owen Andersonb81fd622010-08-18 21:11:37 +0000564 // FIXME: We're currently limited to binops with a constant RHS. This should
565 // be improved.
566 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
567 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
568 DEBUG(dbgs() << " compute BB '" << BB->getName()
569 << "' - overdefined because inst def found.\n");
570
Owen Anderson61863942010-12-20 18:18:16 +0000571 BBLV.markOverdefined();
Owen Anderson87790ab2010-12-20 19:33:41 +0000572 return ODCacheUpdater.markResult(true);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000573 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000574
Owen Anderson87790ab2010-12-20 19:33:41 +0000575 return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000576}
577
578static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
579 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
580 return L->getPointerAddressSpace() == 0 &&
581 GetUnderlyingObject(L->getPointerOperand()) ==
582 GetUnderlyingObject(Ptr);
583 }
584 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
585 return S->getPointerAddressSpace() == 0 &&
586 GetUnderlyingObject(S->getPointerOperand()) ==
587 GetUnderlyingObject(Ptr);
588 }
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000589 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
590 if (MI->isVolatile()) return false;
591 if (MI->getAddressSpace() != 0) return false;
592
593 // FIXME: check whether it has a valuerange that excludes zero?
594 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
595 if (!Len || Len->isZero()) return false;
596
597 if (MI->getRawDest() == Ptr || MI->getDest() == Ptr)
598 return true;
599 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
600 return MTI->getRawSource() == Ptr || MTI->getSource() == Ptr;
601 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000602 return false;
603}
604
Owen Anderson61863942010-12-20 18:18:16 +0000605bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
606 Value *Val, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000607 LVILatticeVal Result; // Start Undefined.
608
609 // If this is a pointer, and there's a load from that pointer in this BB,
610 // then we know that the pointer can't be NULL.
611 bool NotNull = false;
612 if (Val->getType()->isPointerTy()) {
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000613 if (isa<AllocaInst>(Val)) {
614 NotNull = true;
615 } else {
616 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
617 if (InstructionDereferencesPointer(BI, Val)) {
618 NotNull = true;
619 break;
620 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000621 }
622 }
623 }
624
625 // If this is the entry block, we must be asking about an argument. The
626 // value is overdefined.
627 if (BB == &BB->getParent()->getEntryBlock()) {
628 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
629 if (NotNull) {
630 const PointerType *PTy = cast<PointerType>(Val->getType());
631 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
632 } else {
633 Result.markOverdefined();
634 }
Owen Anderson61863942010-12-20 18:18:16 +0000635 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000636 return true;
637 }
638
639 // Loop over all of our predecessors, merging what we know from them into
640 // result.
641 bool EdgesMissing = false;
642 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
643 LVILatticeVal EdgeResult;
644 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
645 if (EdgesMissing)
646 continue;
647
648 Result.mergeIn(EdgeResult);
649
650 // If we hit overdefined, exit early. The BlockVals entry is already set
651 // to overdefined.
652 if (Result.isOverdefined()) {
653 DEBUG(dbgs() << " compute BB '" << BB->getName()
654 << "' - overdefined because of pred.\n");
655 // If we previously determined that this is a pointer that can't be null
656 // then return that rather than giving up entirely.
657 if (NotNull) {
658 const PointerType *PTy = cast<PointerType>(Val->getType());
659 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
660 }
Owen Anderson61863942010-12-20 18:18:16 +0000661
662 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000663 return true;
664 }
665 }
666 if (EdgesMissing)
667 return false;
668
669 // Return the merged value, which is more precise than 'overdefined'.
670 assert(!Result.isOverdefined());
Owen Anderson61863942010-12-20 18:18:16 +0000671 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000672 return true;
673}
674
Owen Anderson61863942010-12-20 18:18:16 +0000675bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
676 PHINode *PN, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000677 LVILatticeVal Result; // Start Undefined.
678
679 // Loop over all of our predecessors, merging what we know from them into
680 // result.
681 bool EdgesMissing = false;
682 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
683 BasicBlock *PhiBB = PN->getIncomingBlock(i);
684 Value *PhiVal = PN->getIncomingValue(i);
685 LVILatticeVal EdgeResult;
686 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
687 if (EdgesMissing)
688 continue;
689
690 Result.mergeIn(EdgeResult);
691
692 // If we hit overdefined, exit early. The BlockVals entry is already set
693 // to overdefined.
694 if (Result.isOverdefined()) {
695 DEBUG(dbgs() << " compute BB '" << BB->getName()
696 << "' - overdefined because of pred.\n");
Owen Anderson61863942010-12-20 18:18:16 +0000697
698 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000699 return true;
700 }
701 }
702 if (EdgesMissing)
703 return false;
704
705 // Return the merged value, which is more precise than 'overdefined'.
706 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson61863942010-12-20 18:18:16 +0000707 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000708 return true;
709}
710
Owen Anderson61863942010-12-20 18:18:16 +0000711bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
712 Instruction *BBI,
Nick Lewycky90862ee2010-12-18 01:00:40 +0000713 BasicBlock *BB) {
Owen Andersonb81fd622010-08-18 21:11:37 +0000714 // Figure out the range of the LHS. If that fails, bail.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000715 if (!hasBlockValue(BBI->getOperand(0), BB)) {
Owen Andersone68713a2011-01-05 23:26:22 +0000716 BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0)));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000717 return false;
718 }
719
Nick Lewycky90862ee2010-12-18 01:00:40 +0000720 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Owen Andersonb81fd622010-08-18 21:11:37 +0000721 if (!LHSVal.isConstantRange()) {
Owen Anderson61863942010-12-20 18:18:16 +0000722 BBLV.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000723 return true;
Owen Andersonb81fd622010-08-18 21:11:37 +0000724 }
725
Owen Andersonb81fd622010-08-18 21:11:37 +0000726 ConstantRange LHSRange = LHSVal.getConstantRange();
727 ConstantRange RHSRange(1);
728 const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
729 if (isa<BinaryOperator>(BBI)) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000730 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
731 RHSRange = ConstantRange(RHS->getValue());
732 } else {
Owen Anderson61863942010-12-20 18:18:16 +0000733 BBLV.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000734 return true;
Owen Anderson59b06dc2010-08-24 07:55:44 +0000735 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000736 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000737
Owen Andersonb81fd622010-08-18 21:11:37 +0000738 // NOTE: We're currently limited by the set of operations that ConstantRange
739 // can evaluate symbolically. Enhancing that set will allows us to analyze
740 // more definitions.
Owen Anderson61863942010-12-20 18:18:16 +0000741 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000742 switch (BBI->getOpcode()) {
743 case Instruction::Add:
744 Result.markConstantRange(LHSRange.add(RHSRange));
745 break;
746 case Instruction::Sub:
747 Result.markConstantRange(LHSRange.sub(RHSRange));
748 break;
749 case Instruction::Mul:
750 Result.markConstantRange(LHSRange.multiply(RHSRange));
751 break;
752 case Instruction::UDiv:
753 Result.markConstantRange(LHSRange.udiv(RHSRange));
754 break;
755 case Instruction::Shl:
756 Result.markConstantRange(LHSRange.shl(RHSRange));
757 break;
758 case Instruction::LShr:
759 Result.markConstantRange(LHSRange.lshr(RHSRange));
760 break;
761 case Instruction::Trunc:
762 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
763 break;
764 case Instruction::SExt:
765 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
766 break;
767 case Instruction::ZExt:
768 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
769 break;
770 case Instruction::BitCast:
771 Result.markConstantRange(LHSRange);
772 break;
Nick Lewycky198381e2010-09-07 05:39:02 +0000773 case Instruction::And:
774 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
775 break;
776 case Instruction::Or:
777 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
778 break;
Owen Andersonb81fd622010-08-18 21:11:37 +0000779
780 // Unhandled instructions are overdefined.
781 default:
782 DEBUG(dbgs() << " compute BB '" << BB->getName()
783 << "' - overdefined because inst def found.\n");
784 Result.markOverdefined();
785 break;
786 }
787
Owen Anderson61863942010-12-20 18:18:16 +0000788 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000789 return true;
Chris Lattner10f2d132009-11-11 00:22:30 +0000790}
791
Chris Lattner800c47e2009-11-15 20:02:12 +0000792/// getEdgeValue - This method attempts to infer more complex
Nick Lewycky90862ee2010-12-18 01:00:40 +0000793bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
794 BasicBlock *BBTo, LVILatticeVal &Result) {
795 // If already a constant, there is nothing to compute.
796 if (Constant *VC = dyn_cast<Constant>(Val)) {
797 Result = LVILatticeVal::get(VC);
798 return true;
799 }
800
Chris Lattner800c47e2009-11-15 20:02:12 +0000801 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
802 // know that v != 0.
Chris Lattner16976522009-11-11 22:48:44 +0000803 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
804 // If this is a conditional branch and only one successor goes to BBTo, then
805 // we maybe able to infer something from the condition.
806 if (BI->isConditional() &&
807 BI->getSuccessor(0) != BI->getSuccessor(1)) {
808 bool isTrueDest = BI->getSuccessor(0) == BBTo;
809 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
810 "BBTo isn't a successor of BBFrom");
811
812 // If V is the condition of the branch itself, then we know exactly what
813 // it is.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000814 if (BI->getCondition() == Val) {
815 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson9f014062010-08-10 20:03:09 +0000816 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000817 return true;
818 }
Chris Lattner16976522009-11-11 22:48:44 +0000819
820 // If the condition of the branch is an equality comparison, we may be
821 // able to infer the value.
Owen Anderson2d0f2472010-08-11 04:24:25 +0000822 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
823 if (ICI && ICI->getOperand(0) == Val &&
824 isa<Constant>(ICI->getOperand(1))) {
825 if (ICI->isEquality()) {
826 // We know that V has the RHS constant if this is a true SETEQ or
827 // false SETNE.
828 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
Nick Lewycky90862ee2010-12-18 01:00:40 +0000829 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
830 else
831 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
832 return true;
Chris Lattner16976522009-11-11 22:48:44 +0000833 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000834
Owen Anderson2d0f2472010-08-11 04:24:25 +0000835 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
836 // Calculate the range of values that would satisfy the comparison.
837 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
838 ConstantRange TrueValues =
839 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000840
Owen Anderson2d0f2472010-08-11 04:24:25 +0000841 // If we're interested in the false dest, invert the condition.
842 if (!isTrueDest) TrueValues = TrueValues.inverse();
843
844 // Figure out the possible values of the query BEFORE this branch.
Owen Andersonbe419012011-01-05 21:37:18 +0000845 if (!hasBlockValue(Val, BBFrom)) {
Owen Andersone68713a2011-01-05 23:26:22 +0000846 BlockValueStack.push(std::make_pair(BBFrom, Val));
Owen Andersonbe419012011-01-05 21:37:18 +0000847 return false;
848 }
849
Owen Andersonf33b3022010-12-09 06:14:58 +0000850 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000851 if (!InBlock.isConstantRange()) {
852 Result = LVILatticeVal::getRange(TrueValues);
853 return true;
854 }
855
Owen Anderson2d0f2472010-08-11 04:24:25 +0000856 // Find all potential values that satisfy both the input and output
857 // conditions.
858 ConstantRange PossibleValues =
859 TrueValues.intersectWith(InBlock.getConstantRange());
Nick Lewycky90862ee2010-12-18 01:00:40 +0000860
861 Result = LVILatticeVal::getRange(PossibleValues);
862 return true;
Owen Anderson2d0f2472010-08-11 04:24:25 +0000863 }
864 }
Chris Lattner16976522009-11-11 22:48:44 +0000865 }
866 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000867
868 // If the edge was formed by a switch on the value, then we may know exactly
869 // what it is.
870 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Owen Andersondae90c62010-08-24 21:59:42 +0000871 if (SI->getCondition() == Val) {
Owen Anderson4caef602010-09-02 22:16:52 +0000872 // We don't know anything in the default case.
Owen Andersondae90c62010-08-24 21:59:42 +0000873 if (SI->getDefaultDest() == BBTo) {
Owen Anderson4caef602010-09-02 22:16:52 +0000874 Result.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000875 return true;
Owen Andersondae90c62010-08-24 21:59:42 +0000876 }
877
Chris Lattner800c47e2009-11-15 20:02:12 +0000878 // We only know something if there is exactly one value that goes from
879 // BBFrom to BBTo.
880 unsigned NumEdges = 0;
881 ConstantInt *EdgeVal = 0;
882 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
883 if (SI->getSuccessor(i) != BBTo) continue;
884 if (NumEdges++) break;
885 EdgeVal = SI->getCaseValue(i);
886 }
887 assert(EdgeVal && "Missing successor?");
Nick Lewycky90862ee2010-12-18 01:00:40 +0000888 if (NumEdges == 1) {
889 Result = LVILatticeVal::get(EdgeVal);
890 return true;
891 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000892 }
893 }
Chris Lattner16976522009-11-11 22:48:44 +0000894
895 // Otherwise see if the value is known in the block.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000896 if (hasBlockValue(Val, BBFrom)) {
897 Result = getBlockValue(Val, BBFrom);
898 return true;
899 }
Owen Andersone68713a2011-01-05 23:26:22 +0000900 BlockValueStack.push(std::make_pair(BBFrom, Val));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000901 return false;
Chris Lattner16976522009-11-11 22:48:44 +0000902}
903
Chris Lattner2c5adf82009-11-15 19:59:49 +0000904LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
David Greene5d93a1f2009-12-23 20:43:58 +0000905 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000906 << BB->getName() << "'\n");
907
Owen Andersone68713a2011-01-05 23:26:22 +0000908 BlockValueStack.push(std::make_pair(BB, V));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000909 solve();
Owen Andersonf33b3022010-12-09 06:14:58 +0000910 LVILatticeVal Result = getBlockValue(V, BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000911
David Greene5d93a1f2009-12-23 20:43:58 +0000912 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000913 return Result;
914}
Chris Lattner16976522009-11-11 22:48:44 +0000915
Chris Lattner2c5adf82009-11-15 19:59:49 +0000916LVILatticeVal LazyValueInfoCache::
917getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
David Greene5d93a1f2009-12-23 20:43:58 +0000918 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000919 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000920
Nick Lewycky90862ee2010-12-18 01:00:40 +0000921 LVILatticeVal Result;
922 if (!getEdgeValue(V, FromBB, ToBB, Result)) {
923 solve();
924 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
925 (void)WasFastQuery;
926 assert(WasFastQuery && "More work to do after problem solved?");
927 }
928
David Greene5d93a1f2009-12-23 20:43:58 +0000929 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000930 return Result;
931}
932
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000933void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
934 BasicBlock *NewSucc) {
935 // When an edge in the graph has been threaded, values that we could not
936 // determine a value for before (i.e. were marked overdefined) may be possible
937 // to solve now. We do NOT try to proactively update these values. Instead,
938 // we clear their entries from the cache, and allow lazy updating to recompute
939 // them when needed.
940
941 // The updating process is fairly simple: we need to dropped cached info
942 // for all values that were marked overdefined in OldSucc, and for those same
943 // values in any successor of OldSucc (except NewSucc) in which they were
944 // also marked overdefined.
945 std::vector<BasicBlock*> worklist;
946 worklist.push_back(OldSucc);
947
Owen Anderson9a65dc92010-07-27 23:58:11 +0000948 DenseSet<Value*> ClearSet;
Owen Anderson89778462011-01-05 21:15:29 +0000949 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
950 E = OverDefinedCache.end(); I != E; ++I) {
Owen Anderson9a65dc92010-07-27 23:58:11 +0000951 if (I->first == OldSucc)
952 ClearSet.insert(I->second);
953 }
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000954
955 // Use a worklist to perform a depth-first search of OldSucc's successors.
956 // NOTE: We do not need a visited list since any blocks we have already
957 // visited will have had their overdefined markers cleared already, and we
958 // thus won't loop to their successors.
959 while (!worklist.empty()) {
960 BasicBlock *ToUpdate = worklist.back();
961 worklist.pop_back();
962
963 // Skip blocks only accessible through NewSucc.
964 if (ToUpdate == NewSucc) continue;
965
966 bool changed = false;
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000967 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000968 I != E; ++I) {
969 // If a value was marked overdefined in OldSucc, and is here too...
Owen Anderson89778462011-01-05 21:15:29 +0000970 DenseSet<OverDefinedPairTy>::iterator OI =
Owen Anderson9a65dc92010-07-27 23:58:11 +0000971 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
972 if (OI == OverDefinedCache.end()) continue;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000973
Owen Anderson9a65dc92010-07-27 23:58:11 +0000974 // Remove it from the caches.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000975 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
Owen Anderson9a65dc92010-07-27 23:58:11 +0000976 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000977
Owen Anderson9a65dc92010-07-27 23:58:11 +0000978 assert(CI != Entry.end() && "Couldn't find entry to update?");
979 Entry.erase(CI);
980 OverDefinedCache.erase(OI);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000981
Owen Anderson9a65dc92010-07-27 23:58:11 +0000982 // If we removed anything, then we potentially need to update
983 // blocks successors too.
984 changed = true;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000985 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000986
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000987 if (!changed) continue;
988
989 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
990 }
991}
992
Chris Lattner2c5adf82009-11-15 19:59:49 +0000993//===----------------------------------------------------------------------===//
994// LazyValueInfo Impl
995//===----------------------------------------------------------------------===//
996
Chris Lattner2c5adf82009-11-15 19:59:49 +0000997/// getCache - This lazily constructs the LazyValueInfoCache.
998static LazyValueInfoCache &getCache(void *&PImpl) {
999 if (!PImpl)
1000 PImpl = new LazyValueInfoCache();
1001 return *static_cast<LazyValueInfoCache*>(PImpl);
1002}
1003
Owen Anderson00ac77e2010-08-18 18:39:01 +00001004bool LazyValueInfo::runOnFunction(Function &F) {
1005 if (PImpl)
1006 getCache(PImpl).clear();
1007
1008 TD = getAnalysisIfAvailable<TargetData>();
1009 // Fully lazy.
1010 return false;
1011}
1012
Chris Lattner2c5adf82009-11-15 19:59:49 +00001013void LazyValueInfo::releaseMemory() {
1014 // If the cache was allocated, free it.
1015 if (PImpl) {
1016 delete &getCache(PImpl);
1017 PImpl = 0;
1018 }
1019}
1020
1021Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
1022 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
1023
Chris Lattner16976522009-11-11 22:48:44 +00001024 if (Result.isConstant())
1025 return Result.getConstant();
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001026 if (Result.isConstantRange()) {
Owen Andersonee61fcf2010-08-27 23:29:38 +00001027 ConstantRange CR = Result.getConstantRange();
1028 if (const APInt *SingleVal = CR.getSingleElement())
1029 return ConstantInt::get(V->getContext(), *SingleVal);
1030 }
Chris Lattner16976522009-11-11 22:48:44 +00001031 return 0;
1032}
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001033
Chris Lattner38392bb2009-11-12 01:29:10 +00001034/// getConstantOnEdge - Determine whether the specified value is known to be a
1035/// constant on the specified edge. Return null if not.
1036Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1037 BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +00001038 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattner38392bb2009-11-12 01:29:10 +00001039
1040 if (Result.isConstant())
1041 return Result.getConstant();
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001042 if (Result.isConstantRange()) {
Owen Anderson9f014062010-08-10 20:03:09 +00001043 ConstantRange CR = Result.getConstantRange();
1044 if (const APInt *SingleVal = CR.getSingleElement())
1045 return ConstantInt::get(V->getContext(), *SingleVal);
1046 }
Chris Lattner38392bb2009-11-12 01:29:10 +00001047 return 0;
1048}
1049
Chris Lattnerb52675b2009-11-12 04:36:58 +00001050/// getPredicateOnEdge - Determine whether the specified value comparison
1051/// with a constant is known to be true or false on the specified CFG edge.
1052/// Pred is a CmpInst predicate.
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001053LazyValueInfo::Tristate
Chris Lattnerb52675b2009-11-12 04:36:58 +00001054LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1055 BasicBlock *FromBB, BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +00001056 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001057
Chris Lattnerb52675b2009-11-12 04:36:58 +00001058 // If we know the value is a constant, evaluate the conditional.
1059 Constant *Res = 0;
1060 if (Result.isConstant()) {
1061 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001062 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Chris Lattnerb52675b2009-11-12 04:36:58 +00001063 return ResCI->isZero() ? False : True;
Chris Lattner2c5adf82009-11-15 19:59:49 +00001064 return Unknown;
1065 }
1066
Owen Anderson9f014062010-08-10 20:03:09 +00001067 if (Result.isConstantRange()) {
Owen Anderson59b06dc2010-08-24 07:55:44 +00001068 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1069 if (!CI) return Unknown;
1070
Owen Anderson9f014062010-08-10 20:03:09 +00001071 ConstantRange CR = Result.getConstantRange();
1072 if (Pred == ICmpInst::ICMP_EQ) {
1073 if (!CR.contains(CI->getValue()))
1074 return False;
1075
1076 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1077 return True;
1078 } else if (Pred == ICmpInst::ICMP_NE) {
1079 if (!CR.contains(CI->getValue()))
1080 return True;
1081
1082 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1083 return False;
1084 }
1085
1086 // Handle more complex predicates.
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001087 ConstantRange TrueValues =
1088 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1089 if (TrueValues.contains(CR))
Owen Anderson9f014062010-08-10 20:03:09 +00001090 return True;
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001091 if (TrueValues.inverse().contains(CR))
1092 return False;
Owen Anderson9f014062010-08-10 20:03:09 +00001093 return Unknown;
1094 }
1095
Chris Lattner2c5adf82009-11-15 19:59:49 +00001096 if (Result.isNotConstant()) {
Chris Lattnerb52675b2009-11-12 04:36:58 +00001097 // If this is an equality comparison, we can try to fold it knowing that
1098 // "V != C1".
1099 if (Pred == ICmpInst::ICMP_EQ) {
1100 // !C1 == C -> false iff C1 == C.
1101 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1102 Result.getNotConstant(), C, TD);
1103 if (Res->isNullValue())
1104 return False;
1105 } else if (Pred == ICmpInst::ICMP_NE) {
1106 // !C1 != C -> true iff C1 == C.
Chris Lattner5553a3a2009-11-15 20:01:24 +00001107 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chris Lattnerb52675b2009-11-12 04:36:58 +00001108 Result.getNotConstant(), C, TD);
1109 if (Res->isNullValue())
1110 return True;
1111 }
Chris Lattner2c5adf82009-11-15 19:59:49 +00001112 return Unknown;
Chris Lattnerb52675b2009-11-12 04:36:58 +00001113 }
1114
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001115 return Unknown;
1116}
1117
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001118void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001119 BasicBlock *NewSucc) {
Owen Anderson00ac77e2010-08-18 18:39:01 +00001120 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1121}
1122
1123void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1124 if (PImpl) getCache(PImpl).eraseBlock(BB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001125}