blob: bcac49856fa7bfbad7990015a242ab1ff7771e0b [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"
20#include "llvm/Analysis/ConstantFolding.h"
21#include "llvm/Target/TargetData.h"
Chris Lattner16976522009-11-11 22:48:44 +000022#include "llvm/Support/CFG.h"
Owen Anderson5be2e782010-08-05 22:59:19 +000023#include "llvm/Support/ConstantRange.h"
Chris Lattnerb8c124c2009-11-12 01:22:16 +000024#include "llvm/Support/Debug.h"
Chris Lattner16976522009-11-11 22:48:44 +000025#include "llvm/Support/raw_ostream.h"
Owen Anderson7f9cb742010-07-30 23:59:40 +000026#include "llvm/Support/ValueHandle.h"
Chris Lattner16976522009-11-11 22:48:44 +000027#include "llvm/ADT/DenseMap.h"
Owen Anderson9a65dc92010-07-27 23:58:11 +000028#include "llvm/ADT/DenseSet.h"
Chris Lattnere5642812009-11-15 20:00:52 +000029#include "llvm/ADT/STLExtras.h"
Owen Anderson6bcd3a02010-09-07 19:16:25 +000030#include <map>
31#include <set>
Nick Lewycky90862ee2010-12-18 01:00:40 +000032#include <stack>
Chris Lattner10f2d132009-11-11 00:22:30 +000033using namespace llvm;
34
35char LazyValueInfo::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000036INITIALIZE_PASS(LazyValueInfo, "lazy-value-info",
Owen Andersonce665bd2010-10-07 22:25:06 +000037 "Lazy Value Information Analysis", false, true)
Chris Lattner10f2d132009-11-11 00:22:30 +000038
39namespace llvm {
40 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
41}
42
Chris Lattnercc4d3b22009-11-11 02:08:33 +000043
44//===----------------------------------------------------------------------===//
45// LVILatticeVal
46//===----------------------------------------------------------------------===//
47
48/// LVILatticeVal - This is the information tracked by LazyValueInfo for each
49/// value.
50///
51/// FIXME: This is basically just for bringup, this can be made a lot more rich
52/// in the future.
53///
54namespace {
55class LVILatticeVal {
56 enum LatticeValueTy {
Nick Lewycky69bfdf52010-12-15 18:57:18 +000057 /// undefined - This Value has no known value yet.
Chris Lattnercc4d3b22009-11-11 02:08:33 +000058 undefined,
Owen Anderson5be2e782010-08-05 22:59:19 +000059
Nick Lewycky69bfdf52010-12-15 18:57:18 +000060 /// constant - This Value has a specific constant value.
Chris Lattnercc4d3b22009-11-11 02:08:33 +000061 constant,
Nick Lewycky69bfdf52010-12-15 18:57:18 +000062 /// notconstant - This Value is known to not have the specified value.
Chris Lattnerb52675b2009-11-12 04:36:58 +000063 notconstant,
64
Nick Lewycky69bfdf52010-12-15 18:57:18 +000065 /// constantrange - The Value falls within this range.
Owen Anderson5be2e782010-08-05 22:59:19 +000066 constantrange,
67
Nick Lewycky69bfdf52010-12-15 18:57:18 +000068 /// overdefined - This value is not known to be constant, and we know that
Chris Lattnercc4d3b22009-11-11 02:08:33 +000069 /// it has a value.
70 overdefined
71 };
72
73 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattnerb52675b2009-11-12 04:36:58 +000074 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersondb78d732010-08-05 22:10:46 +000075 LatticeValueTy Tag;
76 Constant *Val;
Owen Anderson5be2e782010-08-05 22:59:19 +000077 ConstantRange Range;
Chris Lattnercc4d3b22009-11-11 02:08:33 +000078
79public:
Owen Anderson5be2e782010-08-05 22:59:19 +000080 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
Chris Lattnercc4d3b22009-11-11 02:08:33 +000081
Chris Lattner16976522009-11-11 22:48:44 +000082 static LVILatticeVal get(Constant *C) {
83 LVILatticeVal Res;
Nick Lewycky69bfdf52010-12-15 18:57:18 +000084 if (!isa<UndefValue>(C))
Owen Anderson9f014062010-08-10 20:03:09 +000085 Res.markConstant(C);
Chris Lattner16976522009-11-11 22:48:44 +000086 return Res;
87 }
Chris Lattnerb52675b2009-11-12 04:36:58 +000088 static LVILatticeVal getNot(Constant *C) {
89 LVILatticeVal Res;
Nick Lewycky69bfdf52010-12-15 18:57:18 +000090 if (!isa<UndefValue>(C))
Owen Anderson9f014062010-08-10 20:03:09 +000091 Res.markNotConstant(C);
Chris Lattnerb52675b2009-11-12 04:36:58 +000092 return Res;
93 }
Owen Anderson625051b2010-08-10 23:20:01 +000094 static LVILatticeVal getRange(ConstantRange CR) {
95 LVILatticeVal Res;
96 Res.markConstantRange(CR);
97 return Res;
98 }
Chris Lattner16976522009-11-11 22:48:44 +000099
Owen Anderson5be2e782010-08-05 22:59:19 +0000100 bool isUndefined() const { return Tag == undefined; }
101 bool isConstant() const { return Tag == constant; }
102 bool isNotConstant() const { return Tag == notconstant; }
103 bool isConstantRange() const { return Tag == constantrange; }
104 bool isOverdefined() const { return Tag == overdefined; }
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000105
106 Constant *getConstant() const {
107 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000108 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000109 }
110
Chris Lattnerb52675b2009-11-12 04:36:58 +0000111 Constant *getNotConstant() const {
112 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000113 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000114 }
115
Owen Anderson5be2e782010-08-05 22:59:19 +0000116 ConstantRange getConstantRange() const {
117 assert(isConstantRange() &&
118 "Cannot get the constant-range of a non-constant-range!");
119 return Range;
120 }
121
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000122 /// markOverdefined - Return true if this is a change in status.
123 bool markOverdefined() {
124 if (isOverdefined())
125 return false;
Owen Andersondb78d732010-08-05 22:10:46 +0000126 Tag = overdefined;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000127 return true;
128 }
129
130 /// markConstant - Return true if this is a change in status.
131 bool markConstant(Constant *V) {
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000132 assert(V && "Marking constant with NULL");
133 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
134 return markConstantRange(ConstantRange(CI->getValue()));
135 if (isa<UndefValue>(V))
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000136 return false;
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000137
138 assert((!isConstant() || getConstant() == V) &&
139 "Marking constant with different value");
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000140 assert(isUndefined());
Owen Andersondb78d732010-08-05 22:10:46 +0000141 Tag = constant;
Owen Andersondb78d732010-08-05 22:10:46 +0000142 Val = V;
Chris Lattner16976522009-11-11 22:48:44 +0000143 return true;
144 }
145
Chris Lattnerb52675b2009-11-12 04:36:58 +0000146 /// markNotConstant - Return true if this is a change in status.
147 bool markNotConstant(Constant *V) {
Chris Lattnerb52675b2009-11-12 04:36:58 +0000148 assert(V && "Marking constant with NULL");
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000149 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
150 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
151 if (isa<UndefValue>(V))
152 return false;
153
154 assert((!isConstant() || getConstant() != V) &&
155 "Marking constant !constant with same value");
156 assert((!isNotConstant() || getNotConstant() == V) &&
157 "Marking !constant with different value");
158 assert(isUndefined() || isConstant());
159 Tag = notconstant;
Owen Andersondb78d732010-08-05 22:10:46 +0000160 Val = V;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000161 return true;
162 }
163
Owen Anderson5be2e782010-08-05 22:59:19 +0000164 /// markConstantRange - Return true if this is a change in status.
165 bool markConstantRange(const ConstantRange NewR) {
166 if (isConstantRange()) {
167 if (NewR.isEmptySet())
168 return markOverdefined();
169
Owen Anderson5be2e782010-08-05 22:59:19 +0000170 bool changed = Range == NewR;
171 Range = NewR;
172 return changed;
173 }
174
175 assert(isUndefined());
176 if (NewR.isEmptySet())
177 return markOverdefined();
Owen Anderson5be2e782010-08-05 22:59:19 +0000178
179 Tag = constantrange;
180 Range = NewR;
181 return true;
182 }
183
Chris Lattner16976522009-11-11 22:48:44 +0000184 /// mergeIn - Merge the specified lattice value into this one, updating this
185 /// one and returning true if anything changed.
186 bool mergeIn(const LVILatticeVal &RHS) {
187 if (RHS.isUndefined() || isOverdefined()) return false;
188 if (RHS.isOverdefined()) return markOverdefined();
189
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000190 if (isUndefined()) {
191 Tag = RHS.Tag;
192 Val = RHS.Val;
193 Range = RHS.Range;
194 return true;
Chris Lattnerf496e792009-11-12 04:57:13 +0000195 }
196
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000197 if (isConstant()) {
198 if (RHS.isConstant()) {
199 if (Val == RHS.Val)
200 return false;
201 return markOverdefined();
202 }
203
204 if (RHS.isNotConstant()) {
205 if (Val == RHS.Val)
206 return markOverdefined();
207
208 // Unless we can prove that the two Constants are different, we must
209 // move to overdefined.
210 // FIXME: use TargetData for smarter constant folding.
211 if (ConstantInt *Res = dyn_cast<ConstantInt>(
212 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
213 getConstant(),
214 RHS.getNotConstant())))
215 if (Res->isOne())
216 return markNotConstant(RHS.getNotConstant());
217
218 return markOverdefined();
219 }
220
221 // RHS is a ConstantRange, LHS is a non-integer Constant.
222
223 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
224 // a function. The correct result is to pick up RHS.
225
Chris Lattner16976522009-11-11 22:48:44 +0000226 return markOverdefined();
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000227 }
228
229 if (isNotConstant()) {
230 if (RHS.isConstant()) {
231 if (Val == RHS.Val)
232 return markOverdefined();
233
234 // Unless we can prove that the two Constants are different, we must
235 // move to overdefined.
236 // FIXME: use TargetData for smarter constant folding.
237 if (ConstantInt *Res = dyn_cast<ConstantInt>(
238 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
239 getNotConstant(),
240 RHS.getConstant())))
241 if (Res->isOne())
242 return false;
243
244 return markOverdefined();
245 }
246
247 if (RHS.isNotConstant()) {
248 if (Val == RHS.Val)
249 return false;
250 return markOverdefined();
251 }
252
253 return markOverdefined();
254 }
255
256 assert(isConstantRange() && "New LVILattice type?");
257 if (!RHS.isConstantRange())
258 return markOverdefined();
259
260 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
261 if (NewR.isFullSet())
262 return markOverdefined();
263 return markConstantRange(NewR);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000264 }
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000265};
266
267} // end anonymous namespace.
268
Chris Lattner16976522009-11-11 22:48:44 +0000269namespace llvm {
270raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
271 if (Val.isUndefined())
272 return OS << "undefined";
273 if (Val.isOverdefined())
274 return OS << "overdefined";
Chris Lattnerb52675b2009-11-12 04:36:58 +0000275
276 if (Val.isNotConstant())
277 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Owen Anderson2f3ffb82010-08-09 20:50:46 +0000278 else if (Val.isConstantRange())
279 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
280 << Val.getConstantRange().getUpper() << '>';
Chris Lattner16976522009-11-11 22:48:44 +0000281 return OS << "constant<" << *Val.getConstant() << '>';
282}
283}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000284
285//===----------------------------------------------------------------------===//
Chris Lattner2c5adf82009-11-15 19:59:49 +0000286// LazyValueInfoCache Decl
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000287//===----------------------------------------------------------------------===//
288
Chris Lattner2c5adf82009-11-15 19:59:49 +0000289namespace {
290 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
291 /// maintains information about queries across the clients' queries.
292 class LazyValueInfoCache {
Owen Anderson81881bc2010-07-30 20:56:07 +0000293 public:
Chris Lattner2c5adf82009-11-15 19:59:49 +0000294 /// ValueCacheEntryTy - This is all of the cached block information for
295 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
296 /// entries, allowing us to do a lookup with a binary search.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000297 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000298
Owen Anderson81881bc2010-07-30 20:56:07 +0000299 private:
Nick Lewycky90862ee2010-12-18 01:00:40 +0000300 /// LVIValueHandle - A callback value handle update the cache when
301 /// values are erased.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000302 struct LVIValueHandle : public CallbackVH {
303 LazyValueInfoCache *Parent;
304
305 LVIValueHandle(Value *V, LazyValueInfoCache *P)
306 : CallbackVH(V), Parent(P) { }
307
308 void deleted();
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000309 void allUsesReplacedWith(Value *V) {
Owen Anderson7f9cb742010-07-30 23:59:40 +0000310 deleted();
311 }
Owen Anderson7f9cb742010-07-30 23:59:40 +0000312 };
313
Chris Lattner2c5adf82009-11-15 19:59:49 +0000314 /// ValueCache - This is all of the cached information for all values,
315 /// mapped from Value* to key information.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000316 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000317
318 /// OverDefinedCache - This tracks, on a per-block basis, the set of
319 /// values that are over-defined at the end of that block. This is required
320 /// for cache updating.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000321 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > OverDefinedCache;
Owen Anderson7f9cb742010-07-30 23:59:40 +0000322
Owen Andersonf33b3022010-12-09 06:14:58 +0000323 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000324 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
325 LVILatticeVal &Result);
326 bool hasBlockValue(Value *Val, BasicBlock *BB);
327
328 // These methods process one work item and may add more. A false value
329 // returned means that the work item was not completely processed and must
330 // be revisited after going through the new items.
331 bool solveBlockValue(Value *Val, BasicBlock *BB);
332 bool solveBlockValueNonLocal(Value *Val, BasicBlock *BB);
333 bool solveBlockValuePHINode(PHINode *PN, BasicBlock *BB);
334 bool solveBlockValueConstantRange(Instruction *BBI, BasicBlock *BB);
335
336 void solve();
Owen Andersonf33b3022010-12-09 06:14:58 +0000337
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000338 ValueCacheEntryTy &lookup(Value *V) {
Owen Andersonf33b3022010-12-09 06:14:58 +0000339 return ValueCache[LVIValueHandle(V, this)];
340 }
341
342 LVILatticeVal setBlockValue(Value *V, BasicBlock *BB, LVILatticeVal L,
343 ValueCacheEntryTy &Cache) {
344 if (L.isOverdefined()) OverDefinedCache.insert(std::make_pair(BB, V));
345 return Cache[BB] = L;
346 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000347 LVILatticeVal setBlockValue(Value *V, BasicBlock *BB, LVILatticeVal L) {
348 return setBlockValue(V, BB, L, lookup(V));
349 }
Owen Andersonf33b3022010-12-09 06:14:58 +0000350
Nick Lewycky90862ee2010-12-18 01:00:40 +0000351 struct BlockStackEntry {
352 BlockStackEntry(Value *Val, BasicBlock *BB) : Val(Val), BB(BB) {}
353 Value *Val;
354 BasicBlock *BB;
355 };
356 std::stack<BlockStackEntry> block_value_stack;
357
Chris Lattner2c5adf82009-11-15 19:59:49 +0000358 public:
Chris Lattner2c5adf82009-11-15 19:59:49 +0000359 /// getValueInBlock - This is the query interface to determine the lattice
360 /// value for the specified Value* at the end of the specified block.
361 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
362
363 /// getValueOnEdge - This is the query interface to determine the lattice
364 /// value for the specified Value* that is true on the specified edge.
365 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000366
367 /// threadEdge - This is the update interface to inform the cache that an
368 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
369 /// NewSucc.
370 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000371
372 /// eraseBlock - This is part of the update interface to inform the cache
373 /// that a block has been deleted.
374 void eraseBlock(BasicBlock *BB);
375
376 /// clear - Empty the cache.
377 void clear() {
378 ValueCache.clear();
379 OverDefinedCache.clear();
380 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000381 };
382} // end anonymous namespace
383
Owen Anderson7f9cb742010-07-30 23:59:40 +0000384void LazyValueInfoCache::LVIValueHandle::deleted() {
Owen Anderson00ac77e2010-08-18 18:39:01 +0000385 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
Owen Anderson7f9cb742010-07-30 23:59:40 +0000386 I = Parent->OverDefinedCache.begin(),
387 E = Parent->OverDefinedCache.end();
388 I != E; ) {
Owen Anderson00ac77e2010-08-18 18:39:01 +0000389 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
Owen Anderson7f9cb742010-07-30 23:59:40 +0000390 ++I;
391 if (tmp->second == getValPtr())
392 Parent->OverDefinedCache.erase(tmp);
393 }
Owen Andersoncf6abd22010-08-11 22:36:04 +0000394
395 // This erasure deallocates *this, so it MUST happen after we're done
396 // using any and all members of *this.
397 Parent->ValueCache.erase(*this);
Owen Anderson7f9cb742010-07-30 23:59:40 +0000398}
399
Owen Anderson00ac77e2010-08-18 18:39:01 +0000400void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
401 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
402 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ) {
403 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
404 ++I;
405 if (tmp->first == BB)
406 OverDefinedCache.erase(tmp);
407 }
408
409 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
410 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
411 I->second.erase(BB);
412}
Owen Anderson7f9cb742010-07-30 23:59:40 +0000413
Nick Lewycky90862ee2010-12-18 01:00:40 +0000414void LazyValueInfoCache::solve() {
415 while (!block_value_stack.empty()) {
416 BlockStackEntry &e = block_value_stack.top();
417 if (solveBlockValue(e.Val, e.BB))
418 block_value_stack.pop();
419 }
420}
421
422bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
423 // If already a constant, there is nothing to compute.
424 if (isa<Constant>(Val))
425 return true;
426
427 return lookup(Val).count(BB);
428}
429
Owen Andersonf33b3022010-12-09 06:14:58 +0000430LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000431 // If already a constant, there is nothing to compute.
432 if (Constant *VC = dyn_cast<Constant>(Val))
433 return LVILatticeVal::get(VC);
434
435 return lookup(Val)[BB];
436}
437
438bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
439 if (isa<Constant>(Val))
440 return true;
441
Owen Andersonf33b3022010-12-09 06:14:58 +0000442 ValueCacheEntryTy &Cache = lookup(Val);
443 LVILatticeVal &BBLV = Cache[BB];
Nick Lewycky90862ee2010-12-18 01:00:40 +0000444
Chris Lattner2c5adf82009-11-15 19:59:49 +0000445 // If we've already computed this block's value, return it.
Chris Lattnere5642812009-11-15 20:00:52 +0000446 if (!BBLV.isUndefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000447 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
Nick Lewycky90862ee2010-12-18 01:00:40 +0000448 return true;
Chris Lattnere5642812009-11-15 20:00:52 +0000449 }
450
Chris Lattner2c5adf82009-11-15 19:59:49 +0000451 // Otherwise, this is the first time we're seeing this block. Reset the
452 // lattice value to overdefined, so that cycles will terminate and be
453 // conservatively correct.
454 BBLV.markOverdefined();
455
Chris Lattner2c5adf82009-11-15 19:59:49 +0000456 Instruction *BBI = dyn_cast<Instruction>(Val);
457 if (BBI == 0 || BBI->getParent() != BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000458 return solveBlockValueNonLocal(Val, BB);
Chris Lattner2c5adf82009-11-15 19:59:49 +0000459 }
Chris Lattnere5642812009-11-15 20:00:52 +0000460
Nick Lewycky90862ee2010-12-18 01:00:40 +0000461 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
462 return solveBlockValuePHINode(PN, BB);
463 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000464
465 // We can only analyze the definitions of certain classes of instructions
466 // (integral binops and casts at the moment), so bail if this isn't one.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000467 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000468 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
469 !BBI->getType()->isIntegerTy()) {
470 DEBUG(dbgs() << " compute BB '" << BB->getName()
471 << "' - overdefined because inst def found.\n");
472 Result.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000473 setBlockValue(Val, BB, Result, Cache);
474 return true;
Owen Andersonb81fd622010-08-18 21:11:37 +0000475 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000476
Owen Andersonb81fd622010-08-18 21:11:37 +0000477 // FIXME: We're currently limited to binops with a constant RHS. This should
478 // be improved.
479 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
480 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
481 DEBUG(dbgs() << " compute BB '" << BB->getName()
482 << "' - overdefined because inst def found.\n");
483
484 Result.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000485 setBlockValue(Val, BB, Result, Cache);
486 return true;
487 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000488
Nick Lewycky90862ee2010-12-18 01:00:40 +0000489 return solveBlockValueConstantRange(BBI, BB);
490}
491
492static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
493 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
494 return L->getPointerAddressSpace() == 0 &&
495 GetUnderlyingObject(L->getPointerOperand()) ==
496 GetUnderlyingObject(Ptr);
497 }
498 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
499 return S->getPointerAddressSpace() == 0 &&
500 GetUnderlyingObject(S->getPointerOperand()) ==
501 GetUnderlyingObject(Ptr);
502 }
503 // FIXME: llvm.memset, etc.
504 return false;
505}
506
507bool LazyValueInfoCache::solveBlockValueNonLocal(Value *Val, BasicBlock *BB) {
508 LVILatticeVal Result; // Start Undefined.
509
510 // If this is a pointer, and there's a load from that pointer in this BB,
511 // then we know that the pointer can't be NULL.
512 bool NotNull = false;
513 if (Val->getType()->isPointerTy()) {
514 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
515 if (InstructionDereferencesPointer(BI, Val)) {
516 NotNull = true;
517 break;
518 }
519 }
520 }
521
522 // If this is the entry block, we must be asking about an argument. The
523 // value is overdefined.
524 if (BB == &BB->getParent()->getEntryBlock()) {
525 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
526 if (NotNull) {
527 const PointerType *PTy = cast<PointerType>(Val->getType());
528 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
529 } else {
530 Result.markOverdefined();
531 }
532 setBlockValue(Val, BB, Result);
533 return true;
534 }
535
536 // Loop over all of our predecessors, merging what we know from them into
537 // result.
538 bool EdgesMissing = false;
539 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
540 LVILatticeVal EdgeResult;
541 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
542 if (EdgesMissing)
543 continue;
544
545 Result.mergeIn(EdgeResult);
546
547 // If we hit overdefined, exit early. The BlockVals entry is already set
548 // to overdefined.
549 if (Result.isOverdefined()) {
550 DEBUG(dbgs() << " compute BB '" << BB->getName()
551 << "' - overdefined because of pred.\n");
552 // If we previously determined that this is a pointer that can't be null
553 // then return that rather than giving up entirely.
554 if (NotNull) {
555 const PointerType *PTy = cast<PointerType>(Val->getType());
556 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
557 }
558 setBlockValue(Val, BB, Result);
559 return true;
560 }
561 }
562 if (EdgesMissing)
563 return false;
564
565 // Return the merged value, which is more precise than 'overdefined'.
566 assert(!Result.isOverdefined());
567 setBlockValue(Val, BB, Result);
568 return true;
569}
570
571bool LazyValueInfoCache::solveBlockValuePHINode(PHINode *PN, BasicBlock *BB) {
572 LVILatticeVal Result; // Start Undefined.
573
574 // Loop over all of our predecessors, merging what we know from them into
575 // result.
576 bool EdgesMissing = false;
577 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
578 BasicBlock *PhiBB = PN->getIncomingBlock(i);
579 Value *PhiVal = PN->getIncomingValue(i);
580 LVILatticeVal EdgeResult;
581 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
582 if (EdgesMissing)
583 continue;
584
585 Result.mergeIn(EdgeResult);
586
587 // If we hit overdefined, exit early. The BlockVals entry is already set
588 // to overdefined.
589 if (Result.isOverdefined()) {
590 DEBUG(dbgs() << " compute BB '" << BB->getName()
591 << "' - overdefined because of pred.\n");
592 setBlockValue(PN, BB, Result);
593 return true;
594 }
595 }
596 if (EdgesMissing)
597 return false;
598
599 // Return the merged value, which is more precise than 'overdefined'.
600 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
601 setBlockValue(PN, BB, Result);
602 return true;
603}
604
605bool LazyValueInfoCache::solveBlockValueConstantRange(Instruction *BBI,
606 BasicBlock *BB) {
Owen Andersonb81fd622010-08-18 21:11:37 +0000607 // Figure out the range of the LHS. If that fails, bail.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000608 if (!hasBlockValue(BBI->getOperand(0), BB)) {
609 block_value_stack.push(BlockStackEntry(BBI->getOperand(0), BB));
610 return false;
611 }
612
613 LVILatticeVal Result;
614 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Owen Andersonb81fd622010-08-18 21:11:37 +0000615 if (!LHSVal.isConstantRange()) {
616 Result.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000617 setBlockValue(BBI, BB, Result);
618 return true;
Owen Andersonb81fd622010-08-18 21:11:37 +0000619 }
620
Owen Andersonb81fd622010-08-18 21:11:37 +0000621 ConstantRange LHSRange = LHSVal.getConstantRange();
622 ConstantRange RHSRange(1);
623 const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
624 if (isa<BinaryOperator>(BBI)) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000625 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
626 RHSRange = ConstantRange(RHS->getValue());
627 } else {
Owen Anderson59b06dc2010-08-24 07:55:44 +0000628 Result.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000629 setBlockValue(BBI, BB, Result);
630 return true;
Owen Anderson59b06dc2010-08-24 07:55:44 +0000631 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000632 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000633
Owen Andersonb81fd622010-08-18 21:11:37 +0000634 // NOTE: We're currently limited by the set of operations that ConstantRange
635 // can evaluate symbolically. Enhancing that set will allows us to analyze
636 // more definitions.
637 switch (BBI->getOpcode()) {
638 case Instruction::Add:
639 Result.markConstantRange(LHSRange.add(RHSRange));
640 break;
641 case Instruction::Sub:
642 Result.markConstantRange(LHSRange.sub(RHSRange));
643 break;
644 case Instruction::Mul:
645 Result.markConstantRange(LHSRange.multiply(RHSRange));
646 break;
647 case Instruction::UDiv:
648 Result.markConstantRange(LHSRange.udiv(RHSRange));
649 break;
650 case Instruction::Shl:
651 Result.markConstantRange(LHSRange.shl(RHSRange));
652 break;
653 case Instruction::LShr:
654 Result.markConstantRange(LHSRange.lshr(RHSRange));
655 break;
656 case Instruction::Trunc:
657 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
658 break;
659 case Instruction::SExt:
660 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
661 break;
662 case Instruction::ZExt:
663 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
664 break;
665 case Instruction::BitCast:
666 Result.markConstantRange(LHSRange);
667 break;
Nick Lewycky198381e2010-09-07 05:39:02 +0000668 case Instruction::And:
669 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
670 break;
671 case Instruction::Or:
672 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
673 break;
Owen Andersonb81fd622010-08-18 21:11:37 +0000674
675 // Unhandled instructions are overdefined.
676 default:
677 DEBUG(dbgs() << " compute BB '" << BB->getName()
678 << "' - overdefined because inst def found.\n");
679 Result.markOverdefined();
680 break;
681 }
682
Nick Lewycky90862ee2010-12-18 01:00:40 +0000683 setBlockValue(BBI, BB, Result);
684 return true;
Chris Lattner10f2d132009-11-11 00:22:30 +0000685}
686
Chris Lattner800c47e2009-11-15 20:02:12 +0000687/// getEdgeValue - This method attempts to infer more complex
Nick Lewycky90862ee2010-12-18 01:00:40 +0000688bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
689 BasicBlock *BBTo, LVILatticeVal &Result) {
690 // If already a constant, there is nothing to compute.
691 if (Constant *VC = dyn_cast<Constant>(Val)) {
692 Result = LVILatticeVal::get(VC);
693 return true;
694 }
695
Chris Lattner800c47e2009-11-15 20:02:12 +0000696 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
697 // know that v != 0.
Chris Lattner16976522009-11-11 22:48:44 +0000698 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
699 // If this is a conditional branch and only one successor goes to BBTo, then
700 // we maybe able to infer something from the condition.
701 if (BI->isConditional() &&
702 BI->getSuccessor(0) != BI->getSuccessor(1)) {
703 bool isTrueDest = BI->getSuccessor(0) == BBTo;
704 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
705 "BBTo isn't a successor of BBFrom");
706
707 // If V is the condition of the branch itself, then we know exactly what
708 // it is.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000709 if (BI->getCondition() == Val) {
710 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson9f014062010-08-10 20:03:09 +0000711 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000712 return true;
713 }
Chris Lattner16976522009-11-11 22:48:44 +0000714
715 // If the condition of the branch is an equality comparison, we may be
716 // able to infer the value.
Owen Anderson2d0f2472010-08-11 04:24:25 +0000717 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
718 if (ICI && ICI->getOperand(0) == Val &&
719 isa<Constant>(ICI->getOperand(1))) {
720 if (ICI->isEquality()) {
721 // We know that V has the RHS constant if this is a true SETEQ or
722 // false SETNE.
723 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
Nick Lewycky90862ee2010-12-18 01:00:40 +0000724 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
725 else
726 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
727 return true;
Chris Lattner16976522009-11-11 22:48:44 +0000728 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000729
Owen Anderson2d0f2472010-08-11 04:24:25 +0000730 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
731 // Calculate the range of values that would satisfy the comparison.
732 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
733 ConstantRange TrueValues =
734 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000735
Owen Anderson2d0f2472010-08-11 04:24:25 +0000736 // If we're interested in the false dest, invert the condition.
737 if (!isTrueDest) TrueValues = TrueValues.inverse();
738
739 // Figure out the possible values of the query BEFORE this branch.
Owen Andersonf33b3022010-12-09 06:14:58 +0000740 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000741 if (!InBlock.isConstantRange()) {
742 Result = LVILatticeVal::getRange(TrueValues);
743 return true;
744 }
745
Owen Anderson2d0f2472010-08-11 04:24:25 +0000746 // Find all potential values that satisfy both the input and output
747 // conditions.
748 ConstantRange PossibleValues =
749 TrueValues.intersectWith(InBlock.getConstantRange());
Nick Lewycky90862ee2010-12-18 01:00:40 +0000750
751 Result = LVILatticeVal::getRange(PossibleValues);
752 return true;
Owen Anderson2d0f2472010-08-11 04:24:25 +0000753 }
754 }
Chris Lattner16976522009-11-11 22:48:44 +0000755 }
756 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000757
758 // If the edge was formed by a switch on the value, then we may know exactly
759 // what it is.
760 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Owen Andersondae90c62010-08-24 21:59:42 +0000761 if (SI->getCondition() == Val) {
Owen Anderson4caef602010-09-02 22:16:52 +0000762 // We don't know anything in the default case.
Owen Andersondae90c62010-08-24 21:59:42 +0000763 if (SI->getDefaultDest() == BBTo) {
Owen Anderson4caef602010-09-02 22:16:52 +0000764 Result.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000765 return true;
Owen Andersondae90c62010-08-24 21:59:42 +0000766 }
767
Chris Lattner800c47e2009-11-15 20:02:12 +0000768 // We only know something if there is exactly one value that goes from
769 // BBFrom to BBTo.
770 unsigned NumEdges = 0;
771 ConstantInt *EdgeVal = 0;
772 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
773 if (SI->getSuccessor(i) != BBTo) continue;
774 if (NumEdges++) break;
775 EdgeVal = SI->getCaseValue(i);
776 }
777 assert(EdgeVal && "Missing successor?");
Nick Lewycky90862ee2010-12-18 01:00:40 +0000778 if (NumEdges == 1) {
779 Result = LVILatticeVal::get(EdgeVal);
780 return true;
781 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000782 }
783 }
Chris Lattner16976522009-11-11 22:48:44 +0000784
785 // Otherwise see if the value is known in the block.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000786 if (hasBlockValue(Val, BBFrom)) {
787 Result = getBlockValue(Val, BBFrom);
788 return true;
789 }
790 block_value_stack.push(BlockStackEntry(Val, BBFrom));
791 return false;
Chris Lattner16976522009-11-11 22:48:44 +0000792}
793
Chris Lattner2c5adf82009-11-15 19:59:49 +0000794LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
David Greene5d93a1f2009-12-23 20:43:58 +0000795 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000796 << BB->getName() << "'\n");
797
Nick Lewycky90862ee2010-12-18 01:00:40 +0000798 block_value_stack.push(BlockStackEntry(V, BB));
799 solve();
Owen Andersonf33b3022010-12-09 06:14:58 +0000800 LVILatticeVal Result = getBlockValue(V, BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000801
David Greene5d93a1f2009-12-23 20:43:58 +0000802 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000803 return Result;
804}
Chris Lattner16976522009-11-11 22:48:44 +0000805
Chris Lattner2c5adf82009-11-15 19:59:49 +0000806LVILatticeVal LazyValueInfoCache::
807getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
David Greene5d93a1f2009-12-23 20:43:58 +0000808 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000809 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000810
Nick Lewycky90862ee2010-12-18 01:00:40 +0000811 LVILatticeVal Result;
812 if (!getEdgeValue(V, FromBB, ToBB, Result)) {
813 solve();
814 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
815 (void)WasFastQuery;
816 assert(WasFastQuery && "More work to do after problem solved?");
817 }
818
David Greene5d93a1f2009-12-23 20:43:58 +0000819 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000820 return Result;
821}
822
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000823void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
824 BasicBlock *NewSucc) {
825 // When an edge in the graph has been threaded, values that we could not
826 // determine a value for before (i.e. were marked overdefined) may be possible
827 // to solve now. We do NOT try to proactively update these values. Instead,
828 // we clear their entries from the cache, and allow lazy updating to recompute
829 // them when needed.
830
831 // The updating process is fairly simple: we need to dropped cached info
832 // for all values that were marked overdefined in OldSucc, and for those same
833 // values in any successor of OldSucc (except NewSucc) in which they were
834 // also marked overdefined.
835 std::vector<BasicBlock*> worklist;
836 worklist.push_back(OldSucc);
837
Owen Anderson9a65dc92010-07-27 23:58:11 +0000838 DenseSet<Value*> ClearSet;
Owen Anderson00ac77e2010-08-18 18:39:01 +0000839 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
Owen Anderson9a65dc92010-07-27 23:58:11 +0000840 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
841 if (I->first == OldSucc)
842 ClearSet.insert(I->second);
843 }
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000844
845 // Use a worklist to perform a depth-first search of OldSucc's successors.
846 // NOTE: We do not need a visited list since any blocks we have already
847 // visited will have had their overdefined markers cleared already, and we
848 // thus won't loop to their successors.
849 while (!worklist.empty()) {
850 BasicBlock *ToUpdate = worklist.back();
851 worklist.pop_back();
852
853 // Skip blocks only accessible through NewSucc.
854 if (ToUpdate == NewSucc) continue;
855
856 bool changed = false;
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000857 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000858 I != E; ++I) {
859 // If a value was marked overdefined in OldSucc, and is here too...
Owen Anderson00ac77e2010-08-18 18:39:01 +0000860 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator OI =
Owen Anderson9a65dc92010-07-27 23:58:11 +0000861 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
862 if (OI == OverDefinedCache.end()) continue;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000863
Owen Anderson9a65dc92010-07-27 23:58:11 +0000864 // Remove it from the caches.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000865 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
Owen Anderson9a65dc92010-07-27 23:58:11 +0000866 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000867
Owen Anderson9a65dc92010-07-27 23:58:11 +0000868 assert(CI != Entry.end() && "Couldn't find entry to update?");
869 Entry.erase(CI);
870 OverDefinedCache.erase(OI);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000871
Owen Anderson9a65dc92010-07-27 23:58:11 +0000872 // If we removed anything, then we potentially need to update
873 // blocks successors too.
874 changed = true;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000875 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000876
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000877 if (!changed) continue;
878
879 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
880 }
881}
882
Chris Lattner2c5adf82009-11-15 19:59:49 +0000883//===----------------------------------------------------------------------===//
884// LazyValueInfo Impl
885//===----------------------------------------------------------------------===//
886
Chris Lattner2c5adf82009-11-15 19:59:49 +0000887/// getCache - This lazily constructs the LazyValueInfoCache.
888static LazyValueInfoCache &getCache(void *&PImpl) {
889 if (!PImpl)
890 PImpl = new LazyValueInfoCache();
891 return *static_cast<LazyValueInfoCache*>(PImpl);
892}
893
Owen Anderson00ac77e2010-08-18 18:39:01 +0000894bool LazyValueInfo::runOnFunction(Function &F) {
895 if (PImpl)
896 getCache(PImpl).clear();
897
898 TD = getAnalysisIfAvailable<TargetData>();
899 // Fully lazy.
900 return false;
901}
902
Chris Lattner2c5adf82009-11-15 19:59:49 +0000903void LazyValueInfo::releaseMemory() {
904 // If the cache was allocated, free it.
905 if (PImpl) {
906 delete &getCache(PImpl);
907 PImpl = 0;
908 }
909}
910
911Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
912 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
913
Chris Lattner16976522009-11-11 22:48:44 +0000914 if (Result.isConstant())
915 return Result.getConstant();
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000916 if (Result.isConstantRange()) {
Owen Andersonee61fcf2010-08-27 23:29:38 +0000917 ConstantRange CR = Result.getConstantRange();
918 if (const APInt *SingleVal = CR.getSingleElement())
919 return ConstantInt::get(V->getContext(), *SingleVal);
920 }
Chris Lattner16976522009-11-11 22:48:44 +0000921 return 0;
922}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000923
Chris Lattner38392bb2009-11-12 01:29:10 +0000924/// getConstantOnEdge - Determine whether the specified value is known to be a
925/// constant on the specified edge. Return null if not.
926Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
927 BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000928 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattner38392bb2009-11-12 01:29:10 +0000929
930 if (Result.isConstant())
931 return Result.getConstant();
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000932 if (Result.isConstantRange()) {
Owen Anderson9f014062010-08-10 20:03:09 +0000933 ConstantRange CR = Result.getConstantRange();
934 if (const APInt *SingleVal = CR.getSingleElement())
935 return ConstantInt::get(V->getContext(), *SingleVal);
936 }
Chris Lattner38392bb2009-11-12 01:29:10 +0000937 return 0;
938}
939
Chris Lattnerb52675b2009-11-12 04:36:58 +0000940/// getPredicateOnEdge - Determine whether the specified value comparison
941/// with a constant is known to be true or false on the specified CFG edge.
942/// Pred is a CmpInst predicate.
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000943LazyValueInfo::Tristate
Chris Lattnerb52675b2009-11-12 04:36:58 +0000944LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
945 BasicBlock *FromBB, BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000946 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000947
Chris Lattnerb52675b2009-11-12 04:36:58 +0000948 // If we know the value is a constant, evaluate the conditional.
949 Constant *Res = 0;
950 if (Result.isConstant()) {
951 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000952 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Chris Lattnerb52675b2009-11-12 04:36:58 +0000953 return ResCI->isZero() ? False : True;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000954 return Unknown;
955 }
956
Owen Anderson9f014062010-08-10 20:03:09 +0000957 if (Result.isConstantRange()) {
Owen Anderson59b06dc2010-08-24 07:55:44 +0000958 ConstantInt *CI = dyn_cast<ConstantInt>(C);
959 if (!CI) return Unknown;
960
Owen Anderson9f014062010-08-10 20:03:09 +0000961 ConstantRange CR = Result.getConstantRange();
962 if (Pred == ICmpInst::ICMP_EQ) {
963 if (!CR.contains(CI->getValue()))
964 return False;
965
966 if (CR.isSingleElement() && CR.contains(CI->getValue()))
967 return True;
968 } else if (Pred == ICmpInst::ICMP_NE) {
969 if (!CR.contains(CI->getValue()))
970 return True;
971
972 if (CR.isSingleElement() && CR.contains(CI->getValue()))
973 return False;
974 }
975
976 // Handle more complex predicates.
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000977 ConstantRange TrueValues =
978 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
979 if (TrueValues.contains(CR))
Owen Anderson9f014062010-08-10 20:03:09 +0000980 return True;
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000981 if (TrueValues.inverse().contains(CR))
982 return False;
Owen Anderson9f014062010-08-10 20:03:09 +0000983 return Unknown;
984 }
985
Chris Lattner2c5adf82009-11-15 19:59:49 +0000986 if (Result.isNotConstant()) {
Chris Lattnerb52675b2009-11-12 04:36:58 +0000987 // If this is an equality comparison, we can try to fold it knowing that
988 // "V != C1".
989 if (Pred == ICmpInst::ICMP_EQ) {
990 // !C1 == C -> false iff C1 == C.
991 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
992 Result.getNotConstant(), C, TD);
993 if (Res->isNullValue())
994 return False;
995 } else if (Pred == ICmpInst::ICMP_NE) {
996 // !C1 != C -> true iff C1 == C.
Chris Lattner5553a3a2009-11-15 20:01:24 +0000997 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chris Lattnerb52675b2009-11-12 04:36:58 +0000998 Result.getNotConstant(), C, TD);
999 if (Res->isNullValue())
1000 return True;
1001 }
Chris Lattner2c5adf82009-11-15 19:59:49 +00001002 return Unknown;
Chris Lattnerb52675b2009-11-12 04:36:58 +00001003 }
1004
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001005 return Unknown;
1006}
1007
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001008void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001009 BasicBlock *NewSucc) {
Owen Anderson00ac77e2010-08-18 18:39:01 +00001010 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1011}
1012
1013void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1014 if (PImpl) getCache(PImpl).eraseBlock(BB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001015}