blob: 540a73bcb2f3555e40bfb08f7ec1a9448a480041 [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"
Nick Lewycky90862ee2010-12-18 01:00:40 +000032#include <stack>
Chris Lattner10f2d132009-11-11 00:22:30 +000033using namespace llvm;
34
35char LazyValueInfo::ID = 0;
Chad Rosieraab8e282011-12-02 01:26:24 +000036INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
37 "Lazy Value Information Analysis", false, true)
38INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
39INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
Owen Andersonce665bd2010-10-07 22:25:06 +000040 "Lazy Value Information Analysis", false, true)
Chris Lattner10f2d132009-11-11 00:22:30 +000041
42namespace llvm {
43 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
44}
45
Chris Lattnercc4d3b22009-11-11 02:08:33 +000046
47//===----------------------------------------------------------------------===//
48// LVILatticeVal
49//===----------------------------------------------------------------------===//
50
51/// LVILatticeVal - This is the information tracked by LazyValueInfo for each
52/// value.
53///
54/// FIXME: This is basically just for bringup, this can be made a lot more rich
55/// in the future.
56///
57namespace {
58class LVILatticeVal {
59 enum LatticeValueTy {
Nick Lewycky69bfdf52010-12-15 18:57:18 +000060 /// undefined - This Value has no known value yet.
Chris Lattnercc4d3b22009-11-11 02:08:33 +000061 undefined,
Owen Anderson5be2e782010-08-05 22:59:19 +000062
Nick Lewycky69bfdf52010-12-15 18:57:18 +000063 /// constant - This Value has a specific constant value.
Chris Lattnercc4d3b22009-11-11 02:08:33 +000064 constant,
Nick Lewycky69bfdf52010-12-15 18:57:18 +000065 /// notconstant - This Value is known to not have the specified value.
Chris Lattnerb52675b2009-11-12 04:36:58 +000066 notconstant,
Chad Rosieraab8e282011-12-02 01:26:24 +000067
Nick Lewycky69bfdf52010-12-15 18:57:18 +000068 /// constantrange - The Value falls within this range.
Owen Anderson5be2e782010-08-05 22:59:19 +000069 constantrange,
Chad Rosieraab8e282011-12-02 01:26:24 +000070
Nick Lewycky69bfdf52010-12-15 18:57:18 +000071 /// overdefined - This value is not known to be constant, and we know that
Chris Lattnercc4d3b22009-11-11 02:08:33 +000072 /// it has a value.
73 overdefined
74 };
75
76 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattnerb52675b2009-11-12 04:36:58 +000077 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersondb78d732010-08-05 22:10:46 +000078 LatticeValueTy Tag;
79 Constant *Val;
Owen Anderson5be2e782010-08-05 22:59:19 +000080 ConstantRange Range;
Chris Lattnercc4d3b22009-11-11 02:08:33 +000081
82public:
Owen Anderson5be2e782010-08-05 22:59:19 +000083 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
Chris Lattnercc4d3b22009-11-11 02:08:33 +000084
Chris Lattner16976522009-11-11 22:48:44 +000085 static LVILatticeVal get(Constant *C) {
86 LVILatticeVal Res;
Nick Lewycky69bfdf52010-12-15 18:57:18 +000087 if (!isa<UndefValue>(C))
Owen Anderson9f014062010-08-10 20:03:09 +000088 Res.markConstant(C);
Chris Lattner16976522009-11-11 22:48:44 +000089 return Res;
90 }
Chris Lattnerb52675b2009-11-12 04:36:58 +000091 static LVILatticeVal getNot(Constant *C) {
92 LVILatticeVal Res;
Nick Lewycky69bfdf52010-12-15 18:57:18 +000093 if (!isa<UndefValue>(C))
Owen Anderson9f014062010-08-10 20:03:09 +000094 Res.markNotConstant(C);
Chris Lattnerb52675b2009-11-12 04:36:58 +000095 return Res;
96 }
Owen Anderson625051b2010-08-10 23:20:01 +000097 static LVILatticeVal getRange(ConstantRange CR) {
98 LVILatticeVal Res;
99 Res.markConstantRange(CR);
100 return Res;
101 }
Chris Lattner16976522009-11-11 22:48:44 +0000102
Owen Anderson5be2e782010-08-05 22:59:19 +0000103 bool isUndefined() const { return Tag == undefined; }
104 bool isConstant() const { return Tag == constant; }
105 bool isNotConstant() const { return Tag == notconstant; }
106 bool isConstantRange() const { return Tag == constantrange; }
107 bool isOverdefined() const { return Tag == overdefined; }
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000108
109 Constant *getConstant() const {
110 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000111 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000112 }
113
Chris Lattnerb52675b2009-11-12 04:36:58 +0000114 Constant *getNotConstant() const {
115 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000116 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000117 }
118
Owen Anderson5be2e782010-08-05 22:59:19 +0000119 ConstantRange getConstantRange() const {
120 assert(isConstantRange() &&
121 "Cannot get the constant-range of a non-constant-range!");
122 return Range;
123 }
124
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000125 /// markOverdefined - Return true if this is a change in status.
126 bool markOverdefined() {
127 if (isOverdefined())
128 return false;
Owen Andersondb78d732010-08-05 22:10:46 +0000129 Tag = overdefined;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000130 return true;
131 }
132
133 /// markConstant - Return true if this is a change in status.
134 bool markConstant(Constant *V) {
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000135 assert(V && "Marking constant with NULL");
136 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
137 return markConstantRange(ConstantRange(CI->getValue()));
138 if (isa<UndefValue>(V))
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000139 return false;
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000140
141 assert((!isConstant() || getConstant() == V) &&
142 "Marking constant with different value");
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000143 assert(isUndefined());
Owen Andersondb78d732010-08-05 22:10:46 +0000144 Tag = constant;
Owen Andersondb78d732010-08-05 22:10:46 +0000145 Val = V;
Chris Lattner16976522009-11-11 22:48:44 +0000146 return true;
147 }
148
Chris Lattnerb52675b2009-11-12 04:36:58 +0000149 /// markNotConstant - Return true if this is a change in status.
150 bool markNotConstant(Constant *V) {
Chris Lattnerb52675b2009-11-12 04:36:58 +0000151 assert(V && "Marking constant with NULL");
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000152 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
153 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
154 if (isa<UndefValue>(V))
155 return false;
156
157 assert((!isConstant() || getConstant() != V) &&
158 "Marking constant !constant with same value");
159 assert((!isNotConstant() || getNotConstant() == V) &&
160 "Marking !constant with different value");
161 assert(isUndefined() || isConstant());
162 Tag = notconstant;
Owen Andersondb78d732010-08-05 22:10:46 +0000163 Val = V;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000164 return true;
165 }
166
Owen Anderson5be2e782010-08-05 22:59:19 +0000167 /// markConstantRange - Return true if this is a change in status.
168 bool markConstantRange(const ConstantRange NewR) {
169 if (isConstantRange()) {
170 if (NewR.isEmptySet())
171 return markOverdefined();
172
Owen Anderson5be2e782010-08-05 22:59:19 +0000173 bool changed = Range == NewR;
174 Range = NewR;
175 return changed;
176 }
177
178 assert(isUndefined());
179 if (NewR.isEmptySet())
180 return markOverdefined();
Owen Anderson5be2e782010-08-05 22:59:19 +0000181
182 Tag = constantrange;
183 Range = NewR;
184 return true;
185 }
186
Chris Lattner16976522009-11-11 22:48:44 +0000187 /// mergeIn - Merge the specified lattice value into this one, updating this
188 /// one and returning true if anything changed.
189 bool mergeIn(const LVILatticeVal &RHS) {
190 if (RHS.isUndefined() || isOverdefined()) return false;
191 if (RHS.isOverdefined()) return markOverdefined();
192
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000193 if (isUndefined()) {
194 Tag = RHS.Tag;
195 Val = RHS.Val;
196 Range = RHS.Range;
197 return true;
Chris Lattnerf496e792009-11-12 04:57:13 +0000198 }
199
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000200 if (isConstant()) {
201 if (RHS.isConstant()) {
202 if (Val == RHS.Val)
203 return false;
204 return markOverdefined();
205 }
206
207 if (RHS.isNotConstant()) {
208 if (Val == RHS.Val)
209 return markOverdefined();
210
211 // Unless we can prove that the two Constants are different, we must
212 // move to overdefined.
Chad Rosieraab8e282011-12-02 01:26:24 +0000213 // FIXME: use TargetData/TargetLibraryInfo for smarter constant folding.
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000214 if (ConstantInt *Res = dyn_cast<ConstantInt>(
215 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
216 getConstant(),
217 RHS.getNotConstant())))
218 if (Res->isOne())
219 return markNotConstant(RHS.getNotConstant());
220
221 return markOverdefined();
222 }
223
224 // RHS is a ConstantRange, LHS is a non-integer Constant.
225
226 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
227 // a function. The correct result is to pick up RHS.
228
Chris Lattner16976522009-11-11 22:48:44 +0000229 return markOverdefined();
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000230 }
231
232 if (isNotConstant()) {
233 if (RHS.isConstant()) {
234 if (Val == RHS.Val)
235 return markOverdefined();
236
237 // Unless we can prove that the two Constants are different, we must
238 // move to overdefined.
Chad Rosieraab8e282011-12-02 01:26:24 +0000239 // FIXME: use TargetData/TargetLibraryInfo for smarter constant folding.
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000240 if (ConstantInt *Res = dyn_cast<ConstantInt>(
241 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
242 getNotConstant(),
243 RHS.getConstant())))
244 if (Res->isOne())
245 return false;
246
247 return markOverdefined();
248 }
249
250 if (RHS.isNotConstant()) {
251 if (Val == RHS.Val)
252 return false;
253 return markOverdefined();
254 }
255
256 return markOverdefined();
257 }
258
259 assert(isConstantRange() && "New LVILattice type?");
260 if (!RHS.isConstantRange())
261 return markOverdefined();
262
263 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
264 if (NewR.isFullSet())
265 return markOverdefined();
266 return markConstantRange(NewR);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000267 }
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000268};
269
270} // end anonymous namespace.
271
Chris Lattner16976522009-11-11 22:48:44 +0000272namespace llvm {
Chandler Carruth3b55a372011-04-18 18:49:44 +0000273raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
274 LLVM_ATTRIBUTE_USED;
Chris Lattner16976522009-11-11 22:48:44 +0000275raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
276 if (Val.isUndefined())
277 return OS << "undefined";
278 if (Val.isOverdefined())
279 return OS << "overdefined";
Chris Lattnerb52675b2009-11-12 04:36:58 +0000280
281 if (Val.isNotConstant())
282 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Owen Anderson2f3ffb82010-08-09 20:50:46 +0000283 else if (Val.isConstantRange())
284 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
285 << Val.getConstantRange().getUpper() << '>';
Chris Lattner16976522009-11-11 22:48:44 +0000286 return OS << "constant<" << *Val.getConstant() << '>';
287}
288}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000289
290//===----------------------------------------------------------------------===//
Chris Lattner2c5adf82009-11-15 19:59:49 +0000291// LazyValueInfoCache Decl
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000292//===----------------------------------------------------------------------===//
293
Chris Lattner2c5adf82009-11-15 19:59:49 +0000294namespace {
Owen Anderson89778462011-01-05 21:15:29 +0000295 /// LVIValueHandle - A callback value handle update the cache when
296 /// values are erased.
297 class LazyValueInfoCache;
298 struct LVIValueHandle : public CallbackVH {
299 LazyValueInfoCache *Parent;
300
301 LVIValueHandle(Value *V, LazyValueInfoCache *P)
302 : CallbackVH(V), Parent(P) { }
303
304 void deleted();
305 void allUsesReplacedWith(Value *V) {
306 deleted();
307 }
308 };
309}
310
311namespace llvm {
312 template<>
313 struct DenseMapInfo<LVIValueHandle> {
314 typedef DenseMapInfo<Value*> PointerInfo;
315 static inline LVIValueHandle getEmptyKey() {
316 return LVIValueHandle(PointerInfo::getEmptyKey(),
317 static_cast<LazyValueInfoCache*>(0));
318 }
319 static inline LVIValueHandle getTombstoneKey() {
320 return LVIValueHandle(PointerInfo::getTombstoneKey(),
321 static_cast<LazyValueInfoCache*>(0));
322 }
323 static unsigned getHashValue(const LVIValueHandle &Val) {
324 return PointerInfo::getHashValue(Val);
325 }
326 static bool isEqual(const LVIValueHandle &LHS, const LVIValueHandle &RHS) {
327 return LHS == RHS;
328 }
329 };
330
331 template<>
332 struct DenseMapInfo<std::pair<AssertingVH<BasicBlock>, Value*> > {
333 typedef std::pair<AssertingVH<BasicBlock>, Value*> PairTy;
334 typedef DenseMapInfo<AssertingVH<BasicBlock> > APointerInfo;
335 typedef DenseMapInfo<Value*> BPointerInfo;
336 static inline PairTy getEmptyKey() {
337 return std::make_pair(APointerInfo::getEmptyKey(),
338 BPointerInfo::getEmptyKey());
339 }
340 static inline PairTy getTombstoneKey() {
341 return std::make_pair(APointerInfo::getTombstoneKey(),
342 BPointerInfo::getTombstoneKey());
343 }
344 static unsigned getHashValue( const PairTy &Val) {
345 return APointerInfo::getHashValue(Val.first) ^
346 BPointerInfo::getHashValue(Val.second);
347 }
348 static bool isEqual(const PairTy &LHS, const PairTy &RHS) {
349 return APointerInfo::isEqual(LHS.first, RHS.first) &&
350 BPointerInfo::isEqual(LHS.second, RHS.second);
351 }
352 };
353}
354
355namespace {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000356 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
357 /// maintains information about queries across the clients' queries.
358 class LazyValueInfoCache {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000359 /// ValueCacheEntryTy - This is all of the cached block information for
360 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
361 /// entries, allowing us to do a lookup with a binary search.
Bill Wendling337a2692012-01-11 22:57:32 +0000362 typedef DenseMap<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000363
Owen Andersone68713a2011-01-05 23:26:22 +0000364 /// ValueCache - This is all of the cached information for all values,
365 /// mapped from Value* to key information.
366 DenseMap<LVIValueHandle, ValueCacheEntryTy> ValueCache;
367
368 /// OverDefinedCache - This tracks, on a per-block basis, the set of
369 /// values that are over-defined at the end of that block. This is required
370 /// for cache updating.
371 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
372 DenseSet<OverDefinedPairTy> OverDefinedCache;
Benjamin Kramerfeb9b4b2011-12-03 15:16:45 +0000373
374 /// SeenBlocks - Keep track of all blocks that we have ever seen, so we
375 /// don't spend time removing unused blocks from our caches.
376 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
377
Owen Andersone68713a2011-01-05 23:26:22 +0000378 /// BlockValueStack - This stack holds the state of the value solver
379 /// during a query. It basically emulates the callstack of the naive
380 /// recursive value lookup process.
381 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
382
Owen Anderson89778462011-01-05 21:15:29 +0000383 friend struct LVIValueHandle;
Owen Anderson87790ab2010-12-20 19:33:41 +0000384
385 /// OverDefinedCacheUpdater - A helper object that ensures that the
386 /// OverDefinedCache is updated whenever solveBlockValue returns.
387 struct OverDefinedCacheUpdater {
388 LazyValueInfoCache *Parent;
389 Value *Val;
390 BasicBlock *BB;
391 LVILatticeVal &BBLV;
392
393 OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV,
394 LazyValueInfoCache *P)
395 : Parent(P), Val(V), BB(B), BBLV(LV) { }
396
397 bool markResult(bool changed) {
398 if (changed && BBLV.isOverdefined())
399 Parent->OverDefinedCache.insert(std::make_pair(BB, Val));
400 return changed;
401 }
402 };
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000403
Owen Andersone68713a2011-01-05 23:26:22 +0000404
Owen Anderson7f9cb742010-07-30 23:59:40 +0000405
Owen Andersonf33b3022010-12-09 06:14:58 +0000406 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000407 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
408 LVILatticeVal &Result);
409 bool hasBlockValue(Value *Val, BasicBlock *BB);
410
411 // These methods process one work item and may add more. A false value
412 // returned means that the work item was not completely processed and must
413 // be revisited after going through the new items.
414 bool solveBlockValue(Value *Val, BasicBlock *BB);
Owen Anderson61863942010-12-20 18:18:16 +0000415 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
416 Value *Val, BasicBlock *BB);
417 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
418 PHINode *PN, BasicBlock *BB);
419 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
420 Instruction *BBI, BasicBlock *BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000421
422 void solve();
Owen Andersonf33b3022010-12-09 06:14:58 +0000423
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000424 ValueCacheEntryTy &lookup(Value *V) {
Owen Andersonf33b3022010-12-09 06:14:58 +0000425 return ValueCache[LVIValueHandle(V, this)];
426 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000427
Chris Lattner2c5adf82009-11-15 19:59:49 +0000428 public:
Chris Lattner2c5adf82009-11-15 19:59:49 +0000429 /// getValueInBlock - This is the query interface to determine the lattice
430 /// value for the specified Value* at the end of the specified block.
431 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
432
433 /// getValueOnEdge - This is the query interface to determine the lattice
434 /// value for the specified Value* that is true on the specified edge.
435 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000436
437 /// threadEdge - This is the update interface to inform the cache that an
438 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
439 /// NewSucc.
440 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000441
442 /// eraseBlock - This is part of the update interface to inform the cache
443 /// that a block has been deleted.
444 void eraseBlock(BasicBlock *BB);
445
446 /// clear - Empty the cache.
447 void clear() {
Benjamin Kramerc00c05f2011-12-03 15:19:55 +0000448 SeenBlocks.clear();
Owen Anderson00ac77e2010-08-18 18:39:01 +0000449 ValueCache.clear();
450 OverDefinedCache.clear();
451 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000452 };
453} // end anonymous namespace
454
Owen Anderson89778462011-01-05 21:15:29 +0000455void LVIValueHandle::deleted() {
456 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
457
458 SmallVector<OverDefinedPairTy, 4> ToErase;
459 for (DenseSet<OverDefinedPairTy>::iterator
Owen Anderson7f9cb742010-07-30 23:59:40 +0000460 I = Parent->OverDefinedCache.begin(),
461 E = Parent->OverDefinedCache.end();
Owen Anderson89778462011-01-05 21:15:29 +0000462 I != E; ++I) {
463 if (I->second == getValPtr())
464 ToErase.push_back(*I);
Owen Anderson7f9cb742010-07-30 23:59:40 +0000465 }
Owen Andersoncf6abd22010-08-11 22:36:04 +0000466
Owen Anderson89778462011-01-05 21:15:29 +0000467 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
468 E = ToErase.end(); I != E; ++I)
469 Parent->OverDefinedCache.erase(*I);
470
Owen Andersoncf6abd22010-08-11 22:36:04 +0000471 // This erasure deallocates *this, so it MUST happen after we're done
472 // using any and all members of *this.
473 Parent->ValueCache.erase(*this);
Owen Anderson7f9cb742010-07-30 23:59:40 +0000474}
475
Owen Anderson00ac77e2010-08-18 18:39:01 +0000476void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
Benjamin Kramerfeb9b4b2011-12-03 15:16:45 +0000477 // Shortcut if we have never seen this block.
478 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
479 if (I == SeenBlocks.end())
480 return;
481 SeenBlocks.erase(I);
482
Owen Anderson89778462011-01-05 21:15:29 +0000483 SmallVector<OverDefinedPairTy, 4> ToErase;
484 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
485 E = OverDefinedCache.end(); I != E; ++I) {
486 if (I->first == BB)
487 ToErase.push_back(*I);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000488 }
Owen Anderson89778462011-01-05 21:15:29 +0000489
490 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
491 E = ToErase.end(); I != E; ++I)
492 OverDefinedCache.erase(*I);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000493
Owen Anderson89778462011-01-05 21:15:29 +0000494 for (DenseMap<LVIValueHandle, ValueCacheEntryTy>::iterator
Owen Anderson00ac77e2010-08-18 18:39:01 +0000495 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
496 I->second.erase(BB);
497}
Owen Anderson7f9cb742010-07-30 23:59:40 +0000498
Nick Lewycky90862ee2010-12-18 01:00:40 +0000499void LazyValueInfoCache::solve() {
Owen Andersone68713a2011-01-05 23:26:22 +0000500 while (!BlockValueStack.empty()) {
501 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
Owen Anderson87790ab2010-12-20 19:33:41 +0000502 if (solveBlockValue(e.second, e.first))
Owen Andersone68713a2011-01-05 23:26:22 +0000503 BlockValueStack.pop();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000504 }
505}
506
507bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
508 // If already a constant, there is nothing to compute.
509 if (isa<Constant>(Val))
510 return true;
511
Owen Anderson89778462011-01-05 21:15:29 +0000512 LVIValueHandle ValHandle(Val, this);
513 if (!ValueCache.count(ValHandle)) return false;
514 return ValueCache[ValHandle].count(BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000515}
516
Owen Andersonf33b3022010-12-09 06:14:58 +0000517LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000518 // If already a constant, there is nothing to compute.
519 if (Constant *VC = dyn_cast<Constant>(Val))
520 return LVILatticeVal::get(VC);
521
Benjamin Kramerfeb9b4b2011-12-03 15:16:45 +0000522 SeenBlocks.insert(BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000523 return lookup(Val)[BB];
524}
525
526bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
527 if (isa<Constant>(Val))
528 return true;
529
Owen Andersonf33b3022010-12-09 06:14:58 +0000530 ValueCacheEntryTy &Cache = lookup(Val);
Benjamin Kramerfeb9b4b2011-12-03 15:16:45 +0000531 SeenBlocks.insert(BB);
Owen Andersonf33b3022010-12-09 06:14:58 +0000532 LVILatticeVal &BBLV = Cache[BB];
Owen Anderson87790ab2010-12-20 19:33:41 +0000533
534 // OverDefinedCacheUpdater is a helper object that will update
535 // the OverDefinedCache for us when this method exits. Make sure to
536 // call markResult on it as we exist, passing a bool to indicate if the
537 // cache needs updating, i.e. if we have solve a new value or not.
538 OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000539
Chris Lattner2c5adf82009-11-15 19:59:49 +0000540 // If we've already computed this block's value, return it.
Chris Lattnere5642812009-11-15 20:00:52 +0000541 if (!BBLV.isUndefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000542 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
Owen Anderson87790ab2010-12-20 19:33:41 +0000543
544 // Since we're reusing a cached value here, we don't need to update the
545 // OverDefinedCahce. The cache will have been properly updated
546 // whenever the cached value was inserted.
547 ODCacheUpdater.markResult(false);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000548 return true;
Chris Lattnere5642812009-11-15 20:00:52 +0000549 }
550
Chris Lattner2c5adf82009-11-15 19:59:49 +0000551 // Otherwise, this is the first time we're seeing this block. Reset the
552 // lattice value to overdefined, so that cycles will terminate and be
553 // conservatively correct.
554 BBLV.markOverdefined();
555
Chris Lattner2c5adf82009-11-15 19:59:49 +0000556 Instruction *BBI = dyn_cast<Instruction>(Val);
557 if (BBI == 0 || BBI->getParent() != BB) {
Owen Anderson87790ab2010-12-20 19:33:41 +0000558 return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
Chris Lattner2c5adf82009-11-15 19:59:49 +0000559 }
Chris Lattnere5642812009-11-15 20:00:52 +0000560
Nick Lewycky90862ee2010-12-18 01:00:40 +0000561 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Owen Anderson87790ab2010-12-20 19:33:41 +0000562 return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000563 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000564
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000565 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
566 BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
567 return ODCacheUpdater.markResult(true);
568 }
569
Owen Andersonb81fd622010-08-18 21:11:37 +0000570 // We can only analyze the definitions of certain classes of instructions
571 // (integral binops and casts at the moment), so bail if this isn't one.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000572 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000573 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
574 !BBI->getType()->isIntegerTy()) {
575 DEBUG(dbgs() << " compute BB '" << BB->getName()
576 << "' - overdefined because inst def found.\n");
Owen Anderson61863942010-12-20 18:18:16 +0000577 BBLV.markOverdefined();
Owen Anderson87790ab2010-12-20 19:33:41 +0000578 return ODCacheUpdater.markResult(true);
Owen Andersonb81fd622010-08-18 21:11:37 +0000579 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000580
Owen Andersonb81fd622010-08-18 21:11:37 +0000581 // FIXME: We're currently limited to binops with a constant RHS. This should
582 // be improved.
583 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
584 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
585 DEBUG(dbgs() << " compute BB '" << BB->getName()
586 << "' - overdefined because inst def found.\n");
587
Owen Anderson61863942010-12-20 18:18:16 +0000588 BBLV.markOverdefined();
Owen Anderson87790ab2010-12-20 19:33:41 +0000589 return ODCacheUpdater.markResult(true);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000590 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000591
Owen Anderson87790ab2010-12-20 19:33:41 +0000592 return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000593}
594
595static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
596 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
597 return L->getPointerAddressSpace() == 0 &&
598 GetUnderlyingObject(L->getPointerOperand()) ==
599 GetUnderlyingObject(Ptr);
600 }
601 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
602 return S->getPointerAddressSpace() == 0 &&
603 GetUnderlyingObject(S->getPointerOperand()) ==
604 GetUnderlyingObject(Ptr);
605 }
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000606 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
607 if (MI->isVolatile()) return false;
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000608
609 // FIXME: check whether it has a valuerange that excludes zero?
610 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
611 if (!Len || Len->isZero()) return false;
612
Eli Friedman69388e52011-05-31 20:40:16 +0000613 if (MI->getDestAddressSpace() == 0)
614 if (MI->getRawDest() == Ptr || MI->getDest() == Ptr)
615 return true;
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000616 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman69388e52011-05-31 20:40:16 +0000617 if (MTI->getSourceAddressSpace() == 0)
618 if (MTI->getRawSource() == Ptr || MTI->getSource() == Ptr)
619 return true;
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000620 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000621 return false;
622}
623
Owen Anderson61863942010-12-20 18:18:16 +0000624bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
625 Value *Val, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000626 LVILatticeVal Result; // Start Undefined.
627
628 // If this is a pointer, and there's a load from that pointer in this BB,
629 // then we know that the pointer can't be NULL.
630 bool NotNull = false;
631 if (Val->getType()->isPointerTy()) {
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000632 if (isa<AllocaInst>(Val)) {
633 NotNull = true;
634 } else {
635 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
636 if (InstructionDereferencesPointer(BI, Val)) {
637 NotNull = true;
638 break;
639 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000640 }
641 }
642 }
643
644 // If this is the entry block, we must be asking about an argument. The
645 // value is overdefined.
646 if (BB == &BB->getParent()->getEntryBlock()) {
647 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
648 if (NotNull) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000649 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky90862ee2010-12-18 01:00:40 +0000650 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
651 } else {
652 Result.markOverdefined();
653 }
Owen Anderson61863942010-12-20 18:18:16 +0000654 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000655 return true;
656 }
657
658 // Loop over all of our predecessors, merging what we know from them into
659 // result.
660 bool EdgesMissing = false;
661 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
662 LVILatticeVal EdgeResult;
663 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
664 if (EdgesMissing)
665 continue;
666
667 Result.mergeIn(EdgeResult);
668
669 // If we hit overdefined, exit early. The BlockVals entry is already set
670 // to overdefined.
671 if (Result.isOverdefined()) {
672 DEBUG(dbgs() << " compute BB '" << BB->getName()
673 << "' - overdefined because of pred.\n");
674 // If we previously determined that this is a pointer that can't be null
675 // then return that rather than giving up entirely.
676 if (NotNull) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000677 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky90862ee2010-12-18 01:00:40 +0000678 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
679 }
Owen Anderson61863942010-12-20 18:18:16 +0000680
681 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000682 return true;
683 }
684 }
685 if (EdgesMissing)
686 return false;
687
688 // Return the merged value, which is more precise than 'overdefined'.
689 assert(!Result.isOverdefined());
Owen Anderson61863942010-12-20 18:18:16 +0000690 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000691 return true;
692}
693
Owen Anderson61863942010-12-20 18:18:16 +0000694bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
695 PHINode *PN, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000696 LVILatticeVal Result; // Start Undefined.
697
698 // Loop over all of our predecessors, merging what we know from them into
699 // result.
700 bool EdgesMissing = false;
701 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
702 BasicBlock *PhiBB = PN->getIncomingBlock(i);
703 Value *PhiVal = PN->getIncomingValue(i);
704 LVILatticeVal EdgeResult;
705 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
706 if (EdgesMissing)
707 continue;
708
709 Result.mergeIn(EdgeResult);
710
711 // If we hit overdefined, exit early. The BlockVals entry is already set
712 // to overdefined.
713 if (Result.isOverdefined()) {
714 DEBUG(dbgs() << " compute BB '" << BB->getName()
715 << "' - overdefined because of pred.\n");
Owen Anderson61863942010-12-20 18:18:16 +0000716
717 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000718 return true;
719 }
720 }
721 if (EdgesMissing)
722 return false;
723
724 // Return the merged value, which is more precise than 'overdefined'.
725 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson61863942010-12-20 18:18:16 +0000726 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000727 return true;
728}
729
Owen Anderson61863942010-12-20 18:18:16 +0000730bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
731 Instruction *BBI,
Nick Lewycky90862ee2010-12-18 01:00:40 +0000732 BasicBlock *BB) {
Owen Andersonb81fd622010-08-18 21:11:37 +0000733 // Figure out the range of the LHS. If that fails, bail.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000734 if (!hasBlockValue(BBI->getOperand(0), BB)) {
Owen Andersone68713a2011-01-05 23:26:22 +0000735 BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0)));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000736 return false;
737 }
738
Nick Lewycky90862ee2010-12-18 01:00:40 +0000739 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Owen Andersonb81fd622010-08-18 21:11:37 +0000740 if (!LHSVal.isConstantRange()) {
Owen Anderson61863942010-12-20 18:18:16 +0000741 BBLV.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000742 return true;
Owen Andersonb81fd622010-08-18 21:11:37 +0000743 }
744
Owen Andersonb81fd622010-08-18 21:11:37 +0000745 ConstantRange LHSRange = LHSVal.getConstantRange();
746 ConstantRange RHSRange(1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000747 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
Owen Andersonb81fd622010-08-18 21:11:37 +0000748 if (isa<BinaryOperator>(BBI)) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000749 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
750 RHSRange = ConstantRange(RHS->getValue());
751 } else {
Owen Anderson61863942010-12-20 18:18:16 +0000752 BBLV.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000753 return true;
Owen Anderson59b06dc2010-08-24 07:55:44 +0000754 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000755 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000756
Owen Andersonb81fd622010-08-18 21:11:37 +0000757 // NOTE: We're currently limited by the set of operations that ConstantRange
758 // can evaluate symbolically. Enhancing that set will allows us to analyze
759 // more definitions.
Owen Anderson61863942010-12-20 18:18:16 +0000760 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000761 switch (BBI->getOpcode()) {
762 case Instruction::Add:
763 Result.markConstantRange(LHSRange.add(RHSRange));
764 break;
765 case Instruction::Sub:
766 Result.markConstantRange(LHSRange.sub(RHSRange));
767 break;
768 case Instruction::Mul:
769 Result.markConstantRange(LHSRange.multiply(RHSRange));
770 break;
771 case Instruction::UDiv:
772 Result.markConstantRange(LHSRange.udiv(RHSRange));
773 break;
774 case Instruction::Shl:
775 Result.markConstantRange(LHSRange.shl(RHSRange));
776 break;
777 case Instruction::LShr:
778 Result.markConstantRange(LHSRange.lshr(RHSRange));
779 break;
780 case Instruction::Trunc:
781 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
782 break;
783 case Instruction::SExt:
784 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
785 break;
786 case Instruction::ZExt:
787 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
788 break;
789 case Instruction::BitCast:
790 Result.markConstantRange(LHSRange);
791 break;
Nick Lewycky198381e2010-09-07 05:39:02 +0000792 case Instruction::And:
793 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
794 break;
795 case Instruction::Or:
796 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
797 break;
Owen Andersonb81fd622010-08-18 21:11:37 +0000798
799 // Unhandled instructions are overdefined.
800 default:
801 DEBUG(dbgs() << " compute BB '" << BB->getName()
802 << "' - overdefined because inst def found.\n");
803 Result.markOverdefined();
804 break;
805 }
806
Owen Anderson61863942010-12-20 18:18:16 +0000807 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000808 return true;
Chris Lattner10f2d132009-11-11 00:22:30 +0000809}
810
Chris Lattner800c47e2009-11-15 20:02:12 +0000811/// getEdgeValue - This method attempts to infer more complex
Nick Lewycky90862ee2010-12-18 01:00:40 +0000812bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
813 BasicBlock *BBTo, LVILatticeVal &Result) {
814 // If already a constant, there is nothing to compute.
815 if (Constant *VC = dyn_cast<Constant>(Val)) {
816 Result = LVILatticeVal::get(VC);
817 return true;
818 }
819
Chris Lattner800c47e2009-11-15 20:02:12 +0000820 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
821 // know that v != 0.
Chris Lattner16976522009-11-11 22:48:44 +0000822 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
823 // If this is a conditional branch and only one successor goes to BBTo, then
824 // we maybe able to infer something from the condition.
825 if (BI->isConditional() &&
826 BI->getSuccessor(0) != BI->getSuccessor(1)) {
827 bool isTrueDest = BI->getSuccessor(0) == BBTo;
828 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
829 "BBTo isn't a successor of BBFrom");
830
831 // If V is the condition of the branch itself, then we know exactly what
832 // it is.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000833 if (BI->getCondition() == Val) {
834 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson9f014062010-08-10 20:03:09 +0000835 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000836 return true;
837 }
Chris Lattner16976522009-11-11 22:48:44 +0000838
839 // If the condition of the branch is an equality comparison, we may be
840 // able to infer the value.
Owen Anderson2d0f2472010-08-11 04:24:25 +0000841 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
842 if (ICI && ICI->getOperand(0) == Val &&
843 isa<Constant>(ICI->getOperand(1))) {
844 if (ICI->isEquality()) {
845 // We know that V has the RHS constant if this is a true SETEQ or
846 // false SETNE.
847 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
Nick Lewycky90862ee2010-12-18 01:00:40 +0000848 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
849 else
850 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
851 return true;
Chris Lattner16976522009-11-11 22:48:44 +0000852 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000853
Owen Anderson2d0f2472010-08-11 04:24:25 +0000854 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
855 // Calculate the range of values that would satisfy the comparison.
856 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
857 ConstantRange TrueValues =
858 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000859
Owen Anderson2d0f2472010-08-11 04:24:25 +0000860 // If we're interested in the false dest, invert the condition.
861 if (!isTrueDest) TrueValues = TrueValues.inverse();
862
863 // Figure out the possible values of the query BEFORE this branch.
Owen Andersonbe419012011-01-05 21:37:18 +0000864 if (!hasBlockValue(Val, BBFrom)) {
Owen Andersone68713a2011-01-05 23:26:22 +0000865 BlockValueStack.push(std::make_pair(BBFrom, Val));
Owen Andersonbe419012011-01-05 21:37:18 +0000866 return false;
867 }
868
Owen Andersonf33b3022010-12-09 06:14:58 +0000869 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000870 if (!InBlock.isConstantRange()) {
871 Result = LVILatticeVal::getRange(TrueValues);
872 return true;
873 }
874
Owen Anderson2d0f2472010-08-11 04:24:25 +0000875 // Find all potential values that satisfy both the input and output
876 // conditions.
877 ConstantRange PossibleValues =
878 TrueValues.intersectWith(InBlock.getConstantRange());
Nick Lewycky90862ee2010-12-18 01:00:40 +0000879
880 Result = LVILatticeVal::getRange(PossibleValues);
881 return true;
Owen Anderson2d0f2472010-08-11 04:24:25 +0000882 }
883 }
Chris Lattner16976522009-11-11 22:48:44 +0000884 }
885 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000886
887 // If the edge was formed by a switch on the value, then we may know exactly
888 // what it is.
889 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Owen Andersondae90c62010-08-24 21:59:42 +0000890 if (SI->getCondition() == Val) {
Owen Anderson4caef602010-09-02 22:16:52 +0000891 // We don't know anything in the default case.
Owen Andersondae90c62010-08-24 21:59:42 +0000892 if (SI->getDefaultDest() == BBTo) {
Owen Anderson4caef602010-09-02 22:16:52 +0000893 Result.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000894 return true;
Owen Andersondae90c62010-08-24 21:59:42 +0000895 }
896
Chris Lattner800c47e2009-11-15 20:02:12 +0000897 // We only know something if there is exactly one value that goes from
898 // BBFrom to BBTo.
899 unsigned NumEdges = 0;
900 ConstantInt *EdgeVal = 0;
901 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
902 if (SI->getSuccessor(i) != BBTo) continue;
903 if (NumEdges++) break;
904 EdgeVal = SI->getCaseValue(i);
905 }
906 assert(EdgeVal && "Missing successor?");
Nick Lewycky90862ee2010-12-18 01:00:40 +0000907 if (NumEdges == 1) {
908 Result = LVILatticeVal::get(EdgeVal);
909 return true;
910 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000911 }
912 }
Chris Lattner16976522009-11-11 22:48:44 +0000913
914 // Otherwise see if the value is known in the block.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000915 if (hasBlockValue(Val, BBFrom)) {
916 Result = getBlockValue(Val, BBFrom);
917 return true;
918 }
Owen Andersone68713a2011-01-05 23:26:22 +0000919 BlockValueStack.push(std::make_pair(BBFrom, Val));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000920 return false;
Chris Lattner16976522009-11-11 22:48:44 +0000921}
922
Chris Lattner2c5adf82009-11-15 19:59:49 +0000923LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
David Greene5d93a1f2009-12-23 20:43:58 +0000924 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000925 << BB->getName() << "'\n");
926
Owen Andersone68713a2011-01-05 23:26:22 +0000927 BlockValueStack.push(std::make_pair(BB, V));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000928 solve();
Owen Andersonf33b3022010-12-09 06:14:58 +0000929 LVILatticeVal Result = getBlockValue(V, BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000930
David Greene5d93a1f2009-12-23 20:43:58 +0000931 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000932 return Result;
933}
Chris Lattner16976522009-11-11 22:48:44 +0000934
Chris Lattner2c5adf82009-11-15 19:59:49 +0000935LVILatticeVal LazyValueInfoCache::
936getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
David Greene5d93a1f2009-12-23 20:43:58 +0000937 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000938 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000939
Nick Lewycky90862ee2010-12-18 01:00:40 +0000940 LVILatticeVal Result;
941 if (!getEdgeValue(V, FromBB, ToBB, Result)) {
942 solve();
943 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
944 (void)WasFastQuery;
945 assert(WasFastQuery && "More work to do after problem solved?");
946 }
947
David Greene5d93a1f2009-12-23 20:43:58 +0000948 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000949 return Result;
950}
951
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000952void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
953 BasicBlock *NewSucc) {
954 // When an edge in the graph has been threaded, values that we could not
955 // determine a value for before (i.e. were marked overdefined) may be possible
956 // to solve now. We do NOT try to proactively update these values. Instead,
957 // we clear their entries from the cache, and allow lazy updating to recompute
958 // them when needed.
959
960 // The updating process is fairly simple: we need to dropped cached info
961 // for all values that were marked overdefined in OldSucc, and for those same
962 // values in any successor of OldSucc (except NewSucc) in which they were
963 // also marked overdefined.
964 std::vector<BasicBlock*> worklist;
965 worklist.push_back(OldSucc);
966
Owen Anderson9a65dc92010-07-27 23:58:11 +0000967 DenseSet<Value*> ClearSet;
Owen Anderson89778462011-01-05 21:15:29 +0000968 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
969 E = OverDefinedCache.end(); I != E; ++I) {
Owen Anderson9a65dc92010-07-27 23:58:11 +0000970 if (I->first == OldSucc)
971 ClearSet.insert(I->second);
972 }
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000973
974 // Use a worklist to perform a depth-first search of OldSucc's successors.
975 // NOTE: We do not need a visited list since any blocks we have already
976 // visited will have had their overdefined markers cleared already, and we
977 // thus won't loop to their successors.
978 while (!worklist.empty()) {
979 BasicBlock *ToUpdate = worklist.back();
980 worklist.pop_back();
981
982 // Skip blocks only accessible through NewSucc.
983 if (ToUpdate == NewSucc) continue;
984
985 bool changed = false;
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000986 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000987 I != E; ++I) {
988 // If a value was marked overdefined in OldSucc, and is here too...
Owen Anderson89778462011-01-05 21:15:29 +0000989 DenseSet<OverDefinedPairTy>::iterator OI =
Owen Anderson9a65dc92010-07-27 23:58:11 +0000990 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
991 if (OI == OverDefinedCache.end()) continue;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000992
Owen Anderson9a65dc92010-07-27 23:58:11 +0000993 // Remove it from the caches.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000994 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
Owen Anderson9a65dc92010-07-27 23:58:11 +0000995 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000996
Owen Anderson9a65dc92010-07-27 23:58:11 +0000997 assert(CI != Entry.end() && "Couldn't find entry to update?");
998 Entry.erase(CI);
999 OverDefinedCache.erase(OI);
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001000
Owen Anderson9a65dc92010-07-27 23:58:11 +00001001 // If we removed anything, then we potentially need to update
1002 // blocks successors too.
1003 changed = true;
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001004 }
Nick Lewycky90862ee2010-12-18 01:00:40 +00001005
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001006 if (!changed) continue;
1007
1008 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1009 }
1010}
1011
Chris Lattner2c5adf82009-11-15 19:59:49 +00001012//===----------------------------------------------------------------------===//
1013// LazyValueInfo Impl
1014//===----------------------------------------------------------------------===//
1015
Chris Lattner2c5adf82009-11-15 19:59:49 +00001016/// getCache - This lazily constructs the LazyValueInfoCache.
1017static LazyValueInfoCache &getCache(void *&PImpl) {
1018 if (!PImpl)
1019 PImpl = new LazyValueInfoCache();
1020 return *static_cast<LazyValueInfoCache*>(PImpl);
1021}
1022
Owen Anderson00ac77e2010-08-18 18:39:01 +00001023bool LazyValueInfo::runOnFunction(Function &F) {
1024 if (PImpl)
1025 getCache(PImpl).clear();
Chad Rosieraab8e282011-12-02 01:26:24 +00001026
Owen Anderson00ac77e2010-08-18 18:39:01 +00001027 TD = getAnalysisIfAvailable<TargetData>();
Chad Rosieraab8e282011-12-02 01:26:24 +00001028 TLI = &getAnalysis<TargetLibraryInfo>();
1029
Owen Anderson00ac77e2010-08-18 18:39:01 +00001030 // Fully lazy.
1031 return false;
1032}
1033
Chad Rosieraab8e282011-12-02 01:26:24 +00001034void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1035 AU.setPreservesAll();
1036 AU.addRequired<TargetLibraryInfo>();
1037}
1038
Chris Lattner2c5adf82009-11-15 19:59:49 +00001039void LazyValueInfo::releaseMemory() {
1040 // If the cache was allocated, free it.
1041 if (PImpl) {
1042 delete &getCache(PImpl);
1043 PImpl = 0;
1044 }
1045}
1046
1047Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
1048 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
1049
Chris Lattner16976522009-11-11 22:48:44 +00001050 if (Result.isConstant())
1051 return Result.getConstant();
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001052 if (Result.isConstantRange()) {
Owen Andersonee61fcf2010-08-27 23:29:38 +00001053 ConstantRange CR = Result.getConstantRange();
1054 if (const APInt *SingleVal = CR.getSingleElement())
1055 return ConstantInt::get(V->getContext(), *SingleVal);
1056 }
Chris Lattner16976522009-11-11 22:48:44 +00001057 return 0;
1058}
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001059
Chris Lattner38392bb2009-11-12 01:29:10 +00001060/// getConstantOnEdge - Determine whether the specified value is known to be a
1061/// constant on the specified edge. Return null if not.
1062Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1063 BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +00001064 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattner38392bb2009-11-12 01:29:10 +00001065
1066 if (Result.isConstant())
1067 return Result.getConstant();
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001068 if (Result.isConstantRange()) {
Owen Anderson9f014062010-08-10 20:03:09 +00001069 ConstantRange CR = Result.getConstantRange();
1070 if (const APInt *SingleVal = CR.getSingleElement())
1071 return ConstantInt::get(V->getContext(), *SingleVal);
1072 }
Chris Lattner38392bb2009-11-12 01:29:10 +00001073 return 0;
1074}
1075
Chris Lattnerb52675b2009-11-12 04:36:58 +00001076/// getPredicateOnEdge - Determine whether the specified value comparison
1077/// with a constant is known to be true or false on the specified CFG edge.
1078/// Pred is a CmpInst predicate.
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001079LazyValueInfo::Tristate
Chris Lattnerb52675b2009-11-12 04:36:58 +00001080LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1081 BasicBlock *FromBB, BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +00001082 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001083
Chris Lattnerb52675b2009-11-12 04:36:58 +00001084 // If we know the value is a constant, evaluate the conditional.
1085 Constant *Res = 0;
1086 if (Result.isConstant()) {
Chad Rosieraab8e282011-12-02 01:26:24 +00001087 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD,
1088 TLI);
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001089 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Chris Lattnerb52675b2009-11-12 04:36:58 +00001090 return ResCI->isZero() ? False : True;
Chris Lattner2c5adf82009-11-15 19:59:49 +00001091 return Unknown;
1092 }
1093
Owen Anderson9f014062010-08-10 20:03:09 +00001094 if (Result.isConstantRange()) {
Owen Anderson59b06dc2010-08-24 07:55:44 +00001095 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1096 if (!CI) return Unknown;
1097
Owen Anderson9f014062010-08-10 20:03:09 +00001098 ConstantRange CR = Result.getConstantRange();
1099 if (Pred == ICmpInst::ICMP_EQ) {
1100 if (!CR.contains(CI->getValue()))
1101 return False;
1102
1103 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1104 return True;
1105 } else if (Pred == ICmpInst::ICMP_NE) {
1106 if (!CR.contains(CI->getValue()))
1107 return True;
1108
1109 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1110 return False;
1111 }
1112
1113 // Handle more complex predicates.
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001114 ConstantRange TrueValues =
1115 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1116 if (TrueValues.contains(CR))
Owen Anderson9f014062010-08-10 20:03:09 +00001117 return True;
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001118 if (TrueValues.inverse().contains(CR))
1119 return False;
Owen Anderson9f014062010-08-10 20:03:09 +00001120 return Unknown;
1121 }
1122
Chris Lattner2c5adf82009-11-15 19:59:49 +00001123 if (Result.isNotConstant()) {
Chris Lattnerb52675b2009-11-12 04:36:58 +00001124 // If this is an equality comparison, we can try to fold it knowing that
1125 // "V != C1".
1126 if (Pred == ICmpInst::ICMP_EQ) {
1127 // !C1 == C -> false iff C1 == C.
1128 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chad Rosieraab8e282011-12-02 01:26:24 +00001129 Result.getNotConstant(), C, TD,
1130 TLI);
Chris Lattnerb52675b2009-11-12 04:36:58 +00001131 if (Res->isNullValue())
1132 return False;
1133 } else if (Pred == ICmpInst::ICMP_NE) {
1134 // !C1 != C -> true iff C1 == C.
Chris Lattner5553a3a2009-11-15 20:01:24 +00001135 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chad Rosieraab8e282011-12-02 01:26:24 +00001136 Result.getNotConstant(), C, TD,
1137 TLI);
Chris Lattnerb52675b2009-11-12 04:36:58 +00001138 if (Res->isNullValue())
1139 return True;
1140 }
Chris Lattner2c5adf82009-11-15 19:59:49 +00001141 return Unknown;
Chris Lattnerb52675b2009-11-12 04:36:58 +00001142 }
1143
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001144 return Unknown;
1145}
1146
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001147void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001148 BasicBlock *NewSucc) {
Owen Anderson00ac77e2010-08-18 18:39:01 +00001149 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1150}
1151
1152void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1153 if (PImpl) getCache(PImpl).eraseBlock(BB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001154}