blob: e1c099e43560034b10caa399cf6f10e2d0fcbd6b [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"
Owen Anderson9a65dc92010-07-27 23:58:11 +000029#include "llvm/ADT/DenseSet.h"
Chris Lattnere5642812009-11-15 20:00:52 +000030#include "llvm/ADT/STLExtras.h"
Bill Wendlingaa8b9942012-01-11 23:43:34 +000031#include <map>
Nick Lewycky90862ee2010-12-18 01:00:40 +000032#include <stack>
Chris Lattner10f2d132009-11-11 00:22:30 +000033using namespace llvm;
34
35char LazyValueInfo::ID = 0;
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
Owen Anderson89778462011-01-05 21:15:29 +0000311namespace {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000312 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
313 /// maintains information about queries across the clients' queries.
314 class LazyValueInfoCache {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000315 /// ValueCacheEntryTy - This is all of the cached block information for
316 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
317 /// entries, allowing us to do a lookup with a binary search.
Bill Wendlingaa8b9942012-01-11 23:43:34 +0000318 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000319
Owen Andersone68713a2011-01-05 23:26:22 +0000320 /// ValueCache - This is all of the cached information for all values,
321 /// mapped from Value* to key information.
Bill Wendling805e2242012-01-12 01:41:03 +0000322 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
Owen Andersone68713a2011-01-05 23:26:22 +0000323
324 /// OverDefinedCache - This tracks, on a per-block basis, the set of
325 /// values that are over-defined at the end of that block. This is required
326 /// for cache updating.
327 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
328 DenseSet<OverDefinedPairTy> OverDefinedCache;
Benjamin Kramerfeb9b4b2011-12-03 15:16:45 +0000329
330 /// SeenBlocks - Keep track of all blocks that we have ever seen, so we
331 /// don't spend time removing unused blocks from our caches.
332 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
333
Owen Andersone68713a2011-01-05 23:26:22 +0000334 /// BlockValueStack - This stack holds the state of the value solver
335 /// during a query. It basically emulates the callstack of the naive
336 /// recursive value lookup process.
337 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
338
Owen Anderson89778462011-01-05 21:15:29 +0000339 friend struct LVIValueHandle;
Owen Anderson87790ab2010-12-20 19:33:41 +0000340
341 /// OverDefinedCacheUpdater - A helper object that ensures that the
342 /// OverDefinedCache is updated whenever solveBlockValue returns.
343 struct OverDefinedCacheUpdater {
344 LazyValueInfoCache *Parent;
345 Value *Val;
346 BasicBlock *BB;
347 LVILatticeVal &BBLV;
348
349 OverDefinedCacheUpdater(Value *V, BasicBlock *B, LVILatticeVal &LV,
350 LazyValueInfoCache *P)
351 : Parent(P), Val(V), BB(B), BBLV(LV) { }
352
353 bool markResult(bool changed) {
354 if (changed && BBLV.isOverdefined())
355 Parent->OverDefinedCache.insert(std::make_pair(BB, Val));
356 return changed;
357 }
358 };
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000359
Owen Andersone68713a2011-01-05 23:26:22 +0000360
Owen Anderson7f9cb742010-07-30 23:59:40 +0000361
Owen Andersonf33b3022010-12-09 06:14:58 +0000362 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000363 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
364 LVILatticeVal &Result);
365 bool hasBlockValue(Value *Val, BasicBlock *BB);
366
367 // These methods process one work item and may add more. A false value
368 // returned means that the work item was not completely processed and must
369 // be revisited after going through the new items.
370 bool solveBlockValue(Value *Val, BasicBlock *BB);
Owen Anderson61863942010-12-20 18:18:16 +0000371 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
372 Value *Val, BasicBlock *BB);
373 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
374 PHINode *PN, BasicBlock *BB);
375 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
376 Instruction *BBI, BasicBlock *BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000377
378 void solve();
Owen Andersonf33b3022010-12-09 06:14:58 +0000379
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000380 ValueCacheEntryTy &lookup(Value *V) {
Owen Andersonf33b3022010-12-09 06:14:58 +0000381 return ValueCache[LVIValueHandle(V, this)];
382 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000383
Chris Lattner2c5adf82009-11-15 19:59:49 +0000384 public:
Chris Lattner2c5adf82009-11-15 19:59:49 +0000385 /// getValueInBlock - This is the query interface to determine the lattice
386 /// value for the specified Value* at the end of the specified block.
387 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
388
389 /// getValueOnEdge - This is the query interface to determine the lattice
390 /// value for the specified Value* that is true on the specified edge.
391 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000392
393 /// threadEdge - This is the update interface to inform the cache that an
394 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
395 /// NewSucc.
396 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000397
398 /// eraseBlock - This is part of the update interface to inform the cache
399 /// that a block has been deleted.
400 void eraseBlock(BasicBlock *BB);
401
402 /// clear - Empty the cache.
403 void clear() {
Benjamin Kramerc00c05f2011-12-03 15:19:55 +0000404 SeenBlocks.clear();
Owen Anderson00ac77e2010-08-18 18:39:01 +0000405 ValueCache.clear();
406 OverDefinedCache.clear();
407 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000408 };
409} // end anonymous namespace
410
Owen Anderson89778462011-01-05 21:15:29 +0000411void LVIValueHandle::deleted() {
412 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
413
414 SmallVector<OverDefinedPairTy, 4> ToErase;
415 for (DenseSet<OverDefinedPairTy>::iterator
Owen Anderson7f9cb742010-07-30 23:59:40 +0000416 I = Parent->OverDefinedCache.begin(),
417 E = Parent->OverDefinedCache.end();
Owen Anderson89778462011-01-05 21:15:29 +0000418 I != E; ++I) {
419 if (I->second == getValPtr())
420 ToErase.push_back(*I);
Owen Anderson7f9cb742010-07-30 23:59:40 +0000421 }
Owen Andersoncf6abd22010-08-11 22:36:04 +0000422
Owen Anderson89778462011-01-05 21:15:29 +0000423 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
424 E = ToErase.end(); I != E; ++I)
425 Parent->OverDefinedCache.erase(*I);
426
Owen Andersoncf6abd22010-08-11 22:36:04 +0000427 // This erasure deallocates *this, so it MUST happen after we're done
428 // using any and all members of *this.
429 Parent->ValueCache.erase(*this);
Owen Anderson7f9cb742010-07-30 23:59:40 +0000430}
431
Owen Anderson00ac77e2010-08-18 18:39:01 +0000432void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
Benjamin Kramerfeb9b4b2011-12-03 15:16:45 +0000433 // Shortcut if we have never seen this block.
434 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
435 if (I == SeenBlocks.end())
436 return;
437 SeenBlocks.erase(I);
438
Owen Anderson89778462011-01-05 21:15:29 +0000439 SmallVector<OverDefinedPairTy, 4> ToErase;
440 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
441 E = OverDefinedCache.end(); I != E; ++I) {
442 if (I->first == BB)
443 ToErase.push_back(*I);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000444 }
Owen Anderson89778462011-01-05 21:15:29 +0000445
446 for (SmallVector<OverDefinedPairTy, 4>::iterator I = ToErase.begin(),
447 E = ToErase.end(); I != E; ++I)
448 OverDefinedCache.erase(*I);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000449
Bill Wendling805e2242012-01-12 01:41:03 +0000450 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
Owen Anderson00ac77e2010-08-18 18:39:01 +0000451 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
452 I->second.erase(BB);
453}
Owen Anderson7f9cb742010-07-30 23:59:40 +0000454
Nick Lewycky90862ee2010-12-18 01:00:40 +0000455void LazyValueInfoCache::solve() {
Owen Andersone68713a2011-01-05 23:26:22 +0000456 while (!BlockValueStack.empty()) {
457 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
Owen Anderson87790ab2010-12-20 19:33:41 +0000458 if (solveBlockValue(e.second, e.first))
Owen Andersone68713a2011-01-05 23:26:22 +0000459 BlockValueStack.pop();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000460 }
461}
462
463bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
464 // If already a constant, there is nothing to compute.
465 if (isa<Constant>(Val))
466 return true;
467
Owen Anderson89778462011-01-05 21:15:29 +0000468 LVIValueHandle ValHandle(Val, this);
469 if (!ValueCache.count(ValHandle)) return false;
470 return ValueCache[ValHandle].count(BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000471}
472
Owen Andersonf33b3022010-12-09 06:14:58 +0000473LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000474 // If already a constant, there is nothing to compute.
475 if (Constant *VC = dyn_cast<Constant>(Val))
476 return LVILatticeVal::get(VC);
477
Benjamin Kramerfeb9b4b2011-12-03 15:16:45 +0000478 SeenBlocks.insert(BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000479 return lookup(Val)[BB];
480}
481
482bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
483 if (isa<Constant>(Val))
484 return true;
485
Owen Andersonf33b3022010-12-09 06:14:58 +0000486 ValueCacheEntryTy &Cache = lookup(Val);
Benjamin Kramerfeb9b4b2011-12-03 15:16:45 +0000487 SeenBlocks.insert(BB);
Owen Andersonf33b3022010-12-09 06:14:58 +0000488 LVILatticeVal &BBLV = Cache[BB];
Owen Anderson87790ab2010-12-20 19:33:41 +0000489
490 // OverDefinedCacheUpdater is a helper object that will update
491 // the OverDefinedCache for us when this method exits. Make sure to
492 // call markResult on it as we exist, passing a bool to indicate if the
493 // cache needs updating, i.e. if we have solve a new value or not.
494 OverDefinedCacheUpdater ODCacheUpdater(Val, BB, BBLV, this);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000495
Chris Lattner2c5adf82009-11-15 19:59:49 +0000496 // If we've already computed this block's value, return it.
Chris Lattnere5642812009-11-15 20:00:52 +0000497 if (!BBLV.isUndefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000498 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
Owen Anderson87790ab2010-12-20 19:33:41 +0000499
500 // Since we're reusing a cached value here, we don't need to update the
501 // OverDefinedCahce. The cache will have been properly updated
502 // whenever the cached value was inserted.
503 ODCacheUpdater.markResult(false);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000504 return true;
Chris Lattnere5642812009-11-15 20:00:52 +0000505 }
506
Chris Lattner2c5adf82009-11-15 19:59:49 +0000507 // Otherwise, this is the first time we're seeing this block. Reset the
508 // lattice value to overdefined, so that cycles will terminate and be
509 // conservatively correct.
510 BBLV.markOverdefined();
511
Chris Lattner2c5adf82009-11-15 19:59:49 +0000512 Instruction *BBI = dyn_cast<Instruction>(Val);
513 if (BBI == 0 || BBI->getParent() != BB) {
Owen Anderson87790ab2010-12-20 19:33:41 +0000514 return ODCacheUpdater.markResult(solveBlockValueNonLocal(BBLV, Val, BB));
Chris Lattner2c5adf82009-11-15 19:59:49 +0000515 }
Chris Lattnere5642812009-11-15 20:00:52 +0000516
Nick Lewycky90862ee2010-12-18 01:00:40 +0000517 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Owen Anderson87790ab2010-12-20 19:33:41 +0000518 return ODCacheUpdater.markResult(solveBlockValuePHINode(BBLV, PN, BB));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000519 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000520
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000521 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
522 BBLV = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
523 return ODCacheUpdater.markResult(true);
524 }
525
Owen Andersonb81fd622010-08-18 21:11:37 +0000526 // We can only analyze the definitions of certain classes of instructions
527 // (integral binops and casts at the moment), so bail if this isn't one.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000528 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000529 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
530 !BBI->getType()->isIntegerTy()) {
531 DEBUG(dbgs() << " compute BB '" << BB->getName()
532 << "' - overdefined because inst def found.\n");
Owen Anderson61863942010-12-20 18:18:16 +0000533 BBLV.markOverdefined();
Owen Anderson87790ab2010-12-20 19:33:41 +0000534 return ODCacheUpdater.markResult(true);
Owen Andersonb81fd622010-08-18 21:11:37 +0000535 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000536
Owen Andersonb81fd622010-08-18 21:11:37 +0000537 // FIXME: We're currently limited to binops with a constant RHS. This should
538 // be improved.
539 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
540 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
541 DEBUG(dbgs() << " compute BB '" << BB->getName()
542 << "' - overdefined because inst def found.\n");
543
Owen Anderson61863942010-12-20 18:18:16 +0000544 BBLV.markOverdefined();
Owen Anderson87790ab2010-12-20 19:33:41 +0000545 return ODCacheUpdater.markResult(true);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000546 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000547
Owen Anderson87790ab2010-12-20 19:33:41 +0000548 return ODCacheUpdater.markResult(solveBlockValueConstantRange(BBLV, BBI, BB));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000549}
550
551static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
552 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
553 return L->getPointerAddressSpace() == 0 &&
554 GetUnderlyingObject(L->getPointerOperand()) ==
555 GetUnderlyingObject(Ptr);
556 }
557 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
558 return S->getPointerAddressSpace() == 0 &&
559 GetUnderlyingObject(S->getPointerOperand()) ==
560 GetUnderlyingObject(Ptr);
561 }
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000562 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
563 if (MI->isVolatile()) return false;
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000564
565 // FIXME: check whether it has a valuerange that excludes zero?
566 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
567 if (!Len || Len->isZero()) return false;
568
Eli Friedman69388e52011-05-31 20:40:16 +0000569 if (MI->getDestAddressSpace() == 0)
570 if (MI->getRawDest() == Ptr || MI->getDest() == Ptr)
571 return true;
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000572 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman69388e52011-05-31 20:40:16 +0000573 if (MTI->getSourceAddressSpace() == 0)
574 if (MTI->getRawSource() == Ptr || MTI->getSource() == Ptr)
575 return true;
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000576 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000577 return false;
578}
579
Owen Anderson61863942010-12-20 18:18:16 +0000580bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
581 Value *Val, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000582 LVILatticeVal Result; // Start Undefined.
583
584 // If this is a pointer, and there's a load from that pointer in this BB,
585 // then we know that the pointer can't be NULL.
586 bool NotNull = false;
587 if (Val->getType()->isPointerTy()) {
Nick Lewycky786c7cd2011-01-15 09:16:12 +0000588 if (isa<AllocaInst>(Val)) {
589 NotNull = true;
590 } else {
591 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
592 if (InstructionDereferencesPointer(BI, Val)) {
593 NotNull = true;
594 break;
595 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000596 }
597 }
598 }
599
600 // If this is the entry block, we must be asking about an argument. The
601 // value is overdefined.
602 if (BB == &BB->getParent()->getEntryBlock()) {
603 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
604 if (NotNull) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000605 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky90862ee2010-12-18 01:00:40 +0000606 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
607 } else {
608 Result.markOverdefined();
609 }
Owen Anderson61863942010-12-20 18:18:16 +0000610 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000611 return true;
612 }
613
614 // Loop over all of our predecessors, merging what we know from them into
615 // result.
616 bool EdgesMissing = false;
617 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
618 LVILatticeVal EdgeResult;
619 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
620 if (EdgesMissing)
621 continue;
622
623 Result.mergeIn(EdgeResult);
624
625 // If we hit overdefined, exit early. The BlockVals entry is already set
626 // to overdefined.
627 if (Result.isOverdefined()) {
628 DEBUG(dbgs() << " compute BB '" << BB->getName()
629 << "' - overdefined because of pred.\n");
630 // If we previously determined that this is a pointer that can't be null
631 // then return that rather than giving up entirely.
632 if (NotNull) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000633 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky90862ee2010-12-18 01:00:40 +0000634 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
635 }
Owen Anderson61863942010-12-20 18:18:16 +0000636
637 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000638 return true;
639 }
640 }
641 if (EdgesMissing)
642 return false;
643
644 // Return the merged value, which is more precise than 'overdefined'.
645 assert(!Result.isOverdefined());
Owen Anderson61863942010-12-20 18:18:16 +0000646 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000647 return true;
648}
649
Owen Anderson61863942010-12-20 18:18:16 +0000650bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
651 PHINode *PN, BasicBlock *BB) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000652 LVILatticeVal Result; // Start Undefined.
653
654 // Loop over all of our predecessors, merging what we know from them into
655 // result.
656 bool EdgesMissing = false;
657 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
658 BasicBlock *PhiBB = PN->getIncomingBlock(i);
659 Value *PhiVal = PN->getIncomingValue(i);
660 LVILatticeVal EdgeResult;
661 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult);
662 if (EdgesMissing)
663 continue;
664
665 Result.mergeIn(EdgeResult);
666
667 // If we hit overdefined, exit early. The BlockVals entry is already set
668 // to overdefined.
669 if (Result.isOverdefined()) {
670 DEBUG(dbgs() << " compute BB '" << BB->getName()
671 << "' - overdefined because of pred.\n");
Owen Anderson61863942010-12-20 18:18:16 +0000672
673 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000674 return true;
675 }
676 }
677 if (EdgesMissing)
678 return false;
679
680 // Return the merged value, which is more precise than 'overdefined'.
681 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson61863942010-12-20 18:18:16 +0000682 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000683 return true;
684}
685
Owen Anderson61863942010-12-20 18:18:16 +0000686bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
687 Instruction *BBI,
Nick Lewycky90862ee2010-12-18 01:00:40 +0000688 BasicBlock *BB) {
Owen Andersonb81fd622010-08-18 21:11:37 +0000689 // Figure out the range of the LHS. If that fails, bail.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000690 if (!hasBlockValue(BBI->getOperand(0), BB)) {
Owen Andersone68713a2011-01-05 23:26:22 +0000691 BlockValueStack.push(std::make_pair(BB, BBI->getOperand(0)));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000692 return false;
693 }
694
Nick Lewycky90862ee2010-12-18 01:00:40 +0000695 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Owen Andersonb81fd622010-08-18 21:11:37 +0000696 if (!LHSVal.isConstantRange()) {
Owen Anderson61863942010-12-20 18:18:16 +0000697 BBLV.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000698 return true;
Owen Andersonb81fd622010-08-18 21:11:37 +0000699 }
700
Owen Andersonb81fd622010-08-18 21:11:37 +0000701 ConstantRange LHSRange = LHSVal.getConstantRange();
702 ConstantRange RHSRange(1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000703 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
Owen Andersonb81fd622010-08-18 21:11:37 +0000704 if (isa<BinaryOperator>(BBI)) {
Nick Lewycky90862ee2010-12-18 01:00:40 +0000705 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
706 RHSRange = ConstantRange(RHS->getValue());
707 } else {
Owen Anderson61863942010-12-20 18:18:16 +0000708 BBLV.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000709 return true;
Owen Anderson59b06dc2010-08-24 07:55:44 +0000710 }
Owen Andersonb81fd622010-08-18 21:11:37 +0000711 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000712
Owen Andersonb81fd622010-08-18 21:11:37 +0000713 // NOTE: We're currently limited by the set of operations that ConstantRange
714 // can evaluate symbolically. Enhancing that set will allows us to analyze
715 // more definitions.
Owen Anderson61863942010-12-20 18:18:16 +0000716 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000717 switch (BBI->getOpcode()) {
718 case Instruction::Add:
719 Result.markConstantRange(LHSRange.add(RHSRange));
720 break;
721 case Instruction::Sub:
722 Result.markConstantRange(LHSRange.sub(RHSRange));
723 break;
724 case Instruction::Mul:
725 Result.markConstantRange(LHSRange.multiply(RHSRange));
726 break;
727 case Instruction::UDiv:
728 Result.markConstantRange(LHSRange.udiv(RHSRange));
729 break;
730 case Instruction::Shl:
731 Result.markConstantRange(LHSRange.shl(RHSRange));
732 break;
733 case Instruction::LShr:
734 Result.markConstantRange(LHSRange.lshr(RHSRange));
735 break;
736 case Instruction::Trunc:
737 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
738 break;
739 case Instruction::SExt:
740 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
741 break;
742 case Instruction::ZExt:
743 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
744 break;
745 case Instruction::BitCast:
746 Result.markConstantRange(LHSRange);
747 break;
Nick Lewycky198381e2010-09-07 05:39:02 +0000748 case Instruction::And:
749 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
750 break;
751 case Instruction::Or:
752 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
753 break;
Owen Andersonb81fd622010-08-18 21:11:37 +0000754
755 // Unhandled instructions are overdefined.
756 default:
757 DEBUG(dbgs() << " compute BB '" << BB->getName()
758 << "' - overdefined because inst def found.\n");
759 Result.markOverdefined();
760 break;
761 }
762
Owen Anderson61863942010-12-20 18:18:16 +0000763 BBLV = Result;
Nick Lewycky90862ee2010-12-18 01:00:40 +0000764 return true;
Chris Lattner10f2d132009-11-11 00:22:30 +0000765}
766
Chris Lattner800c47e2009-11-15 20:02:12 +0000767/// getEdgeValue - This method attempts to infer more complex
Nick Lewycky90862ee2010-12-18 01:00:40 +0000768bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
769 BasicBlock *BBTo, LVILatticeVal &Result) {
770 // If already a constant, there is nothing to compute.
771 if (Constant *VC = dyn_cast<Constant>(Val)) {
772 Result = LVILatticeVal::get(VC);
773 return true;
774 }
775
Chris Lattner800c47e2009-11-15 20:02:12 +0000776 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
777 // know that v != 0.
Chris Lattner16976522009-11-11 22:48:44 +0000778 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
779 // If this is a conditional branch and only one successor goes to BBTo, then
780 // we maybe able to infer something from the condition.
781 if (BI->isConditional() &&
782 BI->getSuccessor(0) != BI->getSuccessor(1)) {
783 bool isTrueDest = BI->getSuccessor(0) == BBTo;
784 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
785 "BBTo isn't a successor of BBFrom");
786
787 // If V is the condition of the branch itself, then we know exactly what
788 // it is.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000789 if (BI->getCondition() == Val) {
790 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson9f014062010-08-10 20:03:09 +0000791 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000792 return true;
793 }
Chris Lattner16976522009-11-11 22:48:44 +0000794
795 // If the condition of the branch is an equality comparison, we may be
796 // able to infer the value.
Owen Anderson2d0f2472010-08-11 04:24:25 +0000797 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
798 if (ICI && ICI->getOperand(0) == Val &&
799 isa<Constant>(ICI->getOperand(1))) {
800 if (ICI->isEquality()) {
801 // We know that V has the RHS constant if this is a true SETEQ or
802 // false SETNE.
803 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
Nick Lewycky90862ee2010-12-18 01:00:40 +0000804 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
805 else
806 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
807 return true;
Chris Lattner16976522009-11-11 22:48:44 +0000808 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000809
Owen Anderson2d0f2472010-08-11 04:24:25 +0000810 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
811 // Calculate the range of values that would satisfy the comparison.
812 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
813 ConstantRange TrueValues =
814 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000815
Owen Anderson2d0f2472010-08-11 04:24:25 +0000816 // If we're interested in the false dest, invert the condition.
817 if (!isTrueDest) TrueValues = TrueValues.inverse();
818
819 // Figure out the possible values of the query BEFORE this branch.
Owen Andersonbe419012011-01-05 21:37:18 +0000820 if (!hasBlockValue(Val, BBFrom)) {
Owen Andersone68713a2011-01-05 23:26:22 +0000821 BlockValueStack.push(std::make_pair(BBFrom, Val));
Owen Andersonbe419012011-01-05 21:37:18 +0000822 return false;
823 }
824
Owen Andersonf33b3022010-12-09 06:14:58 +0000825 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000826 if (!InBlock.isConstantRange()) {
827 Result = LVILatticeVal::getRange(TrueValues);
828 return true;
829 }
830
Owen Anderson2d0f2472010-08-11 04:24:25 +0000831 // Find all potential values that satisfy both the input and output
832 // conditions.
833 ConstantRange PossibleValues =
834 TrueValues.intersectWith(InBlock.getConstantRange());
Nick Lewycky90862ee2010-12-18 01:00:40 +0000835
836 Result = LVILatticeVal::getRange(PossibleValues);
837 return true;
Owen Anderson2d0f2472010-08-11 04:24:25 +0000838 }
839 }
Chris Lattner16976522009-11-11 22:48:44 +0000840 }
841 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000842
843 // If the edge was formed by a switch on the value, then we may know exactly
844 // what it is.
845 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Owen Andersondae90c62010-08-24 21:59:42 +0000846 if (SI->getCondition() == Val) {
Owen Anderson4caef602010-09-02 22:16:52 +0000847 // We don't know anything in the default case.
Owen Andersondae90c62010-08-24 21:59:42 +0000848 if (SI->getDefaultDest() == BBTo) {
Owen Anderson4caef602010-09-02 22:16:52 +0000849 Result.markOverdefined();
Nick Lewycky90862ee2010-12-18 01:00:40 +0000850 return true;
Owen Andersondae90c62010-08-24 21:59:42 +0000851 }
852
Chris Lattner800c47e2009-11-15 20:02:12 +0000853 // We only know something if there is exactly one value that goes from
854 // BBFrom to BBTo.
855 unsigned NumEdges = 0;
856 ConstantInt *EdgeVal = 0;
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +0000857 for (unsigned i = 0, e = SI->getNumCases(); i != e; ++i) {
858 if (SI->getCaseSuccessor(i) != BBTo) continue;
Chris Lattner800c47e2009-11-15 20:02:12 +0000859 if (NumEdges++) break;
860 EdgeVal = SI->getCaseValue(i);
861 }
862 assert(EdgeVal && "Missing successor?");
Nick Lewycky90862ee2010-12-18 01:00:40 +0000863 if (NumEdges == 1) {
864 Result = LVILatticeVal::get(EdgeVal);
865 return true;
866 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000867 }
868 }
Chris Lattner16976522009-11-11 22:48:44 +0000869
870 // Otherwise see if the value is known in the block.
Nick Lewycky90862ee2010-12-18 01:00:40 +0000871 if (hasBlockValue(Val, BBFrom)) {
872 Result = getBlockValue(Val, BBFrom);
873 return true;
874 }
Owen Andersone68713a2011-01-05 23:26:22 +0000875 BlockValueStack.push(std::make_pair(BBFrom, Val));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000876 return false;
Chris Lattner16976522009-11-11 22:48:44 +0000877}
878
Chris Lattner2c5adf82009-11-15 19:59:49 +0000879LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
David Greene5d93a1f2009-12-23 20:43:58 +0000880 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000881 << BB->getName() << "'\n");
882
Owen Andersone68713a2011-01-05 23:26:22 +0000883 BlockValueStack.push(std::make_pair(BB, V));
Nick Lewycky90862ee2010-12-18 01:00:40 +0000884 solve();
Owen Andersonf33b3022010-12-09 06:14:58 +0000885 LVILatticeVal Result = getBlockValue(V, BB);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000886
David Greene5d93a1f2009-12-23 20:43:58 +0000887 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000888 return Result;
889}
Chris Lattner16976522009-11-11 22:48:44 +0000890
Chris Lattner2c5adf82009-11-15 19:59:49 +0000891LVILatticeVal LazyValueInfoCache::
892getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
David Greene5d93a1f2009-12-23 20:43:58 +0000893 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000894 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000895
Nick Lewycky90862ee2010-12-18 01:00:40 +0000896 LVILatticeVal Result;
897 if (!getEdgeValue(V, FromBB, ToBB, Result)) {
898 solve();
899 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result);
900 (void)WasFastQuery;
901 assert(WasFastQuery && "More work to do after problem solved?");
902 }
903
David Greene5d93a1f2009-12-23 20:43:58 +0000904 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000905 return Result;
906}
907
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000908void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
909 BasicBlock *NewSucc) {
910 // When an edge in the graph has been threaded, values that we could not
911 // determine a value for before (i.e. were marked overdefined) may be possible
912 // to solve now. We do NOT try to proactively update these values. Instead,
913 // we clear their entries from the cache, and allow lazy updating to recompute
914 // them when needed.
915
916 // The updating process is fairly simple: we need to dropped cached info
917 // for all values that were marked overdefined in OldSucc, and for those same
918 // values in any successor of OldSucc (except NewSucc) in which they were
919 // also marked overdefined.
920 std::vector<BasicBlock*> worklist;
921 worklist.push_back(OldSucc);
922
Owen Anderson9a65dc92010-07-27 23:58:11 +0000923 DenseSet<Value*> ClearSet;
Owen Anderson89778462011-01-05 21:15:29 +0000924 for (DenseSet<OverDefinedPairTy>::iterator I = OverDefinedCache.begin(),
925 E = OverDefinedCache.end(); I != E; ++I) {
Owen Anderson9a65dc92010-07-27 23:58:11 +0000926 if (I->first == OldSucc)
927 ClearSet.insert(I->second);
928 }
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000929
930 // Use a worklist to perform a depth-first search of OldSucc's successors.
931 // NOTE: We do not need a visited list since any blocks we have already
932 // visited will have had their overdefined markers cleared already, and we
933 // thus won't loop to their successors.
934 while (!worklist.empty()) {
935 BasicBlock *ToUpdate = worklist.back();
936 worklist.pop_back();
937
938 // Skip blocks only accessible through NewSucc.
939 if (ToUpdate == NewSucc) continue;
940
941 bool changed = false;
Nick Lewycky69bfdf52010-12-15 18:57:18 +0000942 for (DenseSet<Value*>::iterator I = ClearSet.begin(), E = ClearSet.end();
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000943 I != E; ++I) {
944 // If a value was marked overdefined in OldSucc, and is here too...
Owen Anderson89778462011-01-05 21:15:29 +0000945 DenseSet<OverDefinedPairTy>::iterator OI =
Owen Anderson9a65dc92010-07-27 23:58:11 +0000946 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
947 if (OI == OverDefinedCache.end()) continue;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000948
Owen Anderson9a65dc92010-07-27 23:58:11 +0000949 // Remove it from the caches.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000950 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
Owen Anderson9a65dc92010-07-27 23:58:11 +0000951 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
Nick Lewycky90862ee2010-12-18 01:00:40 +0000952
Owen Anderson9a65dc92010-07-27 23:58:11 +0000953 assert(CI != Entry.end() && "Couldn't find entry to update?");
954 Entry.erase(CI);
955 OverDefinedCache.erase(OI);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000956
Owen Anderson9a65dc92010-07-27 23:58:11 +0000957 // If we removed anything, then we potentially need to update
958 // blocks successors too.
959 changed = true;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000960 }
Nick Lewycky90862ee2010-12-18 01:00:40 +0000961
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000962 if (!changed) continue;
963
964 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
965 }
966}
967
Chris Lattner2c5adf82009-11-15 19:59:49 +0000968//===----------------------------------------------------------------------===//
969// LazyValueInfo Impl
970//===----------------------------------------------------------------------===//
971
Chris Lattner2c5adf82009-11-15 19:59:49 +0000972/// getCache - This lazily constructs the LazyValueInfoCache.
973static LazyValueInfoCache &getCache(void *&PImpl) {
974 if (!PImpl)
975 PImpl = new LazyValueInfoCache();
976 return *static_cast<LazyValueInfoCache*>(PImpl);
977}
978
Owen Anderson00ac77e2010-08-18 18:39:01 +0000979bool LazyValueInfo::runOnFunction(Function &F) {
980 if (PImpl)
981 getCache(PImpl).clear();
Chad Rosieraab8e282011-12-02 01:26:24 +0000982
Owen Anderson00ac77e2010-08-18 18:39:01 +0000983 TD = getAnalysisIfAvailable<TargetData>();
Chad Rosieraab8e282011-12-02 01:26:24 +0000984 TLI = &getAnalysis<TargetLibraryInfo>();
985
Owen Anderson00ac77e2010-08-18 18:39:01 +0000986 // Fully lazy.
987 return false;
988}
989
Chad Rosieraab8e282011-12-02 01:26:24 +0000990void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
991 AU.setPreservesAll();
992 AU.addRequired<TargetLibraryInfo>();
993}
994
Chris Lattner2c5adf82009-11-15 19:59:49 +0000995void LazyValueInfo::releaseMemory() {
996 // If the cache was allocated, free it.
997 if (PImpl) {
998 delete &getCache(PImpl);
999 PImpl = 0;
1000 }
1001}
1002
1003Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
1004 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
1005
Chris Lattner16976522009-11-11 22:48:44 +00001006 if (Result.isConstant())
1007 return Result.getConstant();
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001008 if (Result.isConstantRange()) {
Owen Andersonee61fcf2010-08-27 23:29:38 +00001009 ConstantRange CR = Result.getConstantRange();
1010 if (const APInt *SingleVal = CR.getSingleElement())
1011 return ConstantInt::get(V->getContext(), *SingleVal);
1012 }
Chris Lattner16976522009-11-11 22:48:44 +00001013 return 0;
1014}
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001015
Chris Lattner38392bb2009-11-12 01:29:10 +00001016/// getConstantOnEdge - Determine whether the specified value is known to be a
1017/// constant on the specified edge. Return null if not.
1018Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1019 BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +00001020 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattner38392bb2009-11-12 01:29:10 +00001021
1022 if (Result.isConstant())
1023 return Result.getConstant();
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001024 if (Result.isConstantRange()) {
Owen Anderson9f014062010-08-10 20:03:09 +00001025 ConstantRange CR = Result.getConstantRange();
1026 if (const APInt *SingleVal = CR.getSingleElement())
1027 return ConstantInt::get(V->getContext(), *SingleVal);
1028 }
Chris Lattner38392bb2009-11-12 01:29:10 +00001029 return 0;
1030}
1031
Chris Lattnerb52675b2009-11-12 04:36:58 +00001032/// getPredicateOnEdge - Determine whether the specified value comparison
1033/// with a constant is known to be true or false on the specified CFG edge.
1034/// Pred is a CmpInst predicate.
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001035LazyValueInfo::Tristate
Chris Lattnerb52675b2009-11-12 04:36:58 +00001036LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1037 BasicBlock *FromBB, BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +00001038 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001039
Chris Lattnerb52675b2009-11-12 04:36:58 +00001040 // If we know the value is a constant, evaluate the conditional.
1041 Constant *Res = 0;
1042 if (Result.isConstant()) {
Chad Rosieraab8e282011-12-02 01:26:24 +00001043 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD,
1044 TLI);
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001045 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Chris Lattnerb52675b2009-11-12 04:36:58 +00001046 return ResCI->isZero() ? False : True;
Chris Lattner2c5adf82009-11-15 19:59:49 +00001047 return Unknown;
1048 }
1049
Owen Anderson9f014062010-08-10 20:03:09 +00001050 if (Result.isConstantRange()) {
Owen Anderson59b06dc2010-08-24 07:55:44 +00001051 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1052 if (!CI) return Unknown;
1053
Owen Anderson9f014062010-08-10 20:03:09 +00001054 ConstantRange CR = Result.getConstantRange();
1055 if (Pred == ICmpInst::ICMP_EQ) {
1056 if (!CR.contains(CI->getValue()))
1057 return False;
1058
1059 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1060 return True;
1061 } else if (Pred == ICmpInst::ICMP_NE) {
1062 if (!CR.contains(CI->getValue()))
1063 return True;
1064
1065 if (CR.isSingleElement() && CR.contains(CI->getValue()))
1066 return False;
1067 }
1068
1069 // Handle more complex predicates.
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001070 ConstantRange TrueValues =
1071 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1072 if (TrueValues.contains(CR))
Owen Anderson9f014062010-08-10 20:03:09 +00001073 return True;
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001074 if (TrueValues.inverse().contains(CR))
1075 return False;
Owen Anderson9f014062010-08-10 20:03:09 +00001076 return Unknown;
1077 }
1078
Chris Lattner2c5adf82009-11-15 19:59:49 +00001079 if (Result.isNotConstant()) {
Chris Lattnerb52675b2009-11-12 04:36:58 +00001080 // If this is an equality comparison, we can try to fold it knowing that
1081 // "V != C1".
1082 if (Pred == ICmpInst::ICMP_EQ) {
1083 // !C1 == C -> false iff C1 == C.
1084 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chad Rosieraab8e282011-12-02 01:26:24 +00001085 Result.getNotConstant(), C, TD,
1086 TLI);
Chris Lattnerb52675b2009-11-12 04:36:58 +00001087 if (Res->isNullValue())
1088 return False;
1089 } else if (Pred == ICmpInst::ICMP_NE) {
1090 // !C1 != C -> true iff C1 == C.
Chris Lattner5553a3a2009-11-15 20:01:24 +00001091 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chad Rosieraab8e282011-12-02 01:26:24 +00001092 Result.getNotConstant(), C, TD,
1093 TLI);
Chris Lattnerb52675b2009-11-12 04:36:58 +00001094 if (Res->isNullValue())
1095 return True;
1096 }
Chris Lattner2c5adf82009-11-15 19:59:49 +00001097 return Unknown;
Chris Lattnerb52675b2009-11-12 04:36:58 +00001098 }
1099
Chris Lattnercc4d3b22009-11-11 02:08:33 +00001100 return Unknown;
1101}
1102
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001103void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky69bfdf52010-12-15 18:57:18 +00001104 BasicBlock *NewSucc) {
Owen Anderson00ac77e2010-08-18 18:39:01 +00001105 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
1106}
1107
1108void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1109 if (PImpl) getCache(PImpl).eraseBlock(BB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +00001110}