blob: 56e9a0c17e8e17e27c96909ead4460597344fea2 [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"
Chandler Carruth66b31302015-01-04 12:03:27 +000018#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000020#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohmana4fcd242010-12-15 20:02:24 +000021#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000022#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000023#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
Hal Finkel7e184492014-09-07 20:29:59 +000026#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Instructions.h"
28#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000029#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000030#include "llvm/IR/ValueHandle.h"
Chris Lattnerb584d1e2009-11-12 01:22:16 +000031#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/Support/raw_ostream.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)
Chandler Carruth66b31302015-01-04 12:03:27 +000043INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthb98f63d2015-01-15 10:41:28 +000044INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chad Rosier43a33062011-12-02 01:26:24 +000045INITIALIZE_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
Sanjay Patel2a385e22015-01-09 16:47:20 +000057/// This is the information tracked by LazyValueInfo for each value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000058///
59/// FIXME: This is basically just for bringup, this can be made a lot more rich
60/// in the future.
61///
62namespace {
63class LVILatticeVal {
64 enum LatticeValueTy {
Sanjay Patel2a385e22015-01-09 16:47:20 +000065 /// This Value has no known value yet.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000066 undefined,
Owen Anderson0f306a42010-08-05 22:59:19 +000067
Sanjay Patel2a385e22015-01-09 16:47:20 +000068 /// This Value has a specific constant value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000069 constant,
Sanjay Patel2a385e22015-01-09 16:47:20 +000070
71 /// 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
Sanjay Patel2a385e22015-01-09 16:47:20 +000074 /// The Value falls within this range.
Owen Anderson0f306a42010-08-05 22:59:19 +000075 constantrange,
Chad Rosier43a33062011-12-02 01:26:24 +000076
Sanjay Patel2a385e22015-01-09 16:47:20 +000077 /// This value is not known to be constant, and we know that it has a value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000078 overdefined
79 };
80
81 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattner565ee2f2009-11-12 04:36:58 +000082 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersonc3a14132010-08-05 22:10:46 +000083 LatticeValueTy Tag;
84 Constant *Val;
Owen Anderson0f306a42010-08-05 22:59:19 +000085 ConstantRange Range;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000086
87public:
Craig Topper9f008862014-04-15 04:59:12 +000088 LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000089
Chris Lattner19019ea2009-11-11 22:48:44 +000090 static LVILatticeVal get(Constant *C) {
91 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +000092 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +000093 Res.markConstant(C);
Chris Lattner19019ea2009-11-11 22:48:44 +000094 return Res;
95 }
Chris Lattner565ee2f2009-11-12 04:36:58 +000096 static LVILatticeVal getNot(Constant *C) {
97 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +000098 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +000099 Res.markNotConstant(C);
Chris Lattner565ee2f2009-11-12 04:36:58 +0000100 return Res;
101 }
Owen Anderson5f1dd092010-08-10 23:20:01 +0000102 static LVILatticeVal getRange(ConstantRange CR) {
103 LVILatticeVal Res;
104 Res.markConstantRange(CR);
105 return Res;
106 }
Chris Lattner19019ea2009-11-11 22:48:44 +0000107
Owen Anderson0f306a42010-08-05 22:59:19 +0000108 bool isUndefined() const { return Tag == undefined; }
109 bool isConstant() const { return Tag == constant; }
110 bool isNotConstant() const { return Tag == notconstant; }
111 bool isConstantRange() const { return Tag == constantrange; }
112 bool isOverdefined() const { return Tag == overdefined; }
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000113
114 Constant *getConstant() const {
115 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000116 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000117 }
118
Chris Lattner565ee2f2009-11-12 04:36:58 +0000119 Constant *getNotConstant() const {
120 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000121 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000122 }
123
Owen Anderson0f306a42010-08-05 22:59:19 +0000124 ConstantRange getConstantRange() const {
125 assert(isConstantRange() &&
126 "Cannot get the constant-range of a non-constant-range!");
127 return Range;
128 }
129
Sanjay Patel2a385e22015-01-09 16:47:20 +0000130 /// Return true if this is a change in status.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000131 bool markOverdefined() {
132 if (isOverdefined())
133 return false;
Owen Andersonc3a14132010-08-05 22:10:46 +0000134 Tag = overdefined;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000135 return true;
136 }
137
Sanjay Patel2a385e22015-01-09 16:47:20 +0000138 /// Return true if this is a change in status.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000139 bool markConstant(Constant *V) {
Nick Lewycky11678bd2010-12-15 18:57:18 +0000140 assert(V && "Marking constant with NULL");
141 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
142 return markConstantRange(ConstantRange(CI->getValue()));
143 if (isa<UndefValue>(V))
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000144 return false;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000145
146 assert((!isConstant() || getConstant() == V) &&
147 "Marking constant with different value");
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000148 assert(isUndefined());
Owen Andersonc3a14132010-08-05 22:10:46 +0000149 Tag = constant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000150 Val = V;
Chris Lattner19019ea2009-11-11 22:48:44 +0000151 return true;
152 }
153
Sanjay Patel2a385e22015-01-09 16:47:20 +0000154 /// Return true if this is a change in status.
Chris Lattner565ee2f2009-11-12 04:36:58 +0000155 bool markNotConstant(Constant *V) {
Chris Lattner565ee2f2009-11-12 04:36:58 +0000156 assert(V && "Marking constant with NULL");
Nick Lewycky11678bd2010-12-15 18:57:18 +0000157 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
158 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
159 if (isa<UndefValue>(V))
160 return false;
161
162 assert((!isConstant() || getConstant() != V) &&
163 "Marking constant !constant with same value");
164 assert((!isNotConstant() || getNotConstant() == V) &&
165 "Marking !constant with different value");
166 assert(isUndefined() || isConstant());
167 Tag = notconstant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000168 Val = V;
Chris Lattner565ee2f2009-11-12 04:36:58 +0000169 return true;
170 }
171
Sanjay Patel2a385e22015-01-09 16:47:20 +0000172 /// Return true if this is a change in status.
Owen Anderson0f306a42010-08-05 22:59:19 +0000173 bool markConstantRange(const ConstantRange NewR) {
174 if (isConstantRange()) {
175 if (NewR.isEmptySet())
176 return markOverdefined();
177
Nuno Lopese6e04902012-06-28 01:16:18 +0000178 bool changed = Range != NewR;
Owen Anderson0f306a42010-08-05 22:59:19 +0000179 Range = NewR;
180 return changed;
181 }
182
183 assert(isUndefined());
184 if (NewR.isEmptySet())
185 return markOverdefined();
Owen Anderson0f306a42010-08-05 22:59:19 +0000186
187 Tag = constantrange;
188 Range = NewR;
189 return true;
190 }
191
Sanjay Patel2a385e22015-01-09 16:47:20 +0000192 /// Merge the specified lattice value into this one, updating this
Chris Lattner19019ea2009-11-11 22:48:44 +0000193 /// one and returning true if anything changed.
194 bool mergeIn(const LVILatticeVal &RHS) {
195 if (RHS.isUndefined() || isOverdefined()) return false;
196 if (RHS.isOverdefined()) return markOverdefined();
197
Nick Lewycky11678bd2010-12-15 18:57:18 +0000198 if (isUndefined()) {
199 Tag = RHS.Tag;
200 Val = RHS.Val;
201 Range = RHS.Range;
202 return true;
Chris Lattner22db4b52009-11-12 04:57:13 +0000203 }
204
Nick Lewycky11678bd2010-12-15 18:57:18 +0000205 if (isConstant()) {
206 if (RHS.isConstant()) {
207 if (Val == RHS.Val)
208 return false;
209 return markOverdefined();
210 }
211
212 if (RHS.isNotConstant()) {
213 if (Val == RHS.Val)
214 return markOverdefined();
215
216 // Unless we can prove that the two Constants are different, we must
217 // move to overdefined.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000218 // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
Nick Lewycky11678bd2010-12-15 18:57:18 +0000219 if (ConstantInt *Res = dyn_cast<ConstantInt>(
220 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
221 getConstant(),
222 RHS.getNotConstant())))
223 if (Res->isOne())
224 return markNotConstant(RHS.getNotConstant());
225
226 return markOverdefined();
227 }
228
229 // RHS is a ConstantRange, LHS is a non-integer Constant.
230
231 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
232 // a function. The correct result is to pick up RHS.
233
Chris Lattner19019ea2009-11-11 22:48:44 +0000234 return markOverdefined();
Nick Lewycky11678bd2010-12-15 18:57:18 +0000235 }
236
237 if (isNotConstant()) {
238 if (RHS.isConstant()) {
239 if (Val == RHS.Val)
240 return markOverdefined();
241
242 // Unless we can prove that the two Constants are different, we must
243 // move to overdefined.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000244 // FIXME: use DataLayout/TargetLibraryInfo for smarter constant folding.
Nick Lewycky11678bd2010-12-15 18:57:18 +0000245 if (ConstantInt *Res = dyn_cast<ConstantInt>(
246 ConstantFoldCompareInstOperands(CmpInst::ICMP_NE,
247 getNotConstant(),
248 RHS.getConstant())))
249 if (Res->isOne())
250 return false;
251
252 return markOverdefined();
253 }
254
255 if (RHS.isNotConstant()) {
256 if (Val == RHS.Val)
257 return false;
258 return markOverdefined();
259 }
260
261 return markOverdefined();
262 }
263
264 assert(isConstantRange() && "New LVILattice type?");
265 if (!RHS.isConstantRange())
266 return markOverdefined();
267
268 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
269 if (NewR.isFullSet())
270 return markOverdefined();
271 return markConstantRange(NewR);
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000272 }
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000273};
274
275} // end anonymous namespace.
276
Chris Lattner19019ea2009-11-11 22:48:44 +0000277namespace llvm {
Chandler Carruth2b1ba482011-04-18 18:49:44 +0000278raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
279 LLVM_ATTRIBUTE_USED;
Chris Lattner19019ea2009-11-11 22:48:44 +0000280raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
281 if (Val.isUndefined())
282 return OS << "undefined";
283 if (Val.isOverdefined())
284 return OS << "overdefined";
Chris Lattner565ee2f2009-11-12 04:36:58 +0000285
286 if (Val.isNotConstant())
287 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Owen Anderson8afac042010-08-09 20:50:46 +0000288 else if (Val.isConstantRange())
289 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
290 << Val.getConstantRange().getUpper() << '>';
Chris Lattner19019ea2009-11-11 22:48:44 +0000291 return OS << "constant<" << *Val.getConstant() << '>';
292}
293}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000294
295//===----------------------------------------------------------------------===//
Chris Lattneraf025d32009-11-15 19:59:49 +0000296// LazyValueInfoCache Decl
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000297//===----------------------------------------------------------------------===//
298
Chris Lattneraf025d32009-11-15 19:59:49 +0000299namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000300 /// A callback value handle updates the cache when values are erased.
Owen Anderson118ac802011-01-05 21:15:29 +0000301 class LazyValueInfoCache;
302 struct LVIValueHandle : public CallbackVH {
303 LazyValueInfoCache *Parent;
304
305 LVIValueHandle(Value *V, LazyValueInfoCache *P)
306 : CallbackVH(V), Parent(P) { }
Craig Toppere9ba7592014-03-05 07:30:04 +0000307
308 void deleted() override;
309 void allUsesReplacedWith(Value *V) override {
Owen Anderson118ac802011-01-05 21:15:29 +0000310 deleted();
311 }
312 };
313}
314
Owen Anderson118ac802011-01-05 21:15:29 +0000315namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000316 /// This is the cache kept by LazyValueInfo which
Chris Lattneraf025d32009-11-15 19:59:49 +0000317 /// maintains information about queries across the clients' queries.
318 class LazyValueInfoCache {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000319 /// This is all of the cached block information for exactly one Value*.
320 /// The entries are sorted by the BasicBlock* of the
Chris Lattneraf025d32009-11-15 19:59:49 +0000321 /// entries, allowing us to do a lookup with a binary search.
Bill Wendling4ec081a2012-01-11 23:43:34 +0000322 typedef std::map<AssertingVH<BasicBlock>, LVILatticeVal> ValueCacheEntryTy;
Chris Lattneraf025d32009-11-15 19:59:49 +0000323
Sanjay Patel2a385e22015-01-09 16:47:20 +0000324 /// This is all of the cached information for all values,
Owen Anderson6f060af2011-01-05 23:26:22 +0000325 /// mapped from Value* to key information.
Bill Wendling58c75692012-01-12 01:41:03 +0000326 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
Owen Anderson6f060af2011-01-05 23:26:22 +0000327
Sanjay Patel2a385e22015-01-09 16:47:20 +0000328 /// This tracks, on a per-block basis, the set of values that are
329 /// over-defined at the end of that block. This is required
Owen Anderson6f060af2011-01-05 23:26:22 +0000330 /// for cache updating.
331 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
332 DenseSet<OverDefinedPairTy> OverDefinedCache;
Benjamin Kramer36647082011-12-03 15:16:45 +0000333
Sanjay Patel2a385e22015-01-09 16:47:20 +0000334 /// Keep track of all blocks that we have ever seen, so we
Benjamin Kramer36647082011-12-03 15:16:45 +0000335 /// don't spend time removing unused blocks from our caches.
336 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
337
Sanjay Patel2a385e22015-01-09 16:47:20 +0000338 /// This stack holds the state of the value solver during a query.
339 /// It basically emulates the callstack of the naive
Owen Anderson6f060af2011-01-05 23:26:22 +0000340 /// recursive value lookup process.
341 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
Hal Finkel7e184492014-09-07 20:29:59 +0000342
Sanjay Patel2a385e22015-01-09 16:47:20 +0000343 /// Keeps track of which block-value pairs are in BlockValueStack.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000344 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
345
Sanjay Patel2a385e22015-01-09 16:47:20 +0000346 /// Push BV onto BlockValueStack unless it's already in there.
347 /// Returns true on success.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000348 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
Benjamin Kramer4e3b9032015-02-27 21:43:14 +0000349 if (!BlockValueSet.insert(BV).second)
Hans Wennborg45172ac2014-11-25 17:23:05 +0000350 return false; // It's already in the stack.
351
352 BlockValueStack.push(BV);
Hans Wennborg45172ac2014-11-25 17:23:05 +0000353 return true;
354 }
355
Hal Finkel7e184492014-09-07 20:29:59 +0000356 /// A pointer to the cache of @llvm.assume calls.
Chandler Carruth66b31302015-01-04 12:03:27 +0000357 AssumptionCache *AC;
Hal Finkel7e184492014-09-07 20:29:59 +0000358 /// An optional DL pointer.
359 const DataLayout *DL;
360 /// An optional DT pointer.
361 DominatorTree *DT;
Owen Anderson6f060af2011-01-05 23:26:22 +0000362
Owen Anderson118ac802011-01-05 21:15:29 +0000363 friend struct LVIValueHandle;
Owen Anderson6f060af2011-01-05 23:26:22 +0000364
Hans Wennborg45172ac2014-11-25 17:23:05 +0000365 void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
366 SeenBlocks.insert(BB);
367 lookup(Val)[BB] = Result;
368 if (Result.isOverdefined())
369 OverDefinedCache.insert(std::make_pair(BB, Val));
370 }
Owen Andersonc1561b82010-07-30 23:59:40 +0000371
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000372 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000373 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
Hal Finkel7e184492014-09-07 20:29:59 +0000374 LVILatticeVal &Result,
375 Instruction *CxtI = nullptr);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000376 bool hasBlockValue(Value *Val, BasicBlock *BB);
377
378 // These methods process one work item and may add more. A false value
379 // returned means that the work item was not completely processed and must
380 // be revisited after going through the new items.
381 bool solveBlockValue(Value *Val, BasicBlock *BB);
Owen Anderson64c2c572010-12-20 18:18:16 +0000382 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
383 Value *Val, BasicBlock *BB);
384 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
385 PHINode *PN, BasicBlock *BB);
386 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
387 Instruction *BBI, BasicBlock *BB);
Hal Finkel7e184492014-09-07 20:29:59 +0000388 void mergeAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
389 Instruction *BBI);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000390
391 void solve();
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000392
Nick Lewycky11678bd2010-12-15 18:57:18 +0000393 ValueCacheEntryTy &lookup(Value *V) {
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000394 return ValueCache[LVIValueHandle(V, this)];
395 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000396
Chris Lattneraf025d32009-11-15 19:59:49 +0000397 public:
Sanjay Patel2a385e22015-01-09 16:47:20 +0000398 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000399 /// value for the specified Value* at the end of the specified block.
Hal Finkel7e184492014-09-07 20:29:59 +0000400 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
401 Instruction *CxtI = nullptr);
402
Sanjay Patel2a385e22015-01-09 16:47:20 +0000403 /// This is the query interface to determine the lattice
Hal Finkel7e184492014-09-07 20:29:59 +0000404 /// value for the specified Value* at the specified instruction (generally
405 /// from an assume intrinsic).
406 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
Chris Lattneraf025d32009-11-15 19:59:49 +0000407
Sanjay Patel2a385e22015-01-09 16:47:20 +0000408 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000409 /// value for the specified Value* that is true on the specified edge.
Hal Finkel7e184492014-09-07 20:29:59 +0000410 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
411 Instruction *CxtI = nullptr);
Owen Andersonaa7f66b2010-07-26 18:48:03 +0000412
Sanjay Patel2a385e22015-01-09 16:47:20 +0000413 /// This is the update interface to inform the cache that an edge from
414 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
Owen Andersonaa7f66b2010-07-26 18:48:03 +0000415 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Owen Anderson208636f2010-08-18 18:39:01 +0000416
Sanjay Patel2a385e22015-01-09 16:47:20 +0000417 /// This is part of the update interface to inform the cache
Owen Anderson208636f2010-08-18 18:39:01 +0000418 /// that a block has been deleted.
419 void eraseBlock(BasicBlock *BB);
420
421 /// clear - Empty the cache.
422 void clear() {
Benjamin Kramerbbf3c602011-12-03 15:19:55 +0000423 SeenBlocks.clear();
Owen Anderson208636f2010-08-18 18:39:01 +0000424 ValueCache.clear();
425 OverDefinedCache.clear();
426 }
Hal Finkel7e184492014-09-07 20:29:59 +0000427
Chandler Carruth66b31302015-01-04 12:03:27 +0000428 LazyValueInfoCache(AssumptionCache *AC, const DataLayout *DL = nullptr,
429 DominatorTree *DT = nullptr)
430 : AC(AC), DL(DL), DT(DT) {}
Chris Lattneraf025d32009-11-15 19:59:49 +0000431 };
432} // end anonymous namespace
433
Owen Anderson118ac802011-01-05 21:15:29 +0000434void LVIValueHandle::deleted() {
435 typedef std::pair<AssertingVH<BasicBlock>, Value*> OverDefinedPairTy;
436
437 SmallVector<OverDefinedPairTy, 4> ToErase;
Hans Wennborgcbb18e32014-11-21 19:07:46 +0000438 for (const OverDefinedPairTy &P : Parent->OverDefinedCache)
439 if (P.second == getValPtr())
440 ToErase.push_back(P);
441 for (const OverDefinedPairTy &P : ToErase)
442 Parent->OverDefinedCache.erase(P);
Owen Anderson118ac802011-01-05 21:15:29 +0000443
Owen Anderson7b974a42010-08-11 22:36:04 +0000444 // This erasure deallocates *this, so it MUST happen after we're done
445 // using any and all members of *this.
446 Parent->ValueCache.erase(*this);
Owen Andersonc1561b82010-07-30 23:59:40 +0000447}
448
Owen Anderson208636f2010-08-18 18:39:01 +0000449void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
Benjamin Kramer36647082011-12-03 15:16:45 +0000450 // Shortcut if we have never seen this block.
451 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
452 if (I == SeenBlocks.end())
453 return;
454 SeenBlocks.erase(I);
455
Owen Anderson118ac802011-01-05 21:15:29 +0000456 SmallVector<OverDefinedPairTy, 4> ToErase;
Hans Wennborgcbb18e32014-11-21 19:07:46 +0000457 for (const OverDefinedPairTy& P : OverDefinedCache)
458 if (P.first == BB)
459 ToErase.push_back(P);
460 for (const OverDefinedPairTy &P : ToErase)
461 OverDefinedCache.erase(P);
Owen Anderson208636f2010-08-18 18:39:01 +0000462
Bill Wendling58c75692012-01-12 01:41:03 +0000463 for (std::map<LVIValueHandle, ValueCacheEntryTy>::iterator
Owen Anderson208636f2010-08-18 18:39:01 +0000464 I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
465 I->second.erase(BB);
466}
Owen Andersonc1561b82010-07-30 23:59:40 +0000467
Nick Lewycky55a700b2010-12-18 01:00:40 +0000468void LazyValueInfoCache::solve() {
Owen Anderson6f060af2011-01-05 23:26:22 +0000469 while (!BlockValueStack.empty()) {
470 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000471 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
472
Nuno Lopese6e04902012-06-28 01:16:18 +0000473 if (solveBlockValue(e.second, e.first)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000474 // The work item was completely processed.
475 assert(BlockValueStack.top() == e && "Nothing should have been pushed!");
476 assert(lookup(e.second).count(e.first) && "Result should be in cache!");
477
Owen Anderson6f060af2011-01-05 23:26:22 +0000478 BlockValueStack.pop();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000479 BlockValueSet.erase(e);
480 } else {
481 // More work needs to be done before revisiting.
482 assert(BlockValueStack.top() != e && "Stack should have been pushed!");
Nuno Lopese6e04902012-06-28 01:16:18 +0000483 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000484 }
485}
486
487bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
488 // If already a constant, there is nothing to compute.
489 if (isa<Constant>(Val))
490 return true;
491
Owen Anderson118ac802011-01-05 21:15:29 +0000492 LVIValueHandle ValHandle(Val, this);
Benjamin Kramerf29db272012-08-22 15:37:57 +0000493 std::map<LVIValueHandle, ValueCacheEntryTy>::iterator I =
494 ValueCache.find(ValHandle);
495 if (I == ValueCache.end()) return false;
496 return I->second.count(BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000497}
498
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000499LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000500 // If already a constant, there is nothing to compute.
501 if (Constant *VC = dyn_cast<Constant>(Val))
502 return LVILatticeVal::get(VC);
503
Benjamin Kramer36647082011-12-03 15:16:45 +0000504 SeenBlocks.insert(BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000505 return lookup(Val)[BB];
506}
507
508bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
509 if (isa<Constant>(Val))
510 return true;
511
Hans Wennborg45172ac2014-11-25 17:23:05 +0000512 if (lookup(Val).count(BB)) {
513 // If we have a cached value, use that.
514 DEBUG(dbgs() << " reuse BB '" << BB->getName()
515 << "' val=" << lookup(Val)[BB] << '\n');
Nick Lewycky55a700b2010-12-18 01:00:40 +0000516
Hans Wennborg45172ac2014-11-25 17:23:05 +0000517 // Since we're reusing a cached value, we don't need to update the
518 // OverDefinedCache. The cache will have been properly updated whenever the
519 // cached value was inserted.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000520 return true;
Chris Lattner2c708562009-11-15 20:00:52 +0000521 }
522
Hans Wennborg45172ac2014-11-25 17:23:05 +0000523 // Hold off inserting this value into the Cache in case we have to return
524 // false and come back later.
525 LVILatticeVal Res;
Chris Lattneraf025d32009-11-15 19:59:49 +0000526
Chris Lattneraf025d32009-11-15 19:59:49 +0000527 Instruction *BBI = dyn_cast<Instruction>(Val);
Craig Topper9f008862014-04-15 04:59:12 +0000528 if (!BBI || BBI->getParent() != BB) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000529 if (!solveBlockValueNonLocal(Res, Val, BB))
530 return false;
531 insertResult(Val, BB, Res);
532 return true;
Chris Lattneraf025d32009-11-15 19:59:49 +0000533 }
Chris Lattner2c708562009-11-15 20:00:52 +0000534
Nick Lewycky55a700b2010-12-18 01:00:40 +0000535 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000536 if (!solveBlockValuePHINode(Res, PN, BB))
537 return false;
538 insertResult(Val, BB, Res);
539 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000540 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000541
Nick Lewycky367f98f2011-01-15 09:16:12 +0000542 if (AllocaInst *AI = dyn_cast<AllocaInst>(BBI)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000543 Res = LVILatticeVal::getNot(ConstantPointerNull::get(AI->getType()));
544 insertResult(Val, BB, Res);
545 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000546 }
547
Owen Anderson80d19f02010-08-18 21:11:37 +0000548 // We can only analyze the definitions of certain classes of instructions
549 // (integral binops and casts at the moment), so bail if this isn't one.
Chris Lattneraf025d32009-11-15 19:59:49 +0000550 LVILatticeVal Result;
Owen Anderson80d19f02010-08-18 21:11:37 +0000551 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
552 !BBI->getType()->isIntegerTy()) {
553 DEBUG(dbgs() << " compute BB '" << BB->getName()
554 << "' - overdefined because inst def found.\n");
Hans Wennborg45172ac2014-11-25 17:23:05 +0000555 Res.markOverdefined();
556 insertResult(Val, BB, Res);
557 return true;
Owen Anderson80d19f02010-08-18 21:11:37 +0000558 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000559
Owen Anderson80d19f02010-08-18 21:11:37 +0000560 // FIXME: We're currently limited to binops with a constant RHS. This should
561 // be improved.
562 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
563 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
564 DEBUG(dbgs() << " compute BB '" << BB->getName()
565 << "' - overdefined because inst def found.\n");
566
Hans Wennborg45172ac2014-11-25 17:23:05 +0000567 Res.markOverdefined();
568 insertResult(Val, BB, Res);
569 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000570 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000571
Hans Wennborg45172ac2014-11-25 17:23:05 +0000572 if (!solveBlockValueConstantRange(Res, BBI, BB))
573 return false;
574 insertResult(Val, BB, Res);
575 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000576}
577
578static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
579 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
580 return L->getPointerAddressSpace() == 0 &&
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000581 GetUnderlyingObject(L->getPointerOperand()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000582 }
583 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
584 return S->getPointerAddressSpace() == 0 &&
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000585 GetUnderlyingObject(S->getPointerOperand()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000586 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000587 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
588 if (MI->isVolatile()) return false;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000589
590 // FIXME: check whether it has a valuerange that excludes zero?
591 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
592 if (!Len || Len->isZero()) return false;
593
Eli Friedman7a5fc692011-05-31 20:40:16 +0000594 if (MI->getDestAddressSpace() == 0)
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000595 if (GetUnderlyingObject(MI->getRawDest()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000596 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000597 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman7a5fc692011-05-31 20:40:16 +0000598 if (MTI->getSourceAddressSpace() == 0)
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000599 if (GetUnderlyingObject(MTI->getRawSource()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000600 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000601 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000602 return false;
603}
604
Owen Anderson64c2c572010-12-20 18:18:16 +0000605bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
606 Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000607 LVILatticeVal Result; // Start Undefined.
608
609 // If this is a pointer, and there's a load from that pointer in this BB,
610 // then we know that the pointer can't be NULL.
611 bool NotNull = false;
612 if (Val->getType()->isPointerTy()) {
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000613 if (isKnownNonNull(Val)) {
Nick Lewycky367f98f2011-01-15 09:16:12 +0000614 NotNull = true;
615 } else {
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000616 Value *UnderlyingVal = GetUnderlyingObject(Val);
617 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
618 // inside InstructionDereferencesPointer either.
Craig Topper9f008862014-04-15 04:59:12 +0000619 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, nullptr, 1)) {
Hans Wennborgcbb18e32014-11-21 19:07:46 +0000620 for (Instruction &I : *BB) {
621 if (InstructionDereferencesPointer(&I, UnderlyingVal)) {
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000622 NotNull = true;
623 break;
624 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000625 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000626 }
627 }
628 }
629
630 // If this is the entry block, we must be asking about an argument. The
631 // value is overdefined.
632 if (BB == &BB->getParent()->getEntryBlock()) {
633 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
634 if (NotNull) {
Chris Lattner229907c2011-07-18 04:54:35 +0000635 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000636 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
637 } else {
638 Result.markOverdefined();
639 }
Owen Anderson64c2c572010-12-20 18:18:16 +0000640 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000641 return true;
642 }
643
644 // Loop over all of our predecessors, merging what we know from them into
645 // result.
646 bool EdgesMissing = false;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000647 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000648 LVILatticeVal EdgeResult;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000649 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000650 if (EdgesMissing)
651 continue;
652
653 Result.mergeIn(EdgeResult);
654
655 // If we hit overdefined, exit early. The BlockVals entry is already set
656 // to overdefined.
657 if (Result.isOverdefined()) {
658 DEBUG(dbgs() << " compute BB '" << BB->getName()
659 << "' - overdefined because of pred.\n");
660 // If we previously determined that this is a pointer that can't be null
661 // then return that rather than giving up entirely.
662 if (NotNull) {
Chris Lattner229907c2011-07-18 04:54:35 +0000663 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000664 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
665 }
Owen Anderson64c2c572010-12-20 18:18:16 +0000666
667 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000668 return true;
669 }
670 }
671 if (EdgesMissing)
672 return false;
673
674 // Return the merged value, which is more precise than 'overdefined'.
675 assert(!Result.isOverdefined());
Owen Anderson64c2c572010-12-20 18:18:16 +0000676 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000677 return true;
678}
679
Owen Anderson64c2c572010-12-20 18:18:16 +0000680bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
681 PHINode *PN, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000682 LVILatticeVal Result; // Start Undefined.
683
684 // Loop over all of our predecessors, merging what we know from them into
685 // result.
686 bool EdgesMissing = false;
687 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
688 BasicBlock *PhiBB = PN->getIncomingBlock(i);
689 Value *PhiVal = PN->getIncomingValue(i);
690 LVILatticeVal EdgeResult;
Hal Finkel2400c962014-10-16 00:40:05 +0000691 // Note that we can provide PN as the context value to getEdgeValue, even
692 // though the results will be cached, because PN is the value being used as
693 // the cache key in the caller.
Hal Finkel7e184492014-09-07 20:29:59 +0000694 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000695 if (EdgesMissing)
696 continue;
697
698 Result.mergeIn(EdgeResult);
699
700 // If we hit overdefined, exit early. The BlockVals entry is already set
701 // to overdefined.
702 if (Result.isOverdefined()) {
703 DEBUG(dbgs() << " compute BB '" << BB->getName()
704 << "' - overdefined because of pred.\n");
Owen Anderson64c2c572010-12-20 18:18:16 +0000705
706 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000707 return true;
708 }
709 }
710 if (EdgesMissing)
711 return false;
712
713 // Return the merged value, which is more precise than 'overdefined'.
714 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson64c2c572010-12-20 18:18:16 +0000715 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000716 return true;
717}
718
Hal Finkel7e184492014-09-07 20:29:59 +0000719static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
720 LVILatticeVal &Result,
721 bool isTrueDest = true);
722
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000723// If we can determine a constant range for the value Val in the context
Hal Finkel7e184492014-09-07 20:29:59 +0000724// provided by the instruction BBI, then merge it into BBLV. If we did find a
725// constant range, return true.
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000726void LazyValueInfoCache::mergeAssumeBlockValueConstantRange(Value *Val,
727 LVILatticeVal &BBLV,
728 Instruction *BBI) {
Hal Finkel7e184492014-09-07 20:29:59 +0000729 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
730 if (!BBI)
731 return;
732
Chandler Carruth66b31302015-01-04 12:03:27 +0000733 for (auto &AssumeVH : AC->assumptions()) {
734 if (!AssumeVH)
735 continue;
736 auto *I = cast<CallInst>(AssumeVH);
Hal Finkel7e184492014-09-07 20:29:59 +0000737 if (!isValidAssumeForContext(I, BBI, DL, DT))
738 continue;
739
740 Value *C = I->getArgOperand(0);
741 if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) {
742 LVILatticeVal Result;
743 if (getValueFromFromCondition(Val, ICI, Result)) {
744 if (BBLV.isOverdefined())
745 BBLV = Result;
746 else
747 BBLV.mergeIn(Result);
748 }
749 }
750 }
751}
752
Owen Anderson64c2c572010-12-20 18:18:16 +0000753bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
754 Instruction *BBI,
Nick Lewycky55a700b2010-12-18 01:00:40 +0000755 BasicBlock *BB) {
Owen Anderson80d19f02010-08-18 21:11:37 +0000756 // Figure out the range of the LHS. If that fails, bail.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000757 if (!hasBlockValue(BBI->getOperand(0), BB)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000758 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
759 return false;
760 BBLV.markOverdefined();
761 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000762 }
763
Nick Lewycky55a700b2010-12-18 01:00:40 +0000764 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Hal Finkel7e184492014-09-07 20:29:59 +0000765 mergeAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
Owen Anderson80d19f02010-08-18 21:11:37 +0000766 if (!LHSVal.isConstantRange()) {
Owen Anderson64c2c572010-12-20 18:18:16 +0000767 BBLV.markOverdefined();
Nick Lewycky55a700b2010-12-18 01:00:40 +0000768 return true;
Owen Anderson80d19f02010-08-18 21:11:37 +0000769 }
770
Owen Anderson80d19f02010-08-18 21:11:37 +0000771 ConstantRange LHSRange = LHSVal.getConstantRange();
772 ConstantRange RHSRange(1);
Chris Lattner229907c2011-07-18 04:54:35 +0000773 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
Owen Anderson80d19f02010-08-18 21:11:37 +0000774 if (isa<BinaryOperator>(BBI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000775 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
776 RHSRange = ConstantRange(RHS->getValue());
777 } else {
Owen Anderson64c2c572010-12-20 18:18:16 +0000778 BBLV.markOverdefined();
Nick Lewycky55a700b2010-12-18 01:00:40 +0000779 return true;
Owen Andersonc62f7042010-08-24 07:55:44 +0000780 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000781 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000782
Owen Anderson80d19f02010-08-18 21:11:37 +0000783 // NOTE: We're currently limited by the set of operations that ConstantRange
784 // can evaluate symbolically. Enhancing that set will allows us to analyze
785 // more definitions.
Owen Anderson64c2c572010-12-20 18:18:16 +0000786 LVILatticeVal Result;
Owen Anderson80d19f02010-08-18 21:11:37 +0000787 switch (BBI->getOpcode()) {
788 case Instruction::Add:
789 Result.markConstantRange(LHSRange.add(RHSRange));
790 break;
791 case Instruction::Sub:
792 Result.markConstantRange(LHSRange.sub(RHSRange));
793 break;
794 case Instruction::Mul:
795 Result.markConstantRange(LHSRange.multiply(RHSRange));
796 break;
797 case Instruction::UDiv:
798 Result.markConstantRange(LHSRange.udiv(RHSRange));
799 break;
800 case Instruction::Shl:
801 Result.markConstantRange(LHSRange.shl(RHSRange));
802 break;
803 case Instruction::LShr:
804 Result.markConstantRange(LHSRange.lshr(RHSRange));
805 break;
806 case Instruction::Trunc:
807 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
808 break;
809 case Instruction::SExt:
810 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
811 break;
812 case Instruction::ZExt:
813 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
814 break;
815 case Instruction::BitCast:
816 Result.markConstantRange(LHSRange);
817 break;
Nick Lewyckyad48e012010-09-07 05:39:02 +0000818 case Instruction::And:
819 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
820 break;
821 case Instruction::Or:
822 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
823 break;
Owen Anderson80d19f02010-08-18 21:11:37 +0000824
825 // Unhandled instructions are overdefined.
826 default:
827 DEBUG(dbgs() << " compute BB '" << BB->getName()
828 << "' - overdefined because inst def found.\n");
829 Result.markOverdefined();
830 break;
831 }
832
Owen Anderson64c2c572010-12-20 18:18:16 +0000833 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000834 return true;
Chris Lattner741c94c2009-11-11 00:22:30 +0000835}
836
Hal Finkel7e184492014-09-07 20:29:59 +0000837bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
838 LVILatticeVal &Result, bool isTrueDest) {
839 if (ICI && isa<Constant>(ICI->getOperand(1))) {
840 if (ICI->isEquality() && ICI->getOperand(0) == Val) {
841 // We know that V has the RHS constant if this is a true SETEQ or
842 // false SETNE.
843 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
844 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
845 else
846 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
847 return true;
848 }
849
850 // Recognize the range checking idiom that InstCombine produces.
851 // (X-C1) u< C2 --> [C1, C1+C2)
852 ConstantInt *NegOffset = nullptr;
853 if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
854 match(ICI->getOperand(0), m_Add(m_Specific(Val),
855 m_ConstantInt(NegOffset)));
856
857 ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
858 if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
859 // Calculate the range of values that would satisfy the comparison.
860 ConstantRange CmpRange(CI->getValue());
861 ConstantRange TrueValues =
862 ConstantRange::makeICmpRegion(ICI->getPredicate(), CmpRange);
863
864 if (NegOffset) // Apply the offset from above.
865 TrueValues = TrueValues.subtract(NegOffset->getValue());
866
867 // If we're interested in the false dest, invert the condition.
868 if (!isTrueDest) TrueValues = TrueValues.inverse();
869
870 Result = LVILatticeVal::getRange(TrueValues);
871 return true;
872 }
873 }
874
875 return false;
876}
877
Nuno Lopese6e04902012-06-28 01:16:18 +0000878/// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
879/// Val is not constrained on the edge.
880static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
881 BasicBlock *BBTo, LVILatticeVal &Result) {
Chris Lattner77358782009-11-15 20:02:12 +0000882 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
883 // know that v != 0.
Chris Lattner19019ea2009-11-11 22:48:44 +0000884 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
885 // If this is a conditional branch and only one successor goes to BBTo, then
Sanjay Patel938e2792015-01-09 16:35:37 +0000886 // we may be able to infer something from the condition.
Chris Lattner19019ea2009-11-11 22:48:44 +0000887 if (BI->isConditional() &&
888 BI->getSuccessor(0) != BI->getSuccessor(1)) {
889 bool isTrueDest = BI->getSuccessor(0) == BBTo;
890 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
891 "BBTo isn't a successor of BBFrom");
892
893 // If V is the condition of the branch itself, then we know exactly what
894 // it is.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000895 if (BI->getCondition() == Val) {
896 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson185fe002010-08-10 20:03:09 +0000897 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky55a700b2010-12-18 01:00:40 +0000898 return true;
899 }
Chris Lattner19019ea2009-11-11 22:48:44 +0000900
901 // If the condition of the branch is an equality comparison, we may be
902 // able to infer the value.
Sanjay Pateld7291152015-01-09 16:28:15 +0000903 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
904 if (getValueFromFromCondition(Val, ICI, Result, isTrueDest))
905 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +0000906 }
907 }
Chris Lattner77358782009-11-15 20:02:12 +0000908
909 // If the edge was formed by a switch on the value, then we may know exactly
910 // what it is.
911 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Nuno Lopes8650fb82012-06-28 16:13:37 +0000912 if (SI->getCondition() != Val)
913 return false;
914
915 bool DefaultCase = SI->getDefaultDest() == BBTo;
916 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
917 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
918
Hans Wennborgcbb18e32014-11-21 19:07:46 +0000919 for (SwitchInst::CaseIt i : SI->cases()) {
Nuno Lopes8650fb82012-06-28 16:13:37 +0000920 ConstantRange EdgeVal(i.getCaseValue()->getValue());
Manman Renf3fedb62012-09-05 23:45:58 +0000921 if (DefaultCase) {
922 // It is possible that the default destination is the destination of
923 // some cases. There is no need to perform difference for those cases.
924 if (i.getCaseSuccessor() != BBTo)
925 EdgesVals = EdgesVals.difference(EdgeVal);
926 } else if (i.getCaseSuccessor() == BBTo)
Nuno Lopesac593802012-05-18 21:02:10 +0000927 EdgesVals = EdgesVals.unionWith(EdgeVal);
Chris Lattner77358782009-11-15 20:02:12 +0000928 }
Nuno Lopes8650fb82012-06-28 16:13:37 +0000929 Result = LVILatticeVal::getRange(EdgesVals);
930 return true;
Chris Lattner77358782009-11-15 20:02:12 +0000931 }
Nuno Lopese6e04902012-06-28 01:16:18 +0000932 return false;
933}
934
Sanjay Patel938e2792015-01-09 16:35:37 +0000935/// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
936/// the basic block if the edge does not constrain Val.
Nuno Lopese6e04902012-06-28 01:16:18 +0000937bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
Hal Finkel7e184492014-09-07 20:29:59 +0000938 BasicBlock *BBTo, LVILatticeVal &Result,
939 Instruction *CxtI) {
Nuno Lopese6e04902012-06-28 01:16:18 +0000940 // If already a constant, there is nothing to compute.
941 if (Constant *VC = dyn_cast<Constant>(Val)) {
942 Result = LVILatticeVal::get(VC);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000943 return true;
944 }
Nuno Lopese6e04902012-06-28 01:16:18 +0000945
946 if (getEdgeValueLocal(Val, BBFrom, BBTo, Result)) {
947 if (!Result.isConstantRange() ||
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000948 Result.getConstantRange().getSingleElement())
Nuno Lopese6e04902012-06-28 01:16:18 +0000949 return true;
950
951 // FIXME: this check should be moved to the beginning of the function when
952 // LVI better supports recursive values. Even for the single value case, we
953 // can intersect to detect dead code (an empty range).
954 if (!hasBlockValue(Val, BBFrom)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000955 if (pushBlockValue(std::make_pair(BBFrom, Val)))
956 return false;
957 Result.markOverdefined();
958 return true;
Nuno Lopese6e04902012-06-28 01:16:18 +0000959 }
960
961 // Try to intersect ranges of the BB and the constraint on the edge.
962 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Hal Finkela3f23e32014-10-14 16:04:49 +0000963 mergeAssumeBlockValueConstantRange(Val, InBlock, BBFrom->getTerminator());
Hal Finkel2400c962014-10-16 00:40:05 +0000964 // See note on the use of the CxtI with mergeAssumeBlockValueConstantRange,
965 // and caching, below.
Hal Finkel7e184492014-09-07 20:29:59 +0000966 mergeAssumeBlockValueConstantRange(Val, InBlock, CxtI);
Nuno Lopese6e04902012-06-28 01:16:18 +0000967 if (!InBlock.isConstantRange())
968 return true;
969
970 ConstantRange Range =
971 Result.getConstantRange().intersectWith(InBlock.getConstantRange());
972 Result = LVILatticeVal::getRange(Range);
973 return true;
974 }
975
976 if (!hasBlockValue(Val, BBFrom)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000977 if (pushBlockValue(std::make_pair(BBFrom, Val)))
978 return false;
979 Result.markOverdefined();
980 return true;
Nuno Lopese6e04902012-06-28 01:16:18 +0000981 }
982
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000983 // If we couldn't compute the value on the edge, use the value from the BB.
Nuno Lopese6e04902012-06-28 01:16:18 +0000984 Result = getBlockValue(Val, BBFrom);
Hal Finkela3f23e32014-10-14 16:04:49 +0000985 mergeAssumeBlockValueConstantRange(Val, Result, BBFrom->getTerminator());
Hal Finkel2400c962014-10-16 00:40:05 +0000986 // We can use the context instruction (generically the ultimate instruction
987 // the calling pass is trying to simplify) here, even though the result of
988 // this function is generally cached when called from the solve* functions
989 // (and that cached result might be used with queries using a different
990 // context instruction), because when this function is called from the solve*
991 // functions, the context instruction is not provided. When called from
992 // LazyValueInfoCache::getValueOnEdge, the context instruction is provided,
993 // but then the result is not cached.
Hal Finkel7e184492014-09-07 20:29:59 +0000994 mergeAssumeBlockValueConstantRange(Val, Result, CxtI);
Nuno Lopese6e04902012-06-28 01:16:18 +0000995 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +0000996}
997
Hal Finkel7e184492014-09-07 20:29:59 +0000998LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB,
999 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001000 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001001 << BB->getName() << "'\n");
1002
Hans Wennborg45172ac2014-11-25 17:23:05 +00001003 assert(BlockValueStack.empty() && BlockValueSet.empty());
1004 pushBlockValue(std::make_pair(BB, V));
1005
Nick Lewycky55a700b2010-12-18 01:00:40 +00001006 solve();
Owen Andersonc7ed4dc2010-12-09 06:14:58 +00001007 LVILatticeVal Result = getBlockValue(V, BB);
Hal Finkel7e184492014-09-07 20:29:59 +00001008 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
1009
1010 DEBUG(dbgs() << " Result = " << Result << "\n");
1011 return Result;
1012}
1013
1014LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) {
1015 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1016 << CxtI->getName() << "'\n");
1017
1018 LVILatticeVal Result;
1019 mergeAssumeBlockValueConstantRange(V, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001020
David Greene37e98092009-12-23 20:43:58 +00001021 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001022 return Result;
1023}
Chris Lattner19019ea2009-11-11 22:48:44 +00001024
Chris Lattneraf025d32009-11-15 19:59:49 +00001025LVILatticeVal LazyValueInfoCache::
Hal Finkel7e184492014-09-07 20:29:59 +00001026getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1027 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001028 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001029 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001030
Nick Lewycky55a700b2010-12-18 01:00:40 +00001031 LVILatticeVal Result;
Hal Finkel7e184492014-09-07 20:29:59 +00001032 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +00001033 solve();
Hal Finkel7e184492014-09-07 20:29:59 +00001034 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001035 (void)WasFastQuery;
1036 assert(WasFastQuery && "More work to do after problem solved?");
1037 }
1038
David Greene37e98092009-12-23 20:43:58 +00001039 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001040 return Result;
1041}
1042
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001043void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1044 BasicBlock *NewSucc) {
1045 // When an edge in the graph has been threaded, values that we could not
1046 // determine a value for before (i.e. were marked overdefined) may be possible
1047 // to solve now. We do NOT try to proactively update these values. Instead,
1048 // we clear their entries from the cache, and allow lazy updating to recompute
1049 // them when needed.
1050
Hans Wennborgc5ec73d2014-11-21 18:58:23 +00001051 // The updating process is fairly simple: we need to drop cached info
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001052 // for all values that were marked overdefined in OldSucc, and for those same
1053 // values in any successor of OldSucc (except NewSucc) in which they were
1054 // also marked overdefined.
1055 std::vector<BasicBlock*> worklist;
1056 worklist.push_back(OldSucc);
1057
Owen Andersonaac5a722010-07-27 23:58:11 +00001058 DenseSet<Value*> ClearSet;
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001059 for (OverDefinedPairTy &P : OverDefinedCache)
1060 if (P.first == OldSucc)
1061 ClearSet.insert(P.second);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001062
1063 // Use a worklist to perform a depth-first search of OldSucc's successors.
1064 // NOTE: We do not need a visited list since any blocks we have already
1065 // visited will have had their overdefined markers cleared already, and we
1066 // thus won't loop to their successors.
1067 while (!worklist.empty()) {
1068 BasicBlock *ToUpdate = worklist.back();
1069 worklist.pop_back();
1070
1071 // Skip blocks only accessible through NewSucc.
1072 if (ToUpdate == NewSucc) continue;
1073
1074 bool changed = false;
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001075 for (Value *V : ClearSet) {
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001076 // If a value was marked overdefined in OldSucc, and is here too...
Owen Anderson118ac802011-01-05 21:15:29 +00001077 DenseSet<OverDefinedPairTy>::iterator OI =
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001078 OverDefinedCache.find(std::make_pair(ToUpdate, V));
Owen Andersonaac5a722010-07-27 23:58:11 +00001079 if (OI == OverDefinedCache.end()) continue;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001080
Owen Andersonaac5a722010-07-27 23:58:11 +00001081 // Remove it from the caches.
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001082 ValueCacheEntryTy &Entry = ValueCache[LVIValueHandle(V, this)];
Owen Andersonaac5a722010-07-27 23:58:11 +00001083 ValueCacheEntryTy::iterator CI = Entry.find(ToUpdate);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001084
Owen Andersonaac5a722010-07-27 23:58:11 +00001085 assert(CI != Entry.end() && "Couldn't find entry to update?");
1086 Entry.erase(CI);
1087 OverDefinedCache.erase(OI);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001088
Owen Andersonaac5a722010-07-27 23:58:11 +00001089 // If we removed anything, then we potentially need to update
1090 // blocks successors too.
1091 changed = true;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001092 }
Nick Lewycky55a700b2010-12-18 01:00:40 +00001093
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001094 if (!changed) continue;
1095
1096 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1097 }
1098}
1099
Chris Lattneraf025d32009-11-15 19:59:49 +00001100//===----------------------------------------------------------------------===//
1101// LazyValueInfo Impl
1102//===----------------------------------------------------------------------===//
1103
Sanjay Patel2a385e22015-01-09 16:47:20 +00001104/// This lazily constructs the LazyValueInfoCache.
Chandler Carruth66b31302015-01-04 12:03:27 +00001105static LazyValueInfoCache &getCache(void *&PImpl, AssumptionCache *AC,
Hal Finkel7e184492014-09-07 20:29:59 +00001106 const DataLayout *DL = nullptr,
1107 DominatorTree *DT = nullptr) {
Chris Lattneraf025d32009-11-15 19:59:49 +00001108 if (!PImpl)
Chandler Carruth66b31302015-01-04 12:03:27 +00001109 PImpl = new LazyValueInfoCache(AC, DL, DT);
Chris Lattneraf025d32009-11-15 19:59:49 +00001110 return *static_cast<LazyValueInfoCache*>(PImpl);
1111}
1112
Owen Anderson208636f2010-08-18 18:39:01 +00001113bool LazyValueInfo::runOnFunction(Function &F) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001114 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Hal Finkel7e184492014-09-07 20:29:59 +00001115
1116 DominatorTreeWrapperPass *DTWP =
1117 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1118 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Chad Rosier43a33062011-12-02 01:26:24 +00001119
Mehdi Amini46a43552015-03-04 18:43:29 +00001120 DL = &F.getParent()->getDataLayout();
Hans Wennborgc5ec73d2014-11-21 18:58:23 +00001121
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001122 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chad Rosier43a33062011-12-02 01:26:24 +00001123
Hal Finkel7e184492014-09-07 20:29:59 +00001124 if (PImpl)
Chandler Carruth66b31302015-01-04 12:03:27 +00001125 getCache(PImpl, AC, DL, DT).clear();
Hal Finkel7e184492014-09-07 20:29:59 +00001126
Owen Anderson208636f2010-08-18 18:39:01 +00001127 // Fully lazy.
1128 return false;
1129}
1130
Chad Rosier43a33062011-12-02 01:26:24 +00001131void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1132 AU.setPreservesAll();
Chandler Carruth66b31302015-01-04 12:03:27 +00001133 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001134 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chad Rosier43a33062011-12-02 01:26:24 +00001135}
1136
Chris Lattneraf025d32009-11-15 19:59:49 +00001137void LazyValueInfo::releaseMemory() {
1138 // If the cache was allocated, free it.
1139 if (PImpl) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001140 delete &getCache(PImpl, AC);
Craig Topper9f008862014-04-15 04:59:12 +00001141 PImpl = nullptr;
Chris Lattneraf025d32009-11-15 19:59:49 +00001142 }
1143}
1144
Hal Finkel7e184492014-09-07 20:29:59 +00001145Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1146 Instruction *CxtI) {
1147 LVILatticeVal Result =
Chandler Carruth66b31302015-01-04 12:03:27 +00001148 getCache(PImpl, AC, DL, DT).getValueInBlock(V, BB, CxtI);
1149
Chris Lattner19019ea2009-11-11 22:48:44 +00001150 if (Result.isConstant())
1151 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001152 if (Result.isConstantRange()) {
Owen Anderson38f6b7f2010-08-27 23:29:38 +00001153 ConstantRange CR = Result.getConstantRange();
1154 if (const APInt *SingleVal = CR.getSingleElement())
1155 return ConstantInt::get(V->getContext(), *SingleVal);
1156 }
Craig Topper9f008862014-04-15 04:59:12 +00001157 return nullptr;
Chris Lattner19019ea2009-11-11 22:48:44 +00001158}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001159
Sanjay Patel2a385e22015-01-09 16:47:20 +00001160/// Determine whether the specified value is known to be a
Chris Lattnerd5e25432009-11-12 01:29:10 +00001161/// constant on the specified edge. Return null if not.
1162Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
Hal Finkel7e184492014-09-07 20:29:59 +00001163 BasicBlock *ToBB,
1164 Instruction *CxtI) {
1165 LVILatticeVal Result =
Chandler Carruth66b31302015-01-04 12:03:27 +00001166 getCache(PImpl, AC, DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
1167
Chris Lattnerd5e25432009-11-12 01:29:10 +00001168 if (Result.isConstant())
1169 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001170 if (Result.isConstantRange()) {
Owen Anderson185fe002010-08-10 20:03:09 +00001171 ConstantRange CR = Result.getConstantRange();
1172 if (const APInt *SingleVal = CR.getSingleElement())
1173 return ConstantInt::get(V->getContext(), *SingleVal);
1174 }
Craig Topper9f008862014-04-15 04:59:12 +00001175 return nullptr;
Chris Lattnerd5e25432009-11-12 01:29:10 +00001176}
1177
Hal Finkel7e184492014-09-07 20:29:59 +00001178static LazyValueInfo::Tristate
1179getPredicateResult(unsigned Pred, Constant *C, LVILatticeVal &Result,
1180 const DataLayout *DL, TargetLibraryInfo *TLI) {
1181
Chris Lattner565ee2f2009-11-12 04:36:58 +00001182 // If we know the value is a constant, evaluate the conditional.
Craig Topper9f008862014-04-15 04:59:12 +00001183 Constant *Res = nullptr;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001184 if (Result.isConstant()) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001185 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001186 TLI);
Nick Lewycky11678bd2010-12-15 18:57:18 +00001187 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Hal Finkel7e184492014-09-07 20:29:59 +00001188 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1189 return LazyValueInfo::Unknown;
Chris Lattneraf025d32009-11-15 19:59:49 +00001190 }
1191
Owen Anderson185fe002010-08-10 20:03:09 +00001192 if (Result.isConstantRange()) {
Owen Andersonc62f7042010-08-24 07:55:44 +00001193 ConstantInt *CI = dyn_cast<ConstantInt>(C);
Hal Finkel7e184492014-09-07 20:29:59 +00001194 if (!CI) return LazyValueInfo::Unknown;
Owen Andersonc62f7042010-08-24 07:55:44 +00001195
Owen Anderson185fe002010-08-10 20:03:09 +00001196 ConstantRange CR = Result.getConstantRange();
1197 if (Pred == ICmpInst::ICMP_EQ) {
1198 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001199 return LazyValueInfo::False;
Owen Anderson185fe002010-08-10 20:03:09 +00001200
1201 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001202 return LazyValueInfo::True;
Owen Anderson185fe002010-08-10 20:03:09 +00001203 } else if (Pred == ICmpInst::ICMP_NE) {
1204 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001205 return LazyValueInfo::True;
Owen Anderson185fe002010-08-10 20:03:09 +00001206
1207 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001208 return LazyValueInfo::False;
Owen Anderson185fe002010-08-10 20:03:09 +00001209 }
1210
1211 // Handle more complex predicates.
Nick Lewycky11678bd2010-12-15 18:57:18 +00001212 ConstantRange TrueValues =
1213 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1214 if (TrueValues.contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001215 return LazyValueInfo::True;
Nick Lewycky11678bd2010-12-15 18:57:18 +00001216 if (TrueValues.inverse().contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001217 return LazyValueInfo::False;
1218 return LazyValueInfo::Unknown;
Owen Anderson185fe002010-08-10 20:03:09 +00001219 }
1220
Chris Lattneraf025d32009-11-15 19:59:49 +00001221 if (Result.isNotConstant()) {
Chris Lattner565ee2f2009-11-12 04:36:58 +00001222 // If this is an equality comparison, we can try to fold it knowing that
1223 // "V != C1".
1224 if (Pred == ICmpInst::ICMP_EQ) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001225 // !C1 == C -> false iff C1 == C.
Chris Lattner565ee2f2009-11-12 04:36:58 +00001226 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001227 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001228 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001229 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001230 return LazyValueInfo::False;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001231 } else if (Pred == ICmpInst::ICMP_NE) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001232 // !C1 != C -> true iff C1 == C.
Chris Lattnerb0c0a0d2009-11-15 20:01:24 +00001233 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001234 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001235 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001236 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001237 return LazyValueInfo::True;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001238 }
Hal Finkel7e184492014-09-07 20:29:59 +00001239 return LazyValueInfo::Unknown;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001240 }
1241
Hal Finkel7e184492014-09-07 20:29:59 +00001242 return LazyValueInfo::Unknown;
1243}
1244
Sanjay Patel2a385e22015-01-09 16:47:20 +00001245/// Determine whether the specified value comparison with a constant is known to
1246/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
Hal Finkel7e184492014-09-07 20:29:59 +00001247LazyValueInfo::Tristate
1248LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1249 BasicBlock *FromBB, BasicBlock *ToBB,
1250 Instruction *CxtI) {
1251 LVILatticeVal Result =
Chandler Carruth66b31302015-01-04 12:03:27 +00001252 getCache(PImpl, AC, DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001253
1254 return getPredicateResult(Pred, C, Result, DL, TLI);
1255}
1256
1257LazyValueInfo::Tristate
1258LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1259 Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001260 LVILatticeVal Result = getCache(PImpl, AC, DL, DT).getValueAt(V, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001261
1262 return getPredicateResult(Pred, C, Result, DL, TLI);
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001263}
1264
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001265void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky11678bd2010-12-15 18:57:18 +00001266 BasicBlock *NewSucc) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001267 if (PImpl)
1268 getCache(PImpl, AC, DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
Owen Anderson208636f2010-08-18 18:39:01 +00001269}
1270
1271void LazyValueInfo::eraseBlock(BasicBlock *BB) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001272 if (PImpl)
1273 getCache(PImpl, AC, DL, DT).eraseBlock(BB);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001274}