blob: d27d911610386963d304a334918c80213f2b1ae5 [file] [log] [blame]
Chris Lattner10f2d132009-11-11 00:22:30 +00001//===- LazyValueInfo.cpp - Value constraint analysis ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interface for lazy computation of value constraint
11// information.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattnerb8c124c2009-11-12 01:22:16 +000015#define DEBUG_TYPE "lazy-value-info"
Chris Lattner10f2d132009-11-11 00:22:30 +000016#include "llvm/Analysis/LazyValueInfo.h"
Dan Gohman5034dd32010-12-15 20:02:24 +000017#include "llvm/Analysis/ValueTracking.h"
Chris Lattnercc4d3b22009-11-11 02:08:33 +000018#include "llvm/Constants.h"
19#include "llvm/Instructions.h"
Nick Lewycky786c7cd2011-01-15 09:16:12 +000020#include "llvm/IntrinsicInst.h"
Chris Lattnercc4d3b22009-11-11 02:08:33 +000021#include "llvm/Analysis/ConstantFolding.h"
22#include "llvm/Target/TargetData.h"
Chad Rosieraab8e282011-12-02 01:26:24 +000023#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattner16976522009-11-11 22:48:44 +000024#include "llvm/Support/CFG.h"
Owen Anderson5be2e782010-08-05 22:59:19 +000025#include "llvm/Support/ConstantRange.h"
Chris Lattnerb8c124c2009-11-12 01:22:16 +000026#include "llvm/Support/Debug.h"
Chris Lattner16976522009-11-11 22:48:44 +000027#include "llvm/Support/raw_ostream.h"
Owen Anderson7f9cb742010-07-30 23:59:40 +000028#include "llvm/Support/ValueHandle.h"
Chris Lattner16976522009-11-11 22:48:44 +000029#include "llvm/ADT/DenseMap.h"
Owen Anderson9a65dc92010-07-27 23:58:11 +000030#include "llvm/ADT/DenseSet.h"
Chris Lattnere5642812009-11-15 20:00:52 +000031#include "llvm/ADT/STLExtras.h"
Owen Anderson6bcd3a02010-09-07 19:16:25 +000032#include <map>
Nick Lewycky90862ee2010-12-18 01:00:40 +000033#include <stack>
Chris Lattner10f2d132009-11-11 00:22:30 +000034using namespace llvm;
35
36char LazyValueInfo::ID = 0;
Chad Rosieraab8e282011-12-02 01:26:24 +000037INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
38 "Lazy Value Information Analysis", false, true)
39INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
40INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
Owen Andersonce665bd2010-10-07 22:25:06 +000041 "Lazy Value Information Analysis", false, true)
Chris Lattner10f2d132009-11-11 00:22:30 +000042
43namespace llvm {
44 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
45}
46
Chris Lattnercc4d3b22009-11-11 02:08:33 +000047
48//===----------------------------------------------------------------------===//
49// LVILatticeVal
50//===----------------------------------------------------------------------===//
51
52/// LVILatticeVal - This is the information tracked by LazyValueInfo for each
53/// value.
54///
55/// FIXME: This is basically just for bringup, this can be made a lot more rich
56/// in the future.
57///
58namespace {
59class LVILatticeVal {
60 enum LatticeValueTy {
Nick Lewycky69bfdf52010-12-15 18:57:18 +000061 /// undefined - This Value has no known value yet.
Chris Lattnercc4d3b22009-11-11 02:08:33 +000062 undefined,
Owen Anderson5be2e782010-08-05 22:59:19 +000063
Nick Lewycky69bfdf52010-12-15 18:57:18 +000064 /// constant - This Value has a specific constant value.
Chris Lattnercc4d3b22009-11-11 02:08:33 +000065 constant,
Nick Lewycky69bfdf52010-12-15 18:57:18 +000066 /// notconstant - This Value is known to not have the specified value.
Chris Lattnerb52675b2009-11-12 04:36:58 +000067 notconstant,
Chad Rosieraab8e282011-12-02 01:26:24 +000068
Nick Lewycky69bfdf52010-12-15 18:57:18 +000069 /// constantrange - The Value falls within this range.
Owen Anderson5be2e782010-08-05 22:59:19 +000070 constantrange,
Chad Rosieraab8e282011-12-02 01:26:24 +000071
Nick Lewycky69bfdf52010-12-15 18:57:18 +000072 /// overdefined - This value is not known to be constant, and we know that
Chris Lattnercc4d3b22009-11-11 02:08:33 +000073 /// it has a value.
74 overdefined
75 };
76
77 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattnerb52675b2009-11-12 04:36:58 +000078 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersondb78d732010-08-05 22:10:46 +000079 LatticeValueTy Tag;
80 Constant *Val;
Owen Anderson5be2e782010-08-05 22:59:19 +000081 ConstantRange Range;
Chris Lattnercc4d3b22009-11-11 02:08:33 +000082
83public:
Owen Anderson5be2e782010-08-05 22:59:19 +000084 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
Chris Lattnercc4d3b22009-11-11 02:08:33 +000085
Chris Lattner16976522009-11-11 22:48:44 +000086 static LVILatticeVal get(Constant *C) {
87 LVILatticeVal Res;
Nick Lewycky69bfdf52010-12-15 18:57:18 +000088 if (!isa<UndefValue>(C))
Owen Anderson9f014062010-08-10 20:03:09 +000089 Res.markConstant(C);
Chris Lattner16976522009-11-11 22:48:44 +000090 return Res;
91 }
Chris Lattnerb52675b2009-11-12 04:36:58 +000092 static LVILatticeVal getNot(Constant *C) {
93 LVILatticeVal Res;
Nick Lewycky69bfdf52010-12-15 18:57:18 +000094 if (!isa<UndefValue>(C))
Owen Anderson9f014062010-08-10 20:03:09 +000095 Res.markNotConstant(C);
Chris Lattnerb52675b2009-11-12 04:36:58 +000096 return Res;
97 }
Owen Anderson625051b2010-08-10 23:20:01 +000098 static LVILatticeVal getRange(ConstantRange CR) {
99 LVILatticeVal Res;
100 Res.markConstantRange(CR);
101 return Res;
102 }
Chris Lattner16976522009-11-11 22:48:44 +0000103
Owen Anderson5be2e782010-08-05 22:59:19 +0000104 bool isUndefined() const { return Tag == undefined; }
105 bool isConstant() const { return Tag == constant; }
106 bool isNotConstant() const { return Tag == notconstant; }
107 bool isConstantRange() const { return Tag == constantrange; }
108 bool isOverdefined() const { return Tag == overdefined; }
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000109
110 Constant *getConstant() const {
111 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000112 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000113 }
114
Chris Lattnerb52675b2009-11-12 04:36:58 +0000115 Constant *getNotConstant() const {
116 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000117 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000118 }
119
Owen Anderson5be2e782010-08-05 22:59:19 +0000120 ConstantRange getConstantRange() const {
121 assert(isConstantRange() &&
122 "Cannot get the constant-range of a non-constant-range!");
123 return Range;
124 }
125
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000126 /// markOverdefined - Return true if this is a change in status.
127 bool markOverdefined() {
128 if (isOverdefined())
129 return false;
Owen Andersondb78d732010-08-05 22:10:46 +0000130 Tag = overdefined;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000131 return true;
132 }
133
134 /// markConstant - Return true if this is a change in status.
135 bool markConstant(Constant *V) {
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000136 assert(V && "Marking constant with NULL");
137 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
138 return markConstantRange(ConstantRange(CI->getValue()));
139 if (isa<UndefValue>(V))
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000140 return false;
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000141
142 assert((!isConstant() || getConstant() == V) &&
143 "Marking constant with different value");
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000144 assert(isUndefined());
Owen Andersondb78d732010-08-05 22:10:46 +0000145 Tag = constant;
Owen Andersondb78d732010-08-05 22:10:46 +0000146 Val = V;
Chris Lattner16976522009-11-11 22:48:44 +0000147 return true;
148 }
149
Chris Lattnerb52675b2009-11-12 04:36:58 +0000150 /// markNotConstant - Return true if this is a change in status.
151 bool markNotConstant(Constant *V) {
Chris Lattnerb52675b2009-11-12 04:36:58 +0000152 assert(V && "Marking constant with NULL");
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000153 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
154 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
155 if (isa<UndefValue>(V))
156 return false;
157
158 assert((!isConstant() || getConstant() != V) &&
159 "Marking constant !constant with same value");
160 assert((!isNotConstant() || getNotConstant() == V) &&
161 "Marking !constant with different value");
162 assert(isUndefined() || isConstant());
163 Tag = notconstant;
Owen Andersondb78d732010-08-05 22:10:46 +0000164 Val = V;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000165 return true;
166 }
167
Owen Anderson5be2e782010-08-05 22:59:19 +0000168 /// markConstantRange - Return true if this is a change in status.
169 bool markConstantRange(const ConstantRange NewR) {
170 if (isConstantRange()) {
171 if (NewR.isEmptySet())
172 return markOverdefined();
173
Owen Anderson5be2e782010-08-05 22:59:19 +0000174 bool changed = Range == NewR;
175 Range = NewR;
176 return changed;
177 }
178
179 assert(isUndefined());
180 if (NewR.isEmptySet())
181 return markOverdefined();
Owen Anderson5be2e782010-08-05 22:59:19 +0000182
183 Tag = constantrange;
184 Range = NewR;
185 return true;
186 }
187
Chris Lattner16976522009-11-11 22:48:44 +0000188 /// mergeIn - Merge the specified lattice value into this one, updating this
189 /// one and returning true if anything changed.
190 bool mergeIn(const LVILatticeVal &RHS) {
191 if (RHS.isUndefined() || isOverdefined()) return false;
192 if (RHS.isOverdefined()) return markOverdefined();
193
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000194 if (isUndefined()) {
195 Tag = RHS.Tag;
196 Val = RHS.Val;
197 Range = RHS.Range;
198 return true;
Chris Lattnerf496e792009-11-12 04:57:13 +0000199 }
200
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000201 if (isConstant()) {
202 if (RHS.isConstant()) {
203 if (Val == RHS.Val)
204 return false;
205 return markOverdefined();
206 }
207
208 if (RHS.isNotConstant()) {
209 if (Val == RHS.Val)
210 return markOverdefined();
211
212 // Unless we can prove that the two Constants are different, we must
213 // move to overdefined.
Chad Rosieraab8e282011-12-02 01:26:24 +0000214 // FIXME: use TargetData/TargetLibraryInfo for smarter constant folding.
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000215 if (ConstantInt *Res = dyn_cast<ConstantInt>(
216 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
217 getConstant(),
218 RHS.getNotConstant())))
219 if (Res->isOne())
220 return markNotConstant(RHS.getNotConstant());
221
222 return markOverdefined();
223 }
224
225 // RHS is a ConstantRange, LHS is a non-integer Constant.
226
227 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
228 // a function. The correct result is to pick up RHS.
229
Chris Lattner16976522009-11-11 22:48:44 +0000230 return markOverdefined();
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000231 }
232
233 if (isNotConstant()) {
234 if (RHS.isConstant()) {
235 if (Val == RHS.Val)
236 return markOverdefined();
237
238 // Unless we can prove that the two Constants are different, we must
239 // move to overdefined.
Chad Rosieraab8e282011-12-02 01:26:24 +0000240 // FIXME: use TargetData/TargetLibraryInfo for smarter constant folding.
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000241 if (ConstantInt *Res = dyn_cast<ConstantInt>(
242 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
243 getNotConstant(),
244 RHS.getConstant())))
245 if (Res->isOne())
246 return false;
247
248 return markOverdefined();
249 }
250
251 if (RHS.isNotConstant()) {
252 if (Val == RHS.Val)
253 return false;
254 return markOverdefined();
255 }
256
257 return markOverdefined();
258 }
259
260 assert(isConstantRange() && "New LVILattice type?");
261 if (!RHS.isConstantRange())
262 return markOverdefined();
263
264 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
265 if (NewR.isFullSet())
266 return markOverdefined();
267 return markConstantRange(NewR);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000268 }
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000269};
270
271} // end anonymous namespace.
272
Chris Lattner16976522009-11-11 22:48:44 +0000273namespace llvm {
Chandler Carruth3b55a372011-04-18 18:49:44 +0000274raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
275 LLVM_ATTRIBUTE_USED;
Chris Lattner16976522009-11-11 22:48:44 +0000276raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
277 if (Val.isUndefined())
278 return OS << "undefined";
279 if (Val.isOverdefined())
280 return OS << "overdefined";
Chris Lattnerb52675b2009-11-12 04:36:58 +0000281
282 if (Val.isNotConstant())
283 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Owen Anderson2f3ffb82010-08-09 20:50:46 +0000284 else if (Val.isConstantRange())
285 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
286 << Val.getConstantRange().getUpper() << '>';
Chris Lattner16976522009-11-11 22:48:44 +0000287 return OS << "constant<" << *Val.getConstant() << '>';
288}
289}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000290
291//===----------------------------------------------------------------------===//
Chris Lattner2c5adf82009-11-15 19:59:49 +0000292// LazyValueInfoCache Decl
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000293//===----------------------------------------------------------------------===//
294
Chris Lattner2c5adf82009-11-15 19:59:49 +0000295namespace {
Owen Anderson89778462011-01-05 21:15:29 +0000296 /// LVIValueHandle - A callback value handle update the cache when
297 /// values are erased.
298 class LazyValueInfoCache;
299 struct LVIValueHandle : public CallbackVH {
300 LazyValueInfoCache *Parent;
301
302 LVIValueHandle(Value *V, LazyValueInfoCache *P)
303 : CallbackVH(V), Parent(P) { }
304
305 void deleted();
306 void allUsesReplacedWith(Value *V) {
307 deleted();
308 }
309 };
310}
311
312namespace llvm {
313 template<>
314 struct DenseMapInfo<LVIValueHandle> {
315 typedef DenseMapInfo<Value*> PointerInfo;
316 static inline LVIValueHandle getEmptyKey() {
317 return LVIValueHandle(PointerInfo::getEmptyKey(),
318 static_cast<LazyValueInfoCache*>(0));
319 }
320 static inline LVIValueHandle getTombstoneKey() {
321 return LVIValueHandle(PointerInfo::getTombstoneKey(),
322 static_cast<LazyValueInfoCache*>(0));
323 }
324 static unsigned getHashValue(const LVIValueHandle &Val) {
325 return PointerInfo::getHashValue(Val);
326 }
327 static bool isEqual(const LVIValueHandle &LHS, const LVIValueHandle &RHS) {
328 return LHS == RHS;
329 }
330 };
331
332 template<>
333 struct DenseMapInfo<std::pair<AssertingVH<BasicBlock>, Value*> > {
334 typedef std::pair<AssertingVH<BasicBlock>, Value*> PairTy;
335 typedef DenseMapInfo<AssertingVH<BasicBlock> > APointerInfo;
336 typedef DenseMapInfo<Value*> BPointerInfo;
337 static inline PairTy getEmptyKey() {
338 return std::make_pair(APointerInfo::getEmptyKey(),
339 BPointerInfo::getEmptyKey());
340 }
341 static inline PairTy getTombstoneKey() {
342 return std::make_pair(APointerInfo::getTombstoneKey(),
343 BPointerInfo::getTombstoneKey());
344 }
345 static unsigned getHashValue( const PairTy &Val) {
346 return APointerInfo::getHashValue(Val.first) ^
347 BPointerInfo::getHashValue(Val.second);
348 }
349 static bool isEqual(const PairTy &LHS, const PairTy &RHS) {
350 return APointerInfo::isEqual(LHS.first, RHS.first) &&
351 BPointerInfo::isEqual(LHS.second, RHS.second);
352 }
353 };
354}
355
356namespace {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000357 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
358 /// maintains information about queries across the clients' queries.
359 class LazyValueInfoCache {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000360 /// ValueCacheEntryTy - This is all of the cached block information for
361 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
362 /// entries, allowing us to do a lookup with a binary search.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000363 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000364
Owen Andersone68713a2011-01-05 23:26:22 +0000365 /// ValueCache - This is all of the cached information for all values,
366 /// mapped from Value* to key information.
367 DenseMap<LVIValueHandle, ValueCacheEntryTy> ValueCache;
368
369 /// OverDefinedCache - This tracks, on a per-block basis, the set of
370 /// values that are over-defined at the end of that block. This is required
371 /// for cache updating.
372 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
373 DenseSet<OverDefinedPairTy> OverDefinedCache;
Benjamin Kramerfeb9b4b2011-12-03 15:16:45 +0000374
375 /// SeenBlocks - Keep track of all blocks that we have ever seen, so we
376 /// don't spend time removing unused blocks from our caches.
377 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
378
Owen Andersone68713a2011-01-05 23:26:22 +0000379 /// BlockValueStack - This stack holds the state of the value solver
380 /// during a query. It basically emulates the callstack of the naive
381 /// recursive value lookup process.
382 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
383
Owen Anderson89778462011-01-05 21:15:29 +0000384 friend struct LVIValueHandle;
Owen Anderson87790ab2010-12-20 19:33:41 +0000385
386 /// OverDefinedCacheUpdater - A helper object that ensures that the
387 /// OverDefinedCache is updated whenever solveBlockValue returns.
388 struct OverDefinedCacheUpdater {
389 LazyValueInfoCache *Parent;
390 Value *Val;
391 BasicBlock *BB;
392 LVILatticeVal &BBLV;
393
394 OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV,
395 LazyValueInfoCache *P)
396 : Parent(P), Val(V), BB(B), BBLV(LV) { }
397
398 bool markResult(bool changed) {
399 if (changed && BBLV.isOverdefined())
400 Parent->OverDefinedCache.insert(std::make_pair(BB, Val));
401 return changed;
402 }
403 };
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000404
Owen Andersone68713a2011-01-05 23:26:22 +0000405
Owen Anderson7f9cb742010-07-30 23:59:40 +0000406
Owen Andersonf33b3022010-12-09 06:14:58 +0000407 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000408 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
409 LVILatticeVal &Result);
410 bool hasBlockValue(Value *Val, BasicBlock *BB);
411
412 // These methods process one work item and may add more. A false value
413 // returned means that the work item was not completely processed and must
414 // be revisited after going through the new items.
415 bool solveBlockValue(Value *Val, BasicBlock *BB);
Owen Anderson61863942010-12-20 18:18:16 +0000416 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
417 Value *Val, BasicBlock *BB);
418 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
419 PHINode *PN, BasicBlock *BB);
420 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
421 Instruction *BBI, BasicBlock *BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000422
423 void solve();
Owen Andersonf33b3022010-12-09 06:14:58 +0000424
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000425 ValueCacheEntryTy &lookup(Value *V) {
Owen Andersonf33b3022010-12-09 06:14:58 +0000426 return ValueCache[LVIValueHandle(V, this)];
427 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000428
Chris Lattner2c5adf82009-11-15 19:59:49 +0000429 public:
Chris Lattner2c5adf82009-11-15 19:59:49 +0000430 /// getValueInBlock - This is the query interface to determine the lattice
431 /// value for the specified Value* at the end of the specified block.
432 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
433
434 /// getValueOnEdge - This is the query interface to determine the lattice
435 /// value for the specified Value* that is true on the specified edge.
436 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000437
438 /// threadEdge - This is the update interface to inform the cache that an
439 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
440 /// NewSucc.
441 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000442
443 /// eraseBlock - This is part of the update interface to inform the cache
444 /// that a block has been deleted.
445 void eraseBlock(BasicBlock *BB);
446
447 /// clear - Empty the cache.
448 void clear() {
Benjamin Kramerc00c05f2011-12-03 15:19:55 +0000449 SeenBlocks.clear();
Owen Anderson00ac77e2010-08-18 18:39:01 +0000450 ValueCache.clear();
451 OverDefinedCache.clear();
452 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000453 };
454} // end anonymous namespace
455
Owen Anderson89778462011-01-05 21:15:29 +0000456void LVIValueHandle::deleted() {
457 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
458
459 SmallVector<OverDefinedPairTy, 4> ToErase;
460 for (DenseSet<OverDefinedPairTy>::iterator
Owen Anderson7f9cb742010-07-30 23:59:40 +0000461 I = Parent->OverDefinedCache.begin(),
462 E = Parent->OverDefinedCache.end();
Owen Anderson89778462011-01-05 21:15:29 +0000463 I != E; ++I) {
464 if (I->second == getValPtr())
465 ToErase.push_back(*I);
Owen Anderson7f9cb742010-07-30 23:59:40 +0000466 }
Owen Andersoncf6abd22010-08-11 22:36:04 +0000467
Owen Anderson89778462011-01-05 21:15:29 +0000468 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
469 E = ToErase.end(); I != E; ++I)
470 Parent->OverDefinedCache.erase(*I);
471
Owen Andersoncf6abd22010-08-11 22:36:04 +0000472 // This erasure deallocates *this, so it MUST happen after we're done
473 // using any and all members of *this.
474 Parent->ValueCache.erase(*this);
Owen Anderson7f9cb742010-07-30 23:59:40 +0000475}
476
Owen Anderson00ac77e2010-08-18 18:39:01 +0000477void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
Benjamin Kramerfeb9b4b2011-12-03 15:16:45 +0000478 // Shortcut if we have never seen this block.
479 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
480 if (I == SeenBlocks.end())
481 return;
482 SeenBlocks.erase(I);
483
Owen Anderson89778462011-01-05 21:15:29 +0000484 SmallVector<OverDefinedPairTy, 4> ToErase;
485 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
486 E = OverDefinedCache.end(); I != E; ++I) {
487 if (I->first == BB)
488 ToErase.push_back(*I);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000489 }
Owen Anderson89778462011-01-05 21:15:29 +0000490
491 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
492 E = ToErase.end(); I != E; ++I)
493 OverDefinedCache.erase(*I);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000494
Owen Anderson89778462011-01-05 21:15:29 +0000495 for (DenseMap<LVIValueHandle, ValueCacheEntryTy>::iterator
Owen Anderson00ac77e2010-08-18 18:39:01 +0000496 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
497 I->second.erase(BB);
498}
Owen Anderson7f9cb742010-07-30 23:59:40 +0000499
Nick Lewycky90862ee2010-12-18 01:00:40 +0000500void LazyValueInfoCache::solve() {
Owen Andersone68713a2011-01-05 23:26:22 +0000501 while (!BlockValueStack.empty()) {
502 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
Owen Anderson87790ab2010-12-20 19:33:41 +0000503 if (solveBlockValue(e.second, e.first))
Owen Andersone68713a2011-01-05 23:26:22 +0000504 BlockValueStack.pop();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000505 }
506}
507
508bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
509 // If already a constant, there is nothing to compute.
510 if (isa<Constant>(Val))
511 return true;
512
Owen Anderson89778462011-01-05 21:15:29 +0000513 LVIValueHandle ValHandle(Val, this);
514 if (!ValueCache.count(ValHandle)) return false;
515 return ValueCache[ValHandle].count(BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000516}
517
Owen Andersonf33b3022010-12-09 06:14:58 +0000518LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000519 // If already a constant, there is nothing to compute.
520 if (Constant *VC = dyn_cast<Constant>(Val))
521 return LVILatticeVal::get(VC);
522
Benjamin Kramerfeb9b4b2011-12-03 15:16:45 +0000523 SeenBlocks.insert(BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000524 return lookup(Val)[BB];
525}
526
527bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
528 if (isa<Constant>(Val))
529 return true;
530
Owen Andersonf33b3022010-12-09 06:14:58 +0000531 ValueCacheEntryTy &Cache = lookup(Val);
Benjamin Kramerfeb9b4b2011-12-03 15:16:45 +0000532 SeenBlocks.insert(BB);
Owen Andersonf33b3022010-12-09 06:14:58 +0000533 LVILatticeVal &BBLV = Cache[BB];
Owen Anderson87790ab2010-12-20 19:33:41 +0000534
535 // OverDefinedCacheUpdater is a helper object that will update
536 // the OverDefinedCache for us when this method exits. Make sure to
537 // call markResult on it as we exist, passing a bool to indicate if the
538 // cache needs updating, i.e. if we have solve a new value or not.
539 OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000540
Chris Lattner2c5adf82009-11-15 19:59:49 +0000541 // If we've already computed this block's value, return it.
Chris Lattnere5642812009-11-15 20:00:52 +0000542 if (!BBLV.isUndefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000543 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
Owen Anderson87790ab2010-12-20 19:33:41 +0000544
545 // Since we're reusing a cached value here, we don't need to update the
546 // OverDefinedCahce. The cache will have been properly updated
547 // whenever the cached value was inserted.
548 ODCacheUpdater.markResult(false);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000549 return true;
Chris Lattnere5642812009-11-15 20:00:52 +0000550 }
551
Chris Lattner2c5adf82009-11-15 19:59:49 +0000552 // Otherwise, this is the first time we're seeing this block. Reset the
553 // lattice value to overdefined, so that cycles will terminate and be
554 // conservatively correct.
555 BBLV.markOverdefined();
556
Chris Lattner2c5adf82009-11-15 19:59:49 +0000557 Instruction *BBI = dyn_cast<Instruction>(Val);
558 if (BBI == 0 || BBI->getParent() != BB) {
Owen Anderson87790ab2010-12-20 19:33:41 +0000559 return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
Chris Lattner2c5adf82009-11-15 19:59:49 +0000560 }
Chris Lattnere5642812009-11-15 20:00:52 +0000561
Nick Lewycky90862ee2010-12-18 01:00:40 +0000562 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Owen Anderson87790ab2010-12-20 19:33:41 +0000563 return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000564 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000565
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000566 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
567 BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
568 return ODCacheUpdater.markResult(true);
569 }
570
Owen Andersonb81fd622010-08-18 21:11:37 +0000571 // We can only analyze the definitions of certain classes of instructions
572 // (integral binops and casts at the moment), so bail if this isn't one.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000573 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000574 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
575 !BBI->getType()->isIntegerTy()) {
576 DEBUG(dbgs() << " compute BB '" << BB->getName()
577 << "' - overdefined because inst def found.\n");
Owen Anderson61863942010-12-20 18:18:16 +0000578 BBLV.markOverdefined();
Owen Anderson87790ab2010-12-20 19:33:41 +0000579 return ODCacheUpdater.markResult(true);
Owen Andersonb81fd622010-08-18 21:11:37 +0000580 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000581
Owen Andersonb81fd622010-08-18 21:11:37 +0000582 // FIXME: We're currently limited to binops with a constant RHS. This should
583 // be improved.
584 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
585 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
586 DEBUG(dbgs() << " compute BB '" << BB->getName()
587 << "' - overdefined because inst def found.\n");
588
Owen Anderson61863942010-12-20 18:18:16 +0000589 BBLV.markOverdefined();
Owen Anderson87790ab2010-12-20 19:33:41 +0000590 return ODCacheUpdater.markResult(true);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000591 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000592
Owen Anderson87790ab2010-12-20 19:33:41 +0000593 return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000594}
595
596static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
597 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
598 return L->getPointerAddressSpace() == 0 &&
599 GetUnderlyingObject(L->getPointerOperand()) ==
600 GetUnderlyingObject(Ptr);
601 }
602 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
603 return S->getPointerAddressSpace() == 0 &&
604 GetUnderlyingObject(S->getPointerOperand()) ==
605 GetUnderlyingObject(Ptr);
606 }
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000607 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
608 if (MI->isVolatile()) return false;
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000609
610 // FIXME: check whether it has a valuerange that excludes zero?
611 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
612 if (!Len || Len->isZero()) return false;
613
Eli Friedman69388e52011-05-31 20:40:16 +0000614 if (MI->getDestAddressSpace() == 0)
615 if (MI->getRawDest() == Ptr || MI->getDest() == Ptr)
616 return true;
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000617 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman69388e52011-05-31 20:40:16 +0000618 if (MTI->getSourceAddressSpace() == 0)
619 if (MTI->getRawSource() == Ptr || MTI->getSource() == Ptr)
620 return true;
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000621 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000622 return false;
623}
624
Owen Anderson61863942010-12-20 18:18:16 +0000625bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
626 Value *Val, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000627 LVILatticeVal Result; // Start Undefined.
628
629 // If this is a pointer, and there's a load from that pointer in this BB,
630 // then we know that the pointer can't be NULL.
631 bool NotNull = false;
632 if (Val->getType()->isPointerTy()) {
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000633 if (isa<AllocaInst>(Val)) {
634 NotNull = true;
635 } else {
636 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
637 if (InstructionDereferencesPointer(BI, Val)) {
638 NotNull = true;
639 break;
640 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000641 }
642 }
643 }
644
645 // If this is the entry block, we must be asking about an argument. The
646 // value is overdefined.
647 if (BB == &BB->getParent()->getEntryBlock()) {
648 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
649 if (NotNull) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000650 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky90862ee2010-12-18 01:00:40 +0000651 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
652 } else {
653 Result.markOverdefined();
654 }
Owen Anderson61863942010-12-20 18:18:16 +0000655 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000656 return true;
657 }
658
659 // Loop over all of our predecessors, merging what we know from them into
660 // result.
661 bool EdgesMissing = false;
662 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
663 LVILatticeVal EdgeResult;
664 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
665 if (EdgesMissing)
666 continue;
667
668 Result.mergeIn(EdgeResult);
669
670 // If we hit overdefined, exit early. The BlockVals entry is already set
671 // to overdefined.
672 if (Result.isOverdefined()) {
673 DEBUG(dbgs() << " compute BB '" << BB->getName()
674 << "' - overdefined because of pred.\n");
675 // If we previously determined that this is a pointer that can't be null
676 // then return that rather than giving up entirely.
677 if (NotNull) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000678 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky90862ee2010-12-18 01:00:40 +0000679 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
680 }
Owen Anderson61863942010-12-20 18:18:16 +0000681
682 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000683 return true;
684 }
685 }
686 if (EdgesMissing)
687 return false;
688
689 // Return the merged value, which is more precise than 'overdefined'.
690 assert(!Result.isOverdefined());
Owen Anderson61863942010-12-20 18:18:16 +0000691 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000692 return true;
693}
694
Owen Anderson61863942010-12-20 18:18:16 +0000695bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
696 PHINode *PN, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000697 LVILatticeVal Result; // Start Undefined.
698
699 // Loop over all of our predecessors, merging what we know from them into
700 // result.
701 bool EdgesMissing = false;
702 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
703 BasicBlock *PhiBB = PN->getIncomingBlock(i);
704 Value *PhiVal = PN->getIncomingValue(i);
705 LVILatticeVal EdgeResult;
706 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
707 if (EdgesMissing)
708 continue;
709
710 Result.mergeIn(EdgeResult);
711
712 // If we hit overdefined, exit early. The BlockVals entry is already set
713 // to overdefined.
714 if (Result.isOverdefined()) {
715 DEBUG(dbgs() << " compute BB '" << BB->getName()
716 << "' - overdefined because of pred.\n");
Owen Anderson61863942010-12-20 18:18:16 +0000717
718 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000719 return true;
720 }
721 }
722 if (EdgesMissing)
723 return false;
724
725 // Return the merged value, which is more precise than 'overdefined'.
726 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson61863942010-12-20 18:18:16 +0000727 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000728 return true;
729}
730
Owen Anderson61863942010-12-20 18:18:16 +0000731bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
732 Instruction *BBI,
Nick Lewycky90862ee2010-12-18 01:00:40 +0000733 BasicBlock *BB) {
Owen Andersonb81fd622010-08-18 21:11:37 +0000734 // Figure out the range of the LHS. If that fails, bail.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000735 if (!hasBlockValue(BBI->getOperand(0), BB)) {
Owen Andersone68713a2011-01-05 23:26:22 +0000736 BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0)));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000737 return false;
738 }
739
Nick Lewycky90862ee2010-12-18 01:00:40 +0000740 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Owen Andersonb81fd622010-08-18 21:11:37 +0000741 if (!LHSVal.isConstantRange()) {
Owen Anderson61863942010-12-20 18:18:16 +0000742 BBLV.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000743 return true;
Owen Andersonb81fd622010-08-18 21:11:37 +0000744 }
745
Owen Andersonb81fd622010-08-18 21:11:37 +0000746 ConstantRange LHSRange = LHSVal.getConstantRange();
747 ConstantRange RHSRange(1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000748 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
Owen Andersonb81fd622010-08-18 21:11:37 +0000749 if (isa<BinaryOperator>(BBI)) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000750 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
751 RHSRange = ConstantRange(RHS->getValue());
752 } else {
Owen Anderson61863942010-12-20 18:18:16 +0000753 BBLV.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000754 return true;
Owen Anderson59b06dc2010-08-24 07:55:44 +0000755 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000756 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000757
Owen Andersonb81fd622010-08-18 21:11:37 +0000758 // NOTE: We're currently limited by the set of operations that ConstantRange
759 // can evaluate symbolically. Enhancing that set will allows us to analyze
760 // more definitions.
Owen Anderson61863942010-12-20 18:18:16 +0000761 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000762 switch (BBI->getOpcode()) {
763 case Instruction::Add:
764 Result.markConstantRange(LHSRange.add(RHSRange));
765 break;
766 case Instruction::Sub:
767 Result.markConstantRange(LHSRange.sub(RHSRange));
768 break;
769 case Instruction::Mul:
770 Result.markConstantRange(LHSRange.multiply(RHSRange));
771 break;
772 case Instruction::UDiv:
773 Result.markConstantRange(LHSRange.udiv(RHSRange));
774 break;
775 case Instruction::Shl:
776 Result.markConstantRange(LHSRange.shl(RHSRange));
777 break;
778 case Instruction::LShr:
779 Result.markConstantRange(LHSRange.lshr(RHSRange));
780 break;
781 case Instruction::Trunc:
782 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
783 break;
784 case Instruction::SExt:
785 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
786 break;
787 case Instruction::ZExt:
788 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
789 break;
790 case Instruction::BitCast:
791 Result.markConstantRange(LHSRange);
792 break;
Nick Lewycky198381e2010-09-07 05:39:02 +0000793 case Instruction::And:
794 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
795 break;
796 case Instruction::Or:
797 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
798 break;
Owen Andersonb81fd622010-08-18 21:11:37 +0000799
800 // Unhandled instructions are overdefined.
801 default:
802 DEBUG(dbgs() << " compute BB '" << BB->getName()
803 << "' - overdefined because inst def found.\n");
804 Result.markOverdefined();
805 break;
806 }
807
Owen Anderson61863942010-12-20 18:18:16 +0000808 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000809 return true;
Chris Lattner10f2d132009-11-11 00:22:30 +0000810}
811
Chris Lattner800c47e2009-11-15 20:02:12 +0000812/// getEdgeValue - This method attempts to infer more complex
Nick Lewycky90862ee2010-12-18 01:00:40 +0000813bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
814 BasicBlock *BBTo, LVILatticeVal &Result) {
815 // If already a constant, there is nothing to compute.
816 if (Constant *VC = dyn_cast<Constant>(Val)) {
817 Result = LVILatticeVal::get(VC);
818 return true;
819 }
820
Chris Lattner800c47e2009-11-15 20:02:12 +0000821 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
822 // know that v != 0.
Chris Lattner16976522009-11-11 22:48:44 +0000823 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
824 // If this is a conditional branch and only one successor goes to BBTo, then
825 // we maybe able to infer something from the condition.
826 if (BI->isConditional() &&
827 BI->getSuccessor(0) != BI->getSuccessor(1)) {
828 bool isTrueDest = BI->getSuccessor(0) == BBTo;
829 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
830 "BBTo isn't a successor of BBFrom");
831
832 // If V is the condition of the branch itself, then we know exactly what
833 // it is.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000834 if (BI->getCondition() == Val) {
835 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson9f014062010-08-10 20:03:09 +0000836 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000837 return true;
838 }
Chris Lattner16976522009-11-11 22:48:44 +0000839
840 // If the condition of the branch is an equality comparison, we may be
841 // able to infer the value.
Owen Anderson2d0f2472010-08-11 04:24:25 +0000842 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
843 if (ICI && ICI->getOperand(0) == Val &&
844 isa<Constant>(ICI->getOperand(1))) {
845 if (ICI->isEquality()) {
846 // We know that V has the RHS constant if this is a true SETEQ or
847 // false SETNE.
848 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
Nick Lewycky90862ee2010-12-18 01:00:40 +0000849 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
850 else
851 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
852 return true;
Chris Lattner16976522009-11-11 22:48:44 +0000853 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000854
Owen Anderson2d0f2472010-08-11 04:24:25 +0000855 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
856 // Calculate the range of values that would satisfy the comparison.
857 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
858 ConstantRange TrueValues =
859 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000860
Owen Anderson2d0f2472010-08-11 04:24:25 +0000861 // If we're interested in the false dest, invert the condition.
862 if (!isTrueDest) TrueValues = TrueValues.inverse();
863
864 // Figure out the possible values of the query BEFORE this branch.
Owen Andersonbe419012011-01-05 21:37:18 +0000865 if (!hasBlockValue(Val, BBFrom)) {
Owen Andersone68713a2011-01-05 23:26:22 +0000866 BlockValueStack.push(std::make_pair(BBFrom, Val));
Owen Andersonbe419012011-01-05 21:37:18 +0000867 return false;
868 }
869
Owen Andersonf33b3022010-12-09 06:14:58 +0000870 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000871 if (!InBlock.isConstantRange()) {
872 Result = LVILatticeVal::getRange(TrueValues);
873 return true;
874 }
875
Owen Anderson2d0f2472010-08-11 04:24:25 +0000876 // Find all potential values that satisfy both the input and output
877 // conditions.
878 ConstantRange PossibleValues =
879 TrueValues.intersectWith(InBlock.getConstantRange());
Nick Lewycky90862ee2010-12-18 01:00:40 +0000880
881 Result = LVILatticeVal::getRange(PossibleValues);
882 return true;
Owen Anderson2d0f2472010-08-11 04:24:25 +0000883 }
884 }
Chris Lattner16976522009-11-11 22:48:44 +0000885 }
886 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000887
888 // If the edge was formed by a switch on the value, then we may know exactly
889 // what it is.
890 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Owen Andersondae90c62010-08-24 21:59:42 +0000891 if (SI->getCondition() == Val) {
Owen Anderson4caef602010-09-02 22:16:52 +0000892 // We don't know anything in the default case.
Owen Andersondae90c62010-08-24 21:59:42 +0000893 if (SI->getDefaultDest() == BBTo) {
Owen Anderson4caef602010-09-02 22:16:52 +0000894 Result.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000895 return true;
Owen Andersondae90c62010-08-24 21:59:42 +0000896 }
897
Chris Lattner800c47e2009-11-15 20:02:12 +0000898 // We only know something if there is exactly one value that goes from
899 // BBFrom to BBTo.
900 unsigned NumEdges = 0;
901 ConstantInt *EdgeVal = 0;
902 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
903 if (SI->getSuccessor(i) != BBTo) continue;
904 if (NumEdges++) break;
905 EdgeVal = SI->getCaseValue(i);
906 }
907 assert(EdgeVal && "Missing successor?");
Nick Lewycky90862ee2010-12-18 01:00:40 +0000908 if (NumEdges == 1) {
909 Result = LVILatticeVal::get(EdgeVal);
910 return true;
911 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000912 }
913 }
Chris Lattner16976522009-11-11 22:48:44 +0000914
915 // Otherwise see if the value is known in the block.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000916 if (hasBlockValue(Val, BBFrom)) {
917 Result = getBlockValue(Val, BBFrom);
918 return true;
919 }
Owen Andersone68713a2011-01-05 23:26:22 +0000920 BlockValueStack.push(std::make_pair(BBFrom, Val));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000921 return false;
Chris Lattner16976522009-11-11 22:48:44 +0000922}
923
Chris Lattner2c5adf82009-11-15 19:59:49 +0000924LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
David Greene5d93a1f2009-12-23 20:43:58 +0000925 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000926 << BB->getName() << "'\n");
927
Owen Andersone68713a2011-01-05 23:26:22 +0000928 BlockValueStack.push(std::make_pair(BB, V));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000929 solve();
Owen Andersonf33b3022010-12-09 06:14:58 +0000930 LVILatticeVal Result = getBlockValue(V, BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000931
David Greene5d93a1f2009-12-23 20:43:58 +0000932 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000933 return Result;
934}
Chris Lattner16976522009-11-11 22:48:44 +0000935
Chris Lattner2c5adf82009-11-15 19:59:49 +0000936LVILatticeVal LazyValueInfoCache::
937getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
David Greene5d93a1f2009-12-23 20:43:58 +0000938 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000939 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000940
Nick Lewycky90862ee2010-12-18 01:00:40 +0000941 LVILatticeVal Result;
942 if (!getEdgeValue(V, FromBB, ToBB, Result)) {
943 solve();
944 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
945 (void)WasFastQuery;
946 assert(WasFastQuery && "More work to do after problem solved?");
947 }
948
David Greene5d93a1f2009-12-23 20:43:58 +0000949 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000950 return Result;
951}
952
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000953void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
954 BasicBlock *NewSucc) {
955 // When an edge in the graph has been threaded, values that we could not
956 // determine a value for before (i.e. were marked overdefined) may be possible
957 // to solve now. We do NOT try to proactively update these values. Instead,
958 // we clear their entries from the cache, and allow lazy updating to recompute
959 // them when needed.
960
961 // The updating process is fairly simple: we need to dropped cached info
962 // for all values that were marked overdefined in OldSucc, and for those same
963 // values in any successor of OldSucc (except NewSucc) in which they were
964 // also marked overdefined.
965 std::vector<BasicBlock*> worklist;
966 worklist.push_back(OldSucc);
967
Owen Anderson9a65dc92010-07-27 23:58:11 +0000968 DenseSet<Value*> ClearSet;
Owen Anderson89778462011-01-05 21:15:29 +0000969 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
970 E = OverDefinedCache.end(); I != E; ++I) {
Owen Anderson9a65dc92010-07-27 23:58:11 +0000971 if (I->first == OldSucc)
972 ClearSet.insert(I->second);
973 }
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000974
975 // Use a worklist to perform a depth-first search of OldSucc's successors.
976 // NOTE: We do not need a visited list since any blocks we have already
977 // visited will have had their overdefined markers cleared already, and we
978 // thus won't loop to their successors.
979 while (!worklist.empty()) {
980 BasicBlock *ToUpdate = worklist.back();
981 worklist.pop_back();
982
983 // Skip blocks only accessible through NewSucc.
984 if (ToUpdate == NewSucc) continue;
985
986 bool changed = false;
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000987 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000988 I != E; ++I) {
989 // If a value was marked overdefined in OldSucc, and is here too...
Owen Anderson89778462011-01-05 21:15:29 +0000990 DenseSet<OverDefinedPairTy>::iterator OI =
Owen Anderson9a65dc92010-07-27 23:58:11 +0000991 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
992 if (OI == OverDefinedCache.end()) continue;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000993
Owen Anderson9a65dc92010-07-27 23:58:11 +0000994 // Remove it from the caches.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000995 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
Owen Anderson9a65dc92010-07-27 23:58:11 +0000996 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000997
Owen Anderson9a65dc92010-07-27 23:58:11 +0000998 assert(CI != Entry.end() && "Couldn't find entry to update?");
999 Entry.erase(CI);
1000 OverDefinedCache.erase(OI);
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001001
Owen Anderson9a65dc92010-07-27 23:58:11 +00001002 // If we removed anything, then we potentially need to update
1003 // blocks successors too.
1004 changed = true;
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001005 }
Nick Lewycky90862ee2010-12-18 01:00:40 +00001006
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001007 if (!changed) continue;
1008
1009 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1010 }
1011}
1012
Chris Lattner2c5adf82009-11-15 19:59:49 +00001013//===----------------------------------------------------------------------===//
1014// LazyValueInfo Impl
1015//===----------------------------------------------------------------------===//
1016
Chris Lattner2c5adf82009-11-15 19:59:49 +00001017/// getCache - This lazily constructs the LazyValueInfoCache.
1018static LazyValueInfoCache &getCache(void *&PImpl) {
1019 if (!PImpl)
1020 PImpl = new LazyValueInfoCache();
1021 return *static_cast<LazyValueInfoCache*>(PImpl);
1022}
1023
Owen Anderson00ac77e2010-08-18 18:39:01 +00001024bool LazyValueInfo::runOnFunction(Function &F) {
1025 if (PImpl)
1026 getCache(PImpl).clear();
Chad Rosieraab8e282011-12-02 01:26:24 +00001027
Owen Anderson00ac77e2010-08-18 18:39:01 +00001028 TD = getAnalysisIfAvailable<TargetData>();
Chad Rosieraab8e282011-12-02 01:26:24 +00001029 TLI = &getAnalysis<TargetLibraryInfo>();
1030
Owen Anderson00ac77e2010-08-18 18:39:01 +00001031 // Fully lazy.
1032 return false;
1033}
1034
Chad Rosieraab8e282011-12-02 01:26:24 +00001035void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1036 AU.setPreservesAll();
1037 AU.addRequired<TargetLibraryInfo>();
1038}
1039
Chris Lattner2c5adf82009-11-15 19:59:49 +00001040void LazyValueInfo::releaseMemory() {
1041 // If the cache was allocated, free it.
1042 if (PImpl) {
1043 delete &getCache(PImpl);
1044 PImpl = 0;
1045 }
1046}
1047
1048Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
1049 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
1050
Chris Lattner16976522009-11-11 22:48:44 +00001051 if (Result.isConstant())
1052 return Result.getConstant();
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001053 if (Result.isConstantRange()) {
Owen Andersonee61fcf2010-08-27 23:29:38 +00001054 ConstantRange CR = Result.getConstantRange();
1055 if (const APInt *SingleVal = CR.getSingleElement())
1056 return ConstantInt::get(V->getContext(), *SingleVal);
1057 }
Chris Lattner16976522009-11-11 22:48:44 +00001058 return 0;
1059}
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001060
Chris Lattner38392bb2009-11-12 01:29:10 +00001061/// getConstantOnEdge - Determine whether the specified value is known to be a
1062/// constant on the specified edge. Return null if not.
1063Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1064 BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +00001065 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattner38392bb2009-11-12 01:29:10 +00001066
1067 if (Result.isConstant())
1068 return Result.getConstant();
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001069 if (Result.isConstantRange()) {
Owen Anderson9f014062010-08-10 20:03:09 +00001070 ConstantRange CR = Result.getConstantRange();
1071 if (const APInt *SingleVal = CR.getSingleElement())
1072 return ConstantInt::get(V->getContext(), *SingleVal);
1073 }
Chris Lattner38392bb2009-11-12 01:29:10 +00001074 return 0;
1075}
1076
Chris Lattnerb52675b2009-11-12 04:36:58 +00001077/// getPredicateOnEdge - Determine whether the specified value comparison
1078/// with a constant is known to be true or false on the specified CFG edge.
1079/// Pred is a CmpInst predicate.
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001080LazyValueInfo::Tristate
Chris Lattnerb52675b2009-11-12 04:36:58 +00001081LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1082 BasicBlock *FromBB, BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +00001083 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001084
Chris Lattnerb52675b2009-11-12 04:36:58 +00001085 // If we know the value is a constant, evaluate the conditional.
1086 Constant *Res = 0;
1087 if (Result.isConstant()) {
Chad Rosieraab8e282011-12-02 01:26:24 +00001088 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD,
1089 TLI);
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001090 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Chris Lattnerb52675b2009-11-12 04:36:58 +00001091 return ResCI->isZero() ? False : True;
Chris Lattner2c5adf82009-11-15 19:59:49 +00001092 return Unknown;
1093 }
1094
Owen Anderson9f014062010-08-10 20:03:09 +00001095 if (Result.isConstantRange()) {
Owen Anderson59b06dc2010-08-24 07:55:44 +00001096 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1097 if (!CI) return Unknown;
1098
Owen Anderson9f014062010-08-10 20:03:09 +00001099 ConstantRange CR = Result.getConstantRange();
1100 if (Pred == ICmpInst::ICMP_EQ) {
1101 if (!CR.contains(CI->getValue()))
1102 return False;
1103
1104 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1105 return True;
1106 } else if (Pred == ICmpInst::ICMP_NE) {
1107 if (!CR.contains(CI->getValue()))
1108 return True;
1109
1110 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1111 return False;
1112 }
1113
1114 // Handle more complex predicates.
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001115 ConstantRange TrueValues =
1116 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1117 if (TrueValues.contains(CR))
Owen Anderson9f014062010-08-10 20:03:09 +00001118 return True;
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001119 if (TrueValues.inverse().contains(CR))
1120 return False;
Owen Anderson9f014062010-08-10 20:03:09 +00001121 return Unknown;
1122 }
1123
Chris Lattner2c5adf82009-11-15 19:59:49 +00001124 if (Result.isNotConstant()) {
Chris Lattnerb52675b2009-11-12 04:36:58 +00001125 // If this is an equality comparison, we can try to fold it knowing that
1126 // "V != C1".
1127 if (Pred == ICmpInst::ICMP_EQ) {
1128 // !C1 == C -> false iff C1 == C.
1129 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chad Rosieraab8e282011-12-02 01:26:24 +00001130 Result.getNotConstant(), C, TD,
1131 TLI);
Chris Lattnerb52675b2009-11-12 04:36:58 +00001132 if (Res->isNullValue())
1133 return False;
1134 } else if (Pred == ICmpInst::ICMP_NE) {
1135 // !C1 != C -> true iff C1 == C.
Chris Lattner5553a3a2009-11-15 20:01:24 +00001136 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chad Rosieraab8e282011-12-02 01:26:24 +00001137 Result.getNotConstant(), C, TD,
1138 TLI);
Chris Lattnerb52675b2009-11-12 04:36:58 +00001139 if (Res->isNullValue())
1140 return True;
1141 }
Chris Lattner2c5adf82009-11-15 19:59:49 +00001142 return Unknown;
Chris Lattnerb52675b2009-11-12 04:36:58 +00001143 }
1144
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001145 return Unknown;
1146}
1147
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001148void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001149 BasicBlock *NewSucc) {
Owen Anderson00ac77e2010-08-18 18:39:01 +00001150 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1151}
1152
1153void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1154 if (PImpl) getCache(PImpl).eraseBlock(BB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001155}