blob: cd1f25090d604e2a9d088ccf010cd4f2744af1b0 [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"
Daniel Jasperaec2fa32016-12-19 08:22:17 +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"
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +000029#include "llvm/IR/Intrinsics.h"
Philip Reameseb3e9da2015-10-29 03:57:17 +000030#include "llvm/IR/LLVMContext.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000031#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000032#include "llvm/IR/ValueHandle.h"
Chris Lattnerb584d1e2009-11-12 01:22:16 +000033#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Support/raw_ostream.h"
Bill Wendling4ec081a2012-01-11 23:43:34 +000035#include <map>
Nick Lewycky55a700b2010-12-18 01:00:40 +000036#include <stack>
Chris Lattner741c94c2009-11-11 00:22:30 +000037using namespace llvm;
Benjamin Kramerd9d80b12012-03-02 15:34:43 +000038using namespace PatternMatch;
Chris Lattner741c94c2009-11-11 00:22:30 +000039
Chandler Carruthf1221bd2014-04-22 02:48:03 +000040#define DEBUG_TYPE "lazy-value-info"
41
Sean Silva687019f2016-06-13 22:01:25 +000042char LazyValueInfoWrapperPass::ID = 0;
43INITIALIZE_PASS_BEGIN(LazyValueInfoWrapperPass, "lazy-value-info",
Chad Rosier43a33062011-12-02 01:26:24 +000044 "Lazy Value Information Analysis", false, true)
Daniel Jasperaec2fa32016-12-19 08:22:17 +000045INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthb98f63d2015-01-15 10:41:28 +000046INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Sean Silva687019f2016-06-13 22:01:25 +000047INITIALIZE_PASS_END(LazyValueInfoWrapperPass, "lazy-value-info",
Owen Andersondf7a4f22010-10-07 22:25:06 +000048 "Lazy Value Information Analysis", false, true)
Chris Lattner741c94c2009-11-11 00:22:30 +000049
50namespace llvm {
Sean Silva687019f2016-06-13 22:01:25 +000051 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfoWrapperPass(); }
Chris Lattner741c94c2009-11-11 00:22:30 +000052}
53
Chandler Carruthdab4eae2016-11-23 17:53:26 +000054AnalysisKey LazyValueAnalysis::Key;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000055
56//===----------------------------------------------------------------------===//
57// LVILatticeVal
58//===----------------------------------------------------------------------===//
59
Sanjay Patel2a385e22015-01-09 16:47:20 +000060/// This is the information tracked by LazyValueInfo for each value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000061///
62/// FIXME: This is basically just for bringup, this can be made a lot more rich
63/// in the future.
64///
65namespace {
66class LVILatticeVal {
67 enum LatticeValueTy {
Philip Reames3bb28322016-04-25 18:48:43 +000068 /// This Value has no known value yet. As a result, this implies the
69 /// producing instruction is dead. Caution: We use this as the starting
70 /// state in our local meet rules. In this usage, it's taken to mean
NAKAMURA Takumif2529512016-07-04 01:26:27 +000071 /// "nothing known yet".
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000072 undefined,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000073
Philip Reames02bb6a62016-12-07 04:48:50 +000074 /// This Value has a specific constant value. (For constant integers,
75 /// constantrange is used instead. Integer typed constantexprs can appear
76 /// as constant.)
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000077 constant,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000078
Philip Reames02bb6a62016-12-07 04:48:50 +000079 /// This Value is known to not have the specified value. (For constant
80 /// integers, constantrange is used instead. As above, integer typed
81 /// constantexprs can appear here.)
Chris Lattner565ee2f2009-11-12 04:36:58 +000082 notconstant,
Chad Rosier43a33062011-12-02 01:26:24 +000083
Philip Reames3bb28322016-04-25 18:48:43 +000084 /// The Value falls within this range. (Used only for integer typed values.)
Owen Anderson0f306a42010-08-05 22:59:19 +000085 constantrange,
Chad Rosier43a33062011-12-02 01:26:24 +000086
Philip Reames3bb28322016-04-25 18:48:43 +000087 /// We can not precisely model the dynamic values this value might take.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000088 overdefined
89 };
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000090
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000091 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattner565ee2f2009-11-12 04:36:58 +000092 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersonc3a14132010-08-05 22:10:46 +000093 LatticeValueTy Tag;
94 Constant *Val;
Owen Anderson0f306a42010-08-05 22:59:19 +000095 ConstantRange Range;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000096
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000097public:
Craig Topper9f008862014-04-15 04:59:12 +000098 LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000099
Chris Lattner19019ea2009-11-11 22:48:44 +0000100 static LVILatticeVal get(Constant *C) {
101 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000102 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +0000103 Res.markConstant(C);
Chris Lattner19019ea2009-11-11 22:48:44 +0000104 return Res;
105 }
Chris Lattner565ee2f2009-11-12 04:36:58 +0000106 static LVILatticeVal getNot(Constant *C) {
107 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000108 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +0000109 Res.markNotConstant(C);
Chris Lattner565ee2f2009-11-12 04:36:58 +0000110 return Res;
111 }
Owen Anderson5f1dd092010-08-10 23:20:01 +0000112 static LVILatticeVal getRange(ConstantRange CR) {
113 LVILatticeVal Res;
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000114 Res.markConstantRange(std::move(CR));
Owen Anderson5f1dd092010-08-10 23:20:01 +0000115 return Res;
116 }
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000117 static LVILatticeVal getOverdefined() {
118 LVILatticeVal Res;
119 Res.markOverdefined();
120 return Res;
121 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +0000122
Owen Anderson0f306a42010-08-05 22:59:19 +0000123 bool isUndefined() const { return Tag == undefined; }
124 bool isConstant() const { return Tag == constant; }
125 bool isNotConstant() const { return Tag == notconstant; }
126 bool isConstantRange() const { return Tag == constantrange; }
127 bool isOverdefined() const { return Tag == overdefined; }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000128
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000129 Constant *getConstant() const {
130 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000131 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000132 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000133
Chris Lattner565ee2f2009-11-12 04:36:58 +0000134 Constant *getNotConstant() const {
135 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000136 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000137 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000138
Owen Anderson0f306a42010-08-05 22:59:19 +0000139 ConstantRange getConstantRange() const {
140 assert(isConstantRange() &&
141 "Cannot get the constant-range of a non-constant-range!");
142 return Range;
143 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000144
Philip Reames1baaef12016-12-06 03:01:08 +0000145private:
Philip Reames71a49672016-12-07 01:03:56 +0000146 void markOverdefined() {
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000147 if (isOverdefined())
Philip Reames71a49672016-12-07 01:03:56 +0000148 return;
Owen Andersonc3a14132010-08-05 22:10:46 +0000149 Tag = overdefined;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000150 }
151
Philip Reames71a49672016-12-07 01:03:56 +0000152 void markConstant(Constant *V) {
Nick Lewycky11678bd2010-12-15 18:57:18 +0000153 assert(V && "Marking constant with NULL");
Philip Reames71a49672016-12-07 01:03:56 +0000154 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
155 markConstantRange(ConstantRange(CI->getValue()));
156 return;
157 }
Nick Lewycky11678bd2010-12-15 18:57:18 +0000158 if (isa<UndefValue>(V))
Philip Reames71a49672016-12-07 01:03:56 +0000159 return;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000160
161 assert((!isConstant() || getConstant() == V) &&
162 "Marking constant with different value");
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000163 assert(isUndefined());
Owen Andersonc3a14132010-08-05 22:10:46 +0000164 Tag = constant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000165 Val = V;
Chris Lattner19019ea2009-11-11 22:48:44 +0000166 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000167
Philip Reames71a49672016-12-07 01:03:56 +0000168 void markNotConstant(Constant *V) {
Chris Lattner565ee2f2009-11-12 04:36:58 +0000169 assert(V && "Marking constant with NULL");
Philip Reames71a49672016-12-07 01:03:56 +0000170 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
171 markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
172 return;
173 }
Nick Lewycky11678bd2010-12-15 18:57:18 +0000174 if (isa<UndefValue>(V))
Philip Reames71a49672016-12-07 01:03:56 +0000175 return;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000176
177 assert((!isConstant() || getConstant() != V) &&
178 "Marking constant !constant with same value");
179 assert((!isNotConstant() || getNotConstant() == V) &&
180 "Marking !constant with different value");
181 assert(isUndefined() || isConstant());
182 Tag = notconstant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000183 Val = V;
Chris Lattner565ee2f2009-11-12 04:36:58 +0000184 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000185
Philip Reames71a49672016-12-07 01:03:56 +0000186 void markConstantRange(ConstantRange NewR) {
Owen Anderson0f306a42010-08-05 22:59:19 +0000187 if (isConstantRange()) {
188 if (NewR.isEmptySet())
Philip Reames71a49672016-12-07 01:03:56 +0000189 markOverdefined();
190 else {
Philip Reames71a49672016-12-07 01:03:56 +0000191 Range = std::move(NewR);
192 }
193 return;
Owen Anderson0f306a42010-08-05 22:59:19 +0000194 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000195
Owen Anderson0f306a42010-08-05 22:59:19 +0000196 assert(isUndefined());
197 if (NewR.isEmptySet())
Philip Reames71a49672016-12-07 01:03:56 +0000198 markOverdefined();
199 else {
200 Tag = constantrange;
201 Range = std::move(NewR);
202 }
Owen Anderson0f306a42010-08-05 22:59:19 +0000203 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000204
Philip Reamesb2949622016-12-06 02:54:16 +0000205public:
206
Sanjay Patel2a385e22015-01-09 16:47:20 +0000207 /// Merge the specified lattice value into this one, updating this
Chris Lattner19019ea2009-11-11 22:48:44 +0000208 /// one and returning true if anything changed.
Philip Reamesb47a7192016-12-07 00:54:21 +0000209 void mergeIn(const LVILatticeVal &RHS, const DataLayout &DL) {
210 if (RHS.isUndefined() || isOverdefined())
211 return;
212 if (RHS.isOverdefined()) {
213 markOverdefined();
214 return;
215 }
Chris Lattner19019ea2009-11-11 22:48:44 +0000216
Nick Lewycky11678bd2010-12-15 18:57:18 +0000217 if (isUndefined()) {
Philip Reamesb47a7192016-12-07 00:54:21 +0000218 *this = RHS;
219 return;
Chris Lattner22db4b52009-11-12 04:57:13 +0000220 }
221
Nick Lewycky11678bd2010-12-15 18:57:18 +0000222 if (isConstant()) {
Philip Reamesb47a7192016-12-07 00:54:21 +0000223 if (RHS.isConstant() && Val == RHS.Val)
224 return;
225 markOverdefined();
226 return;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000227 }
228
229 if (isNotConstant()) {
Philip Reamesb47a7192016-12-07 00:54:21 +0000230 if (RHS.isNotConstant() && Val == RHS.Val)
231 return;
232 markOverdefined();
233 return;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000234 }
235
236 assert(isConstantRange() && "New LVILattice type?");
Philip Reames02bb6a62016-12-07 04:48:50 +0000237 if (!RHS.isConstantRange()) {
238 // We can get here if we've encountered a constantexpr of integer type
239 // and merge it with a constantrange.
240 markOverdefined();
241 return;
242 }
Nick Lewycky11678bd2010-12-15 18:57:18 +0000243 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
244 if (NewR.isFullSet())
Philip Reamesb47a7192016-12-07 00:54:21 +0000245 markOverdefined();
246 else
247 markConstantRange(NewR);
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000248 }
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000249};
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000250
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000251} // end anonymous namespace.
252
Chris Lattner19019ea2009-11-11 22:48:44 +0000253namespace llvm {
Chandler Carruth2b1ba482011-04-18 18:49:44 +0000254raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
255 LLVM_ATTRIBUTE_USED;
Chris Lattner19019ea2009-11-11 22:48:44 +0000256raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
257 if (Val.isUndefined())
258 return OS << "undefined";
259 if (Val.isOverdefined())
260 return OS << "overdefined";
Chris Lattner565ee2f2009-11-12 04:36:58 +0000261
262 if (Val.isNotConstant())
263 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Davide Italianobd543d02016-05-25 22:29:34 +0000264 if (Val.isConstantRange())
Owen Anderson8afac042010-08-09 20:50:46 +0000265 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
266 << Val.getConstantRange().getUpper() << '>';
Chris Lattner19019ea2009-11-11 22:48:44 +0000267 return OS << "constant<" << *Val.getConstant() << '>';
268}
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000269}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000270
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000271/// Returns true if this lattice value represents at most one possible value.
272/// This is as precise as any lattice value can get while still representing
273/// reachable code.
Benjamin Kramerc321e532016-06-08 19:09:22 +0000274static bool hasSingleValue(const LVILatticeVal &Val) {
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000275 if (Val.isConstantRange() &&
276 Val.getConstantRange().isSingleElement())
277 // Integer constants are single element ranges
278 return true;
279 if (Val.isConstant())
280 // Non integer constants
281 return true;
282 return false;
283}
284
285/// Combine two sets of facts about the same value into a single set of
286/// facts. Note that this method is not suitable for merging facts along
287/// different paths in a CFG; that's what the mergeIn function is for. This
288/// is for merging facts gathered about the same value at the same location
289/// through two independent means.
290/// Notes:
291/// * This method does not promise to return the most precise possible lattice
292/// value implied by A and B. It is allowed to return any lattice element
293/// which is at least as strong as *either* A or B (unless our facts
NAKAMURA Takumif2529512016-07-04 01:26:27 +0000294/// conflict, see below).
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000295/// * Due to unreachable code, the intersection of two lattice values could be
296/// contradictory. If this happens, we return some valid lattice value so as
297/// not confuse the rest of LVI. Ideally, we'd always return Undefined, but
298/// we do not make this guarantee. TODO: This would be a useful enhancement.
299static LVILatticeVal intersect(LVILatticeVal A, LVILatticeVal B) {
300 // Undefined is the strongest state. It means the value is known to be along
301 // an unreachable path.
302 if (A.isUndefined())
303 return A;
304 if (B.isUndefined())
305 return B;
306
307 // If we gave up for one, but got a useable fact from the other, use it.
308 if (A.isOverdefined())
309 return B;
310 if (B.isOverdefined())
311 return A;
312
313 // Can't get any more precise than constants.
314 if (hasSingleValue(A))
315 return A;
316 if (hasSingleValue(B))
317 return B;
318
319 // Could be either constant range or not constant here.
320 if (!A.isConstantRange() || !B.isConstantRange()) {
321 // TODO: Arbitrary choice, could be improved
322 return A;
323 }
324
325 // Intersect two constant ranges
326 ConstantRange Range =
327 A.getConstantRange().intersectWith(B.getConstantRange());
328 // Note: An empty range is implicitly converted to overdefined internally.
329 // TODO: We could instead use Undefined here since we've proven a conflict
NAKAMURA Takumif2529512016-07-04 01:26:27 +0000330 // and thus know this path must be unreachable.
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000331 return LVILatticeVal::getRange(std::move(Range));
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000332}
Philip Reamesd1f829d2016-02-02 21:57:37 +0000333
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000334//===----------------------------------------------------------------------===//
Chris Lattneraf025d32009-11-15 19:59:49 +0000335// LazyValueInfoCache Decl
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000336//===----------------------------------------------------------------------===//
337
Chris Lattneraf025d32009-11-15 19:59:49 +0000338namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000339 /// A callback value handle updates the cache when values are erased.
Owen Anderson118ac802011-01-05 21:15:29 +0000340 class LazyValueInfoCache;
David Blaikie774b5842015-08-03 22:30:24 +0000341 struct LVIValueHandle final : public CallbackVH {
Justin Lebar58b377e2016-07-27 22:33:36 +0000342 // Needs to access getValPtr(), which is protected.
343 friend struct DenseMapInfo<LVIValueHandle>;
344
Owen Anderson118ac802011-01-05 21:15:29 +0000345 LazyValueInfoCache *Parent;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000346
Owen Anderson118ac802011-01-05 21:15:29 +0000347 LVIValueHandle(Value *V, LazyValueInfoCache *P)
348 : CallbackVH(V), Parent(P) { }
Craig Toppere9ba7592014-03-05 07:30:04 +0000349
350 void deleted() override;
351 void allUsesReplacedWith(Value *V) override {
Owen Anderson118ac802011-01-05 21:15:29 +0000352 deleted();
353 }
354 };
Justin Lebar58b377e2016-07-27 22:33:36 +0000355} // end anonymous namespace
Owen Anderson118ac802011-01-05 21:15:29 +0000356
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000357namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000358 /// This is the cache kept by LazyValueInfo which
Chris Lattneraf025d32009-11-15 19:59:49 +0000359 /// maintains information about queries across the clients' queries.
360 class LazyValueInfoCache {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000361 /// This is all of the cached block information for exactly one Value*.
362 /// The entries are sorted by the BasicBlock* of the
Chris Lattneraf025d32009-11-15 19:59:49 +0000363 /// entries, allowing us to do a lookup with a binary search.
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000364 /// Over-defined lattice values are recorded in OverDefinedCache to reduce
365 /// memory overhead.
Justin Lebar58b377e2016-07-27 22:33:36 +0000366 struct ValueCacheEntryTy {
367 ValueCacheEntryTy(Value *V, LazyValueInfoCache *P) : Handle(V, P) {}
368 LVIValueHandle Handle;
369 SmallDenseMap<AssertingVH<BasicBlock>, LVILatticeVal, 4> BlockVals;
370 };
Chris Lattneraf025d32009-11-15 19:59:49 +0000371
Sanjay Patel2a385e22015-01-09 16:47:20 +0000372 /// This is all of the cached information for all values,
Owen Anderson6f060af2011-01-05 23:26:22 +0000373 /// mapped from Value* to key information.
Justin Lebar58b377e2016-07-27 22:33:36 +0000374 DenseMap<Value *, std::unique_ptr<ValueCacheEntryTy>> ValueCache;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000375
Sanjay Patel2a385e22015-01-09 16:47:20 +0000376 /// This tracks, on a per-block basis, the set of values that are
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000377 /// over-defined at the end of that block.
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000378 typedef DenseMap<AssertingVH<BasicBlock>, SmallPtrSet<Value *, 4>>
379 OverDefinedCacheTy;
380 OverDefinedCacheTy OverDefinedCache;
Benjamin Kramer36647082011-12-03 15:16:45 +0000381
Sanjay Patel2a385e22015-01-09 16:47:20 +0000382 /// Keep track of all blocks that we have ever seen, so we
Benjamin Kramer36647082011-12-03 15:16:45 +0000383 /// don't spend time removing unused blocks from our caches.
384 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
385
Philip Reames9db79482016-09-12 22:38:44 +0000386 public:
Hans Wennborg45172ac2014-11-25 17:23:05 +0000387 void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
388 SeenBlocks.insert(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000389
390 // Insert over-defined values into their own cache to reduce memory
391 // overhead.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000392 if (Result.isOverdefined())
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000393 OverDefinedCache[BB].insert(Val);
Justin Lebar58b377e2016-07-27 22:33:36 +0000394 else {
395 auto It = ValueCache.find_as(Val);
396 if (It == ValueCache.end()) {
397 ValueCache[Val] = make_unique<ValueCacheEntryTy>(Val, this);
398 It = ValueCache.find_as(Val);
399 assert(It != ValueCache.end() && "Val was just added to the map!");
400 }
401 It->second->BlockVals[BB] = Result;
402 }
Hans Wennborg45172ac2014-11-25 17:23:05 +0000403 }
Owen Andersonc1561b82010-07-30 23:59:40 +0000404
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000405 bool isOverdefined(Value *V, BasicBlock *BB) const {
406 auto ODI = OverDefinedCache.find(BB);
407
408 if (ODI == OverDefinedCache.end())
409 return false;
410
411 return ODI->second.count(V);
412 }
413
Philip Reames9db79482016-09-12 22:38:44 +0000414 bool hasCachedValueInfo(Value *V, BasicBlock *BB) const {
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000415 if (isOverdefined(V, BB))
416 return true;
417
Justin Lebar58b377e2016-07-27 22:33:36 +0000418 auto I = ValueCache.find_as(V);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000419 if (I == ValueCache.end())
420 return false;
421
Justin Lebar58b377e2016-07-27 22:33:36 +0000422 return I->second->BlockVals.count(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000423 }
424
Philip Reames9db79482016-09-12 22:38:44 +0000425 LVILatticeVal getCachedValueInfo(Value *V, BasicBlock *BB) const {
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000426 if (isOverdefined(V, BB))
427 return LVILatticeVal::getOverdefined();
428
Justin Lebar58b377e2016-07-27 22:33:36 +0000429 auto I = ValueCache.find_as(V);
430 if (I == ValueCache.end())
431 return LVILatticeVal();
432 auto BBI = I->second->BlockVals.find(BB);
433 if (BBI == I->second->BlockVals.end())
434 return LVILatticeVal();
435 return BBI->second;
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000436 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +0000437
Philip Reames92e5e1b2016-09-12 21:46:58 +0000438 /// clear - Empty the cache.
439 void clear() {
440 SeenBlocks.clear();
441 ValueCache.clear();
442 OverDefinedCache.clear();
443 }
444
Philip Reamesb627aec2016-09-12 22:03:36 +0000445 /// Inform the cache that a given value has been deleted.
446 void eraseValue(Value *V);
447
448 /// This is part of the update interface to inform the cache
449 /// that a block has been deleted.
450 void eraseBlock(BasicBlock *BB);
451
Philip Reames9db79482016-09-12 22:38:44 +0000452 /// Updates the cache to remove any influence an overdefined value in
453 /// OldSucc might have (unless also overdefined in NewSucc). This just
454 /// flushes elements from the cache and does not add any.
455 void threadEdgeImpl(BasicBlock *OldSucc,BasicBlock *NewSucc);
456
Philip Reames92e5e1b2016-09-12 21:46:58 +0000457 friend struct LVIValueHandle;
458 };
Philip Reamesb627aec2016-09-12 22:03:36 +0000459}
Philip Reames92e5e1b2016-09-12 21:46:58 +0000460
Philip Reamesb627aec2016-09-12 22:03:36 +0000461void LazyValueInfoCache::eraseValue(Value *V) {
462 SmallVector<AssertingVH<BasicBlock>, 4> ToErase;
463 for (auto &I : OverDefinedCache) {
464 SmallPtrSetImpl<Value *> &ValueSet = I.second;
465 if (ValueSet.count(V))
466 ValueSet.erase(V);
467 if (ValueSet.empty())
468 ToErase.push_back(I.first);
469 }
470 for (auto &BB : ToErase)
471 OverDefinedCache.erase(BB);
472
473 ValueCache.erase(V);
474}
475
476void LVIValueHandle::deleted() {
477 // This erasure deallocates *this, so it MUST happen after we're done
478 // using any and all members of *this.
479 Parent->eraseValue(*this);
480}
481
482void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
483 // Shortcut if we have never seen this block.
484 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
485 if (I == SeenBlocks.end())
486 return;
487 SeenBlocks.erase(I);
488
489 auto ODI = OverDefinedCache.find(BB);
490 if (ODI != OverDefinedCache.end())
491 OverDefinedCache.erase(ODI);
492
493 for (auto &I : ValueCache)
494 I.second->BlockVals.erase(BB);
495}
496
Philip Reames9db79482016-09-12 22:38:44 +0000497void LazyValueInfoCache::threadEdgeImpl(BasicBlock *OldSucc,
498 BasicBlock *NewSucc) {
499 // When an edge in the graph has been threaded, values that we could not
500 // determine a value for before (i.e. were marked overdefined) may be
501 // possible to solve now. We do NOT try to proactively update these values.
502 // Instead, we clear their entries from the cache, and allow lazy updating to
503 // recompute them when needed.
504
505 // The updating process is fairly simple: we need to drop cached info
506 // for all values that were marked overdefined in OldSucc, and for those same
507 // values in any successor of OldSucc (except NewSucc) in which they were
508 // also marked overdefined.
509 std::vector<BasicBlock*> worklist;
510 worklist.push_back(OldSucc);
511
512 auto I = OverDefinedCache.find(OldSucc);
513 if (I == OverDefinedCache.end())
514 return; // Nothing to process here.
515 SmallVector<Value *, 4> ValsToClear(I->second.begin(), I->second.end());
516
517 // Use a worklist to perform a depth-first search of OldSucc's successors.
518 // NOTE: We do not need a visited list since any blocks we have already
519 // visited will have had their overdefined markers cleared already, and we
520 // thus won't loop to their successors.
521 while (!worklist.empty()) {
522 BasicBlock *ToUpdate = worklist.back();
523 worklist.pop_back();
524
525 // Skip blocks only accessible through NewSucc.
526 if (ToUpdate == NewSucc) continue;
527
Philip Reames1e48efc2016-12-30 17:56:47 +0000528 // If a value was marked overdefined in OldSucc, and is here too...
529 auto OI = OverDefinedCache.find(ToUpdate);
530 if (OI == OverDefinedCache.end())
531 continue;
532 SmallPtrSetImpl<Value *> &ValueSet = OI->second;
533
Philip Reames9db79482016-09-12 22:38:44 +0000534 bool changed = false;
535 for (Value *V : ValsToClear) {
Philip Reames1e48efc2016-12-30 17:56:47 +0000536 // TODO: count and erase can be converted to a find/erase(itr) pattern
Philip Reames9db79482016-09-12 22:38:44 +0000537 if (!ValueSet.count(V))
538 continue;
539
540 ValueSet.erase(V);
Philip Reames9db79482016-09-12 22:38:44 +0000541
542 // If we removed anything, then we potentially need to update
543 // blocks successors too.
544 changed = true;
Philip Reames1e48efc2016-12-30 17:56:47 +0000545
546 if (ValueSet.empty()) {
547 OverDefinedCache.erase(OI);
548 break;
549 }
Philip Reames9db79482016-09-12 22:38:44 +0000550 }
551
552 if (!changed) continue;
553
554 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
555 }
556}
557
Philip Reamesb627aec2016-09-12 22:03:36 +0000558namespace {
Philip Reames92e5e1b2016-09-12 21:46:58 +0000559 // The actual implementation of the lazy analysis and update. Note that the
560 // inheritance from LazyValueInfoCache is intended to be temporary while
561 // splitting the code and then transitioning to a has-a relationship.
Philip Reames9db79482016-09-12 22:38:44 +0000562 class LazyValueInfoImpl {
563
564 /// Cached results from previous queries
565 LazyValueInfoCache TheCache;
Philip Reames92e5e1b2016-09-12 21:46:58 +0000566
567 /// This stack holds the state of the value solver during a query.
568 /// It basically emulates the callstack of the naive
569 /// recursive value lookup process.
570 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
571
572 /// Keeps track of which block-value pairs are in BlockValueStack.
573 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
574
575 /// Push BV onto BlockValueStack unless it's already in there.
576 /// Returns true on success.
577 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
578 if (!BlockValueSet.insert(BV).second)
579 return false; // It's already in the stack.
580
581 DEBUG(dbgs() << "PUSH: " << *BV.second << " in " << BV.first->getName()
582 << "\n");
583 BlockValueStack.push(BV);
584 return true;
585 }
586
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000587 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
Philip Reames92e5e1b2016-09-12 21:46:58 +0000588 const DataLayout &DL; ///< A mandatory DataLayout
589 DominatorTree *DT; ///< An optional DT pointer.
590
591 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
592 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
593 LVILatticeVal &Result, Instruction *CxtI = nullptr);
594 bool hasBlockValue(Value *Val, BasicBlock *BB);
595
596 // These methods process one work item and may add more. A false value
597 // returned means that the work item was not completely processed and must
598 // be revisited after going through the new items.
599 bool solveBlockValue(Value *Val, BasicBlock *BB);
Philip Reames05c435e2016-12-06 03:22:03 +0000600 bool solveBlockValueImpl(LVILatticeVal &Res, Value *Val, BasicBlock *BB);
Philip Reames92e5e1b2016-09-12 21:46:58 +0000601 bool solveBlockValueNonLocal(LVILatticeVal &BBLV, Value *Val, BasicBlock *BB);
602 bool solveBlockValuePHINode(LVILatticeVal &BBLV, PHINode *PN, BasicBlock *BB);
603 bool solveBlockValueSelect(LVILatticeVal &BBLV, SelectInst *S,
604 BasicBlock *BB);
605 bool solveBlockValueBinaryOp(LVILatticeVal &BBLV, Instruction *BBI,
606 BasicBlock *BB);
607 bool solveBlockValueCast(LVILatticeVal &BBLV, Instruction *BBI,
608 BasicBlock *BB);
609 void intersectAssumeOrGuardBlockValueConstantRange(Value *Val,
610 LVILatticeVal &BBLV,
611 Instruction *BBI);
612
613 void solve();
614
615 public:
Sanjay Patel2a385e22015-01-09 16:47:20 +0000616 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000617 /// value for the specified Value* at the end of the specified block.
Hal Finkel7e184492014-09-07 20:29:59 +0000618 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
619 Instruction *CxtI = nullptr);
620
Sanjay Patel2a385e22015-01-09 16:47:20 +0000621 /// This is the query interface to determine the lattice
Hal Finkel7e184492014-09-07 20:29:59 +0000622 /// value for the specified Value* at the specified instruction (generally
623 /// from an assume intrinsic).
624 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
Chris Lattneraf025d32009-11-15 19:59:49 +0000625
Sanjay Patel2a385e22015-01-09 16:47:20 +0000626 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000627 /// value for the specified Value* that is true on the specified edge.
Hal Finkel7e184492014-09-07 20:29:59 +0000628 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
629 Instruction *CxtI = nullptr);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000630
Philip Reames9db79482016-09-12 22:38:44 +0000631 /// Complete flush all previously computed values
632 void clear() {
633 TheCache.clear();
634 }
635
636 /// This is part of the update interface to inform the cache
637 /// that a block has been deleted.
638 void eraseBlock(BasicBlock *BB) {
639 TheCache.eraseBlock(BB);
640 }
641
Sanjay Patel2a385e22015-01-09 16:47:20 +0000642 /// This is the update interface to inform the cache that an edge from
643 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
Owen Andersonaa7f66b2010-07-26 18:48:03 +0000644 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000645
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000646 LazyValueInfoImpl(AssumptionCache *AC, const DataLayout &DL,
647 DominatorTree *DT = nullptr)
648 : AC(AC), DL(DL), DT(DT) {}
Chris Lattneraf025d32009-11-15 19:59:49 +0000649 };
650} // end anonymous namespace
651
Philip Reames92e5e1b2016-09-12 21:46:58 +0000652void LazyValueInfoImpl::solve() {
Owen Anderson6f060af2011-01-05 23:26:22 +0000653 while (!BlockValueStack.empty()) {
654 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000655 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
656
Nuno Lopese6e04902012-06-28 01:16:18 +0000657 if (solveBlockValue(e.second, e.first)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000658 // The work item was completely processed.
659 assert(BlockValueStack.top() == e && "Nothing should have been pushed!");
Philip Reames9db79482016-09-12 22:38:44 +0000660 assert(TheCache.hasCachedValueInfo(e.second, e.first) &&
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000661 "Result should be in cache!");
Hans Wennborg45172ac2014-11-25 17:23:05 +0000662
Philip Reames44456b82016-02-02 03:15:40 +0000663 DEBUG(dbgs() << "POP " << *e.second << " in " << e.first->getName()
Philip Reames9db79482016-09-12 22:38:44 +0000664 << " = " << TheCache.getCachedValueInfo(e.second, e.first) << "\n");
Philip Reames44456b82016-02-02 03:15:40 +0000665
Owen Anderson6f060af2011-01-05 23:26:22 +0000666 BlockValueStack.pop();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000667 BlockValueSet.erase(e);
668 } else {
669 // More work needs to be done before revisiting.
670 assert(BlockValueStack.top() != e && "Stack should have been pushed!");
Nuno Lopese6e04902012-06-28 01:16:18 +0000671 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000672 }
673}
674
Philip Reames92e5e1b2016-09-12 21:46:58 +0000675bool LazyValueInfoImpl::hasBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000676 // If already a constant, there is nothing to compute.
677 if (isa<Constant>(Val))
678 return true;
679
Philip Reames9db79482016-09-12 22:38:44 +0000680 return TheCache.hasCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000681}
682
Philip Reames92e5e1b2016-09-12 21:46:58 +0000683LVILatticeVal LazyValueInfoImpl::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000684 // If already a constant, there is nothing to compute.
685 if (Constant *VC = dyn_cast<Constant>(Val))
686 return LVILatticeVal::get(VC);
687
Philip Reames9db79482016-09-12 22:38:44 +0000688 return TheCache.getCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000689}
690
Philip Reameseb3e9da2015-10-29 03:57:17 +0000691static LVILatticeVal getFromRangeMetadata(Instruction *BBI) {
692 switch (BBI->getOpcode()) {
693 default: break;
694 case Instruction::Load:
695 case Instruction::Call:
696 case Instruction::Invoke:
NAKAMURA Takumibd072a92016-07-25 00:59:46 +0000697 if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
Philip Reames70efccd2015-10-29 04:21:49 +0000698 if (isa<IntegerType>(BBI->getType())) {
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000699 return LVILatticeVal::getRange(getConstantRangeFromMetadata(*Ranges));
Philip Reameseb3e9da2015-10-29 03:57:17 +0000700 }
701 break;
702 };
Philip Reamesd1f829d2016-02-02 21:57:37 +0000703 // Nothing known - will be intersected with other facts
704 return LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +0000705}
706
Philip Reames92e5e1b2016-09-12 21:46:58 +0000707bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000708 if (isa<Constant>(Val))
709 return true;
710
Philip Reames9db79482016-09-12 22:38:44 +0000711 if (TheCache.hasCachedValueInfo(Val, BB)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000712 // If we have a cached value, use that.
713 DEBUG(dbgs() << " reuse BB '" << BB->getName()
Philip Reames9db79482016-09-12 22:38:44 +0000714 << "' val=" << TheCache.getCachedValueInfo(Val, BB) << '\n');
Nick Lewycky55a700b2010-12-18 01:00:40 +0000715
Hans Wennborg45172ac2014-11-25 17:23:05 +0000716 // Since we're reusing a cached value, we don't need to update the
717 // OverDefinedCache. The cache will have been properly updated whenever the
718 // cached value was inserted.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000719 return true;
Chris Lattner2c708562009-11-15 20:00:52 +0000720 }
721
Hans Wennborg45172ac2014-11-25 17:23:05 +0000722 // Hold off inserting this value into the Cache in case we have to return
723 // false and come back later.
724 LVILatticeVal Res;
Philip Reames05c435e2016-12-06 03:22:03 +0000725 if (!solveBlockValueImpl(Res, Val, BB))
726 // Work pushed, will revisit
727 return false;
728
729 TheCache.insertResult(Val, BB, Res);
730 return true;
731}
732
733bool LazyValueInfoImpl::solveBlockValueImpl(LVILatticeVal &Res,
734 Value *Val, BasicBlock *BB) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000735
Chris Lattneraf025d32009-11-15 19:59:49 +0000736 Instruction *BBI = dyn_cast<Instruction>(Val);
Philip Reames05c435e2016-12-06 03:22:03 +0000737 if (!BBI || BBI->getParent() != BB)
738 return solveBlockValueNonLocal(Res, Val, BB);
Chris Lattner2c708562009-11-15 20:00:52 +0000739
Philip Reames05c435e2016-12-06 03:22:03 +0000740 if (PHINode *PN = dyn_cast<PHINode>(BBI))
741 return solveBlockValuePHINode(Res, PN, BB);
Owen Anderson80d19f02010-08-18 21:11:37 +0000742
Philip Reames05c435e2016-12-06 03:22:03 +0000743 if (auto *SI = dyn_cast<SelectInst>(BBI))
744 return solveBlockValueSelect(Res, SI, BB);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000745
Philip Reames2ab964e2016-04-27 01:02:25 +0000746 // If this value is a nonnull pointer, record it's range and bailout. Note
747 // that for all other pointer typed values, we terminate the search at the
748 // definition. We could easily extend this to look through geps, bitcasts,
749 // and the like to prove non-nullness, but it's not clear that's worth it
750 // compile time wise. The context-insensative value walk done inside
751 // isKnownNonNull gets most of the profitable cases at much less expense.
752 // This does mean that we have a sensativity to where the defining
753 // instruction is placed, even if it could legally be hoisted much higher.
754 // That is unfortunate.
Igor Laevsky0fa48192015-09-18 13:01:48 +0000755 PointerType *PT = dyn_cast<PointerType>(BBI->getType());
756 if (PT && isKnownNonNull(BBI)) {
757 Res = LVILatticeVal::getNot(ConstantPointerNull::get(PT));
Hans Wennborg45172ac2014-11-25 17:23:05 +0000758 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000759 }
Davide Italianobd543d02016-05-25 22:29:34 +0000760 if (BBI->getType()->isIntegerTy()) {
Philip Reames05c435e2016-12-06 03:22:03 +0000761 if (isa<CastInst>(BBI))
762 return solveBlockValueCast(Res, BBI, BB);
763
Philip Reames2ab964e2016-04-27 01:02:25 +0000764 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
Philip Reames05c435e2016-12-06 03:22:03 +0000765 if (BO && isa<ConstantInt>(BO->getOperand(1)))
766 return solveBlockValueBinaryOp(Res, BBI, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000767 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000768
Philip Reamesa0c9f6e2016-03-04 22:27:39 +0000769 DEBUG(dbgs() << " compute BB '" << BB->getName()
770 << "' - unknown inst def found.\n");
771 Res = getFromRangeMetadata(BBI);
Hans Wennborg45172ac2014-11-25 17:23:05 +0000772 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000773}
774
775static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
776 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
777 return L->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000778 GetUnderlyingObject(L->getPointerOperand(),
779 L->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000780 }
781 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
782 return S->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000783 GetUnderlyingObject(S->getPointerOperand(),
784 S->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000785 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000786 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
787 if (MI->isVolatile()) return false;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000788
789 // FIXME: check whether it has a valuerange that excludes zero?
790 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
791 if (!Len || Len->isZero()) return false;
792
Eli Friedman7a5fc692011-05-31 20:40:16 +0000793 if (MI->getDestAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000794 if (GetUnderlyingObject(MI->getRawDest(),
795 MI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000796 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000797 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman7a5fc692011-05-31 20:40:16 +0000798 if (MTI->getSourceAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000799 if (GetUnderlyingObject(MTI->getRawSource(),
800 MTI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000801 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000802 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000803 return false;
804}
805
Philip Reames3f83dbe2016-04-27 00:30:55 +0000806/// Return true if the allocation associated with Val is ever dereferenced
807/// within the given basic block. This establishes the fact Val is not null,
808/// but does not imply that the memory at Val is dereferenceable. (Val may
809/// point off the end of the dereferenceable part of the object.)
810static bool isObjectDereferencedInBlock(Value *Val, BasicBlock *BB) {
811 assert(Val->getType()->isPointerTy());
812
813 const DataLayout &DL = BB->getModule()->getDataLayout();
814 Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
815 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
816 // inside InstructionDereferencesPointer either.
817 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1))
818 for (Instruction &I : *BB)
819 if (InstructionDereferencesPointer(&I, UnderlyingVal))
820 return true;
821 return false;
822}
823
Philip Reames92e5e1b2016-09-12 21:46:58 +0000824bool LazyValueInfoImpl::solveBlockValueNonLocal(LVILatticeVal &BBLV,
Owen Anderson64c2c572010-12-20 18:18:16 +0000825 Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000826 LVILatticeVal Result; // Start Undefined.
827
Nick Lewycky55a700b2010-12-18 01:00:40 +0000828 // If this is the entry block, we must be asking about an argument. The
829 // value is overdefined.
830 if (BB == &BB->getParent()->getEntryBlock()) {
831 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
Philip Reames3f83dbe2016-04-27 00:30:55 +0000832 // Bofore giving up, see if we can prove the pointer non-null local to
833 // this particular block.
834 if (Val->getType()->isPointerTy() &&
835 (isKnownNonNull(Val) || isObjectDereferencedInBlock(Val, BB))) {
Chris Lattner229907c2011-07-18 04:54:35 +0000836 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000837 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
838 } else {
Philip Reames1baaef12016-12-06 03:01:08 +0000839 Result = LVILatticeVal::getOverdefined();
Nick Lewycky55a700b2010-12-18 01:00:40 +0000840 }
Owen Anderson64c2c572010-12-20 18:18:16 +0000841 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000842 return true;
843 }
844
845 // Loop over all of our predecessors, merging what we know from them into
846 // result.
847 bool EdgesMissing = false;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000848 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000849 LVILatticeVal EdgeResult;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000850 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000851 if (EdgesMissing)
852 continue;
853
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000854 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000855
856 // If we hit overdefined, exit early. The BlockVals entry is already set
857 // to overdefined.
858 if (Result.isOverdefined()) {
859 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000860 << "' - overdefined because of pred (non local).\n");
Artur Pilipenkoadcd01f2016-08-09 09:14:29 +0000861 // Before giving up, see if we can prove the pointer non-null local to
Philip Reames3f83dbe2016-04-27 00:30:55 +0000862 // this particular block.
863 if (Val->getType()->isPointerTy() &&
864 isObjectDereferencedInBlock(Val, BB)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000865 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000866 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
867 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000868
Owen Anderson64c2c572010-12-20 18:18:16 +0000869 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000870 return true;
871 }
872 }
873 if (EdgesMissing)
874 return false;
875
876 // Return the merged value, which is more precise than 'overdefined'.
877 assert(!Result.isOverdefined());
Owen Anderson64c2c572010-12-20 18:18:16 +0000878 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000879 return true;
880}
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000881
Philip Reames92e5e1b2016-09-12 21:46:58 +0000882bool LazyValueInfoImpl::solveBlockValuePHINode(LVILatticeVal &BBLV,
Owen Anderson64c2c572010-12-20 18:18:16 +0000883 PHINode *PN, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000884 LVILatticeVal Result; // Start Undefined.
885
886 // Loop over all of our predecessors, merging what we know from them into
887 // result.
888 bool EdgesMissing = false;
889 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
890 BasicBlock *PhiBB = PN->getIncomingBlock(i);
891 Value *PhiVal = PN->getIncomingValue(i);
892 LVILatticeVal EdgeResult;
Hal Finkel2400c962014-10-16 00:40:05 +0000893 // Note that we can provide PN as the context value to getEdgeValue, even
894 // though the results will be cached, because PN is the value being used as
895 // the cache key in the caller.
Hal Finkel7e184492014-09-07 20:29:59 +0000896 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000897 if (EdgesMissing)
898 continue;
899
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000900 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000901
902 // If we hit overdefined, exit early. The BlockVals entry is already set
903 // to overdefined.
904 if (Result.isOverdefined()) {
905 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000906 << "' - overdefined because of pred (local).\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000907
Owen Anderson64c2c572010-12-20 18:18:16 +0000908 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000909 return true;
910 }
911 }
912 if (EdgesMissing)
913 return false;
914
915 // Return the merged value, which is more precise than 'overdefined'.
916 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson64c2c572010-12-20 18:18:16 +0000917 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000918 return true;
919}
920
Artur Pilipenko933c07a2016-08-10 13:38:07 +0000921static LVILatticeVal getValueFromCondition(Value *Val, Value *Cond,
922 bool isTrueDest = true);
Hal Finkel7e184492014-09-07 20:29:59 +0000923
Philip Reamesd1f829d2016-02-02 21:57:37 +0000924// If we can determine a constraint on the value given conditions assumed by
925// the program, intersect those constraints with BBLV
Philip Reames92e5e1b2016-09-12 21:46:58 +0000926void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +0000927 Value *Val, LVILatticeVal &BBLV, Instruction *BBI) {
Hal Finkel7e184492014-09-07 20:29:59 +0000928 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
929 if (!BBI)
930 return;
931
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000932 for (auto &AssumeVH : AC->assumptions()) {
933 if (!AssumeVH)
Chandler Carruth66b31302015-01-04 12:03:27 +0000934 continue;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000935 auto *I = cast<CallInst>(AssumeVH);
936 if (!isValidAssumeForContext(I, BBI, DT))
Hal Finkel7e184492014-09-07 20:29:59 +0000937 continue;
938
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000939 BBLV = intersect(BBLV, getValueFromCondition(Val, I->getArgOperand(0)));
Hal Finkel7e184492014-09-07 20:29:59 +0000940 }
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +0000941
942 // If guards are not used in the module, don't spend time looking for them
943 auto *GuardDecl = BBI->getModule()->getFunction(
944 Intrinsic::getName(Intrinsic::experimental_guard));
945 if (!GuardDecl || GuardDecl->use_empty())
946 return;
947
Artur Pilipenko47dc0982016-10-21 15:02:21 +0000948 for (Instruction &I : make_range(BBI->getIterator().getReverse(),
949 BBI->getParent()->rend())) {
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +0000950 Value *Cond = nullptr;
Artur Pilipenko47dc0982016-10-21 15:02:21 +0000951 if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(Cond))))
952 BBLV = intersect(BBLV, getValueFromCondition(Val, Cond));
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +0000953 }
Hal Finkel7e184492014-09-07 20:29:59 +0000954}
955
Philip Reames92e5e1b2016-09-12 21:46:58 +0000956bool LazyValueInfoImpl::solveBlockValueSelect(LVILatticeVal &BBLV,
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000957 SelectInst *SI, BasicBlock *BB) {
958
959 // Recurse on our inputs if needed
960 if (!hasBlockValue(SI->getTrueValue(), BB)) {
961 if (pushBlockValue(std::make_pair(BB, SI->getTrueValue())))
962 return false;
Philip Reames1baaef12016-12-06 03:01:08 +0000963 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000964 return true;
965 }
966 LVILatticeVal TrueVal = getBlockValue(SI->getTrueValue(), BB);
967 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
968 // extra slots in the table if we can.
969 if (TrueVal.isOverdefined()) {
Philip Reames1baaef12016-12-06 03:01:08 +0000970 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000971 return true;
972 }
973
974 if (!hasBlockValue(SI->getFalseValue(), BB)) {
975 if (pushBlockValue(std::make_pair(BB, SI->getFalseValue())))
976 return false;
Philip Reames1baaef12016-12-06 03:01:08 +0000977 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000978 return true;
979 }
980 LVILatticeVal FalseVal = getBlockValue(SI->getFalseValue(), BB);
981 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
982 // extra slots in the table if we can.
983 if (FalseVal.isOverdefined()) {
Philip Reames1baaef12016-12-06 03:01:08 +0000984 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000985 return true;
986 }
987
Philip Reamesadf0e352016-02-26 22:53:59 +0000988 if (TrueVal.isConstantRange() && FalseVal.isConstantRange()) {
989 ConstantRange TrueCR = TrueVal.getConstantRange();
990 ConstantRange FalseCR = FalseVal.getConstantRange();
991 Value *LHS = nullptr;
992 Value *RHS = nullptr;
993 SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
994 // Is this a min specifically of our two inputs? (Avoid the risk of
995 // ValueTracking getting smarter looking back past our immediate inputs.)
996 if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
997 LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) {
Philip Reamesb2949622016-12-06 02:54:16 +0000998 ConstantRange ResultCR = [&]() {
999 switch (SPR.Flavor) {
1000 default:
1001 llvm_unreachable("unexpected minmax type!");
1002 case SPF_SMIN: /// Signed minimum
1003 return TrueCR.smin(FalseCR);
1004 case SPF_UMIN: /// Unsigned minimum
1005 return TrueCR.umin(FalseCR);
1006 case SPF_SMAX: /// Signed maximum
1007 return TrueCR.smax(FalseCR);
1008 case SPF_UMAX: /// Unsigned maximum
1009 return TrueCR.umax(FalseCR);
1010 };
1011 }();
1012 BBLV = LVILatticeVal::getRange(ResultCR);
1013 return true;
Philip Reamesadf0e352016-02-26 22:53:59 +00001014 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001015
Philip Reamesadf0e352016-02-26 22:53:59 +00001016 // TODO: ABS, NABS from the SelectPatternResult
1017 }
1018
Philip Reames854a84c2016-02-12 00:09:18 +00001019 // Can we constrain the facts about the true and false values by using the
1020 // condition itself? This shows up with idioms like e.g. select(a > 5, a, 5).
1021 // TODO: We could potentially refine an overdefined true value above.
Artur Pilipenko2e19f592016-08-02 16:20:48 +00001022 Value *Cond = SI->getCondition();
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001023 TrueVal = intersect(TrueVal,
1024 getValueFromCondition(SI->getTrueValue(), Cond, true));
1025 FalseVal = intersect(FalseVal,
1026 getValueFromCondition(SI->getFalseValue(), Cond, false));
Philip Reames854a84c2016-02-12 00:09:18 +00001027
Artur Pilipenko2e19f592016-08-02 16:20:48 +00001028 // Handle clamp idioms such as:
1029 // %24 = constantrange<0, 17>
1030 // %39 = icmp eq i32 %24, 0
1031 // %40 = add i32 %24, -1
1032 // %siv.next = select i1 %39, i32 16, i32 %40
1033 // %siv.next = constantrange<0, 17> not <-1, 17>
1034 // In general, this can handle any clamp idiom which tests the edge
1035 // condition via an equality or inequality.
1036 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
Philip Reamesadf0e352016-02-26 22:53:59 +00001037 ICmpInst::Predicate Pred = ICI->getPredicate();
1038 Value *A = ICI->getOperand(0);
1039 if (ConstantInt *CIBase = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
1040 auto addConstants = [](ConstantInt *A, ConstantInt *B) {
1041 assert(A->getType() == B->getType());
1042 return ConstantInt::get(A->getType(), A->getValue() + B->getValue());
1043 };
1044 // See if either input is A + C2, subject to the constraint from the
1045 // condition that A != C when that input is used. We can assume that
1046 // that input doesn't include C + C2.
1047 ConstantInt *CIAdded;
1048 switch (Pred) {
Philip Reames70b39182016-02-27 05:18:30 +00001049 default: break;
Philip Reamesadf0e352016-02-26 22:53:59 +00001050 case ICmpInst::ICMP_EQ:
1051 if (match(SI->getFalseValue(), m_Add(m_Specific(A),
1052 m_ConstantInt(CIAdded)))) {
1053 auto ResNot = addConstants(CIBase, CIAdded);
1054 FalseVal = intersect(FalseVal,
1055 LVILatticeVal::getNot(ResNot));
1056 }
1057 break;
1058 case ICmpInst::ICMP_NE:
1059 if (match(SI->getTrueValue(), m_Add(m_Specific(A),
1060 m_ConstantInt(CIAdded)))) {
1061 auto ResNot = addConstants(CIBase, CIAdded);
1062 TrueVal = intersect(TrueVal,
1063 LVILatticeVal::getNot(ResNot));
1064 }
1065 break;
1066 };
1067 }
1068 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001069
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001070 LVILatticeVal Result; // Start Undefined.
1071 Result.mergeIn(TrueVal, DL);
1072 Result.mergeIn(FalseVal, DL);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001073 BBLV = Result;
1074 return true;
1075}
1076
Philip Reames92e5e1b2016-09-12 21:46:58 +00001077bool LazyValueInfoImpl::solveBlockValueCast(LVILatticeVal &BBLV,
Philip Reames66715772016-04-25 18:30:31 +00001078 Instruction *BBI,
Philip Reamese5030e82016-04-26 22:52:30 +00001079 BasicBlock *BB) {
1080 if (!BBI->getOperand(0)->getType()->isSized()) {
1081 // Without knowing how wide the input is, we can't analyze it in any useful
1082 // way.
Philip Reames1baaef12016-12-06 03:01:08 +00001083 BBLV = LVILatticeVal::getOverdefined();
Philip Reamese5030e82016-04-26 22:52:30 +00001084 return true;
1085 }
Philip Reamesf105db42016-04-26 23:27:33 +00001086
1087 // Filter out casts we don't know how to reason about before attempting to
1088 // recurse on our operand. This can cut a long search short if we know we're
1089 // not going to be able to get any useful information anways.
1090 switch (BBI->getOpcode()) {
1091 case Instruction::Trunc:
1092 case Instruction::SExt:
1093 case Instruction::ZExt:
1094 case Instruction::BitCast:
1095 break;
1096 default:
1097 // Unhandled instructions are overdefined.
1098 DEBUG(dbgs() << " compute BB '" << BB->getName()
1099 << "' - overdefined (unknown cast).\n");
Philip Reames1baaef12016-12-06 03:01:08 +00001100 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesf105db42016-04-26 23:27:33 +00001101 return true;
1102 }
1103
Philip Reames38c87c22016-04-26 21:48:16 +00001104 // Figure out the range of the LHS. If that fails, we still apply the
1105 // transfer rule on the full set since we may be able to locally infer
1106 // interesting facts.
1107 if (!hasBlockValue(BBI->getOperand(0), BB))
Hans Wennborg45172ac2014-11-25 17:23:05 +00001108 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
Philip Reames38c87c22016-04-26 21:48:16 +00001109 // More work to do before applying this transfer rule.
Hans Wennborg45172ac2014-11-25 17:23:05 +00001110 return false;
Philip Reames38c87c22016-04-26 21:48:16 +00001111
1112 const unsigned OperandBitWidth =
Philip Reamese5030e82016-04-26 22:52:30 +00001113 DL.getTypeSizeInBits(BBI->getOperand(0)->getType());
Philip Reames38c87c22016-04-26 21:48:16 +00001114 ConstantRange LHSRange = ConstantRange(OperandBitWidth);
1115 if (hasBlockValue(BBI->getOperand(0), BB)) {
1116 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001117 intersectAssumeOrGuardBlockValueConstantRange(BBI->getOperand(0), LHSVal,
1118 BBI);
Philip Reames38c87c22016-04-26 21:48:16 +00001119 if (LHSVal.isConstantRange())
1120 LHSRange = LHSVal.getConstantRange();
Nick Lewycky55a700b2010-12-18 01:00:40 +00001121 }
1122
Philip Reames38c87c22016-04-26 21:48:16 +00001123 const unsigned ResultBitWidth =
1124 cast<IntegerType>(BBI->getType())->getBitWidth();
Philip Reames66715772016-04-25 18:30:31 +00001125
1126 // NOTE: We're currently limited by the set of operations that ConstantRange
1127 // can evaluate symbolically. Enhancing that set will allows us to analyze
1128 // more definitions.
Philip Reames4d00af12016-12-01 20:08:47 +00001129 auto CastOp = (Instruction::CastOps) BBI->getOpcode();
Philip Reames0e613f72016-12-06 02:36:58 +00001130 BBLV = LVILatticeVal::getRange(LHSRange.castOp(CastOp, ResultBitWidth));
Philip Reames66715772016-04-25 18:30:31 +00001131 return true;
1132}
1133
Philip Reames92e5e1b2016-09-12 21:46:58 +00001134bool LazyValueInfoImpl::solveBlockValueBinaryOp(LVILatticeVal &BBLV,
Philip Reames66715772016-04-25 18:30:31 +00001135 Instruction *BBI,
Philip Reamese5030e82016-04-26 22:52:30 +00001136 BasicBlock *BB) {
Philip Reames66715772016-04-25 18:30:31 +00001137
Philip Reames053c2a62016-04-26 23:10:35 +00001138 assert(BBI->getOperand(0)->getType()->isSized() &&
1139 "all operands to binary operators are sized");
Philip Reamesf105db42016-04-26 23:27:33 +00001140
1141 // Filter out operators we don't know how to reason about before attempting to
1142 // recurse on our operand(s). This can cut a long search short if we know
1143 // we're not going to be able to get any useful information anways.
1144 switch (BBI->getOpcode()) {
1145 case Instruction::Add:
1146 case Instruction::Sub:
1147 case Instruction::Mul:
1148 case Instruction::UDiv:
1149 case Instruction::Shl:
1150 case Instruction::LShr:
1151 case Instruction::And:
1152 case Instruction::Or:
1153 // continue into the code below
1154 break;
1155 default:
1156 // Unhandled instructions are overdefined.
1157 DEBUG(dbgs() << " compute BB '" << BB->getName()
1158 << "' - overdefined (unknown binary operator).\n");
Philip Reames1baaef12016-12-06 03:01:08 +00001159 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesf105db42016-04-26 23:27:33 +00001160 return true;
1161 };
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001162
Philip Reames053c2a62016-04-26 23:10:35 +00001163 // Figure out the range of the LHS. If that fails, use a conservative range,
1164 // but apply the transfer rule anyways. This lets us pick up facts from
1165 // expressions like "and i32 (call i32 @foo()), 32"
1166 if (!hasBlockValue(BBI->getOperand(0), BB))
1167 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
1168 // More work to do before applying this transfer rule.
1169 return false;
1170
1171 const unsigned OperandBitWidth =
1172 DL.getTypeSizeInBits(BBI->getOperand(0)->getType());
1173 ConstantRange LHSRange = ConstantRange(OperandBitWidth);
1174 if (hasBlockValue(BBI->getOperand(0), BB)) {
1175 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001176 intersectAssumeOrGuardBlockValueConstantRange(BBI->getOperand(0), LHSVal,
1177 BBI);
Philip Reames053c2a62016-04-26 23:10:35 +00001178 if (LHSVal.isConstantRange())
1179 LHSRange = LHSVal.getConstantRange();
Philip Reames66715772016-04-25 18:30:31 +00001180 }
Philip Reames66715772016-04-25 18:30:31 +00001181
1182 ConstantInt *RHS = cast<ConstantInt>(BBI->getOperand(1));
1183 ConstantRange RHSRange = ConstantRange(RHS->getValue());
1184
Owen Anderson80d19f02010-08-18 21:11:37 +00001185 // NOTE: We're currently limited by the set of operations that ConstantRange
1186 // can evaluate symbolically. Enhancing that set will allows us to analyze
1187 // more definitions.
Philip Reames4d00af12016-12-01 20:08:47 +00001188 auto BinOp = (Instruction::BinaryOps) BBI->getOpcode();
Philip Reames0e613f72016-12-06 02:36:58 +00001189 BBLV = LVILatticeVal::getRange(LHSRange.binaryOp(BinOp, RHSRange));
Nick Lewycky55a700b2010-12-18 01:00:40 +00001190 return true;
Chris Lattner741c94c2009-11-11 00:22:30 +00001191}
1192
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001193static LVILatticeVal getValueFromICmpCondition(Value *Val, ICmpInst *ICI,
1194 bool isTrueDest) {
Artur Pilipenko21472912016-08-08 14:08:37 +00001195 Value *LHS = ICI->getOperand(0);
1196 Value *RHS = ICI->getOperand(1);
1197 CmpInst::Predicate Predicate = ICI->getPredicate();
1198
1199 if (isa<Constant>(RHS)) {
1200 if (ICI->isEquality() && LHS == Val) {
Hal Finkel7e184492014-09-07 20:29:59 +00001201 // We know that V has the RHS constant if this is a true SETEQ or
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001202 // false SETNE.
Artur Pilipenko21472912016-08-08 14:08:37 +00001203 if (isTrueDest == (Predicate == ICmpInst::ICMP_EQ))
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001204 return LVILatticeVal::get(cast<Constant>(RHS));
Hal Finkel7e184492014-09-07 20:29:59 +00001205 else
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001206 return LVILatticeVal::getNot(cast<Constant>(RHS));
Hal Finkel7e184492014-09-07 20:29:59 +00001207 }
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001208 }
Hal Finkel7e184492014-09-07 20:29:59 +00001209
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001210 if (!Val->getType()->isIntegerTy())
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001211 return LVILatticeVal::getOverdefined();
Hal Finkel7e184492014-09-07 20:29:59 +00001212
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001213 // Use ConstantRange::makeAllowedICmpRegion in order to determine the possible
1214 // range of Val guaranteed by the condition. Recognize comparisons in the from
1215 // of:
1216 // icmp <pred> Val, ...
Artur Pilipenko63562582016-08-12 10:05:11 +00001217 // icmp <pred> (add Val, Offset), ...
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001218 // The latter is the range checking idiom that InstCombine produces. Subtract
1219 // the offset from the allowed range for RHS in this case.
Artur Pilipenkoeed618d2016-08-08 14:33:11 +00001220
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001221 // Val or (add Val, Offset) can be on either hand of the comparison
1222 if (LHS != Val && !match(LHS, m_Add(m_Specific(Val), m_ConstantInt()))) {
1223 std::swap(LHS, RHS);
1224 Predicate = CmpInst::getSwappedPredicate(Predicate);
1225 }
Hal Finkel7e184492014-09-07 20:29:59 +00001226
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001227 ConstantInt *Offset = nullptr;
Artur Pilipenko63562582016-08-12 10:05:11 +00001228 if (LHS != Val)
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001229 match(LHS, m_Add(m_Specific(Val), m_ConstantInt(Offset)));
Hal Finkel7e184492014-09-07 20:29:59 +00001230
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001231 if (LHS == Val || Offset) {
1232 // Calculate the range of values that are allowed by the comparison
1233 ConstantRange RHSRange(RHS->getType()->getIntegerBitWidth(),
1234 /*isFullSet=*/true);
1235 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS))
1236 RHSRange = ConstantRange(CI->getValue());
Artur Pilipenko6669f252016-08-12 10:14:11 +00001237 else if (Instruction *I = dyn_cast<Instruction>(RHS))
1238 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
1239 RHSRange = getConstantRangeFromMetadata(*Ranges);
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001240
1241 // If we're interested in the false dest, invert the condition
1242 CmpInst::Predicate Pred =
1243 isTrueDest ? Predicate : CmpInst::getInversePredicate(Predicate);
1244 ConstantRange TrueValues =
1245 ConstantRange::makeAllowedICmpRegion(Pred, RHSRange);
1246
1247 if (Offset) // Apply the offset from above.
1248 TrueValues = TrueValues.subtract(Offset->getValue());
1249
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001250 return LVILatticeVal::getRange(std::move(TrueValues));
Hal Finkel7e184492014-09-07 20:29:59 +00001251 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001252
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001253 return LVILatticeVal::getOverdefined();
Hal Finkel7e184492014-09-07 20:29:59 +00001254}
1255
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001256static LVILatticeVal
1257getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1258 DenseMap<Value*, LVILatticeVal> &Visited);
1259
1260static LVILatticeVal
1261getValueFromConditionImpl(Value *Val, Value *Cond, bool isTrueDest,
1262 DenseMap<Value*, LVILatticeVal> &Visited) {
1263 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
1264 return getValueFromICmpCondition(Val, ICI, isTrueDest);
1265
1266 // Handle conditions in the form of (cond1 && cond2), we know that on the
1267 // true dest path both of the conditions hold.
1268 if (!isTrueDest)
1269 return LVILatticeVal::getOverdefined();
1270
1271 BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond);
1272 if (!BO || BO->getOpcode() != BinaryOperator::And)
1273 return LVILatticeVal::getOverdefined();
1274
1275 auto RHS = getValueFromCondition(Val, BO->getOperand(0), isTrueDest, Visited);
1276 auto LHS = getValueFromCondition(Val, BO->getOperand(1), isTrueDest, Visited);
1277 return intersect(RHS, LHS);
1278}
1279
1280static LVILatticeVal
1281getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1282 DenseMap<Value*, LVILatticeVal> &Visited) {
1283 auto I = Visited.find(Cond);
1284 if (I != Visited.end())
1285 return I->second;
Artur Pilipenkob6230882016-08-12 15:08:15 +00001286
1287 auto Result = getValueFromConditionImpl(Val, Cond, isTrueDest, Visited);
1288 Visited[Cond] = Result;
1289 return Result;
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001290}
1291
1292LVILatticeVal getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest) {
1293 assert(Cond && "precondition");
1294 DenseMap<Value*, LVILatticeVal> Visited;
1295 return getValueFromCondition(Val, Cond, isTrueDest, Visited);
1296}
1297
Nuno Lopese6e04902012-06-28 01:16:18 +00001298/// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
Philip Reames13f73242016-02-01 23:21:11 +00001299/// Val is not constrained on the edge. Result is unspecified if return value
1300/// is false.
Nuno Lopese6e04902012-06-28 01:16:18 +00001301static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1302 BasicBlock *BBTo, LVILatticeVal &Result) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001303 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
Chris Lattner77358782009-11-15 20:02:12 +00001304 // know that v != 0.
Chris Lattner19019ea2009-11-11 22:48:44 +00001305 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
1306 // If this is a conditional branch and only one successor goes to BBTo, then
Sanjay Patel938e2792015-01-09 16:35:37 +00001307 // we may be able to infer something from the condition.
Chris Lattner19019ea2009-11-11 22:48:44 +00001308 if (BI->isConditional() &&
1309 BI->getSuccessor(0) != BI->getSuccessor(1)) {
1310 bool isTrueDest = BI->getSuccessor(0) == BBTo;
1311 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1312 "BBTo isn't a successor of BBFrom");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001313
Chris Lattner19019ea2009-11-11 22:48:44 +00001314 // If V is the condition of the branch itself, then we know exactly what
1315 // it is.
Nick Lewycky55a700b2010-12-18 01:00:40 +00001316 if (BI->getCondition() == Val) {
1317 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson185fe002010-08-10 20:03:09 +00001318 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky55a700b2010-12-18 01:00:40 +00001319 return true;
1320 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001321
Chris Lattner19019ea2009-11-11 22:48:44 +00001322 // If the condition of the branch is an equality comparison, we may be
1323 // able to infer the value.
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001324 Result = getValueFromCondition(Val, BI->getCondition(), isTrueDest);
1325 if (!Result.isOverdefined())
Artur Pilipenko2e19f592016-08-02 16:20:48 +00001326 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001327 }
1328 }
Chris Lattner77358782009-11-15 20:02:12 +00001329
1330 // If the edge was formed by a switch on the value, then we may know exactly
1331 // what it is.
1332 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Nuno Lopes8650fb82012-06-28 16:13:37 +00001333 if (SI->getCondition() != Val)
1334 return false;
1335
1336 bool DefaultCase = SI->getDefaultDest() == BBTo;
1337 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1338 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1339
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001340 for (SwitchInst::CaseIt i : SI->cases()) {
Nuno Lopes8650fb82012-06-28 16:13:37 +00001341 ConstantRange EdgeVal(i.getCaseValue()->getValue());
Manman Renf3fedb62012-09-05 23:45:58 +00001342 if (DefaultCase) {
1343 // It is possible that the default destination is the destination of
1344 // some cases. There is no need to perform difference for those cases.
1345 if (i.getCaseSuccessor() != BBTo)
1346 EdgesVals = EdgesVals.difference(EdgeVal);
1347 } else if (i.getCaseSuccessor() == BBTo)
Nuno Lopesac593802012-05-18 21:02:10 +00001348 EdgesVals = EdgesVals.unionWith(EdgeVal);
Chris Lattner77358782009-11-15 20:02:12 +00001349 }
Benjamin Kramer2337c1f2016-02-20 10:40:34 +00001350 Result = LVILatticeVal::getRange(std::move(EdgesVals));
Nuno Lopes8650fb82012-06-28 16:13:37 +00001351 return true;
Chris Lattner77358782009-11-15 20:02:12 +00001352 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001353 return false;
1354}
1355
Sanjay Patel938e2792015-01-09 16:35:37 +00001356/// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
1357/// the basic block if the edge does not constrain Val.
Philip Reames92e5e1b2016-09-12 21:46:58 +00001358bool LazyValueInfoImpl::getEdgeValue(Value *Val, BasicBlock *BBFrom,
Hal Finkel7e184492014-09-07 20:29:59 +00001359 BasicBlock *BBTo, LVILatticeVal &Result,
1360 Instruction *CxtI) {
Nuno Lopese6e04902012-06-28 01:16:18 +00001361 // If already a constant, there is nothing to compute.
1362 if (Constant *VC = dyn_cast<Constant>(Val)) {
1363 Result = LVILatticeVal::get(VC);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001364 return true;
1365 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001366
Philip Reames44456b82016-02-02 03:15:40 +00001367 LVILatticeVal LocalResult;
1368 if (!getEdgeValueLocal(Val, BBFrom, BBTo, LocalResult))
1369 // If we couldn't constrain the value on the edge, LocalResult doesn't
1370 // provide any information.
Philip Reames1baaef12016-12-06 03:01:08 +00001371 LocalResult = LVILatticeVal::getOverdefined();
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001372
Philip Reames44456b82016-02-02 03:15:40 +00001373 if (hasSingleValue(LocalResult)) {
1374 // Can't get any more precise here
1375 Result = LocalResult;
Nuno Lopese6e04902012-06-28 01:16:18 +00001376 return true;
1377 }
1378
1379 if (!hasBlockValue(Val, BBFrom)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +00001380 if (pushBlockValue(std::make_pair(BBFrom, Val)))
1381 return false;
Philip Reames44456b82016-02-02 03:15:40 +00001382 // No new information.
1383 Result = LocalResult;
Hans Wennborg45172ac2014-11-25 17:23:05 +00001384 return true;
Nuno Lopese6e04902012-06-28 01:16:18 +00001385 }
1386
Philip Reames44456b82016-02-02 03:15:40 +00001387 // Try to intersect ranges of the BB and the constraint on the edge.
1388 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001389 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock,
1390 BBFrom->getTerminator());
Hal Finkel2400c962014-10-16 00:40:05 +00001391 // We can use the context instruction (generically the ultimate instruction
1392 // the calling pass is trying to simplify) here, even though the result of
1393 // this function is generally cached when called from the solve* functions
1394 // (and that cached result might be used with queries using a different
1395 // context instruction), because when this function is called from the solve*
1396 // functions, the context instruction is not provided. When called from
Philip Reames92e5e1b2016-09-12 21:46:58 +00001397 // LazyValueInfoImpl::getValueOnEdge, the context instruction is provided,
Hal Finkel2400c962014-10-16 00:40:05 +00001398 // but then the result is not cached.
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001399 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CxtI);
Philip Reames44456b82016-02-02 03:15:40 +00001400
1401 Result = intersect(LocalResult, InBlock);
Nuno Lopese6e04902012-06-28 01:16:18 +00001402 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001403}
1404
Philip Reames92e5e1b2016-09-12 21:46:58 +00001405LVILatticeVal LazyValueInfoImpl::getValueInBlock(Value *V, BasicBlock *BB,
Hal Finkel7e184492014-09-07 20:29:59 +00001406 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001407 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001408 << BB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001409
Hans Wennborg45172ac2014-11-25 17:23:05 +00001410 assert(BlockValueStack.empty() && BlockValueSet.empty());
Philip Reamesbb781b42016-02-10 21:46:32 +00001411 if (!hasBlockValue(V, BB)) {
NAKAMURA Takumibd072a92016-07-25 00:59:46 +00001412 pushBlockValue(std::make_pair(BB, V));
Philip Reamesbb781b42016-02-10 21:46:32 +00001413 solve();
1414 }
Owen Andersonc7ed4dc2010-12-09 06:14:58 +00001415 LVILatticeVal Result = getBlockValue(V, BB);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001416 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001417
1418 DEBUG(dbgs() << " Result = " << Result << "\n");
1419 return Result;
1420}
1421
Philip Reames92e5e1b2016-09-12 21:46:58 +00001422LVILatticeVal LazyValueInfoImpl::getValueAt(Value *V, Instruction *CxtI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001423 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1424 << CxtI->getName() << "'\n");
1425
Philip Reamesbb781b42016-02-10 21:46:32 +00001426 if (auto *C = dyn_cast<Constant>(V))
1427 return LVILatticeVal::get(C);
1428
Philip Reamesd1f829d2016-02-02 21:57:37 +00001429 LVILatticeVal Result = LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +00001430 if (auto *I = dyn_cast<Instruction>(V))
1431 Result = getFromRangeMetadata(I);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001432 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
Philip Reames2c275cc2016-02-02 00:45:30 +00001433
David Greene37e98092009-12-23 20:43:58 +00001434 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001435 return Result;
1436}
Chris Lattner19019ea2009-11-11 22:48:44 +00001437
Philip Reames92e5e1b2016-09-12 21:46:58 +00001438LVILatticeVal LazyValueInfoImpl::
Hal Finkel7e184492014-09-07 20:29:59 +00001439getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1440 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001441 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001442 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001443
Nick Lewycky55a700b2010-12-18 01:00:40 +00001444 LVILatticeVal Result;
Hal Finkel7e184492014-09-07 20:29:59 +00001445 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +00001446 solve();
Hal Finkel7e184492014-09-07 20:29:59 +00001447 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001448 (void)WasFastQuery;
1449 assert(WasFastQuery && "More work to do after problem solved?");
1450 }
1451
David Greene37e98092009-12-23 20:43:58 +00001452 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001453 return Result;
1454}
1455
Philip Reames92e5e1b2016-09-12 21:46:58 +00001456void LazyValueInfoImpl::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Philip Reames9db79482016-09-12 22:38:44 +00001457 BasicBlock *NewSucc) {
1458 TheCache.threadEdgeImpl(OldSucc, NewSucc);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001459}
1460
Chris Lattneraf025d32009-11-15 19:59:49 +00001461//===----------------------------------------------------------------------===//
1462// LazyValueInfo Impl
1463//===----------------------------------------------------------------------===//
1464
Philip Reames92e5e1b2016-09-12 21:46:58 +00001465/// This lazily constructs the LazyValueInfoImpl.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001466static LazyValueInfoImpl &getImpl(void *&PImpl, AssumptionCache *AC,
1467 const DataLayout *DL,
Philip Reames92e5e1b2016-09-12 21:46:58 +00001468 DominatorTree *DT = nullptr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001469 if (!PImpl) {
1470 assert(DL && "getCache() called with a null DataLayout");
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001471 PImpl = new LazyValueInfoImpl(AC, *DL, DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001472 }
Philip Reames92e5e1b2016-09-12 21:46:58 +00001473 return *static_cast<LazyValueInfoImpl*>(PImpl);
Chris Lattneraf025d32009-11-15 19:59:49 +00001474}
1475
Sean Silva687019f2016-06-13 22:01:25 +00001476bool LazyValueInfoWrapperPass::runOnFunction(Function &F) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001477 Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001478 const DataLayout &DL = F.getParent()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001479
1480 DominatorTreeWrapperPass *DTWP =
1481 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Sean Silva687019f2016-06-13 22:01:25 +00001482 Info.DT = DTWP ? &DTWP->getDomTree() : nullptr;
1483 Info.TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chad Rosier43a33062011-12-02 01:26:24 +00001484
Sean Silva687019f2016-06-13 22:01:25 +00001485 if (Info.PImpl)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001486 getImpl(Info.PImpl, Info.AC, &DL, Info.DT).clear();
Hal Finkel7e184492014-09-07 20:29:59 +00001487
Owen Anderson208636f2010-08-18 18:39:01 +00001488 // Fully lazy.
1489 return false;
1490}
1491
Sean Silva687019f2016-06-13 22:01:25 +00001492void LazyValueInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosier43a33062011-12-02 01:26:24 +00001493 AU.setPreservesAll();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001494 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001495 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chad Rosier43a33062011-12-02 01:26:24 +00001496}
1497
Sean Silva687019f2016-06-13 22:01:25 +00001498LazyValueInfo &LazyValueInfoWrapperPass::getLVI() { return Info; }
1499
1500LazyValueInfo::~LazyValueInfo() { releaseMemory(); }
1501
Chris Lattneraf025d32009-11-15 19:59:49 +00001502void LazyValueInfo::releaseMemory() {
1503 // If the cache was allocated, free it.
1504 if (PImpl) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001505 delete &getImpl(PImpl, AC, nullptr);
Craig Topper9f008862014-04-15 04:59:12 +00001506 PImpl = nullptr;
Chris Lattneraf025d32009-11-15 19:59:49 +00001507 }
1508}
1509
Sean Silva687019f2016-06-13 22:01:25 +00001510void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
1511
1512LazyValueInfo LazyValueAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001513 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
Sean Silva687019f2016-06-13 22:01:25 +00001514 auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
1515 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
1516
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001517 return LazyValueInfo(&AC, &TLI, DT);
Sean Silva687019f2016-06-13 22:01:25 +00001518}
1519
Wei Mif160e342016-09-15 06:28:34 +00001520/// Returns true if we can statically tell that this value will never be a
1521/// "useful" constant. In practice, this means we've got something like an
1522/// alloca or a malloc call for which a comparison against a constant can
1523/// only be guarding dead code. Note that we are potentially giving up some
1524/// precision in dead code (a constant result) in favour of avoiding a
1525/// expensive search for a easily answered common query.
1526static bool isKnownNonConstant(Value *V) {
1527 V = V->stripPointerCasts();
1528 // The return val of alloc cannot be a Constant.
1529 if (isa<AllocaInst>(V))
1530 return true;
1531 return false;
1532}
1533
Hal Finkel7e184492014-09-07 20:29:59 +00001534Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1535 Instruction *CxtI) {
Wei Mif160e342016-09-15 06:28:34 +00001536 // Bail out early if V is known not to be a Constant.
1537 if (isKnownNonConstant(V))
1538 return nullptr;
1539
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001540 const DataLayout &DL = BB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001541 LVILatticeVal Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001542 getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001543
Chris Lattner19019ea2009-11-11 22:48:44 +00001544 if (Result.isConstant())
1545 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001546 if (Result.isConstantRange()) {
Owen Anderson38f6b7f2010-08-27 23:29:38 +00001547 ConstantRange CR = Result.getConstantRange();
1548 if (const APInt *SingleVal = CR.getSingleElement())
1549 return ConstantInt::get(V->getContext(), *SingleVal);
1550 }
Craig Topper9f008862014-04-15 04:59:12 +00001551 return nullptr;
Chris Lattner19019ea2009-11-11 22:48:44 +00001552}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001553
John Regehre1c481d2016-05-02 19:58:00 +00001554ConstantRange LazyValueInfo::getConstantRange(Value *V, BasicBlock *BB,
NAKAMURA Takumi940cd932016-07-04 01:26:21 +00001555 Instruction *CxtI) {
John Regehre1c481d2016-05-02 19:58:00 +00001556 assert(V->getType()->isIntegerTy());
1557 unsigned Width = V->getType()->getIntegerBitWidth();
1558 const DataLayout &DL = BB->getModule()->getDataLayout();
1559 LVILatticeVal Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001560 getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
John Regehre1c481d2016-05-02 19:58:00 +00001561 if (Result.isUndefined())
1562 return ConstantRange(Width, /*isFullSet=*/false);
1563 if (Result.isConstantRange())
1564 return Result.getConstantRange();
Artur Pilipenkoa4b6a702016-08-10 12:54:54 +00001565 // We represent ConstantInt constants as constant ranges but other kinds
1566 // of integer constants, i.e. ConstantExpr will be tagged as constants
1567 assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&
1568 "ConstantInt value must be represented as constantrange");
Davide Italianobd543d02016-05-25 22:29:34 +00001569 return ConstantRange(Width, /*isFullSet=*/true);
John Regehre1c481d2016-05-02 19:58:00 +00001570}
1571
Sanjay Patel2a385e22015-01-09 16:47:20 +00001572/// Determine whether the specified value is known to be a
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001573/// constant on the specified edge. Return null if not.
Chris Lattnerd5e25432009-11-12 01:29:10 +00001574Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
Hal Finkel7e184492014-09-07 20:29:59 +00001575 BasicBlock *ToBB,
1576 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001577 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001578 LVILatticeVal Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001579 getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001580
Chris Lattnerd5e25432009-11-12 01:29:10 +00001581 if (Result.isConstant())
1582 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001583 if (Result.isConstantRange()) {
Owen Anderson185fe002010-08-10 20:03:09 +00001584 ConstantRange CR = Result.getConstantRange();
1585 if (const APInt *SingleVal = CR.getSingleElement())
1586 return ConstantInt::get(V->getContext(), *SingleVal);
1587 }
Craig Topper9f008862014-04-15 04:59:12 +00001588 return nullptr;
Chris Lattnerd5e25432009-11-12 01:29:10 +00001589}
1590
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001591static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C,
1592 LVILatticeVal &Result,
1593 const DataLayout &DL,
1594 TargetLibraryInfo *TLI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001595
Chris Lattner565ee2f2009-11-12 04:36:58 +00001596 // If we know the value is a constant, evaluate the conditional.
Craig Topper9f008862014-04-15 04:59:12 +00001597 Constant *Res = nullptr;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001598 if (Result.isConstant()) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001599 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001600 TLI);
Nick Lewycky11678bd2010-12-15 18:57:18 +00001601 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Hal Finkel7e184492014-09-07 20:29:59 +00001602 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1603 return LazyValueInfo::Unknown;
Chris Lattneraf025d32009-11-15 19:59:49 +00001604 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001605
Owen Anderson185fe002010-08-10 20:03:09 +00001606 if (Result.isConstantRange()) {
Owen Andersonc62f7042010-08-24 07:55:44 +00001607 ConstantInt *CI = dyn_cast<ConstantInt>(C);
Hal Finkel7e184492014-09-07 20:29:59 +00001608 if (!CI) return LazyValueInfo::Unknown;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001609
Owen Anderson185fe002010-08-10 20:03:09 +00001610 ConstantRange CR = Result.getConstantRange();
1611 if (Pred == ICmpInst::ICMP_EQ) {
1612 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001613 return LazyValueInfo::False;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001614
Owen Anderson185fe002010-08-10 20:03:09 +00001615 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001616 return LazyValueInfo::True;
Owen Anderson185fe002010-08-10 20:03:09 +00001617 } else if (Pred == ICmpInst::ICMP_NE) {
1618 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001619 return LazyValueInfo::True;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001620
Owen Anderson185fe002010-08-10 20:03:09 +00001621 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001622 return LazyValueInfo::False;
Owen Anderson185fe002010-08-10 20:03:09 +00001623 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001624
Owen Anderson185fe002010-08-10 20:03:09 +00001625 // Handle more complex predicates.
Sanjoy Das1f7b8132016-10-02 00:09:57 +00001626 ConstantRange TrueValues = ConstantRange::makeExactICmpRegion(
1627 (ICmpInst::Predicate)Pred, CI->getValue());
Nick Lewycky11678bd2010-12-15 18:57:18 +00001628 if (TrueValues.contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001629 return LazyValueInfo::True;
Nick Lewycky11678bd2010-12-15 18:57:18 +00001630 if (TrueValues.inverse().contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001631 return LazyValueInfo::False;
1632 return LazyValueInfo::Unknown;
Owen Anderson185fe002010-08-10 20:03:09 +00001633 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001634
Chris Lattneraf025d32009-11-15 19:59:49 +00001635 if (Result.isNotConstant()) {
Chris Lattner565ee2f2009-11-12 04:36:58 +00001636 // If this is an equality comparison, we can try to fold it knowing that
1637 // "V != C1".
1638 if (Pred == ICmpInst::ICMP_EQ) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001639 // !C1 == C -> false iff C1 == C.
Chris Lattner565ee2f2009-11-12 04:36:58 +00001640 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001641 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001642 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001643 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001644 return LazyValueInfo::False;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001645 } else if (Pred == ICmpInst::ICMP_NE) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001646 // !C1 != C -> true iff C1 == C.
Chris Lattnerb0c0a0d2009-11-15 20:01:24 +00001647 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001648 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001649 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001650 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001651 return LazyValueInfo::True;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001652 }
Hal Finkel7e184492014-09-07 20:29:59 +00001653 return LazyValueInfo::Unknown;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001654 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001655
Hal Finkel7e184492014-09-07 20:29:59 +00001656 return LazyValueInfo::Unknown;
1657}
1658
Sanjay Patel2a385e22015-01-09 16:47:20 +00001659/// Determine whether the specified value comparison with a constant is known to
1660/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
Hal Finkel7e184492014-09-07 20:29:59 +00001661LazyValueInfo::Tristate
1662LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1663 BasicBlock *FromBB, BasicBlock *ToBB,
1664 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001665 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001666 LVILatticeVal Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001667 getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001668
1669 return getPredicateResult(Pred, C, Result, DL, TLI);
1670}
1671
1672LazyValueInfo::Tristate
1673LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1674 Instruction *CxtI) {
Wei Mif160e342016-09-15 06:28:34 +00001675 // Is or is not NonNull are common predicates being queried. If
1676 // isKnownNonNull can tell us the result of the predicate, we can
1677 // return it quickly. But this is only a fastpath, and falling
1678 // through would still be correct.
1679 if (V->getType()->isPointerTy() && C->isNullValue() &&
1680 isKnownNonNull(V->stripPointerCasts())) {
1681 if (Pred == ICmpInst::ICMP_EQ)
1682 return LazyValueInfo::False;
1683 else if (Pred == ICmpInst::ICMP_NE)
1684 return LazyValueInfo::True;
1685 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001686 const DataLayout &DL = CxtI->getModule()->getDataLayout();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001687 LVILatticeVal Result = getImpl(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
Philip Reames66ab0f02015-06-16 00:49:59 +00001688 Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1689 if (Ret != Unknown)
1690 return Ret;
Hal Finkel7e184492014-09-07 20:29:59 +00001691
Philip Reamesaeefae02015-11-04 01:47:04 +00001692 // Note: The following bit of code is somewhat distinct from the rest of LVI;
1693 // LVI as a whole tries to compute a lattice value which is conservatively
1694 // correct at a given location. In this case, we have a predicate which we
1695 // weren't able to prove about the merged result, and we're pushing that
1696 // predicate back along each incoming edge to see if we can prove it
1697 // separately for each input. As a motivating example, consider:
1698 // bb1:
1699 // %v1 = ... ; constantrange<1, 5>
1700 // br label %merge
1701 // bb2:
1702 // %v2 = ... ; constantrange<10, 20>
1703 // br label %merge
1704 // merge:
1705 // %phi = phi [%v1, %v2] ; constantrange<1,20>
1706 // %pred = icmp eq i32 %phi, 8
1707 // We can't tell from the lattice value for '%phi' that '%pred' is false
1708 // along each path, but by checking the predicate over each input separately,
1709 // we can.
1710 // We limit the search to one step backwards from the current BB and value.
1711 // We could consider extending this to search further backwards through the
1712 // CFG and/or value graph, but there are non-obvious compile time vs quality
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001713 // tradeoffs.
Philip Reames66ab0f02015-06-16 00:49:59 +00001714 if (CxtI) {
Philip Reamesbb11d622015-08-31 18:31:48 +00001715 BasicBlock *BB = CxtI->getParent();
1716
1717 // Function entry or an unreachable block. Bail to avoid confusing
1718 // analysis below.
1719 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1720 if (PI == PE)
1721 return Unknown;
1722
1723 // If V is a PHI node in the same block as the context, we need to ask
1724 // questions about the predicate as applied to the incoming value along
1725 // each edge. This is useful for eliminating cases where the predicate is
1726 // known along all incoming edges.
1727 if (auto *PHI = dyn_cast<PHINode>(V))
1728 if (PHI->getParent() == BB) {
1729 Tristate Baseline = Unknown;
1730 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1731 Value *Incoming = PHI->getIncomingValue(i);
1732 BasicBlock *PredBB = PHI->getIncomingBlock(i);
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001733 // Note that PredBB may be BB itself.
Philip Reamesbb11d622015-08-31 18:31:48 +00001734 Tristate Result = getPredicateOnEdge(Pred, Incoming, C, PredBB, BB,
1735 CxtI);
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001736
Philip Reamesbb11d622015-08-31 18:31:48 +00001737 // Keep going as long as we've seen a consistent known result for
1738 // all inputs.
1739 Baseline = (i == 0) ? Result /* First iteration */
1740 : (Baseline == Result ? Baseline : Unknown); /* All others */
1741 if (Baseline == Unknown)
1742 break;
1743 }
1744 if (Baseline != Unknown)
1745 return Baseline;
NAKAMURA Takumibd072a92016-07-25 00:59:46 +00001746 }
Philip Reamesbb11d622015-08-31 18:31:48 +00001747
Philip Reames66ab0f02015-06-16 00:49:59 +00001748 // For a comparison where the V is outside this block, it's possible
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001749 // that we've branched on it before. Look to see if the value is known
Philip Reames66ab0f02015-06-16 00:49:59 +00001750 // on all incoming edges.
Philip Reamesbb11d622015-08-31 18:31:48 +00001751 if (!isa<Instruction>(V) ||
1752 cast<Instruction>(V)->getParent() != BB) {
Philip Reames66ab0f02015-06-16 00:49:59 +00001753 // For predecessor edge, determine if the comparison is true or false
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001754 // on that edge. If they're all true or all false, we can conclude
Philip Reames66ab0f02015-06-16 00:49:59 +00001755 // the value of the comparison in this block.
1756 Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1757 if (Baseline != Unknown) {
1758 // Check that all remaining incoming values match the first one.
1759 while (++PI != PE) {
1760 Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1761 if (Ret != Baseline) break;
1762 }
1763 // If we terminated early, then one of the values didn't match.
1764 if (PI == PE) {
1765 return Baseline;
1766 }
1767 }
1768 }
1769 }
1770 return Unknown;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001771}
1772
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001773void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky11678bd2010-12-15 18:57:18 +00001774 BasicBlock *NewSucc) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001775 if (PImpl) {
1776 const DataLayout &DL = PredBB->getModule()->getDataLayout();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001777 getImpl(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001778 }
Owen Anderson208636f2010-08-18 18:39:01 +00001779}
1780
1781void LazyValueInfo::eraseBlock(BasicBlock *BB) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001782 if (PImpl) {
1783 const DataLayout &DL = BB->getModule()->getDataLayout();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001784 getImpl(PImpl, AC, &DL, DT).eraseBlock(BB);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001785 }
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001786}