blob: d56df14355df266358b3e2e771c18c9ea9929545 [file] [log] [blame]
Hans Wennborgc5ec73d2014-11-21 18:58:23 +00001//===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===//
Chris Lattner741c94c2009-11-11 00:22:30 +00002//
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
15#include "llvm/Analysis/LazyValueInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/STLExtras.h"
Hal Finkel7e184492014-09-07 20:29:59 +000018#include "llvm/Analysis/AssumptionTracker.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Analysis/ConstantFolding.h"
Dan Gohmana4fcd242010-12-15 20:02:24 +000020#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000021#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000022#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Constants.h"
24#include "llvm/IR/DataLayout.h"
Hal Finkel7e184492014-09-07 20:29:59 +000025#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Instructions.h"
27#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000028#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000029#include "llvm/IR/ValueHandle.h"
Chris Lattnerb584d1e2009-11-12 01:22:16 +000030#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Support/raw_ostream.h"
32#include "llvm/Target/TargetLibraryInfo.h"
Bill Wendling4ec081a2012-01-11 23:43:34 +000033#include <map>
Nick Lewycky55a700b2010-12-18 01:00:40 +000034#include <stack>
Chris Lattner741c94c2009-11-11 00:22:30 +000035using namespace llvm;
Benjamin Kramerd9d80b12012-03-02 15:34:43 +000036using namespace PatternMatch;
Chris Lattner741c94c2009-11-11 00:22:30 +000037
Chandler Carruthf1221bd2014-04-22 02:48:03 +000038#define DEBUG_TYPE "lazy-value-info"
39
Chris Lattner741c94c2009-11-11 00:22:30 +000040char LazyValueInfo::ID = 0;
Chad Rosier43a33062011-12-02 01:26:24 +000041INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
42 "Lazy Value Information Analysis", false, true)
Hal Finkel7e184492014-09-07 20:29:59 +000043INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
Chad Rosier43a33062011-12-02 01:26:24 +000044INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
45INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
Owen Andersondf7a4f22010-10-07 22:25:06 +000046 "Lazy Value Information Analysis", false, true)
Chris Lattner741c94c2009-11-11 00:22:30 +000047
48namespace llvm {
49 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
50}
51
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000052
53//===----------------------------------------------------------------------===//
54// LVILatticeVal
55//===----------------------------------------------------------------------===//
56
57/// LVILatticeVal - This is the information tracked by LazyValueInfo for each
58/// value.
59///
60/// FIXME: This is basically just for bringup, this can be made a lot more rich
61/// in the future.
62///
63namespace {
64class LVILatticeVal {
65 enum LatticeValueTy {
Nick Lewycky11678bd2010-12-15 18:57:18 +000066 /// undefined - This Value has no known value yet.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000067 undefined,
Owen Anderson0f306a42010-08-05 22:59:19 +000068
Nick Lewycky11678bd2010-12-15 18:57:18 +000069 /// constant - This Value has a specific constant value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000070 constant,
Nick Lewycky11678bd2010-12-15 18:57:18 +000071 /// notconstant - This Value is known to not have the specified value.
Chris Lattner565ee2f2009-11-12 04:36:58 +000072 notconstant,
Chad Rosier43a33062011-12-02 01:26:24 +000073
Nick Lewycky11678bd2010-12-15 18:57:18 +000074 /// constantrange - The Value falls within this range.
Owen Anderson0f306a42010-08-05 22:59:19 +000075 constantrange,
Chad Rosier43a33062011-12-02 01:26:24 +000076
Nick Lewycky11678bd2010-12-15 18:57:18 +000077 /// overdefined - This value is not known to be constant, and we know that
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000078 /// it has a value.
79 overdefined
80 };
81
82 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattner565ee2f2009-11-12 04:36:58 +000083 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersonc3a14132010-08-05 22:10:46 +000084 LatticeValueTy Tag;
85 Constant *Val;
Owen Anderson0f306a42010-08-05 22:59:19 +000086 ConstantRange Range;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000087
88public:
Craig Topper9f008862014-04-15 04:59:12 +000089 LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000090
Chris Lattner19019ea2009-11-11 22:48:44 +000091 static LVILatticeVal get(Constant *C) {
92 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +000093 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +000094 Res.markConstant(C);
Chris Lattner19019ea2009-11-11 22:48:44 +000095 return Res;
96 }
Chris Lattner565ee2f2009-11-12 04:36:58 +000097 static LVILatticeVal getNot(Constant *C) {
98 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +000099 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +0000100 Res.markNotConstant(C);
Chris Lattner565ee2f2009-11-12 04:36:58 +0000101 return Res;
102 }
Owen Anderson5f1dd092010-08-10 23:20:01 +0000103 static LVILatticeVal getRange(ConstantRange CR) {
104 LVILatticeVal Res;
105 Res.markConstantRange(CR);
106 return Res;
107 }
Chris Lattner19019ea2009-11-11 22:48:44 +0000108
Owen Anderson0f306a42010-08-05 22:59:19 +0000109 bool isUndefined() const { return Tag == undefined; }
110 bool isConstant() const { return Tag == constant; }
111 bool isNotConstant() const { return Tag == notconstant; }
112 bool isConstantRange() const { return Tag == constantrange; }
113 bool isOverdefined() const { return Tag == overdefined; }
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000114
115 Constant *getConstant() const {
116 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000117 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000118 }
119
Chris Lattner565ee2f2009-11-12 04:36:58 +0000120 Constant *getNotConstant() const {
121 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000122 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000123 }
124
Owen Anderson0f306a42010-08-05 22:59:19 +0000125 ConstantRange getConstantRange() const {
126 assert(isConstantRange() &&
127 "Cannot get the constant-range of a non-constant-range!");
128 return Range;
129 }
130
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000131 /// markOverdefined - Return true if this is a change in status.
132 bool markOverdefined() {
133 if (isOverdefined())
134 return false;
Owen Andersonc3a14132010-08-05 22:10:46 +0000135 Tag = overdefined;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000136 return true;
137 }
138
139 /// markConstant - Return true if this is a change in status.
140 bool markConstant(Constant *V) {
Nick Lewycky11678bd2010-12-15 18:57:18 +0000141 assert(V && "Marking constant with NULL");
142 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
143 return markConstantRange(ConstantRange(CI->getValue()));
144 if (isa<UndefValue>(V))
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000145 return false;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000146
147 assert((!isConstant() || getConstant() == V) &&
148 "Marking constant with different value");
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000149 assert(isUndefined());
Owen Andersonc3a14132010-08-05 22:10:46 +0000150 Tag = constant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000151 Val = V;
Chris Lattner19019ea2009-11-11 22:48:44 +0000152 return true;
153 }
154
Chris Lattner565ee2f2009-11-12 04:36:58 +0000155 /// markNotConstant - Return true if this is a change in status.
156 bool markNotConstant(Constant *V) {
Chris Lattner565ee2f2009-11-12 04:36:58 +0000157 assert(V && "Marking constant with NULL");
Nick Lewycky11678bd2010-12-15 18:57:18 +0000158 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
159 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
160 if (isa<UndefValue>(V))
161 return false;
162
163 assert((!isConstant() || getConstant() != V) &&
164 "Marking constant !constant with same value");
165 assert((!isNotConstant() || getNotConstant() == V) &&
166 "Marking !constant with different value");
167 assert(isUndefined() || isConstant());
168 Tag = notconstant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000169 Val = V;
Chris Lattner565ee2f2009-11-12 04:36:58 +0000170 return true;
171 }
172
Owen Anderson0f306a42010-08-05 22:59:19 +0000173 /// markConstantRange - Return true if this is a change in status.
174 bool markConstantRange(const ConstantRange NewR) {
175 if (isConstantRange()) {
176 if (NewR.isEmptySet())
177 return markOverdefined();
178
Nuno Lopese6e04902012-06-28 01:16:18 +0000179 bool changed = Range != NewR;
Owen Anderson0f306a42010-08-05 22:59:19 +0000180 Range = NewR;
181 return changed;
182 }
183
184 assert(isUndefined());
185 if (NewR.isEmptySet())
186 return markOverdefined();
Owen Anderson0f306a42010-08-05 22:59:19 +0000187
188 Tag = constantrange;
189 Range = NewR;
190 return true;
191 }
192
Chris Lattner19019ea2009-11-11 22:48:44 +0000193 /// mergeIn - Merge the specified lattice value into this one, updating this
194 /// one and returning true if anything changed.
195 bool mergeIn(const LVILatticeVal &RHS) {
196 if (RHS.isUndefined() || isOverdefined()) return false;
197 if (RHS.isOverdefined()) return markOverdefined();
198
Nick Lewycky11678bd2010-12-15 18:57:18 +0000199 if (isUndefined()) {
200 Tag = RHS.Tag;
201 Val = RHS.Val;
202 Range = RHS.Range;
203 return true;
Chris Lattner22db4b52009-11-12 04:57:13 +0000204 }
205
Nick Lewycky11678bd2010-12-15 18:57:18 +0000206 if (isConstant()) {
207 if (RHS.isConstant()) {
208 if (Val == RHS.Val)
209 return false;
210 return markOverdefined();
211 }
212
213 if (RHS.isNotConstant()) {
214 if (Val == RHS.Val)
215 return markOverdefined();
216
217 // Unless we can prove that the two Constants are different, we must
218 // move to overdefined.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000219 // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
Nick Lewycky11678bd2010-12-15 18:57:18 +0000220 if (ConstantInt *Res = dyn_cast<ConstantInt>(
221 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
222 getConstant(),
223 RHS.getNotConstant())))
224 if (Res->isOne())
225 return markNotConstant(RHS.getNotConstant());
226
227 return markOverdefined();
228 }
229
230 // RHS is a ConstantRange, LHS is a non-integer Constant.
231
232 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
233 // a function. The correct result is to pick up RHS.
234
Chris Lattner19019ea2009-11-11 22:48:44 +0000235 return markOverdefined();
Nick Lewycky11678bd2010-12-15 18:57:18 +0000236 }
237
238 if (isNotConstant()) {
239 if (RHS.isConstant()) {
240 if (Val == RHS.Val)
241 return markOverdefined();
242
243 // Unless we can prove that the two Constants are different, we must
244 // move to overdefined.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000245 // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
Nick Lewycky11678bd2010-12-15 18:57:18 +0000246 if (ConstantInt *Res = dyn_cast<ConstantInt>(
247 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
248 getNotConstant(),
249 RHS.getConstant())))
250 if (Res->isOne())
251 return false;
252
253 return markOverdefined();
254 }
255
256 if (RHS.isNotConstant()) {
257 if (Val == RHS.Val)
258 return false;
259 return markOverdefined();
260 }
261
262 return markOverdefined();
263 }
264
265 assert(isConstantRange() && "New LVILattice type?");
266 if (!RHS.isConstantRange())
267 return markOverdefined();
268
269 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
270 if (NewR.isFullSet())
271 return markOverdefined();
272 return markConstantRange(NewR);
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000273 }
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000274};
275
276} // end anonymous namespace.
277
Chris Lattner19019ea2009-11-11 22:48:44 +0000278namespace llvm {
Chandler Carruth2b1ba482011-04-18 18:49:44 +0000279raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
280 LLVM_ATTRIBUTE_USED;
Chris Lattner19019ea2009-11-11 22:48:44 +0000281raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
282 if (Val.isUndefined())
283 return OS << "undefined";
284 if (Val.isOverdefined())
285 return OS << "overdefined";
Chris Lattner565ee2f2009-11-12 04:36:58 +0000286
287 if (Val.isNotConstant())
288 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Owen Anderson8afac042010-08-09 20:50:46 +0000289 else if (Val.isConstantRange())
290 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
291 << Val.getConstantRange().getUpper() << '>';
Chris Lattner19019ea2009-11-11 22:48:44 +0000292 return OS << "constant<" << *Val.getConstant() << '>';
293}
294}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000295
296//===----------------------------------------------------------------------===//
Chris Lattneraf025d32009-11-15 19:59:49 +0000297// LazyValueInfoCache Decl
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000298//===----------------------------------------------------------------------===//
299
Chris Lattneraf025d32009-11-15 19:59:49 +0000300namespace {
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000301 /// LVIValueHandle - A callback value handle updates the cache when
Owen Anderson118ac802011-01-05 21:15:29 +0000302 /// values are erased.
303 class LazyValueInfoCache;
304 struct LVIValueHandle : public CallbackVH {
305 LazyValueInfoCache *Parent;
306
307 LVIValueHandle(Value *V, LazyValueInfoCache *P)
308 : CallbackVH(V), Parent(P) { }
Craig Toppere9ba7592014-03-05 07:30:04 +0000309
310 void deleted() override;
311 void allUsesReplacedWith(Value *V) override {
Owen Anderson118ac802011-01-05 21:15:29 +0000312 deleted();
313 }
314 };
315}
316
Owen Anderson118ac802011-01-05 21:15:29 +0000317namespace {
Chris Lattneraf025d32009-11-15 19:59:49 +0000318 /// LazyValueInfoCache - This is the cache kept by LazyValueInfo which
319 /// maintains information about queries across the clients' queries.
320 class LazyValueInfoCache {
Chris Lattneraf025d32009-11-15 19:59:49 +0000321 /// ValueCacheEntryTy - This is all of the cached block information for
322 /// exactly one Value*. The entries are sorted by the BasicBlock* of the
323 /// entries, allowing us to do a lookup with a binary search.
Bill Wendling4ec081a2012-01-11 23:43:34 +0000324 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
Chris Lattneraf025d32009-11-15 19:59:49 +0000325
Owen Anderson6f060af2011-01-05 23:26:22 +0000326 /// ValueCache - This is all of the cached information for all values,
327 /// mapped from Value* to key information.
Bill Wendling58c75692012-01-12 01:41:03 +0000328 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
Owen Anderson6f060af2011-01-05 23:26:22 +0000329
330 /// OverDefinedCache - This tracks, on a per-block basis, the set of
331 /// values that are over-defined at the end of that block. This is required
332 /// for cache updating.
333 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
334 DenseSet<OverDefinedPairTy> OverDefinedCache;
Benjamin Kramer36647082011-12-03 15:16:45 +0000335
336 /// SeenBlocks - Keep track of all blocks that we have ever seen, so we
337 /// don't spend time removing unused blocks from our caches.
338 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
339
Owen Anderson6f060af2011-01-05 23:26:22 +0000340 /// BlockValueStack - This stack holds the state of the value solver
341 /// during a query. It basically emulates the callstack of the naive
342 /// recursive value lookup process.
343 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
Hal Finkel7e184492014-09-07 20:29:59 +0000344
Hans Wennborg45172ac2014-11-25 17:23:05 +0000345 /// BlockValueSet - Keeps track of which block-value pairs are in
346 /// BlockValueStack.
347 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
348
349 /// pushBlockValue - Push BV onto BlockValueStack unless it's already in
350 /// there. Returns true on success.
351 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
352 if (BlockValueSet.count(BV))
353 return false; // It's already in the stack.
354
355 BlockValueStack.push(BV);
356 BlockValueSet.insert(BV);
357 return true;
358 }
359
Hal Finkel7e184492014-09-07 20:29:59 +0000360 /// A pointer to the cache of @llvm.assume calls.
361 AssumptionTracker *AT;
362 /// An optional DL pointer.
363 const DataLayout *DL;
364 /// An optional DT pointer.
365 DominatorTree *DT;
Owen Anderson6f060af2011-01-05 23:26:22 +0000366
Owen Anderson118ac802011-01-05 21:15:29 +0000367 friend struct LVIValueHandle;
Owen Anderson6f060af2011-01-05 23:26:22 +0000368
Hans Wennborg45172ac2014-11-25 17:23:05 +0000369 void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
370 SeenBlocks.insert(BB);
371 lookup(Val)[BB] = Result;
372 if (Result.isOverdefined())
373 OverDefinedCache.insert(std::make_pair(BB, Val));
374 }
Owen Andersonc1561b82010-07-30 23:59:40 +0000375
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000376 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000377 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
Hal Finkel7e184492014-09-07 20:29:59 +0000378 LVILatticeVal &Result,
379 Instruction *CxtI = nullptr);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000380 bool hasBlockValue(Value *Val, BasicBlock *BB);
381
382 // These methods process one work item and may add more. A false value
383 // returned means that the work item was not completely processed and must
384 // be revisited after going through the new items.
385 bool solveBlockValue(Value *Val, BasicBlock *BB);
Owen Anderson64c2c572010-12-20 18:18:16 +0000386 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
387 Value *Val, BasicBlock *BB);
388 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
389 PHINode *PN, BasicBlock *BB);
390 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
391 Instruction *BBI, BasicBlock *BB);
Hal Finkel7e184492014-09-07 20:29:59 +0000392 void mergeAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
393 Instruction *BBI);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000394
395 void solve();
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000396
Nick Lewycky11678bd2010-12-15 18:57:18 +0000397 ValueCacheEntryTy &lookup(Value *V) {
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000398 return ValueCache[LVIValueHandle(V, this)];
399 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000400
Chris Lattneraf025d32009-11-15 19:59:49 +0000401 public:
Chris Lattneraf025d32009-11-15 19:59:49 +0000402 /// getValueInBlock - This is the query interface to determine the lattice
403 /// value for the specified Value* at the end of the specified block.
Hal Finkel7e184492014-09-07 20:29:59 +0000404 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
405 Instruction *CxtI = nullptr);
406
407 /// getValueAt - This is the query interface to determine the lattice
408 /// value for the specified Value* at the specified instruction (generally
409 /// from an assume intrinsic).
410 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
Chris Lattneraf025d32009-11-15 19:59:49 +0000411
412 /// getValueOnEdge - This is the query interface to determine the lattice
413 /// value for the specified Value* that is true on the specified edge.
Hal Finkel7e184492014-09-07 20:29:59 +0000414 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
415 Instruction *CxtI = nullptr);
Owen Andersonaa7f66b2010-07-26 18:48:03 +0000416
417 /// threadEdge - This is the update interface to inform the cache that an
418 /// edge from PredBB to OldSucc has been threaded to be from PredBB to
419 /// NewSucc.
420 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Owen Anderson208636f2010-08-18 18:39:01 +0000421
422 /// eraseBlock - This is part of the update interface to inform the cache
423 /// that a block has been deleted.
424 void eraseBlock(BasicBlock *BB);
425
426 /// clear - Empty the cache.
427 void clear() {
Benjamin Kramerbbf3c602011-12-03 15:19:55 +0000428 SeenBlocks.clear();
Owen Anderson208636f2010-08-18 18:39:01 +0000429 ValueCache.clear();
430 OverDefinedCache.clear();
431 }
Hal Finkel7e184492014-09-07 20:29:59 +0000432
433 LazyValueInfoCache(AssumptionTracker *AT,
434 const DataLayout *DL = nullptr,
435 DominatorTree *DT = nullptr) : AT(AT), DL(DL), DT(DT) {}
Chris Lattneraf025d32009-11-15 19:59:49 +0000436 };
437} // end anonymous namespace
438
Owen Anderson118ac802011-01-05 21:15:29 +0000439void LVIValueHandle::deleted() {
440 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
441
442 SmallVector<OverDefinedPairTy, 4> ToErase;
Hans Wennborgcbb18e32014-11-21 19:07:46 +0000443 for (const OverDefinedPairTy &P : Parent->OverDefinedCache)
444 if (P.second == getValPtr())
445 ToErase.push_back(P);
446 for (const OverDefinedPairTy &P : ToErase)
447 Parent->OverDefinedCache.erase(P);
Owen Anderson118ac802011-01-05 21:15:29 +0000448
Owen Anderson7b974a42010-08-11 22:36:04 +0000449 // This erasure deallocates *this, so it MUST happen after we're done
450 // using any and all members of *this.
451 Parent->ValueCache.erase(*this);
Owen Andersonc1561b82010-07-30 23:59:40 +0000452}
453
Owen Anderson208636f2010-08-18 18:39:01 +0000454void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
Benjamin Kramer36647082011-12-03 15:16:45 +0000455 // Shortcut if we have never seen this block.
456 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
457 if (I == SeenBlocks.end())
458 return;
459 SeenBlocks.erase(I);
460
Owen Anderson118ac802011-01-05 21:15:29 +0000461 SmallVector<OverDefinedPairTy, 4> ToErase;
Hans Wennborgcbb18e32014-11-21 19:07:46 +0000462 for (const OverDefinedPairTy& P : OverDefinedCache)
463 if (P.first == BB)
464 ToErase.push_back(P);
465 for (const OverDefinedPairTy &P : ToErase)
466 OverDefinedCache.erase(P);
Owen Anderson208636f2010-08-18 18:39:01 +0000467
Bill Wendling58c75692012-01-12 01:41:03 +0000468 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
Owen Anderson208636f2010-08-18 18:39:01 +0000469 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
470 I->second.erase(BB);
471}
Owen Andersonc1561b82010-07-30 23:59:40 +0000472
Nick Lewycky55a700b2010-12-18 01:00:40 +0000473void LazyValueInfoCache::solve() {
Owen Anderson6f060af2011-01-05 23:26:22 +0000474 while (!BlockValueStack.empty()) {
475 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000476 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
477
Nuno Lopese6e04902012-06-28 01:16:18 +0000478 if (solveBlockValue(e.second, e.first)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000479 // The work item was completely processed.
480 assert(BlockValueStack.top() == e && "Nothing should have been pushed!");
481 assert(lookup(e.second).count(e.first) && "Result should be in cache!");
482
Owen Anderson6f060af2011-01-05 23:26:22 +0000483 BlockValueStack.pop();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000484 BlockValueSet.erase(e);
485 } else {
486 // More work needs to be done before revisiting.
487 assert(BlockValueStack.top() != e && "Stack should have been pushed!");
Nuno Lopese6e04902012-06-28 01:16:18 +0000488 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000489 }
490}
491
492bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
493 // If already a constant, there is nothing to compute.
494 if (isa<Constant>(Val))
495 return true;
496
Owen Anderson118ac802011-01-05 21:15:29 +0000497 LVIValueHandle ValHandle(Val, this);
Benjamin Kramerf29db272012-08-22 15:37:57 +0000498 std::map<LVIValueHandle, ValueCacheEntryTy>::iterator I =
499 ValueCache.find(ValHandle);
500 if (I == ValueCache.end()) return false;
501 return I->second.count(BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000502}
503
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000504LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000505 // If already a constant, there is nothing to compute.
506 if (Constant *VC = dyn_cast<Constant>(Val))
507 return LVILatticeVal::get(VC);
508
Benjamin Kramer36647082011-12-03 15:16:45 +0000509 SeenBlocks.insert(BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000510 return lookup(Val)[BB];
511}
512
513bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
514 if (isa<Constant>(Val))
515 return true;
516
Hans Wennborg45172ac2014-11-25 17:23:05 +0000517 if (lookup(Val).count(BB)) {
518 // If we have a cached value, use that.
519 DEBUG(dbgs() << " reuse BB '" << BB->getName()
520 << "' val=" << lookup(Val)[BB] << '\n');
Nick Lewycky55a700b2010-12-18 01:00:40 +0000521
Hans Wennborg45172ac2014-11-25 17:23:05 +0000522 // Since we're reusing a cached value, we don't need to update the
523 // OverDefinedCache. The cache will have been properly updated whenever the
524 // cached value was inserted.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000525 return true;
Chris Lattner2c708562009-11-15 20:00:52 +0000526 }
527
Hans Wennborg45172ac2014-11-25 17:23:05 +0000528 // Hold off inserting this value into the Cache in case we have to return
529 // false and come back later.
530 LVILatticeVal Res;
Chris Lattneraf025d32009-11-15 19:59:49 +0000531
Chris Lattneraf025d32009-11-15 19:59:49 +0000532 Instruction *BBI = dyn_cast<Instruction>(Val);
Craig Topper9f008862014-04-15 04:59:12 +0000533 if (!BBI || BBI->getParent() != BB) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000534 if (!solveBlockValueNonLocal(Res, Val, BB))
535 return false;
536 insertResult(Val, BB, Res);
537 return true;
Chris Lattneraf025d32009-11-15 19:59:49 +0000538 }
Chris Lattner2c708562009-11-15 20:00:52 +0000539
Nick Lewycky55a700b2010-12-18 01:00:40 +0000540 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000541 if (!solveBlockValuePHINode(Res, PN, BB))
542 return false;
543 insertResult(Val, BB, Res);
544 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000545 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000546
Nick Lewycky367f98f2011-01-15 09:16:12 +0000547 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000548 Res = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
549 insertResult(Val, BB, Res);
550 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000551 }
552
Owen Anderson80d19f02010-08-18 21:11:37 +0000553 // We can only analyze the definitions of certain classes of instructions
554 // (integral binops and casts at the moment), so bail if this isn't one.
Chris Lattneraf025d32009-11-15 19:59:49 +0000555 LVILatticeVal Result;
Owen Anderson80d19f02010-08-18 21:11:37 +0000556 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
557 !BBI->getType()->isIntegerTy()) {
558 DEBUG(dbgs() << " compute BB '" << BB->getName()
559 << "' - overdefined because inst def found.\n");
Hans Wennborg45172ac2014-11-25 17:23:05 +0000560 Res.markOverdefined();
561 insertResult(Val, BB, Res);
562 return true;
Owen Anderson80d19f02010-08-18 21:11:37 +0000563 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000564
Owen Anderson80d19f02010-08-18 21:11:37 +0000565 // FIXME: We're currently limited to binops with a constant RHS. This should
566 // be improved.
567 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
568 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
569 DEBUG(dbgs() << " compute BB '" << BB->getName()
570 << "' - overdefined because inst def found.\n");
571
Hans Wennborg45172ac2014-11-25 17:23:05 +0000572 Res.markOverdefined();
573 insertResult(Val, BB, Res);
574 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000575 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000576
Hans Wennborg45172ac2014-11-25 17:23:05 +0000577 if (!solveBlockValueConstantRange(Res, BBI, BB))
578 return false;
579 insertResult(Val, BB, Res);
580 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000581}
582
583static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
584 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
585 return L->getPointerAddressSpace() == 0 &&
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000586 GetUnderlyingObject(L->getPointerOperand()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000587 }
588 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
589 return S->getPointerAddressSpace() == 0 &&
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000590 GetUnderlyingObject(S->getPointerOperand()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000591 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000592 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
593 if (MI->isVolatile()) return false;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000594
595 // FIXME: check whether it has a valuerange that excludes zero?
596 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
597 if (!Len || Len->isZero()) return false;
598
Eli Friedman7a5fc692011-05-31 20:40:16 +0000599 if (MI->getDestAddressSpace() == 0)
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000600 if (GetUnderlyingObject(MI->getRawDest()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000601 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000602 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman7a5fc692011-05-31 20:40:16 +0000603 if (MTI->getSourceAddressSpace() == 0)
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000604 if (GetUnderlyingObject(MTI->getRawSource()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000605 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000606 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000607 return false;
608}
609
Owen Anderson64c2c572010-12-20 18:18:16 +0000610bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
611 Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000612 LVILatticeVal Result; // Start Undefined.
613
614 // If this is a pointer, and there's a load from that pointer in this BB,
615 // then we know that the pointer can't be NULL.
616 bool NotNull = false;
617 if (Val->getType()->isPointerTy()) {
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000618 if (isKnownNonNull(Val)) {
Nick Lewycky367f98f2011-01-15 09:16:12 +0000619 NotNull = true;
620 } else {
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000621 Value *UnderlyingVal = GetUnderlyingObject(Val);
622 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
623 // inside InstructionDereferencesPointer either.
Craig Topper9f008862014-04-15 04:59:12 +0000624 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, nullptr, 1)) {
Hans Wennborgcbb18e32014-11-21 19:07:46 +0000625 for (Instruction &I : *BB) {
626 if (InstructionDereferencesPointer(&I, UnderlyingVal)) {
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000627 NotNull = true;
628 break;
629 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000630 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000631 }
632 }
633 }
634
635 // If this is the entry block, we must be asking about an argument. The
636 // value is overdefined.
637 if (BB == &BB->getParent()->getEntryBlock()) {
638 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
639 if (NotNull) {
Chris Lattner229907c2011-07-18 04:54:35 +0000640 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000641 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
642 } else {
643 Result.markOverdefined();
644 }
Owen Anderson64c2c572010-12-20 18:18:16 +0000645 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000646 return true;
647 }
648
649 // Loop over all of our predecessors, merging what we know from them into
650 // result.
651 bool EdgesMissing = false;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000652 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000653 LVILatticeVal EdgeResult;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000654 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000655 if (EdgesMissing)
656 continue;
657
658 Result.mergeIn(EdgeResult);
659
660 // If we hit overdefined, exit early. The BlockVals entry is already set
661 // to overdefined.
662 if (Result.isOverdefined()) {
663 DEBUG(dbgs() << " compute BB '" << BB->getName()
664 << "' - overdefined because of pred.\n");
665 // If we previously determined that this is a pointer that can't be null
666 // then return that rather than giving up entirely.
667 if (NotNull) {
Chris Lattner229907c2011-07-18 04:54:35 +0000668 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000669 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
670 }
Owen Anderson64c2c572010-12-20 18:18:16 +0000671
672 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000673 return true;
674 }
675 }
676 if (EdgesMissing)
677 return false;
678
679 // Return the merged value, which is more precise than 'overdefined'.
680 assert(!Result.isOverdefined());
Owen Anderson64c2c572010-12-20 18:18:16 +0000681 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000682 return true;
683}
684
Owen Anderson64c2c572010-12-20 18:18:16 +0000685bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
686 PHINode *PN, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000687 LVILatticeVal Result; // Start Undefined.
688
689 // Loop over all of our predecessors, merging what we know from them into
690 // result.
691 bool EdgesMissing = false;
692 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
693 BasicBlock *PhiBB = PN->getIncomingBlock(i);
694 Value *PhiVal = PN->getIncomingValue(i);
695 LVILatticeVal EdgeResult;
Hal Finkel2400c962014-10-16 00:40:05 +0000696 // Note that we can provide PN as the context value to getEdgeValue, even
697 // though the results will be cached, because PN is the value being used as
698 // the cache key in the caller.
Hal Finkel7e184492014-09-07 20:29:59 +0000699 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000700 if (EdgesMissing)
701 continue;
702
703 Result.mergeIn(EdgeResult);
704
705 // If we hit overdefined, exit early. The BlockVals entry is already set
706 // to overdefined.
707 if (Result.isOverdefined()) {
708 DEBUG(dbgs() << " compute BB '" << BB->getName()
709 << "' - overdefined because of pred.\n");
Owen Anderson64c2c572010-12-20 18:18:16 +0000710
711 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000712 return true;
713 }
714 }
715 if (EdgesMissing)
716 return false;
717
718 // Return the merged value, which is more precise than 'overdefined'.
719 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson64c2c572010-12-20 18:18:16 +0000720 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000721 return true;
722}
723
Hal Finkel7e184492014-09-07 20:29:59 +0000724static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
725 LVILatticeVal &Result,
726 bool isTrueDest = true);
727
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000728// If we can determine a constant range for the value Val in the context
Hal Finkel7e184492014-09-07 20:29:59 +0000729// provided by the instruction BBI, then merge it into BBLV. If we did find a
730// constant range, return true.
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000731void LazyValueInfoCache::mergeAssumeBlockValueConstantRange(Value *Val,
732 LVILatticeVal &BBLV,
733 Instruction *BBI) {
Hal Finkel7e184492014-09-07 20:29:59 +0000734 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
735 if (!BBI)
736 return;
737
738 for (auto &I : AT->assumptions(BBI->getParent()->getParent())) {
739 if (!isValidAssumeForContext(I, BBI, DL, DT))
740 continue;
741
742 Value *C = I->getArgOperand(0);
743 if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) {
744 LVILatticeVal Result;
745 if (getValueFromFromCondition(Val, ICI, Result)) {
746 if (BBLV.isOverdefined())
747 BBLV = Result;
748 else
749 BBLV.mergeIn(Result);
750 }
751 }
752 }
753}
754
Owen Anderson64c2c572010-12-20 18:18:16 +0000755bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
756 Instruction *BBI,
Nick Lewycky55a700b2010-12-18 01:00:40 +0000757 BasicBlock *BB) {
Owen Anderson80d19f02010-08-18 21:11:37 +0000758 // Figure out the range of the LHS. If that fails, bail.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000759 if (!hasBlockValue(BBI->getOperand(0), BB)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000760 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
761 return false;
762 BBLV.markOverdefined();
763 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000764 }
765
Nick Lewycky55a700b2010-12-18 01:00:40 +0000766 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Hal Finkel7e184492014-09-07 20:29:59 +0000767 mergeAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
Owen Anderson80d19f02010-08-18 21:11:37 +0000768 if (!LHSVal.isConstantRange()) {
Owen Anderson64c2c572010-12-20 18:18:16 +0000769 BBLV.markOverdefined();
Nick Lewycky55a700b2010-12-18 01:00:40 +0000770 return true;
Owen Anderson80d19f02010-08-18 21:11:37 +0000771 }
772
Owen Anderson80d19f02010-08-18 21:11:37 +0000773 ConstantRange LHSRange = LHSVal.getConstantRange();
774 ConstantRange RHSRange(1);
Chris Lattner229907c2011-07-18 04:54:35 +0000775 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
Owen Anderson80d19f02010-08-18 21:11:37 +0000776 if (isa<BinaryOperator>(BBI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000777 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
778 RHSRange = ConstantRange(RHS->getValue());
779 } else {
Owen Anderson64c2c572010-12-20 18:18:16 +0000780 BBLV.markOverdefined();
Nick Lewycky55a700b2010-12-18 01:00:40 +0000781 return true;
Owen Andersonc62f7042010-08-24 07:55:44 +0000782 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000783 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000784
Owen Anderson80d19f02010-08-18 21:11:37 +0000785 // NOTE: We're currently limited by the set of operations that ConstantRange
786 // can evaluate symbolically. Enhancing that set will allows us to analyze
787 // more definitions.
Owen Anderson64c2c572010-12-20 18:18:16 +0000788 LVILatticeVal Result;
Owen Anderson80d19f02010-08-18 21:11:37 +0000789 switch (BBI->getOpcode()) {
790 case Instruction::Add:
791 Result.markConstantRange(LHSRange.add(RHSRange));
792 break;
793 case Instruction::Sub:
794 Result.markConstantRange(LHSRange.sub(RHSRange));
795 break;
796 case Instruction::Mul:
797 Result.markConstantRange(LHSRange.multiply(RHSRange));
798 break;
799 case Instruction::UDiv:
800 Result.markConstantRange(LHSRange.udiv(RHSRange));
801 break;
802 case Instruction::Shl:
803 Result.markConstantRange(LHSRange.shl(RHSRange));
804 break;
805 case Instruction::LShr:
806 Result.markConstantRange(LHSRange.lshr(RHSRange));
807 break;
808 case Instruction::Trunc:
809 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
810 break;
811 case Instruction::SExt:
812 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
813 break;
814 case Instruction::ZExt:
815 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
816 break;
817 case Instruction::BitCast:
818 Result.markConstantRange(LHSRange);
819 break;
Nick Lewyckyad48e012010-09-07 05:39:02 +0000820 case Instruction::And:
821 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
822 break;
823 case Instruction::Or:
824 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
825 break;
Owen Anderson80d19f02010-08-18 21:11:37 +0000826
827 // Unhandled instructions are overdefined.
828 default:
829 DEBUG(dbgs() << " compute BB '" << BB->getName()
830 << "' - overdefined because inst def found.\n");
831 Result.markOverdefined();
832 break;
833 }
834
Owen Anderson64c2c572010-12-20 18:18:16 +0000835 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000836 return true;
Chris Lattner741c94c2009-11-11 00:22:30 +0000837}
838
Hal Finkel7e184492014-09-07 20:29:59 +0000839bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
840 LVILatticeVal &Result, bool isTrueDest) {
841 if (ICI && isa<Constant>(ICI->getOperand(1))) {
842 if (ICI->isEquality() && ICI->getOperand(0) == Val) {
843 // We know that V has the RHS constant if this is a true SETEQ or
844 // false SETNE.
845 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
846 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
847 else
848 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
849 return true;
850 }
851
852 // Recognize the range checking idiom that InstCombine produces.
853 // (X-C1) u< C2 --> [C1, C1+C2)
854 ConstantInt *NegOffset = nullptr;
855 if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
856 match(ICI->getOperand(0), m_Add(m_Specific(Val),
857 m_ConstantInt(NegOffset)));
858
859 ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
860 if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
861 // Calculate the range of values that would satisfy the comparison.
862 ConstantRange CmpRange(CI->getValue());
863 ConstantRange TrueValues =
864 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
865
866 if (NegOffset) // Apply the offset from above.
867 TrueValues = TrueValues.subtract(NegOffset->getValue());
868
869 // If we're interested in the false dest, invert the condition.
870 if (!isTrueDest) TrueValues = TrueValues.inverse();
871
872 Result = LVILatticeVal::getRange(TrueValues);
873 return true;
874 }
875 }
876
877 return false;
878}
879
Nuno Lopese6e04902012-06-28 01:16:18 +0000880/// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
881/// Val is not constrained on the edge.
882static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
883 BasicBlock *BBTo, LVILatticeVal &Result) {
Chris Lattner77358782009-11-15 20:02:12 +0000884 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
885 // know that v != 0.
Chris Lattner19019ea2009-11-11 22:48:44 +0000886 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
887 // If this is a conditional branch and only one successor goes to BBTo, then
888 // we maybe able to infer something from the condition.
889 if (BI->isConditional() &&
890 BI->getSuccessor(0) != BI->getSuccessor(1)) {
891 bool isTrueDest = BI->getSuccessor(0) == BBTo;
892 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
893 "BBTo isn't a successor of BBFrom");
894
895 // If V is the condition of the branch itself, then we know exactly what
896 // it is.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000897 if (BI->getCondition() == Val) {
898 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson185fe002010-08-10 20:03:09 +0000899 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky55a700b2010-12-18 01:00:40 +0000900 return true;
901 }
Chris Lattner19019ea2009-11-11 22:48:44 +0000902
903 // If the condition of the branch is an equality comparison, we may be
904 // able to infer the value.
Owen Anderson0bd61242010-08-11 04:24:25 +0000905 ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition());
Hal Finkel7e184492014-09-07 20:29:59 +0000906 if (getValueFromFromCondition(Val, ICI, Result, isTrueDest))
907 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +0000908 }
909 }
Chris Lattner77358782009-11-15 20:02:12 +0000910
911 // If the edge was formed by a switch on the value, then we may know exactly
912 // what it is.
913 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Nuno Lopes8650fb82012-06-28 16:13:37 +0000914 if (SI->getCondition() != Val)
915 return false;
916
917 bool DefaultCase = SI->getDefaultDest() == BBTo;
918 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
919 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
920
Hans Wennborgcbb18e32014-11-21 19:07:46 +0000921 for (SwitchInst::CaseIt i : SI->cases()) {
Nuno Lopes8650fb82012-06-28 16:13:37 +0000922 ConstantRange EdgeVal(i.getCaseValue()->getValue());
Manman Renf3fedb62012-09-05 23:45:58 +0000923 if (DefaultCase) {
924 // It is possible that the default destination is the destination of
925 // some cases. There is no need to perform difference for those cases.
926 if (i.getCaseSuccessor() != BBTo)
927 EdgesVals = EdgesVals.difference(EdgeVal);
928 } else if (i.getCaseSuccessor() == BBTo)
Nuno Lopesac593802012-05-18 21:02:10 +0000929 EdgesVals = EdgesVals.unionWith(EdgeVal);
Chris Lattner77358782009-11-15 20:02:12 +0000930 }
Nuno Lopes8650fb82012-06-28 16:13:37 +0000931 Result = LVILatticeVal::getRange(EdgesVals);
932 return true;
Chris Lattner77358782009-11-15 20:02:12 +0000933 }
Nuno Lopese6e04902012-06-28 01:16:18 +0000934 return false;
935}
936
937/// \brief Compute the value of Val on the edge BBFrom -> BBTo, or the value at
938/// the basic block if the edge does not constraint Val.
939bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
Hal Finkel7e184492014-09-07 20:29:59 +0000940 BasicBlock *BBTo, LVILatticeVal &Result,
941 Instruction *CxtI) {
Nuno Lopese6e04902012-06-28 01:16:18 +0000942 // If already a constant, there is nothing to compute.
943 if (Constant *VC = dyn_cast<Constant>(Val)) {
944 Result = LVILatticeVal::get(VC);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000945 return true;
946 }
Nuno Lopese6e04902012-06-28 01:16:18 +0000947
948 if (getEdgeValueLocal(Val, BBFrom, BBTo, Result)) {
949 if (!Result.isConstantRange() ||
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000950 Result.getConstantRange().getSingleElement())
Nuno Lopese6e04902012-06-28 01:16:18 +0000951 return true;
952
953 // FIXME: this check should be moved to the beginning of the function when
954 // LVI better supports recursive values. Even for the single value case, we
955 // can intersect to detect dead code (an empty range).
956 if (!hasBlockValue(Val, BBFrom)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000957 if (pushBlockValue(std::make_pair(BBFrom, Val)))
958 return false;
959 Result.markOverdefined();
960 return true;
Nuno Lopese6e04902012-06-28 01:16:18 +0000961 }
962
963 // Try to intersect ranges of the BB and the constraint on the edge.
964 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Hal Finkela3f23e32014-10-14 16:04:49 +0000965 mergeAssumeBlockValueConstantRange(Val, InBlock, BBFrom->getTerminator());
Hal Finkel2400c962014-10-16 00:40:05 +0000966 // See note on the use of the CxtI with mergeAssumeBlockValueConstantRange,
967 // and caching, below.
Hal Finkel7e184492014-09-07 20:29:59 +0000968 mergeAssumeBlockValueConstantRange(Val, InBlock, CxtI);
Nuno Lopese6e04902012-06-28 01:16:18 +0000969 if (!InBlock.isConstantRange())
970 return true;
971
972 ConstantRange Range =
973 Result.getConstantRange().intersectWith(InBlock.getConstantRange());
974 Result = LVILatticeVal::getRange(Range);
975 return true;
976 }
977
978 if (!hasBlockValue(Val, BBFrom)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000979 if (pushBlockValue(std::make_pair(BBFrom, Val)))
980 return false;
981 Result.markOverdefined();
982 return true;
Nuno Lopese6e04902012-06-28 01:16:18 +0000983 }
984
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000985 // If we couldn't compute the value on the edge, use the value from the BB.
Nuno Lopese6e04902012-06-28 01:16:18 +0000986 Result = getBlockValue(Val, BBFrom);
Hal Finkela3f23e32014-10-14 16:04:49 +0000987 mergeAssumeBlockValueConstantRange(Val, Result, BBFrom->getTerminator());
Hal Finkel2400c962014-10-16 00:40:05 +0000988 // We can use the context instruction (generically the ultimate instruction
989 // the calling pass is trying to simplify) here, even though the result of
990 // this function is generally cached when called from the solve* functions
991 // (and that cached result might be used with queries using a different
992 // context instruction), because when this function is called from the solve*
993 // functions, the context instruction is not provided. When called from
994 // LazyValueInfoCache::getValueOnEdge, the context instruction is provided,
995 // but then the result is not cached.
Hal Finkel7e184492014-09-07 20:29:59 +0000996 mergeAssumeBlockValueConstantRange(Val, Result, CxtI);
Nuno Lopese6e04902012-06-28 01:16:18 +0000997 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +0000998}
999
Hal Finkel7e184492014-09-07 20:29:59 +00001000LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB,
1001 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001002 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001003 << BB->getName() << "'\n");
1004
Hans Wennborg45172ac2014-11-25 17:23:05 +00001005 assert(BlockValueStack.empty() && BlockValueSet.empty());
1006 pushBlockValue(std::make_pair(BB, V));
1007
Nick Lewycky55a700b2010-12-18 01:00:40 +00001008 solve();
Owen Andersonc7ed4dc2010-12-09 06:14:58 +00001009 LVILatticeVal Result = getBlockValue(V, BB);
Hal Finkel7e184492014-09-07 20:29:59 +00001010 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
1011
1012 DEBUG(dbgs() << " Result = " << Result << "\n");
1013 return Result;
1014}
1015
1016LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) {
1017 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1018 << CxtI->getName() << "'\n");
1019
1020 LVILatticeVal Result;
1021 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001022
David Greene37e98092009-12-23 20:43:58 +00001023 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001024 return Result;
1025}
Chris Lattner19019ea2009-11-11 22:48:44 +00001026
Chris Lattneraf025d32009-11-15 19:59:49 +00001027LVILatticeVal LazyValueInfoCache::
Hal Finkel7e184492014-09-07 20:29:59 +00001028getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1029 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001030 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001031 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001032
Nick Lewycky55a700b2010-12-18 01:00:40 +00001033 LVILatticeVal Result;
Hal Finkel7e184492014-09-07 20:29:59 +00001034 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +00001035 solve();
Hal Finkel7e184492014-09-07 20:29:59 +00001036 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001037 (void)WasFastQuery;
1038 assert(WasFastQuery && "More work to do after problem solved?");
1039 }
1040
David Greene37e98092009-12-23 20:43:58 +00001041 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001042 return Result;
1043}
1044
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001045void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1046 BasicBlock *NewSucc) {
1047 // When an edge in the graph has been threaded, values that we could not
1048 // determine a value for before (i.e. were marked overdefined) may be possible
1049 // to solve now. We do NOT try to proactively update these values. Instead,
1050 // we clear their entries from the cache, and allow lazy updating to recompute
1051 // them when needed.
1052
Hans Wennborgc5ec73d2014-11-21 18:58:23 +00001053 // The updating process is fairly simple: we need to drop cached info
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001054 // for all values that were marked overdefined in OldSucc, and for those same
1055 // values in any successor of OldSucc (except NewSucc) in which they were
1056 // also marked overdefined.
1057 std::vector<BasicBlock*> worklist;
1058 worklist.push_back(OldSucc);
1059
Owen Andersonaac5a722010-07-27 23:58:11 +00001060 DenseSet<Value*> ClearSet;
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001061 for (OverDefinedPairTy &P : OverDefinedCache)
1062 if (P.first == OldSucc)
1063 ClearSet.insert(P.second);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001064
1065 // Use a worklist to perform a depth-first search of OldSucc's successors.
1066 // NOTE: We do not need a visited list since any blocks we have already
1067 // visited will have had their overdefined markers cleared already, and we
1068 // thus won't loop to their successors.
1069 while (!worklist.empty()) {
1070 BasicBlock *ToUpdate = worklist.back();
1071 worklist.pop_back();
1072
1073 // Skip blocks only accessible through NewSucc.
1074 if (ToUpdate == NewSucc) continue;
1075
1076 bool changed = false;
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001077 for (Value *V : ClearSet) {
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001078 // If a value was marked overdefined in OldSucc, and is here too...
Owen Anderson118ac802011-01-05 21:15:29 +00001079 DenseSet<OverDefinedPairTy>::iterator OI =
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001080 OverDefinedCache.find(std::make_pair(ToUpdate, V));
Owen Andersonaac5a722010-07-27 23:58:11 +00001081 if (OI == OverDefinedCache.end()) continue;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001082
Owen Andersonaac5a722010-07-27 23:58:11 +00001083 // Remove it from the caches.
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001084 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(V, this)];
Owen Andersonaac5a722010-07-27 23:58:11 +00001085 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001086
Owen Andersonaac5a722010-07-27 23:58:11 +00001087 assert(CI != Entry.end() && "Couldn't find entry to update?");
1088 Entry.erase(CI);
1089 OverDefinedCache.erase(OI);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001090
Owen Andersonaac5a722010-07-27 23:58:11 +00001091 // If we removed anything, then we potentially need to update
1092 // blocks successors too.
1093 changed = true;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001094 }
Nick Lewycky55a700b2010-12-18 01:00:40 +00001095
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001096 if (!changed) continue;
1097
1098 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1099 }
1100}
1101
Chris Lattneraf025d32009-11-15 19:59:49 +00001102//===----------------------------------------------------------------------===//
1103// LazyValueInfo Impl
1104//===----------------------------------------------------------------------===//
1105
Chris Lattneraf025d32009-11-15 19:59:49 +00001106/// getCache - This lazily constructs the LazyValueInfoCache.
Hal Finkel7e184492014-09-07 20:29:59 +00001107static LazyValueInfoCache &getCache(void *&PImpl,
1108 AssumptionTracker *AT,
1109 const DataLayout *DL = nullptr,
1110 DominatorTree *DT = nullptr) {
Chris Lattneraf025d32009-11-15 19:59:49 +00001111 if (!PImpl)
Hal Finkel7e184492014-09-07 20:29:59 +00001112 PImpl = new LazyValueInfoCache(AT, DL, DT);
Chris Lattneraf025d32009-11-15 19:59:49 +00001113 return *static_cast<LazyValueInfoCache*>(PImpl);
1114}
1115
Owen Anderson208636f2010-08-18 18:39:01 +00001116bool LazyValueInfo::runOnFunction(Function &F) {
Hal Finkel7e184492014-09-07 20:29:59 +00001117 AT = &getAnalysis<AssumptionTracker>();
1118
1119 DominatorTreeWrapperPass *DTWP =
1120 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1121 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Chad Rosier43a33062011-12-02 01:26:24 +00001122
Rafael Espindola93512512014-02-25 17:30:31 +00001123 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
Craig Topper9f008862014-04-15 04:59:12 +00001124 DL = DLP ? &DLP->getDataLayout() : nullptr;
Hans Wennborgc5ec73d2014-11-21 18:58:23 +00001125
Chad Rosier43a33062011-12-02 01:26:24 +00001126 TLI = &getAnalysis<TargetLibraryInfo>();
1127
Hal Finkel7e184492014-09-07 20:29:59 +00001128 if (PImpl)
1129 getCache(PImpl, AT, DL, DT).clear();
1130
Owen Anderson208636f2010-08-18 18:39:01 +00001131 // Fully lazy.
1132 return false;
1133}
1134
Chad Rosier43a33062011-12-02 01:26:24 +00001135void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1136 AU.setPreservesAll();
Hal Finkel7e184492014-09-07 20:29:59 +00001137 AU.addRequired<AssumptionTracker>();
Chad Rosier43a33062011-12-02 01:26:24 +00001138 AU.addRequired<TargetLibraryInfo>();
1139}
1140
Chris Lattneraf025d32009-11-15 19:59:49 +00001141void LazyValueInfo::releaseMemory() {
1142 // If the cache was allocated, free it.
1143 if (PImpl) {
Hal Finkel7e184492014-09-07 20:29:59 +00001144 delete &getCache(PImpl, AT);
Craig Topper9f008862014-04-15 04:59:12 +00001145 PImpl = nullptr;
Chris Lattneraf025d32009-11-15 19:59:49 +00001146 }
1147}
1148
Hal Finkel7e184492014-09-07 20:29:59 +00001149Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1150 Instruction *CxtI) {
1151 LVILatticeVal Result =
1152 getCache(PImpl, AT, DL, DT).getValueInBlock(V, BB, CxtI);
Chris Lattneraf025d32009-11-15 19:59:49 +00001153
Chris Lattner19019ea2009-11-11 22:48:44 +00001154 if (Result.isConstant())
1155 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001156 if (Result.isConstantRange()) {
Owen Anderson38f6b7f2010-08-27 23:29:38 +00001157 ConstantRange CR = Result.getConstantRange();
1158 if (const APInt *SingleVal = CR.getSingleElement())
1159 return ConstantInt::get(V->getContext(), *SingleVal);
1160 }
Craig Topper9f008862014-04-15 04:59:12 +00001161 return nullptr;
Chris Lattner19019ea2009-11-11 22:48:44 +00001162}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001163
Chris Lattnerd5e25432009-11-12 01:29:10 +00001164/// getConstantOnEdge - Determine whether the specified value is known to be a
1165/// constant on the specified edge. Return null if not.
1166Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
Hal Finkel7e184492014-09-07 20:29:59 +00001167 BasicBlock *ToBB,
1168 Instruction *CxtI) {
1169 LVILatticeVal Result =
1170 getCache(PImpl, AT, DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Chris Lattnerd5e25432009-11-12 01:29:10 +00001171
1172 if (Result.isConstant())
1173 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001174 if (Result.isConstantRange()) {
Owen Anderson185fe002010-08-10 20:03:09 +00001175 ConstantRange CR = Result.getConstantRange();
1176 if (const APInt *SingleVal = CR.getSingleElement())
1177 return ConstantInt::get(V->getContext(), *SingleVal);
1178 }
Craig Topper9f008862014-04-15 04:59:12 +00001179 return nullptr;
Chris Lattnerd5e25432009-11-12 01:29:10 +00001180}
1181
Hal Finkel7e184492014-09-07 20:29:59 +00001182static LazyValueInfo::Tristate
1183getPredicateResult(unsigned Pred, Constant *C, LVILatticeVal &Result,
1184 const DataLayout *DL, TargetLibraryInfo *TLI) {
1185
Chris Lattner565ee2f2009-11-12 04:36:58 +00001186 // If we know the value is a constant, evaluate the conditional.
Craig Topper9f008862014-04-15 04:59:12 +00001187 Constant *Res = nullptr;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001188 if (Result.isConstant()) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001189 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001190 TLI);
Nick Lewycky11678bd2010-12-15 18:57:18 +00001191 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Hal Finkel7e184492014-09-07 20:29:59 +00001192 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1193 return LazyValueInfo::Unknown;
Chris Lattneraf025d32009-11-15 19:59:49 +00001194 }
1195
Owen Anderson185fe002010-08-10 20:03:09 +00001196 if (Result.isConstantRange()) {
Owen Andersonc62f7042010-08-24 07:55:44 +00001197 ConstantInt *CI = dyn_cast<ConstantInt>(C);
Hal Finkel7e184492014-09-07 20:29:59 +00001198 if (!CI) return LazyValueInfo::Unknown;
Owen Andersonc62f7042010-08-24 07:55:44 +00001199
Owen Anderson185fe002010-08-10 20:03:09 +00001200 ConstantRange CR = Result.getConstantRange();
1201 if (Pred == ICmpInst::ICMP_EQ) {
1202 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001203 return LazyValueInfo::False;
Owen Anderson185fe002010-08-10 20:03:09 +00001204
1205 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001206 return LazyValueInfo::True;
Owen Anderson185fe002010-08-10 20:03:09 +00001207 } else if (Pred == ICmpInst::ICMP_NE) {
1208 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001209 return LazyValueInfo::True;
Owen Anderson185fe002010-08-10 20:03:09 +00001210
1211 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001212 return LazyValueInfo::False;
Owen Anderson185fe002010-08-10 20:03:09 +00001213 }
1214
1215 // Handle more complex predicates.
Nick Lewycky11678bd2010-12-15 18:57:18 +00001216 ConstantRange TrueValues =
1217 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1218 if (TrueValues.contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001219 return LazyValueInfo::True;
Nick Lewycky11678bd2010-12-15 18:57:18 +00001220 if (TrueValues.inverse().contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001221 return LazyValueInfo::False;
1222 return LazyValueInfo::Unknown;
Owen Anderson185fe002010-08-10 20:03:09 +00001223 }
1224
Chris Lattneraf025d32009-11-15 19:59:49 +00001225 if (Result.isNotConstant()) {
Chris Lattner565ee2f2009-11-12 04:36:58 +00001226 // If this is an equality comparison, we can try to fold it knowing that
1227 // "V != C1".
1228 if (Pred == ICmpInst::ICMP_EQ) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001229 // !C1 == C -> false iff C1 == C.
Chris Lattner565ee2f2009-11-12 04:36:58 +00001230 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001231 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001232 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001233 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001234 return LazyValueInfo::False;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001235 } else if (Pred == ICmpInst::ICMP_NE) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001236 // !C1 != C -> true iff C1 == C.
Chris Lattnerb0c0a0d2009-11-15 20:01:24 +00001237 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001238 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001239 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001240 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001241 return LazyValueInfo::True;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001242 }
Hal Finkel7e184492014-09-07 20:29:59 +00001243 return LazyValueInfo::Unknown;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001244 }
1245
Hal Finkel7e184492014-09-07 20:29:59 +00001246 return LazyValueInfo::Unknown;
1247}
1248
1249/// getPredicateOnEdge - Determine whether the specified value comparison
1250/// with a constant is known to be true or false on the specified CFG edge.
1251/// Pred is a CmpInst predicate.
1252LazyValueInfo::Tristate
1253LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1254 BasicBlock *FromBB, BasicBlock *ToBB,
1255 Instruction *CxtI) {
1256 LVILatticeVal Result =
1257 getCache(PImpl, AT, DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1258
1259 return getPredicateResult(Pred, C, Result, DL, TLI);
1260}
1261
1262LazyValueInfo::Tristate
1263LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1264 Instruction *CxtI) {
1265 LVILatticeVal Result =
1266 getCache(PImpl, AT, DL, DT).getValueAt(V, CxtI);
1267
1268 return getPredicateResult(Pred, C, Result, DL, TLI);
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001269}
1270
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001271void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky11678bd2010-12-15 18:57:18 +00001272 BasicBlock *NewSucc) {
Hal Finkel7e184492014-09-07 20:29:59 +00001273 if (PImpl) getCache(PImpl, AT, DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
Owen Anderson208636f2010-08-18 18:39:01 +00001274}
1275
1276void LazyValueInfo::eraseBlock(BasicBlock *BB) {
Hal Finkel7e184492014-09-07 20:29:59 +00001277 if (PImpl) getCache(PImpl, AT, DL, DT).eraseBlock(BB);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001278}