blob: 88e18fa17918d21f17acd4556438dea3e052c950 [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"
Chris Lattnercc4d3b22009-11-11 02:08:33 +000017#include "llvm/Constants.h"
18#include "llvm/Instructions.h"
19#include "llvm/Analysis/ConstantFolding.h"
20#include "llvm/Target/TargetData.h"
Chris Lattner16976522009-11-11 22:48:44 +000021#include "llvm/Support/CFG.h"
Owen Anderson5be2e782010-08-05 22:59:19 +000022#include "llvm/Support/ConstantRange.h"
Chris Lattnerb8c124c2009-11-12 01:22:16 +000023#include "llvm/Support/Debug.h"
Chris Lattner16976522009-11-11 22:48:44 +000024#include "llvm/Support/raw_ostream.h"
Owen Anderson7f9cb742010-07-30 23:59:40 +000025#include "llvm/Support/ValueHandle.h"
Chris Lattner16976522009-11-11 22:48:44 +000026#include "llvm/ADT/DenseMap.h"
Owen Anderson9a65dc92010-07-27 23:58:11 +000027#include "llvm/ADT/DenseSet.h"
Chris Lattnere5642812009-11-15 20:00:52 +000028#include "llvm/ADT/STLExtras.h"
Owen Anderson6bcd3a02010-09-07 19:16:25 +000029#include <map>
30#include <set>
Chris Lattner10f2d132009-11-11 00:22:30 +000031using namespace llvm;
32
33char LazyValueInfo::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000034INITIALIZE_PASS(LazyValueInfo, "lazy-value-info",
Owen Andersonce665bd2010-10-07 22:25:06 +000035 "Lazy Value Information Analysis", false, true)
Chris Lattner10f2d132009-11-11 00:22:30 +000036
37namespace llvm {
38 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
39}
40
Chris Lattnercc4d3b22009-11-11 02:08:33 +000041
42//===----------------------------------------------------------------------===//
43// LVILatticeVal
44//===----------------------------------------------------------------------===//
45
46/// LVILatticeVal - This is the information tracked by LazyValueInfo for each
47/// value.
48///
49/// FIXME: This is basically just for bringup, this can be made a lot more rich
50/// in the future.
51///
52namespace {
53class LVILatticeVal {
54 enum LatticeValueTy {
55 /// undefined - This LLVM Value has no known value yet.
56 undefined,
Owen Anderson5be2e782010-08-05 22:59:19 +000057
Chris Lattnercc4d3b22009-11-11 02:08:33 +000058 /// constant - This LLVM Value has a specific constant value.
59 constant,
Chris Lattnerb52675b2009-11-12 04:36:58 +000060 /// notconstant - This LLVM value is known to not have the specified value.
61 notconstant,
62
Owen Anderson5be2e782010-08-05 22:59:19 +000063 /// constantrange
64 constantrange,
65
Chris Lattnercc4d3b22009-11-11 02:08:33 +000066 /// overdefined - This instruction is not known to be constant, and we know
67 /// it has a value.
68 overdefined
69 };
70
71 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattnerb52675b2009-11-12 04:36:58 +000072 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersondb78d732010-08-05 22:10:46 +000073 LatticeValueTy Tag;
74 Constant *Val;
Owen Anderson5be2e782010-08-05 22:59:19 +000075 ConstantRange Range;
Chris Lattnercc4d3b22009-11-11 02:08:33 +000076
77public:
Owen Anderson5be2e782010-08-05 22:59:19 +000078 LVILatticeVal() : Tag(undefined), Val(0), Range(1, true) {}
Chris Lattnercc4d3b22009-11-11 02:08:33 +000079
Chris Lattner16976522009-11-11 22:48:44 +000080 static LVILatticeVal get(Constant *C) {
81 LVILatticeVal Res;
Owen Anderson9f014062010-08-10 20:03:09 +000082 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
83 Res.markConstantRange(ConstantRange(CI->getValue(), CI->getValue()+1));
84 else if (!isa<UndefValue>(C))
85 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;
Owen Anderson9f014062010-08-10 20:03:09 +000090 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
91 Res.markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
92 else
93 Res.markNotConstant(C);
Chris Lattnerb52675b2009-11-12 04:36:58 +000094 return Res;
95 }
Owen Anderson625051b2010-08-10 23:20:01 +000096 static LVILatticeVal getRange(ConstantRange CR) {
97 LVILatticeVal Res;
98 Res.markConstantRange(CR);
99 return Res;
100 }
Chris Lattner16976522009-11-11 22:48:44 +0000101
Owen Anderson5be2e782010-08-05 22:59:19 +0000102 bool isUndefined() const { return Tag == undefined; }
103 bool isConstant() const { return Tag == constant; }
104 bool isNotConstant() const { return Tag == notconstant; }
105 bool isConstantRange() const { return Tag == constantrange; }
106 bool isOverdefined() const { return Tag == overdefined; }
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000107
108 Constant *getConstant() const {
109 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000110 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000111 }
112
Chris Lattnerb52675b2009-11-12 04:36:58 +0000113 Constant *getNotConstant() const {
114 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersondb78d732010-08-05 22:10:46 +0000115 return Val;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000116 }
117
Owen Anderson5be2e782010-08-05 22:59:19 +0000118 ConstantRange getConstantRange() const {
119 assert(isConstantRange() &&
120 "Cannot get the constant-range of a non-constant-range!");
121 return Range;
122 }
123
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000124 /// markOverdefined - Return true if this is a change in status.
125 bool markOverdefined() {
126 if (isOverdefined())
127 return false;
Owen Andersondb78d732010-08-05 22:10:46 +0000128 Tag = overdefined;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000129 return true;
130 }
131
132 /// markConstant - Return true if this is a change in status.
133 bool markConstant(Constant *V) {
134 if (isConstant()) {
135 assert(getConstant() == V && "Marking constant with different value");
136 return false;
137 }
138
139 assert(isUndefined());
Owen Andersondb78d732010-08-05 22:10:46 +0000140 Tag = constant;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000141 assert(V && "Marking constant with NULL");
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) {
148 if (isNotConstant()) {
149 assert(getNotConstant() == V && "Marking !constant with different value");
150 return false;
151 }
152
153 if (isConstant())
154 assert(getConstant() != V && "Marking not constant with different value");
155 else
156 assert(isUndefined());
157
Owen Andersondb78d732010-08-05 22:10:46 +0000158 Tag = notconstant;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000159 assert(V && "Marking constant with NULL");
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
Chris Lattnerb52675b2009-11-12 04:36:58 +0000190 if (RHS.isNotConstant()) {
191 if (isNotConstant()) {
Chris Lattnerf496e792009-11-12 04:57:13 +0000192 if (getNotConstant() != RHS.getNotConstant() ||
193 isa<ConstantExpr>(getNotConstant()) ||
194 isa<ConstantExpr>(RHS.getNotConstant()))
Chris Lattnerb52675b2009-11-12 04:36:58 +0000195 return markOverdefined();
196 return false;
Owen Anderson39295322010-08-30 17:03:45 +0000197 } else if (isConstant()) {
Chris Lattnerf496e792009-11-12 04:57:13 +0000198 if (getConstant() == RHS.getNotConstant() ||
199 isa<ConstantExpr>(RHS.getNotConstant()) ||
200 isa<ConstantExpr>(getConstant()))
201 return markOverdefined();
202 return markNotConstant(RHS.getNotConstant());
Owen Anderson39295322010-08-30 17:03:45 +0000203 } else if (isConstantRange()) {
Owen Andersonc2ce21a2010-09-16 18:28:33 +0000204 // FIXME: This could be made more precise.
Owen Anderson39295322010-08-30 17:03:45 +0000205 return markOverdefined();
Chris Lattnerf496e792009-11-12 04:57:13 +0000206 }
207
208 assert(isUndefined() && "Unexpected lattice");
Chris Lattnerb52675b2009-11-12 04:36:58 +0000209 return markNotConstant(RHS.getNotConstant());
210 }
211
Owen Anderson5be2e782010-08-05 22:59:19 +0000212 if (RHS.isConstantRange()) {
213 if (isConstantRange()) {
Owen Anderson9f014062010-08-10 20:03:09 +0000214 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
215 if (NewR.isFullSet())
Owen Anderson5be2e782010-08-05 22:59:19 +0000216 return markOverdefined();
217 else
218 return markConstantRange(NewR);
Owen Anderson59b06dc2010-08-24 07:55:44 +0000219 } else if (!isUndefined()) {
220 return markOverdefined();
Owen Anderson5be2e782010-08-05 22:59:19 +0000221 }
222
223 assert(isUndefined() && "Unexpected lattice");
224 return markConstantRange(RHS.getConstantRange());
225 }
226
Owen Andersonc2ce21a2010-09-16 18:28:33 +0000227 // RHS must be a constant, we must be constantrange,
228 // undef, constant, or notconstant.
229 if (isConstantRange()) {
230 // FIXME: This could be made more precise.
231 return markOverdefined();
232 }
Owen Anderson5be2e782010-08-05 22:59:19 +0000233
Chris Lattnerf496e792009-11-12 04:57:13 +0000234 if (isUndefined())
235 return markConstant(RHS.getConstant());
236
237 if (isConstant()) {
238 if (getConstant() != RHS.getConstant())
239 return markOverdefined();
240 return false;
241 }
242
243 // If we are known "!=4" and RHS is "==5", stay at "!=4".
244 if (getNotConstant() == RHS.getConstant() ||
245 isa<ConstantExpr>(getNotConstant()) ||
246 isa<ConstantExpr>(RHS.getConstant()))
Chris Lattner16976522009-11-11 22:48:44 +0000247 return markOverdefined();
Chris Lattnerf496e792009-11-12 04:57:13 +0000248 return false;
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000249 }
250
251};
252
253} // end anonymous namespace.
254
Chris Lattner16976522009-11-11 22:48:44 +0000255namespace llvm {
256raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
257 if (Val.isUndefined())
258 return OS << "undefined";
259 if (Val.isOverdefined())
260 return OS << "overdefined";
Chris Lattnerb52675b2009-11-12 04:36:58 +0000261
262 if (Val.isNotConstant())
263 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Owen Anderson2f3ffb82010-08-09 20:50:46 +0000264 else if (Val.isConstantRange())
265 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
266 << Val.getConstantRange().getUpper() << '>';
Chris Lattner16976522009-11-11 22:48:44 +0000267 return OS << "constant<" << *Val.getConstant() << '>';
268}
269}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000270
271//===----------------------------------------------------------------------===//
Chris Lattner2c5adf82009-11-15 19:59:49 +0000272// LazyValueInfoCache Decl
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000273//===----------------------------------------------------------------------===//
274
Chris Lattner2c5adf82009-11-15 19:59:49 +0000275namespace {
276 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
277 /// maintains information about queries across the clients' queries.
278 class LazyValueInfoCache {
Owen Anderson81881bc2010-07-30 20:56:07 +0000279 public:
Chris Lattner2c5adf82009-11-15 19:59:49 +0000280 /// BlockCacheEntryTy - This is a computed lattice value at the end of the
281 /// specified basic block for a Value* that depends on context.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000282 typedef std::pair<AssertingVH<BasicBlock>, LVILatticeVal> BlockCacheEntryTy;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000283
284 /// ValueCacheEntryTy - This is all of the cached block information for
285 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
286 /// entries, allowing us to do a lookup with a binary search.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000287 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000288
Owen Anderson81881bc2010-07-30 20:56:07 +0000289 private:
Owen Anderson7f9cb742010-07-30 23:59:40 +0000290 /// LVIValueHandle - A callback value handle update the cache when
291 /// values are erased.
292 struct LVIValueHandle : public CallbackVH {
293 LazyValueInfoCache *Parent;
294
295 LVIValueHandle(Value *V, LazyValueInfoCache *P)
296 : CallbackVH(V), Parent(P) { }
297
298 void deleted();
299 void allUsesReplacedWith(Value* V) {
300 deleted();
301 }
Owen Anderson7f9cb742010-07-30 23:59:40 +0000302 };
303
Chris Lattner2c5adf82009-11-15 19:59:49 +0000304 /// ValueCache - This is all of the cached information for all values,
305 /// mapped from Value* to key information.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000306 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000307
308 /// OverDefinedCache - This tracks, on a per-block basis, the set of
309 /// values that are over-defined at the end of that block. This is required
310 /// for cache updating.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000311 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > OverDefinedCache;
Owen Anderson7f9cb742010-07-30 23:59:40 +0000312
Chris Lattner2c5adf82009-11-15 19:59:49 +0000313 public:
314
315 /// getValueInBlock - This is the query interface to determine the lattice
316 /// value for the specified Value* at the end of the specified block.
317 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB);
318
319 /// getValueOnEdge - This is the query interface to determine the lattice
320 /// value for the specified Value* that is true on the specified edge.
321 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000322
323 /// threadEdge - This is the update interface to inform the cache that an
324 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
325 /// NewSucc.
326 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Owen Anderson00ac77e2010-08-18 18:39:01 +0000327
328 /// eraseBlock - This is part of the update interface to inform the cache
329 /// that a block has been deleted.
330 void eraseBlock(BasicBlock *BB);
331
332 /// clear - Empty the cache.
333 void clear() {
334 ValueCache.clear();
335 OverDefinedCache.clear();
336 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000337 };
338} // end anonymous namespace
339
Owen Anderson81881bc2010-07-30 20:56:07 +0000340//===----------------------------------------------------------------------===//
341// LVIQuery Impl
342//===----------------------------------------------------------------------===//
343
344namespace {
345 /// LVIQuery - This is a transient object that exists while a query is
346 /// being performed.
347 ///
348 /// TODO: Reuse LVIQuery instead of recreating it for every query, this avoids
349 /// reallocation of the densemap on every query.
350 class LVIQuery {
351 typedef LazyValueInfoCache::BlockCacheEntryTy BlockCacheEntryTy;
352 typedef LazyValueInfoCache::ValueCacheEntryTy ValueCacheEntryTy;
353
354 /// This is the current value being queried for.
355 Value *Val;
356
Owen Anderson7f9cb742010-07-30 23:59:40 +0000357 /// This is a pointer to the owning cache, for recursive queries.
358 LazyValueInfoCache &Parent;
359
Owen Anderson81881bc2010-07-30 20:56:07 +0000360 /// This is all of the cached information about this value.
361 ValueCacheEntryTy &Cache;
362
363 /// This tracks, for each block, what values are overdefined.
Owen Anderson00ac77e2010-08-18 18:39:01 +0000364 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > &OverDefinedCache;
Owen Anderson81881bc2010-07-30 20:56:07 +0000365
366 /// NewBlocks - This is a mapping of the new BasicBlocks which have been
367 /// added to cache but that are not in sorted order.
368 DenseSet<BasicBlock*> NewBlockInfo;
Owen Andersonc8ef7502010-08-24 20:47:29 +0000369
Owen Anderson81881bc2010-07-30 20:56:07 +0000370 public:
371
Owen Anderson7f9cb742010-07-30 23:59:40 +0000372 LVIQuery(Value *V, LazyValueInfoCache &P,
373 ValueCacheEntryTy &VC,
Owen Anderson00ac77e2010-08-18 18:39:01 +0000374 std::set<std::pair<AssertingVH<BasicBlock>, Value*> > &ODC)
Owen Anderson7f9cb742010-07-30 23:59:40 +0000375 : Val(V), Parent(P), Cache(VC), OverDefinedCache(ODC) {
Owen Anderson81881bc2010-07-30 20:56:07 +0000376 }
377
378 ~LVIQuery() {
379 // When the query is done, insert the newly discovered facts into the
380 // cache in sorted order.
381 if (NewBlockInfo.empty()) return;
382
383 for (DenseSet<BasicBlock*>::iterator I = NewBlockInfo.begin(),
384 E = NewBlockInfo.end(); I != E; ++I) {
385 if (Cache[*I].isOverdefined())
386 OverDefinedCache.insert(std::make_pair(*I, Val));
387 }
388 }
389
390 LVILatticeVal getBlockValue(BasicBlock *BB);
391 LVILatticeVal getEdgeValue(BasicBlock *FromBB, BasicBlock *ToBB);
392
393 private:
Owen Anderson4bb3eaf2010-08-16 23:42:33 +0000394 LVILatticeVal getCachedEntryForBlock(BasicBlock *BB);
Owen Anderson81881bc2010-07-30 20:56:07 +0000395 };
396} // end anonymous namespace
Chris Lattner2c5adf82009-11-15 19:59:49 +0000397
Owen Anderson7f9cb742010-07-30 23:59:40 +0000398void LazyValueInfoCache::LVIValueHandle::deleted() {
Owen Anderson00ac77e2010-08-18 18:39:01 +0000399 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
Owen Anderson7f9cb742010-07-30 23:59:40 +0000400 I = Parent->OverDefinedCache.begin(),
401 E = Parent->OverDefinedCache.end();
402 I != E; ) {
Owen Anderson00ac77e2010-08-18 18:39:01 +0000403 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
Owen Anderson7f9cb742010-07-30 23:59:40 +0000404 ++I;
405 if (tmp->second == getValPtr())
406 Parent->OverDefinedCache.erase(tmp);
407 }
Owen Andersoncf6abd22010-08-11 22:36:04 +0000408
409 // This erasure deallocates *this, so it MUST happen after we're done
410 // using any and all members of *this.
411 Parent->ValueCache.erase(*this);
Owen Anderson7f9cb742010-07-30 23:59:40 +0000412}
413
Owen Anderson00ac77e2010-08-18 18:39:01 +0000414void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
415 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
416 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ) {
417 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator tmp = I;
418 ++I;
419 if (tmp->first == BB)
420 OverDefinedCache.erase(tmp);
421 }
422
423 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
424 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
425 I->second.erase(BB);
426}
Owen Anderson7f9cb742010-07-30 23:59:40 +0000427
Chris Lattnere5642812009-11-15 20:00:52 +0000428/// getCachedEntryForBlock - See if we already have a value for this block. If
Owen Anderson9a65dc92010-07-27 23:58:11 +0000429/// so, return it, otherwise create a new entry in the Cache map to use.
Owen Anderson4bb3eaf2010-08-16 23:42:33 +0000430LVILatticeVal LVIQuery::getCachedEntryForBlock(BasicBlock *BB) {
Owen Anderson81881bc2010-07-30 20:56:07 +0000431 NewBlockInfo.insert(BB);
Owen Anderson9a65dc92010-07-27 23:58:11 +0000432 return Cache[BB];
Chris Lattnere5642812009-11-15 20:00:52 +0000433}
Chris Lattner2c5adf82009-11-15 19:59:49 +0000434
Owen Anderson81881bc2010-07-30 20:56:07 +0000435LVILatticeVal LVIQuery::getBlockValue(BasicBlock *BB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000436 // See if we already have a value for this block.
Owen Anderson4bb3eaf2010-08-16 23:42:33 +0000437 LVILatticeVal BBLV = getCachedEntryForBlock(BB);
Chris Lattner2c5adf82009-11-15 19:59:49 +0000438
439 // If we've already computed this block's value, return it.
Chris Lattnere5642812009-11-15 20:00:52 +0000440 if (!BBLV.isUndefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000441 DEBUG(dbgs() << " reuse BB '" << BB->getName() << "' val=" << BBLV <<'\n');
Chris Lattner2c5adf82009-11-15 19:59:49 +0000442 return BBLV;
Chris Lattnere5642812009-11-15 20:00:52 +0000443 }
444
Chris Lattner2c5adf82009-11-15 19:59:49 +0000445 // Otherwise, this is the first time we're seeing this block. Reset the
446 // lattice value to overdefined, so that cycles will terminate and be
447 // conservatively correct.
448 BBLV.markOverdefined();
Owen Anderson4bb3eaf2010-08-16 23:42:33 +0000449 Cache[BB] = BBLV;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000450
Chris Lattner2c5adf82009-11-15 19:59:49 +0000451 Instruction *BBI = dyn_cast<Instruction>(Val);
452 if (BBI == 0 || BBI->getParent() != BB) {
453 LVILatticeVal Result; // Start Undefined.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000454
Owen Andersonc8ef7502010-08-24 20:47:29 +0000455 // If this is a pointer, and there's a load from that pointer in this BB,
456 // then we know that the pointer can't be NULL.
Owen Anderson1593dd62010-09-03 19:08:37 +0000457 bool NotNull = false;
Owen Andersonc8ef7502010-08-24 20:47:29 +0000458 if (Val->getType()->isPointerTy()) {
Owen Anderson6cd20752010-08-25 01:16:47 +0000459 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();BI != BE;++BI){
460 LoadInst *L = dyn_cast<LoadInst>(BI);
461 if (L && L->getPointerAddressSpace() == 0 &&
462 L->getPointerOperand()->getUnderlyingObject() ==
463 Val->getUnderlyingObject()) {
Owen Anderson1593dd62010-09-03 19:08:37 +0000464 NotNull = true;
465 break;
Owen Andersonc8ef7502010-08-24 20:47:29 +0000466 }
467 }
468 }
469
470 unsigned NumPreds = 0;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000471 // Loop over all of our predecessors, merging what we know from them into
472 // result.
473 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Owen Anderson81881bc2010-07-30 20:56:07 +0000474 Result.mergeIn(getEdgeValue(*PI, BB));
Chris Lattner2c5adf82009-11-15 19:59:49 +0000475
476 // If we hit overdefined, exit early. The BlockVals entry is already set
477 // to overdefined.
Chris Lattnere5642812009-11-15 20:00:52 +0000478 if (Result.isOverdefined()) {
David Greene5d93a1f2009-12-23 20:43:58 +0000479 DEBUG(dbgs() << " compute BB '" << BB->getName()
Chris Lattnere5642812009-11-15 20:00:52 +0000480 << "' - overdefined because of pred.\n");
Owen Anderson1593dd62010-09-03 19:08:37 +0000481 // If we previously determined that this is a pointer that can't be null
482 // then return that rather than giving up entirely.
483 if (NotNull) {
484 const PointerType *PTy = cast<PointerType>(Val->getType());
485 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
486 }
487
Chris Lattner2c5adf82009-11-15 19:59:49 +0000488 return Result;
Chris Lattnere5642812009-11-15 20:00:52 +0000489 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000490 ++NumPreds;
491 }
492
Owen Anderson1593dd62010-09-03 19:08:37 +0000493
Chris Lattner2c5adf82009-11-15 19:59:49 +0000494 // If this is the entry block, we must be asking about an argument. The
495 // value is overdefined.
496 if (NumPreds == 0 && BB == &BB->getParent()->front()) {
497 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
498 Result.markOverdefined();
499 return Result;
500 }
501
502 // Return the merged value, which is more precise than 'overdefined'.
503 assert(!Result.isOverdefined());
Owen Anderson4bb3eaf2010-08-16 23:42:33 +0000504 return Cache[BB] = Result;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000505 }
506
507 // If this value is defined by an instruction in this block, we have to
508 // process it here somehow or return overdefined.
509 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Owen Anderson7f9cb742010-07-30 23:59:40 +0000510 LVILatticeVal Result; // Start Undefined.
511
512 // Loop over all of our predecessors, merging what we know from them into
513 // result.
514 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
515 Value* PhiVal = PN->getIncomingValueForBlock(*PI);
516 Result.mergeIn(Parent.getValueOnEdge(PhiVal, *PI, BB));
517
518 // If we hit overdefined, exit early. The BlockVals entry is already set
519 // to overdefined.
520 if (Result.isOverdefined()) {
521 DEBUG(dbgs() << " compute BB '" << BB->getName()
522 << "' - overdefined because of pred.\n");
523 return Result;
524 }
525 }
526
527 // Return the merged value, which is more precise than 'overdefined'.
528 assert(!Result.isOverdefined());
Owen Anderson00ac77e2010-08-18 18:39:01 +0000529 return Cache[BB] = Result;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000530 }
Chris Lattnere5642812009-11-15 20:00:52 +0000531
Owen Andersonb81fd622010-08-18 21:11:37 +0000532 assert(Cache[BB].isOverdefined() && "Recursive query changed our cache?");
533
534 // We can only analyze the definitions of certain classes of instructions
535 // (integral binops and casts at the moment), so bail if this isn't one.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000536 LVILatticeVal Result;
Owen Andersonb81fd622010-08-18 21:11:37 +0000537 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
538 !BBI->getType()->isIntegerTy()) {
539 DEBUG(dbgs() << " compute BB '" << BB->getName()
540 << "' - overdefined because inst def found.\n");
541 Result.markOverdefined();
542 return Result;
543 }
544
545 // FIXME: We're currently limited to binops with a constant RHS. This should
546 // be improved.
547 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
548 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
549 DEBUG(dbgs() << " compute BB '" << BB->getName()
550 << "' - overdefined because inst def found.\n");
551
552 Result.markOverdefined();
553 return Result;
554 }
555
556 // Figure out the range of the LHS. If that fails, bail.
557 LVILatticeVal LHSVal = Parent.getValueInBlock(BBI->getOperand(0), BB);
558 if (!LHSVal.isConstantRange()) {
559 Result.markOverdefined();
560 return Result;
561 }
562
563 ConstantInt *RHS = 0;
564 ConstantRange LHSRange = LHSVal.getConstantRange();
565 ConstantRange RHSRange(1);
566 const IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
567 if (isa<BinaryOperator>(BBI)) {
Owen Anderson59b06dc2010-08-24 07:55:44 +0000568 RHS = dyn_cast<ConstantInt>(BBI->getOperand(1));
569 if (!RHS) {
570 Result.markOverdefined();
571 return Result;
572 }
573
Owen Andersonb81fd622010-08-18 21:11:37 +0000574 RHSRange = ConstantRange(RHS->getValue(), RHS->getValue()+1);
575 }
576
577 // NOTE: We're currently limited by the set of operations that ConstantRange
578 // can evaluate symbolically. Enhancing that set will allows us to analyze
579 // more definitions.
580 switch (BBI->getOpcode()) {
581 case Instruction::Add:
582 Result.markConstantRange(LHSRange.add(RHSRange));
583 break;
584 case Instruction::Sub:
585 Result.markConstantRange(LHSRange.sub(RHSRange));
586 break;
587 case Instruction::Mul:
588 Result.markConstantRange(LHSRange.multiply(RHSRange));
589 break;
590 case Instruction::UDiv:
591 Result.markConstantRange(LHSRange.udiv(RHSRange));
592 break;
593 case Instruction::Shl:
594 Result.markConstantRange(LHSRange.shl(RHSRange));
595 break;
596 case Instruction::LShr:
597 Result.markConstantRange(LHSRange.lshr(RHSRange));
598 break;
599 case Instruction::Trunc:
600 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
601 break;
602 case Instruction::SExt:
603 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
604 break;
605 case Instruction::ZExt:
606 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
607 break;
608 case Instruction::BitCast:
609 Result.markConstantRange(LHSRange);
610 break;
Nick Lewycky198381e2010-09-07 05:39:02 +0000611 case Instruction::And:
612 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
613 break;
614 case Instruction::Or:
615 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
616 break;
Owen Andersonb81fd622010-08-18 21:11:37 +0000617
618 // Unhandled instructions are overdefined.
619 default:
620 DEBUG(dbgs() << " compute BB '" << BB->getName()
621 << "' - overdefined because inst def found.\n");
622 Result.markOverdefined();
623 break;
624 }
625
626 return Cache[BB] = Result;
Chris Lattner10f2d132009-11-11 00:22:30 +0000627}
628
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000629
Chris Lattner800c47e2009-11-15 20:02:12 +0000630/// getEdgeValue - This method attempts to infer more complex
Owen Anderson81881bc2010-07-30 20:56:07 +0000631LVILatticeVal LVIQuery::getEdgeValue(BasicBlock *BBFrom, BasicBlock *BBTo) {
Chris Lattner800c47e2009-11-15 20:02:12 +0000632 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
633 // know that v != 0.
Chris Lattner16976522009-11-11 22:48:44 +0000634 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
635 // If this is a conditional branch and only one successor goes to BBTo, then
636 // we maybe able to infer something from the condition.
637 if (BI->isConditional() &&
638 BI->getSuccessor(0) != BI->getSuccessor(1)) {
639 bool isTrueDest = BI->getSuccessor(0) == BBTo;
640 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
641 "BBTo isn't a successor of BBFrom");
642
643 // If V is the condition of the branch itself, then we know exactly what
644 // it is.
Chris Lattner2c5adf82009-11-15 19:59:49 +0000645 if (BI->getCondition() == Val)
Chris Lattner16976522009-11-11 22:48:44 +0000646 return LVILatticeVal::get(ConstantInt::get(
Owen Anderson9f014062010-08-10 20:03:09 +0000647 Type::getInt1Ty(Val->getContext()), isTrueDest));
Chris Lattner16976522009-11-11 22:48:44 +0000648
649 // If the condition of the branch is an equality comparison, we may be
650 // able to infer the value.
Owen Anderson2d0f2472010-08-11 04:24:25 +0000651 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
652 if (ICI && ICI->getOperand(0) == Val &&
653 isa<Constant>(ICI->getOperand(1))) {
654 if (ICI->isEquality()) {
655 // We know that V has the RHS constant if this is a true SETEQ or
656 // false SETNE.
657 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
658 return LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
659 return LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
Chris Lattner16976522009-11-11 22:48:44 +0000660 }
Owen Anderson2d0f2472010-08-11 04:24:25 +0000661
662 if (ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
663 // Calculate the range of values that would satisfy the comparison.
664 ConstantRange CmpRange(CI->getValue(), CI->getValue()+1);
665 ConstantRange TrueValues =
666 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
667
668 // If we're interested in the false dest, invert the condition.
669 if (!isTrueDest) TrueValues = TrueValues.inverse();
670
671 // Figure out the possible values of the query BEFORE this branch.
672 LVILatticeVal InBlock = getBlockValue(BBFrom);
Owen Anderson660cab32010-08-27 17:12:29 +0000673 if (!InBlock.isConstantRange())
674 return LVILatticeVal::getRange(TrueValues);
Owen Anderson2d0f2472010-08-11 04:24:25 +0000675
676 // Find all potential values that satisfy both the input and output
677 // conditions.
678 ConstantRange PossibleValues =
679 TrueValues.intersectWith(InBlock.getConstantRange());
680
681 return LVILatticeVal::getRange(PossibleValues);
682 }
683 }
Chris Lattner16976522009-11-11 22:48:44 +0000684 }
685 }
Chris Lattner800c47e2009-11-15 20:02:12 +0000686
687 // If the edge was formed by a switch on the value, then we may know exactly
688 // what it is.
689 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Owen Andersondae90c62010-08-24 21:59:42 +0000690 if (SI->getCondition() == Val) {
Owen Anderson4caef602010-09-02 22:16:52 +0000691 // We don't know anything in the default case.
Owen Andersondae90c62010-08-24 21:59:42 +0000692 if (SI->getDefaultDest() == BBTo) {
Owen Andersondae90c62010-08-24 21:59:42 +0000693 LVILatticeVal Result;
Owen Anderson4caef602010-09-02 22:16:52 +0000694 Result.markOverdefined();
Owen Andersondae90c62010-08-24 21:59:42 +0000695 return Result;
696 }
697
Chris Lattner800c47e2009-11-15 20:02:12 +0000698 // We only know something if there is exactly one value that goes from
699 // BBFrom to BBTo.
700 unsigned NumEdges = 0;
701 ConstantInt *EdgeVal = 0;
702 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
703 if (SI->getSuccessor(i) != BBTo) continue;
704 if (NumEdges++) break;
705 EdgeVal = SI->getCaseValue(i);
706 }
707 assert(EdgeVal && "Missing successor?");
708 if (NumEdges == 1)
709 return LVILatticeVal::get(EdgeVal);
710 }
711 }
Chris Lattner16976522009-11-11 22:48:44 +0000712
713 // Otherwise see if the value is known in the block.
Owen Anderson81881bc2010-07-30 20:56:07 +0000714 return getBlockValue(BBFrom);
Chris Lattner16976522009-11-11 22:48:44 +0000715}
716
Owen Anderson81881bc2010-07-30 20:56:07 +0000717
718//===----------------------------------------------------------------------===//
719// LazyValueInfoCache Impl
720//===----------------------------------------------------------------------===//
721
Chris Lattner2c5adf82009-11-15 19:59:49 +0000722LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB) {
723 // If already a constant, there is nothing to compute.
Chris Lattner16976522009-11-11 22:48:44 +0000724 if (Constant *VC = dyn_cast<Constant>(V))
Chris Lattner2c5adf82009-11-15 19:59:49 +0000725 return LVILatticeVal::get(VC);
Chris Lattner16976522009-11-11 22:48:44 +0000726
David Greene5d93a1f2009-12-23 20:43:58 +0000727 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000728 << BB->getName() << "'\n");
729
Owen Anderson7f9cb742010-07-30 23:59:40 +0000730 LVILatticeVal Result = LVIQuery(V, *this,
Owen Andersonc8ef7502010-08-24 20:47:29 +0000731 ValueCache[LVIValueHandle(V, this)],
732 OverDefinedCache).getBlockValue(BB);
Chris Lattner16976522009-11-11 22:48:44 +0000733
David Greene5d93a1f2009-12-23 20:43:58 +0000734 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000735 return Result;
736}
Chris Lattner16976522009-11-11 22:48:44 +0000737
Chris Lattner2c5adf82009-11-15 19:59:49 +0000738LVILatticeVal LazyValueInfoCache::
739getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB) {
740 // If already a constant, there is nothing to compute.
741 if (Constant *VC = dyn_cast<Constant>(V))
742 return LVILatticeVal::get(VC);
743
David Greene5d93a1f2009-12-23 20:43:58 +0000744 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattner2c5adf82009-11-15 19:59:49 +0000745 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000746
Owen Anderson81881bc2010-07-30 20:56:07 +0000747 LVILatticeVal Result =
Owen Anderson7f9cb742010-07-30 23:59:40 +0000748 LVIQuery(V, *this, ValueCache[LVIValueHandle(V, this)],
Owen Anderson81881bc2010-07-30 20:56:07 +0000749 OverDefinedCache).getEdgeValue(FromBB, ToBB);
Chris Lattner2c5adf82009-11-15 19:59:49 +0000750
David Greene5d93a1f2009-12-23 20:43:58 +0000751 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattner2c5adf82009-11-15 19:59:49 +0000752
753 return Result;
754}
755
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000756void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
757 BasicBlock *NewSucc) {
758 // When an edge in the graph has been threaded, values that we could not
759 // determine a value for before (i.e. were marked overdefined) may be possible
760 // to solve now. We do NOT try to proactively update these values. Instead,
761 // we clear their entries from the cache, and allow lazy updating to recompute
762 // them when needed.
763
764 // The updating process is fairly simple: we need to dropped cached info
765 // for all values that were marked overdefined in OldSucc, and for those same
766 // values in any successor of OldSucc (except NewSucc) in which they were
767 // also marked overdefined.
768 std::vector<BasicBlock*> worklist;
769 worklist.push_back(OldSucc);
770
Owen Anderson9a65dc92010-07-27 23:58:11 +0000771 DenseSet<Value*> ClearSet;
Owen Anderson00ac77e2010-08-18 18:39:01 +0000772 for (std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator
Owen Anderson9a65dc92010-07-27 23:58:11 +0000773 I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E; ++I) {
774 if (I->first == OldSucc)
775 ClearSet.insert(I->second);
776 }
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000777
778 // Use a worklist to perform a depth-first search of OldSucc's successors.
779 // NOTE: We do not need a visited list since any blocks we have already
780 // visited will have had their overdefined markers cleared already, and we
781 // thus won't loop to their successors.
782 while (!worklist.empty()) {
783 BasicBlock *ToUpdate = worklist.back();
784 worklist.pop_back();
785
786 // Skip blocks only accessible through NewSucc.
787 if (ToUpdate == NewSucc) continue;
788
789 bool changed = false;
Owen Anderson9a65dc92010-07-27 23:58:11 +0000790 for (DenseSet<Value*>::iterator I = ClearSet.begin(),E = ClearSet.end();
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000791 I != E; ++I) {
792 // If a value was marked overdefined in OldSucc, and is here too...
Owen Anderson00ac77e2010-08-18 18:39:01 +0000793 std::set<std::pair<AssertingVH<BasicBlock>, Value*> >::iterator OI =
Owen Anderson9a65dc92010-07-27 23:58:11 +0000794 OverDefinedCache.find(std::make_pair(ToUpdate, *I));
795 if (OI == OverDefinedCache.end()) continue;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000796
Owen Anderson9a65dc92010-07-27 23:58:11 +0000797 // Remove it from the caches.
Owen Anderson7f9cb742010-07-30 23:59:40 +0000798 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(*I, this)];
Owen Anderson9a65dc92010-07-27 23:58:11 +0000799 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
800
801 assert(CI != Entry.end() && "Couldn't find entry to update?");
802 Entry.erase(CI);
803 OverDefinedCache.erase(OI);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000804
Owen Anderson9a65dc92010-07-27 23:58:11 +0000805 // If we removed anything, then we potentially need to update
806 // blocks successors too.
807 changed = true;
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000808 }
809
810 if (!changed) continue;
811
812 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
813 }
814}
815
Chris Lattner2c5adf82009-11-15 19:59:49 +0000816//===----------------------------------------------------------------------===//
817// LazyValueInfo Impl
818//===----------------------------------------------------------------------===//
819
Chris Lattner2c5adf82009-11-15 19:59:49 +0000820/// getCache - This lazily constructs the LazyValueInfoCache.
821static LazyValueInfoCache &getCache(void *&PImpl) {
822 if (!PImpl)
823 PImpl = new LazyValueInfoCache();
824 return *static_cast<LazyValueInfoCache*>(PImpl);
825}
826
Owen Anderson00ac77e2010-08-18 18:39:01 +0000827bool LazyValueInfo::runOnFunction(Function &F) {
828 if (PImpl)
829 getCache(PImpl).clear();
830
831 TD = getAnalysisIfAvailable<TargetData>();
832 // Fully lazy.
833 return false;
834}
835
Chris Lattner2c5adf82009-11-15 19:59:49 +0000836void LazyValueInfo::releaseMemory() {
837 // If the cache was allocated, free it.
838 if (PImpl) {
839 delete &getCache(PImpl);
840 PImpl = 0;
841 }
842}
843
844Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB) {
845 LVILatticeVal Result = getCache(PImpl).getValueInBlock(V, BB);
846
Chris Lattner16976522009-11-11 22:48:44 +0000847 if (Result.isConstant())
848 return Result.getConstant();
Owen Andersonee61fcf2010-08-27 23:29:38 +0000849 else if (Result.isConstantRange()) {
850 ConstantRange CR = Result.getConstantRange();
851 if (const APInt *SingleVal = CR.getSingleElement())
852 return ConstantInt::get(V->getContext(), *SingleVal);
853 }
Chris Lattner16976522009-11-11 22:48:44 +0000854 return 0;
855}
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000856
Chris Lattner38392bb2009-11-12 01:29:10 +0000857/// getConstantOnEdge - Determine whether the specified value is known to be a
858/// constant on the specified edge. Return null if not.
859Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
860 BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000861 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattner38392bb2009-11-12 01:29:10 +0000862
863 if (Result.isConstant())
864 return Result.getConstant();
Owen Anderson9f014062010-08-10 20:03:09 +0000865 else if (Result.isConstantRange()) {
866 ConstantRange CR = Result.getConstantRange();
867 if (const APInt *SingleVal = CR.getSingleElement())
868 return ConstantInt::get(V->getContext(), *SingleVal);
869 }
Chris Lattner38392bb2009-11-12 01:29:10 +0000870 return 0;
871}
872
Chris Lattnerb52675b2009-11-12 04:36:58 +0000873/// getPredicateOnEdge - Determine whether the specified value comparison
874/// with a constant is known to be true or false on the specified CFG edge.
875/// Pred is a CmpInst predicate.
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000876LazyValueInfo::Tristate
Chris Lattnerb52675b2009-11-12 04:36:58 +0000877LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
878 BasicBlock *FromBB, BasicBlock *ToBB) {
Chris Lattner2c5adf82009-11-15 19:59:49 +0000879 LVILatticeVal Result = getCache(PImpl).getValueOnEdge(V, FromBB, ToBB);
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000880
Chris Lattnerb52675b2009-11-12 04:36:58 +0000881 // If we know the value is a constant, evaluate the conditional.
882 Constant *Res = 0;
883 if (Result.isConstant()) {
884 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, TD);
885 if (ConstantInt *ResCI = dyn_cast_or_null<ConstantInt>(Res))
886 return ResCI->isZero() ? False : True;
Chris Lattner2c5adf82009-11-15 19:59:49 +0000887 return Unknown;
888 }
889
Owen Anderson9f014062010-08-10 20:03:09 +0000890 if (Result.isConstantRange()) {
Owen Anderson59b06dc2010-08-24 07:55:44 +0000891 ConstantInt *CI = dyn_cast<ConstantInt>(C);
892 if (!CI) return Unknown;
893
Owen Anderson9f014062010-08-10 20:03:09 +0000894 ConstantRange CR = Result.getConstantRange();
895 if (Pred == ICmpInst::ICMP_EQ) {
896 if (!CR.contains(CI->getValue()))
897 return False;
898
899 if (CR.isSingleElement() && CR.contains(CI->getValue()))
900 return True;
901 } else if (Pred == ICmpInst::ICMP_NE) {
902 if (!CR.contains(CI->getValue()))
903 return True;
904
905 if (CR.isSingleElement() && CR.contains(CI->getValue()))
906 return False;
907 }
908
909 // Handle more complex predicates.
910 ConstantRange RHS(CI->getValue(), CI->getValue()+1);
911 ConstantRange TrueValues = ConstantRange::makeICmpRegion(Pred, RHS);
912 if (CR.intersectWith(TrueValues).isEmptySet())
913 return False;
Owen Anderson625051b2010-08-10 23:20:01 +0000914 else if (TrueValues.contains(CR))
Owen Anderson9f014062010-08-10 20:03:09 +0000915 return True;
916
917 return Unknown;
918 }
919
Chris Lattner2c5adf82009-11-15 19:59:49 +0000920 if (Result.isNotConstant()) {
Chris Lattnerb52675b2009-11-12 04:36:58 +0000921 // If this is an equality comparison, we can try to fold it knowing that
922 // "V != C1".
923 if (Pred == ICmpInst::ICMP_EQ) {
924 // !C1 == C -> false iff C1 == C.
925 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
926 Result.getNotConstant(), C, TD);
927 if (Res->isNullValue())
928 return False;
929 } else if (Pred == ICmpInst::ICMP_NE) {
930 // !C1 != C -> true iff C1 == C.
Chris Lattner5553a3a2009-11-15 20:01:24 +0000931 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Chris Lattnerb52675b2009-11-12 04:36:58 +0000932 Result.getNotConstant(), C, TD);
933 if (Res->isNullValue())
934 return True;
935 }
Chris Lattner2c5adf82009-11-15 19:59:49 +0000936 return Unknown;
Chris Lattnerb52675b2009-11-12 04:36:58 +0000937 }
938
Chris Lattnercc4d3b22009-11-11 02:08:33 +0000939 return Unknown;
940}
941
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000942void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
943 BasicBlock* NewSucc) {
Owen Anderson00ac77e2010-08-18 18:39:01 +0000944 if (PImpl) getCache(PImpl).threadEdge(PredBB, OldSucc, NewSucc);
945}
946
947void LazyValueInfo::eraseBlock(BasicBlock *BB) {
948 if (PImpl) getCache(PImpl).eraseBlock(BB);
Owen Andersoncfa7fb62010-07-26 18:48:03 +0000949}