blob: 6a9ae6440aceca2b42328835820201c349aea34b [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"
Anna Thomase27b39a2017-03-22 19:27:12 +000022#include "llvm/IR/AssemblyAnnotationWriter.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000023#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000024#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Constants.h"
26#include "llvm/IR/DataLayout.h"
Hal Finkel7e184492014-09-07 20:29:59 +000027#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Instructions.h"
29#include "llvm/IR/IntrinsicInst.h"
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +000030#include "llvm/IR/Intrinsics.h"
Philip Reameseb3e9da2015-10-29 03:57:17 +000031#include "llvm/IR/LLVMContext.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000032#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000033#include "llvm/IR/ValueHandle.h"
Chris Lattnerb584d1e2009-11-12 01:22:16 +000034#include "llvm/Support/Debug.h"
Anna Thomase27b39a2017-03-22 19:27:12 +000035#include "llvm/Support/FormattedStream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Support/raw_ostream.h"
Bill Wendling4ec081a2012-01-11 23:43:34 +000037#include <map>
Nick Lewycky55a700b2010-12-18 01:00:40 +000038#include <stack>
Chris Lattner741c94c2009-11-11 00:22:30 +000039using namespace llvm;
Benjamin Kramerd9d80b12012-03-02 15:34:43 +000040using namespace PatternMatch;
Chris Lattner741c94c2009-11-11 00:22:30 +000041
Chandler Carruthf1221bd2014-04-22 02:48:03 +000042#define DEBUG_TYPE "lazy-value-info"
43
Daniel Berlin9c92a462017-02-08 15:22:52 +000044// This is the number of worklist items we will process to try to discover an
45// answer for a given value.
46static const unsigned MaxProcessedPerValue = 500;
47
Sean Silva687019f2016-06-13 22:01:25 +000048char LazyValueInfoWrapperPass::ID = 0;
49INITIALIZE_PASS_BEGIN(LazyValueInfoWrapperPass, "lazy-value-info",
Chad Rosier43a33062011-12-02 01:26:24 +000050 "Lazy Value Information Analysis", false, true)
Daniel Jasperaec2fa32016-12-19 08:22:17 +000051INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthb98f63d2015-01-15 10:41:28 +000052INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Sean Silva687019f2016-06-13 22:01:25 +000053INITIALIZE_PASS_END(LazyValueInfoWrapperPass, "lazy-value-info",
Owen Andersondf7a4f22010-10-07 22:25:06 +000054 "Lazy Value Information Analysis", false, true)
Chris Lattner741c94c2009-11-11 00:22:30 +000055
56namespace llvm {
Sean Silva687019f2016-06-13 22:01:25 +000057 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfoWrapperPass(); }
Chris Lattner741c94c2009-11-11 00:22:30 +000058}
59
Chandler Carruthdab4eae2016-11-23 17:53:26 +000060AnalysisKey LazyValueAnalysis::Key;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000061
62//===----------------------------------------------------------------------===//
63// LVILatticeVal
64//===----------------------------------------------------------------------===//
65
Sanjay Patel2a385e22015-01-09 16:47:20 +000066/// This is the information tracked by LazyValueInfo for each value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000067///
68/// FIXME: This is basically just for bringup, this can be made a lot more rich
69/// in the future.
70///
71namespace {
72class LVILatticeVal {
73 enum LatticeValueTy {
Philip Reames3bb28322016-04-25 18:48:43 +000074 /// This Value has no known value yet. As a result, this implies the
75 /// producing instruction is dead. Caution: We use this as the starting
76 /// state in our local meet rules. In this usage, it's taken to mean
NAKAMURA Takumif2529512016-07-04 01:26:27 +000077 /// "nothing known yet".
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000078 undefined,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000079
Philip Reames02bb6a62016-12-07 04:48:50 +000080 /// This Value has a specific constant value. (For constant integers,
81 /// constantrange is used instead. Integer typed constantexprs can appear
82 /// as constant.)
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000083 constant,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000084
Philip Reames02bb6a62016-12-07 04:48:50 +000085 /// This Value is known to not have the specified value. (For constant
86 /// integers, constantrange is used instead. As above, integer typed
87 /// constantexprs can appear here.)
Chris Lattner565ee2f2009-11-12 04:36:58 +000088 notconstant,
Chad Rosier43a33062011-12-02 01:26:24 +000089
Philip Reames3bb28322016-04-25 18:48:43 +000090 /// The Value falls within this range. (Used only for integer typed values.)
Owen Anderson0f306a42010-08-05 22:59:19 +000091 constantrange,
Chad Rosier43a33062011-12-02 01:26:24 +000092
Philip Reames3bb28322016-04-25 18:48:43 +000093 /// We can not precisely model the dynamic values this value might take.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000094 overdefined
95 };
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000096
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000097 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattner565ee2f2009-11-12 04:36:58 +000098 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersonc3a14132010-08-05 22:10:46 +000099 LatticeValueTy Tag;
100 Constant *Val;
Owen Anderson0f306a42010-08-05 22:59:19 +0000101 ConstantRange Range;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000102
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000103public:
Craig Topper9f008862014-04-15 04:59:12 +0000104 LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000105
Chris Lattner19019ea2009-11-11 22:48:44 +0000106 static LVILatticeVal get(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.markConstant(C);
Chris Lattner19019ea2009-11-11 22:48:44 +0000110 return Res;
111 }
Chris Lattner565ee2f2009-11-12 04:36:58 +0000112 static LVILatticeVal getNot(Constant *C) {
113 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000114 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +0000115 Res.markNotConstant(C);
Chris Lattner565ee2f2009-11-12 04:36:58 +0000116 return Res;
117 }
Owen Anderson5f1dd092010-08-10 23:20:01 +0000118 static LVILatticeVal getRange(ConstantRange CR) {
119 LVILatticeVal Res;
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000120 Res.markConstantRange(std::move(CR));
Owen Anderson5f1dd092010-08-10 23:20:01 +0000121 return Res;
122 }
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000123 static LVILatticeVal getOverdefined() {
124 LVILatticeVal Res;
125 Res.markOverdefined();
126 return Res;
127 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +0000128
Owen Anderson0f306a42010-08-05 22:59:19 +0000129 bool isUndefined() const { return Tag == undefined; }
130 bool isConstant() const { return Tag == constant; }
131 bool isNotConstant() const { return Tag == notconstant; }
132 bool isConstantRange() const { return Tag == constantrange; }
133 bool isOverdefined() const { return Tag == overdefined; }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000134
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000135 Constant *getConstant() const {
136 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000137 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000138 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000139
Chris Lattner565ee2f2009-11-12 04:36:58 +0000140 Constant *getNotConstant() const {
141 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000142 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000143 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000144
Craig Topper2b195fd2017-05-06 03:35:15 +0000145 const ConstantRange &getConstantRange() const {
Owen Anderson0f306a42010-08-05 22:59:19 +0000146 assert(isConstantRange() &&
147 "Cannot get the constant-range of a non-constant-range!");
148 return Range;
149 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000150
Philip Reames1baaef12016-12-06 03:01:08 +0000151private:
Philip Reames71a49672016-12-07 01:03:56 +0000152 void markOverdefined() {
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000153 if (isOverdefined())
Philip Reames71a49672016-12-07 01:03:56 +0000154 return;
Owen Andersonc3a14132010-08-05 22:10:46 +0000155 Tag = overdefined;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000156 }
157
Philip Reames71a49672016-12-07 01:03:56 +0000158 void markConstant(Constant *V) {
Nick Lewycky11678bd2010-12-15 18:57:18 +0000159 assert(V && "Marking constant with NULL");
Philip Reames71a49672016-12-07 01:03:56 +0000160 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
161 markConstantRange(ConstantRange(CI->getValue()));
162 return;
163 }
Nick Lewycky11678bd2010-12-15 18:57:18 +0000164 if (isa<UndefValue>(V))
Philip Reames71a49672016-12-07 01:03:56 +0000165 return;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000166
167 assert((!isConstant() || getConstant() == V) &&
168 "Marking constant with different value");
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000169 assert(isUndefined());
Owen Andersonc3a14132010-08-05 22:10:46 +0000170 Tag = constant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000171 Val = V;
Chris Lattner19019ea2009-11-11 22:48:44 +0000172 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000173
Philip Reames71a49672016-12-07 01:03:56 +0000174 void markNotConstant(Constant *V) {
Chris Lattner565ee2f2009-11-12 04:36:58 +0000175 assert(V && "Marking constant with NULL");
Philip Reames71a49672016-12-07 01:03:56 +0000176 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
177 markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
178 return;
179 }
Nick Lewycky11678bd2010-12-15 18:57:18 +0000180 if (isa<UndefValue>(V))
Philip Reames71a49672016-12-07 01:03:56 +0000181 return;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000182
183 assert((!isConstant() || getConstant() != V) &&
184 "Marking constant !constant with same value");
185 assert((!isNotConstant() || getNotConstant() == V) &&
186 "Marking !constant with different value");
187 assert(isUndefined() || isConstant());
188 Tag = notconstant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000189 Val = V;
Chris Lattner565ee2f2009-11-12 04:36:58 +0000190 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000191
Philip Reames71a49672016-12-07 01:03:56 +0000192 void markConstantRange(ConstantRange NewR) {
Owen Anderson0f306a42010-08-05 22:59:19 +0000193 if (isConstantRange()) {
194 if (NewR.isEmptySet())
Philip Reames71a49672016-12-07 01:03:56 +0000195 markOverdefined();
196 else {
Philip Reames71a49672016-12-07 01:03:56 +0000197 Range = std::move(NewR);
198 }
199 return;
Owen Anderson0f306a42010-08-05 22:59:19 +0000200 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000201
Owen Anderson0f306a42010-08-05 22:59:19 +0000202 assert(isUndefined());
203 if (NewR.isEmptySet())
Philip Reames71a49672016-12-07 01:03:56 +0000204 markOverdefined();
205 else {
206 Tag = constantrange;
207 Range = std::move(NewR);
208 }
Owen Anderson0f306a42010-08-05 22:59:19 +0000209 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000210
Philip Reamesb2949622016-12-06 02:54:16 +0000211public:
212
Sanjay Patel2a385e22015-01-09 16:47:20 +0000213 /// Merge the specified lattice value into this one, updating this
Chris Lattner19019ea2009-11-11 22:48:44 +0000214 /// one and returning true if anything changed.
Philip Reamesb47a7192016-12-07 00:54:21 +0000215 void mergeIn(const LVILatticeVal &RHS, const DataLayout &DL) {
216 if (RHS.isUndefined() || isOverdefined())
217 return;
218 if (RHS.isOverdefined()) {
219 markOverdefined();
220 return;
221 }
Chris Lattner19019ea2009-11-11 22:48:44 +0000222
Nick Lewycky11678bd2010-12-15 18:57:18 +0000223 if (isUndefined()) {
Philip Reamesb47a7192016-12-07 00:54:21 +0000224 *this = RHS;
225 return;
Chris Lattner22db4b52009-11-12 04:57:13 +0000226 }
227
Nick Lewycky11678bd2010-12-15 18:57:18 +0000228 if (isConstant()) {
Philip Reamesb47a7192016-12-07 00:54:21 +0000229 if (RHS.isConstant() && Val == RHS.Val)
230 return;
231 markOverdefined();
232 return;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000233 }
234
235 if (isNotConstant()) {
Philip Reamesb47a7192016-12-07 00:54:21 +0000236 if (RHS.isNotConstant() && Val == RHS.Val)
237 return;
238 markOverdefined();
239 return;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000240 }
241
242 assert(isConstantRange() && "New LVILattice type?");
Philip Reames02bb6a62016-12-07 04:48:50 +0000243 if (!RHS.isConstantRange()) {
244 // We can get here if we've encountered a constantexpr of integer type
245 // and merge it with a constantrange.
246 markOverdefined();
247 return;
248 }
Nick Lewycky11678bd2010-12-15 18:57:18 +0000249 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
250 if (NewR.isFullSet())
Philip Reamesb47a7192016-12-07 00:54:21 +0000251 markOverdefined();
252 else
Craig Topper2b195fd2017-05-06 03:35:15 +0000253 markConstantRange(std::move(NewR));
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000254 }
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000255};
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000256
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000257} // end anonymous namespace.
258
Chris Lattner19019ea2009-11-11 22:48:44 +0000259namespace llvm {
Chandler Carruth2b1ba482011-04-18 18:49:44 +0000260raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
261 LLVM_ATTRIBUTE_USED;
Chris Lattner19019ea2009-11-11 22:48:44 +0000262raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
263 if (Val.isUndefined())
264 return OS << "undefined";
265 if (Val.isOverdefined())
266 return OS << "overdefined";
Chris Lattner565ee2f2009-11-12 04:36:58 +0000267
268 if (Val.isNotConstant())
269 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Davide Italianobd543d02016-05-25 22:29:34 +0000270 if (Val.isConstantRange())
Owen Anderson8afac042010-08-09 20:50:46 +0000271 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
272 << Val.getConstantRange().getUpper() << '>';
Chris Lattner19019ea2009-11-11 22:48:44 +0000273 return OS << "constant<" << *Val.getConstant() << '>';
274}
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000275}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000276
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000277/// Returns true if this lattice value represents at most one possible value.
278/// This is as precise as any lattice value can get while still representing
279/// reachable code.
Benjamin Kramerc321e532016-06-08 19:09:22 +0000280static bool hasSingleValue(const LVILatticeVal &Val) {
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000281 if (Val.isConstantRange() &&
282 Val.getConstantRange().isSingleElement())
283 // Integer constants are single element ranges
284 return true;
285 if (Val.isConstant())
286 // Non integer constants
287 return true;
288 return false;
289}
290
291/// Combine two sets of facts about the same value into a single set of
292/// facts. Note that this method is not suitable for merging facts along
293/// different paths in a CFG; that's what the mergeIn function is for. This
294/// is for merging facts gathered about the same value at the same location
295/// through two independent means.
296/// Notes:
297/// * This method does not promise to return the most precise possible lattice
298/// value implied by A and B. It is allowed to return any lattice element
299/// which is at least as strong as *either* A or B (unless our facts
NAKAMURA Takumif2529512016-07-04 01:26:27 +0000300/// conflict, see below).
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000301/// * Due to unreachable code, the intersection of two lattice values could be
302/// contradictory. If this happens, we return some valid lattice value so as
303/// not confuse the rest of LVI. Ideally, we'd always return Undefined, but
304/// we do not make this guarantee. TODO: This would be a useful enhancement.
305static LVILatticeVal intersect(LVILatticeVal A, LVILatticeVal B) {
306 // Undefined is the strongest state. It means the value is known to be along
307 // an unreachable path.
308 if (A.isUndefined())
309 return A;
310 if (B.isUndefined())
311 return B;
312
313 // If we gave up for one, but got a useable fact from the other, use it.
314 if (A.isOverdefined())
315 return B;
316 if (B.isOverdefined())
317 return A;
318
319 // Can't get any more precise than constants.
320 if (hasSingleValue(A))
321 return A;
322 if (hasSingleValue(B))
323 return B;
324
325 // Could be either constant range or not constant here.
326 if (!A.isConstantRange() || !B.isConstantRange()) {
327 // TODO: Arbitrary choice, could be improved
328 return A;
329 }
330
331 // Intersect two constant ranges
332 ConstantRange Range =
333 A.getConstantRange().intersectWith(B.getConstantRange());
334 // Note: An empty range is implicitly converted to overdefined internally.
335 // TODO: We could instead use Undefined here since we've proven a conflict
NAKAMURA Takumif2529512016-07-04 01:26:27 +0000336 // and thus know this path must be unreachable.
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000337 return LVILatticeVal::getRange(std::move(Range));
Philip Reamesed8cd0d2016-02-02 22:03:19 +0000338}
Philip Reamesd1f829d2016-02-02 21:57:37 +0000339
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000340//===----------------------------------------------------------------------===//
Chris Lattneraf025d32009-11-15 19:59:49 +0000341// LazyValueInfoCache Decl
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000342//===----------------------------------------------------------------------===//
343
Chris Lattneraf025d32009-11-15 19:59:49 +0000344namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000345 /// A callback value handle updates the cache when values are erased.
Owen Anderson118ac802011-01-05 21:15:29 +0000346 class LazyValueInfoCache;
David Blaikie774b5842015-08-03 22:30:24 +0000347 struct LVIValueHandle final : public CallbackVH {
Justin Lebar58b377e2016-07-27 22:33:36 +0000348 // Needs to access getValPtr(), which is protected.
349 friend struct DenseMapInfo<LVIValueHandle>;
350
Owen Anderson118ac802011-01-05 21:15:29 +0000351 LazyValueInfoCache *Parent;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000352
Owen Anderson118ac802011-01-05 21:15:29 +0000353 LVIValueHandle(Value *V, LazyValueInfoCache *P)
354 : CallbackVH(V), Parent(P) { }
Craig Toppere9ba7592014-03-05 07:30:04 +0000355
356 void deleted() override;
357 void allUsesReplacedWith(Value *V) override {
Owen Anderson118ac802011-01-05 21:15:29 +0000358 deleted();
359 }
360 };
Justin Lebar58b377e2016-07-27 22:33:36 +0000361} // end anonymous namespace
Owen Anderson118ac802011-01-05 21:15:29 +0000362
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000363namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000364 /// This is the cache kept by LazyValueInfo which
Chris Lattneraf025d32009-11-15 19:59:49 +0000365 /// maintains information about queries across the clients' queries.
366 class LazyValueInfoCache {
Anna Thomase27b39a2017-03-22 19:27:12 +0000367 friend class LazyValueInfoAnnotatedWriter;
Sanjay Patel2a385e22015-01-09 16:47:20 +0000368 /// This is all of the cached block information for exactly one Value*.
369 /// The entries are sorted by the BasicBlock* of the
Chris Lattneraf025d32009-11-15 19:59:49 +0000370 /// entries, allowing us to do a lookup with a binary search.
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000371 /// Over-defined lattice values are recorded in OverDefinedCache to reduce
372 /// memory overhead.
Justin Lebar58b377e2016-07-27 22:33:36 +0000373 struct ValueCacheEntryTy {
374 ValueCacheEntryTy(Value *V, LazyValueInfoCache *P) : Handle(V, P) {}
375 LVIValueHandle Handle;
Chandler Carruth6acdca72017-01-24 12:55:57 +0000376 SmallDenseMap<PoisoningVH<BasicBlock>, LVILatticeVal, 4> BlockVals;
Justin Lebar58b377e2016-07-27 22:33:36 +0000377 };
Chris Lattneraf025d32009-11-15 19:59:49 +0000378
Sanjay Patel2a385e22015-01-09 16:47:20 +0000379 /// This tracks, on a per-block basis, the set of values that are
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000380 /// over-defined at the end of that block.
Chandler Carruth6acdca72017-01-24 12:55:57 +0000381 typedef DenseMap<PoisoningVH<BasicBlock>, SmallPtrSet<Value *, 4>>
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000382 OverDefinedCacheTy;
Sanjay Patel2a385e22015-01-09 16:47:20 +0000383 /// Keep track of all blocks that we have ever seen, so we
Benjamin Kramer36647082011-12-03 15:16:45 +0000384 /// don't spend time removing unused blocks from our caches.
Chandler Carruth6acdca72017-01-24 12:55:57 +0000385 DenseSet<PoisoningVH<BasicBlock> > SeenBlocks;
Benjamin Kramer36647082011-12-03 15:16:45 +0000386
Anna Thomase27b39a2017-03-22 19:27:12 +0000387 protected:
388 /// This is all of the cached information for all values,
389 /// mapped from Value* to key information.
390 DenseMap<Value *, std::unique_ptr<ValueCacheEntryTy>> ValueCache;
391 OverDefinedCacheTy OverDefinedCache;
392
393
Philip Reames9db79482016-09-12 22:38:44 +0000394 public:
Hans Wennborg45172ac2014-11-25 17:23:05 +0000395 void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
396 SeenBlocks.insert(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000397
398 // Insert over-defined values into their own cache to reduce memory
399 // overhead.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000400 if (Result.isOverdefined())
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000401 OverDefinedCache[BB].insert(Val);
Justin Lebar58b377e2016-07-27 22:33:36 +0000402 else {
403 auto It = ValueCache.find_as(Val);
404 if (It == ValueCache.end()) {
405 ValueCache[Val] = make_unique<ValueCacheEntryTy>(Val, this);
406 It = ValueCache.find_as(Val);
407 assert(It != ValueCache.end() && "Val was just added to the map!");
408 }
409 It->second->BlockVals[BB] = Result;
410 }
Hans Wennborg45172ac2014-11-25 17:23:05 +0000411 }
Owen Andersonc1561b82010-07-30 23:59:40 +0000412
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000413 bool isOverdefined(Value *V, BasicBlock *BB) const {
414 auto ODI = OverDefinedCache.find(BB);
415
416 if (ODI == OverDefinedCache.end())
417 return false;
418
419 return ODI->second.count(V);
420 }
421
Philip Reames9db79482016-09-12 22:38:44 +0000422 bool hasCachedValueInfo(Value *V, BasicBlock *BB) const {
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000423 if (isOverdefined(V, BB))
424 return true;
425
Justin Lebar58b377e2016-07-27 22:33:36 +0000426 auto I = ValueCache.find_as(V);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000427 if (I == ValueCache.end())
428 return false;
429
Justin Lebar58b377e2016-07-27 22:33:36 +0000430 return I->second->BlockVals.count(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000431 }
432
Philip Reames9db79482016-09-12 22:38:44 +0000433 LVILatticeVal getCachedValueInfo(Value *V, BasicBlock *BB) const {
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000434 if (isOverdefined(V, BB))
435 return LVILatticeVal::getOverdefined();
436
Justin Lebar58b377e2016-07-27 22:33:36 +0000437 auto I = ValueCache.find_as(V);
438 if (I == ValueCache.end())
439 return LVILatticeVal();
440 auto BBI = I->second->BlockVals.find(BB);
441 if (BBI == I->second->BlockVals.end())
442 return LVILatticeVal();
443 return BBI->second;
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000444 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +0000445
Anna Thomase27b39a2017-03-22 19:27:12 +0000446 void printCache(Function &F, raw_ostream &OS);
Philip Reames92e5e1b2016-09-12 21:46:58 +0000447 /// clear - Empty the cache.
448 void clear() {
449 SeenBlocks.clear();
450 ValueCache.clear();
451 OverDefinedCache.clear();
452 }
453
Philip Reamesb627aec2016-09-12 22:03:36 +0000454 /// Inform the cache that a given value has been deleted.
455 void eraseValue(Value *V);
456
457 /// This is part of the update interface to inform the cache
458 /// that a block has been deleted.
459 void eraseBlock(BasicBlock *BB);
460
Philip Reames9db79482016-09-12 22:38:44 +0000461 /// Updates the cache to remove any influence an overdefined value in
462 /// OldSucc might have (unless also overdefined in NewSucc). This just
463 /// flushes elements from the cache and does not add any.
464 void threadEdgeImpl(BasicBlock *OldSucc,BasicBlock *NewSucc);
465
Philip Reames92e5e1b2016-09-12 21:46:58 +0000466 friend struct LVIValueHandle;
467 };
Philip Reamesb627aec2016-09-12 22:03:36 +0000468}
Philip Reames92e5e1b2016-09-12 21:46:58 +0000469
Anna Thomase27b39a2017-03-22 19:27:12 +0000470
471namespace {
472
473 /// An assembly annotator class to print LazyValueCache information in
474 /// comments.
475 class LazyValueInfoAnnotatedWriter : public AssemblyAnnotationWriter {
476 const LazyValueInfoCache* LVICache;
477
478 public:
479 LazyValueInfoAnnotatedWriter(const LazyValueInfoCache *L) : LVICache(L) {}
480
481 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
482 formatted_raw_ostream &OS) {
483 auto ODI = LVICache->OverDefinedCache.find(const_cast<BasicBlock*>(BB));
484 if (ODI == LVICache->OverDefinedCache.end())
485 return;
486 OS << "; OverDefined values for block are: \n";
487 for (auto *V : ODI->second)
488 OS << ";" << *V << "\n";
Anna Thomasa8ce8fa2017-03-23 20:00:54 +0000489
490 // Find if there are latticevalues defined for arguments of the function.
491 auto *F = const_cast<Function *>(BB->getParent());
492 for (auto &Arg : F->args()) {
493 auto VI = LVICache->ValueCache.find_as(&Arg);
494 if (VI == LVICache->ValueCache.end())
495 continue;
496 auto BBI = VI->second->BlockVals.find(const_cast<BasicBlock *>(BB));
497 if (BBI != VI->second->BlockVals.end())
498 OS << "; CachedLatticeValue for: '" << *VI->first << "' is: '"
499 << BBI->second << "'\n";
500 }
Anna Thomase27b39a2017-03-22 19:27:12 +0000501 }
502
503 virtual void emitInstructionAnnot(const Instruction *I,
504 formatted_raw_ostream &OS) {
505
506 auto VI = LVICache->ValueCache.find_as(const_cast<Instruction *>(I));
507 if (VI == LVICache->ValueCache.end())
508 return;
509 OS << "; CachedLatticeValues for: '" << *VI->first << "'\n";
510 for (auto &BV : VI->second->BlockVals) {
511 OS << "; at beginning of BasicBlock: '";
512 BV.first->printAsOperand(OS, false);
513 OS << "' LatticeVal: '" << BV.second << "' \n";
514 }
515 }
516};
517}
518
519void LazyValueInfoCache::printCache(Function &F, raw_ostream &OS) {
520 LazyValueInfoAnnotatedWriter Writer(this);
521 F.print(OS, &Writer);
522
523}
524
Philip Reamesb627aec2016-09-12 22:03:36 +0000525void LazyValueInfoCache::eraseValue(Value *V) {
Chandler Carruth41421df2017-01-26 08:31:54 +0000526 for (auto I = OverDefinedCache.begin(), E = OverDefinedCache.end(); I != E;) {
527 // Copy and increment the iterator immediately so we can erase behind
528 // ourselves.
529 auto Iter = I++;
530 SmallPtrSetImpl<Value *> &ValueSet = Iter->second;
Philip Reamesfdbb05b2016-12-30 22:09:10 +0000531 ValueSet.erase(V);
Philip Reamesb627aec2016-09-12 22:03:36 +0000532 if (ValueSet.empty())
Chandler Carruth41421df2017-01-26 08:31:54 +0000533 OverDefinedCache.erase(Iter);
Philip Reamesb627aec2016-09-12 22:03:36 +0000534 }
Philip Reamesb627aec2016-09-12 22:03:36 +0000535
536 ValueCache.erase(V);
537}
538
539void LVIValueHandle::deleted() {
540 // This erasure deallocates *this, so it MUST happen after we're done
541 // using any and all members of *this.
542 Parent->eraseValue(*this);
543}
544
545void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
546 // Shortcut if we have never seen this block.
Chandler Carruth6acdca72017-01-24 12:55:57 +0000547 DenseSet<PoisoningVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
Philip Reamesb627aec2016-09-12 22:03:36 +0000548 if (I == SeenBlocks.end())
549 return;
550 SeenBlocks.erase(I);
551
552 auto ODI = OverDefinedCache.find(BB);
553 if (ODI != OverDefinedCache.end())
554 OverDefinedCache.erase(ODI);
555
556 for (auto &I : ValueCache)
557 I.second->BlockVals.erase(BB);
558}
559
Philip Reames9db79482016-09-12 22:38:44 +0000560void LazyValueInfoCache::threadEdgeImpl(BasicBlock *OldSucc,
561 BasicBlock *NewSucc) {
562 // When an edge in the graph has been threaded, values that we could not
563 // determine a value for before (i.e. were marked overdefined) may be
564 // possible to solve now. We do NOT try to proactively update these values.
565 // Instead, we clear their entries from the cache, and allow lazy updating to
566 // recompute them when needed.
567
568 // The updating process is fairly simple: we need to drop cached info
569 // for all values that were marked overdefined in OldSucc, and for those same
570 // values in any successor of OldSucc (except NewSucc) in which they were
571 // also marked overdefined.
572 std::vector<BasicBlock*> worklist;
573 worklist.push_back(OldSucc);
574
575 auto I = OverDefinedCache.find(OldSucc);
576 if (I == OverDefinedCache.end())
577 return; // Nothing to process here.
578 SmallVector<Value *, 4> ValsToClear(I->second.begin(), I->second.end());
579
580 // Use a worklist to perform a depth-first search of OldSucc's successors.
581 // NOTE: We do not need a visited list since any blocks we have already
582 // visited will have had their overdefined markers cleared already, and we
583 // thus won't loop to their successors.
584 while (!worklist.empty()) {
585 BasicBlock *ToUpdate = worklist.back();
586 worklist.pop_back();
587
588 // Skip blocks only accessible through NewSucc.
589 if (ToUpdate == NewSucc) continue;
590
Philip Reames1e48efc2016-12-30 17:56:47 +0000591 // If a value was marked overdefined in OldSucc, and is here too...
592 auto OI = OverDefinedCache.find(ToUpdate);
593 if (OI == OverDefinedCache.end())
594 continue;
595 SmallPtrSetImpl<Value *> &ValueSet = OI->second;
596
Philip Reames9db79482016-09-12 22:38:44 +0000597 bool changed = false;
598 for (Value *V : ValsToClear) {
Philip Reamesfdbb05b2016-12-30 22:09:10 +0000599 if (!ValueSet.erase(V))
Philip Reames9db79482016-09-12 22:38:44 +0000600 continue;
601
Philip Reames9db79482016-09-12 22:38:44 +0000602 // If we removed anything, then we potentially need to update
603 // blocks successors too.
604 changed = true;
Philip Reames1e48efc2016-12-30 17:56:47 +0000605
606 if (ValueSet.empty()) {
607 OverDefinedCache.erase(OI);
608 break;
609 }
Philip Reames9db79482016-09-12 22:38:44 +0000610 }
611
612 if (!changed) continue;
613
614 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
615 }
616}
617
Philip Reamesb627aec2016-09-12 22:03:36 +0000618namespace {
Philip Reames92e5e1b2016-09-12 21:46:58 +0000619 // The actual implementation of the lazy analysis and update. Note that the
620 // inheritance from LazyValueInfoCache is intended to be temporary while
621 // splitting the code and then transitioning to a has-a relationship.
Philip Reames9db79482016-09-12 22:38:44 +0000622 class LazyValueInfoImpl {
623
624 /// Cached results from previous queries
625 LazyValueInfoCache TheCache;
Philip Reames92e5e1b2016-09-12 21:46:58 +0000626
627 /// This stack holds the state of the value solver during a query.
628 /// It basically emulates the callstack of the naive
629 /// recursive value lookup process.
Daniel Berlin9c92a462017-02-08 15:22:52 +0000630 SmallVector<std::pair<BasicBlock*, Value*>, 8> BlockValueStack;
Philip Reames92e5e1b2016-09-12 21:46:58 +0000631
632 /// Keeps track of which block-value pairs are in BlockValueStack.
633 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
634
635 /// Push BV onto BlockValueStack unless it's already in there.
636 /// Returns true on success.
637 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
638 if (!BlockValueSet.insert(BV).second)
639 return false; // It's already in the stack.
640
641 DEBUG(dbgs() << "PUSH: " << *BV.second << " in " << BV.first->getName()
642 << "\n");
Daniel Berlin9c92a462017-02-08 15:22:52 +0000643 BlockValueStack.push_back(BV);
Philip Reames92e5e1b2016-09-12 21:46:58 +0000644 return true;
645 }
646
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000647 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
Philip Reames92e5e1b2016-09-12 21:46:58 +0000648 const DataLayout &DL; ///< A mandatory DataLayout
649 DominatorTree *DT; ///< An optional DT pointer.
650
651 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
652 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
653 LVILatticeVal &Result, Instruction *CxtI = nullptr);
654 bool hasBlockValue(Value *Val, BasicBlock *BB);
655
656 // These methods process one work item and may add more. A false value
657 // returned means that the work item was not completely processed and must
658 // be revisited after going through the new items.
659 bool solveBlockValue(Value *Val, BasicBlock *BB);
Philip Reames05c435e2016-12-06 03:22:03 +0000660 bool solveBlockValueImpl(LVILatticeVal &Res, Value *Val, BasicBlock *BB);
Philip Reames92e5e1b2016-09-12 21:46:58 +0000661 bool solveBlockValueNonLocal(LVILatticeVal &BBLV, Value *Val, BasicBlock *BB);
662 bool solveBlockValuePHINode(LVILatticeVal &BBLV, PHINode *PN, BasicBlock *BB);
663 bool solveBlockValueSelect(LVILatticeVal &BBLV, SelectInst *S,
664 BasicBlock *BB);
Craig Topper3778c892017-06-02 16:33:13 +0000665 bool solveBlockValueBinaryOp(LVILatticeVal &BBLV, BinaryOperator *BBI,
Philip Reames92e5e1b2016-09-12 21:46:58 +0000666 BasicBlock *BB);
Craig Topper0e5f1092017-06-03 07:47:08 +0000667 bool solveBlockValueCast(LVILatticeVal &BBLV, CastInst *CI,
Philip Reames92e5e1b2016-09-12 21:46:58 +0000668 BasicBlock *BB);
669 void intersectAssumeOrGuardBlockValueConstantRange(Value *Val,
670 LVILatticeVal &BBLV,
Craig Topper9277a862017-06-02 17:28:12 +0000671 Instruction *BBI);
Philip Reames92e5e1b2016-09-12 21:46:58 +0000672
673 void solve();
674
675 public:
Sanjay Patel2a385e22015-01-09 16:47:20 +0000676 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000677 /// value for the specified Value* at the end of the specified block.
Hal Finkel7e184492014-09-07 20:29:59 +0000678 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
679 Instruction *CxtI = nullptr);
680
Sanjay Patel2a385e22015-01-09 16:47:20 +0000681 /// This is the query interface to determine the lattice
Hal Finkel7e184492014-09-07 20:29:59 +0000682 /// value for the specified Value* at the specified instruction (generally
683 /// from an assume intrinsic).
684 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
Chris Lattneraf025d32009-11-15 19:59:49 +0000685
Sanjay Patel2a385e22015-01-09 16:47:20 +0000686 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000687 /// value for the specified Value* that is true on the specified edge.
Hal Finkel7e184492014-09-07 20:29:59 +0000688 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
689 Instruction *CxtI = nullptr);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000690
Philip Reames9db79482016-09-12 22:38:44 +0000691 /// Complete flush all previously computed values
692 void clear() {
693 TheCache.clear();
694 }
695
Anna Thomase27b39a2017-03-22 19:27:12 +0000696 /// Printing the LazyValueInfoCache.
697 void printCache(Function &F, raw_ostream &OS) {
698 TheCache.printCache(F, OS);
699 }
700
Philip Reames9db79482016-09-12 22:38:44 +0000701 /// This is part of the update interface to inform the cache
702 /// that a block has been deleted.
703 void eraseBlock(BasicBlock *BB) {
704 TheCache.eraseBlock(BB);
705 }
706
Sanjay Patel2a385e22015-01-09 16:47:20 +0000707 /// This is the update interface to inform the cache that an edge from
708 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
Owen Andersonaa7f66b2010-07-26 18:48:03 +0000709 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000710
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000711 LazyValueInfoImpl(AssumptionCache *AC, const DataLayout &DL,
712 DominatorTree *DT = nullptr)
713 : AC(AC), DL(DL), DT(DT) {}
Chris Lattneraf025d32009-11-15 19:59:49 +0000714 };
715} // end anonymous namespace
716
Philip Reames92e5e1b2016-09-12 21:46:58 +0000717void LazyValueInfoImpl::solve() {
Daniel Berlin9c92a462017-02-08 15:22:52 +0000718 SmallVector<std::pair<BasicBlock *, Value *>, 8> StartingStack(
719 BlockValueStack.begin(), BlockValueStack.end());
720
721 unsigned processedCount = 0;
Owen Anderson6f060af2011-01-05 23:26:22 +0000722 while (!BlockValueStack.empty()) {
Daniel Berlin9c92a462017-02-08 15:22:52 +0000723 processedCount++;
724 // Abort if we have to process too many values to get a result for this one.
725 // Because of the design of the overdefined cache currently being per-block
726 // to avoid naming-related issues (IE it wants to try to give different
727 // results for the same name in different blocks), overdefined results don't
728 // get cached globally, which in turn means we will often try to rediscover
729 // the same overdefined result again and again. Once something like
730 // PredicateInfo is used in LVI or CVP, we should be able to make the
731 // overdefined cache global, and remove this throttle.
732 if (processedCount > MaxProcessedPerValue) {
733 DEBUG(dbgs() << "Giving up on stack because we are getting too deep\n");
734 // Fill in the original values
735 while (!StartingStack.empty()) {
736 std::pair<BasicBlock *, Value *> &e = StartingStack.back();
737 TheCache.insertResult(e.second, e.first,
738 LVILatticeVal::getOverdefined());
739 StartingStack.pop_back();
740 }
741 BlockValueSet.clear();
742 BlockValueStack.clear();
743 return;
744 }
Vitaly Buka9987d982017-02-09 09:28:05 +0000745 std::pair<BasicBlock *, Value *> e = BlockValueStack.back();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000746 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
747
Nuno Lopese6e04902012-06-28 01:16:18 +0000748 if (solveBlockValue(e.second, e.first)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000749 // The work item was completely processed.
Daniel Berlin9c92a462017-02-08 15:22:52 +0000750 assert(BlockValueStack.back() == e && "Nothing should have been pushed!");
Philip Reames9db79482016-09-12 22:38:44 +0000751 assert(TheCache.hasCachedValueInfo(e.second, e.first) &&
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000752 "Result should be in cache!");
Hans Wennborg45172ac2014-11-25 17:23:05 +0000753
Philip Reames44456b82016-02-02 03:15:40 +0000754 DEBUG(dbgs() << "POP " << *e.second << " in " << e.first->getName()
Philip Reames9db79482016-09-12 22:38:44 +0000755 << " = " << TheCache.getCachedValueInfo(e.second, e.first) << "\n");
Philip Reames44456b82016-02-02 03:15:40 +0000756
Daniel Berlin9c92a462017-02-08 15:22:52 +0000757 BlockValueStack.pop_back();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000758 BlockValueSet.erase(e);
759 } else {
760 // More work needs to be done before revisiting.
Daniel Berlin9c92a462017-02-08 15:22:52 +0000761 assert(BlockValueStack.back() != e && "Stack should have been pushed!");
Nuno Lopese6e04902012-06-28 01:16:18 +0000762 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000763 }
764}
765
Philip Reames92e5e1b2016-09-12 21:46:58 +0000766bool LazyValueInfoImpl::hasBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000767 // If already a constant, there is nothing to compute.
768 if (isa<Constant>(Val))
769 return true;
770
Philip Reames9db79482016-09-12 22:38:44 +0000771 return TheCache.hasCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000772}
773
Philip Reames92e5e1b2016-09-12 21:46:58 +0000774LVILatticeVal LazyValueInfoImpl::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000775 // If already a constant, there is nothing to compute.
776 if (Constant *VC = dyn_cast<Constant>(Val))
777 return LVILatticeVal::get(VC);
778
Philip Reames9db79482016-09-12 22:38:44 +0000779 return TheCache.getCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000780}
781
Philip Reameseb3e9da2015-10-29 03:57:17 +0000782static LVILatticeVal getFromRangeMetadata(Instruction *BBI) {
783 switch (BBI->getOpcode()) {
784 default: break;
785 case Instruction::Load:
786 case Instruction::Call:
787 case Instruction::Invoke:
NAKAMURA Takumibd072a92016-07-25 00:59:46 +0000788 if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
Philip Reames70efccd2015-10-29 04:21:49 +0000789 if (isa<IntegerType>(BBI->getType())) {
Benjamin Kramer2337c1f2016-02-20 10:40:34 +0000790 return LVILatticeVal::getRange(getConstantRangeFromMetadata(*Ranges));
Philip Reameseb3e9da2015-10-29 03:57:17 +0000791 }
792 break;
793 };
Philip Reamesd1f829d2016-02-02 21:57:37 +0000794 // Nothing known - will be intersected with other facts
795 return LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +0000796}
797
Philip Reames92e5e1b2016-09-12 21:46:58 +0000798bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000799 if (isa<Constant>(Val))
800 return true;
801
Philip Reames9db79482016-09-12 22:38:44 +0000802 if (TheCache.hasCachedValueInfo(Val, BB)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000803 // If we have a cached value, use that.
804 DEBUG(dbgs() << " reuse BB '" << BB->getName()
Philip Reames9db79482016-09-12 22:38:44 +0000805 << "' val=" << TheCache.getCachedValueInfo(Val, BB) << '\n');
Nick Lewycky55a700b2010-12-18 01:00:40 +0000806
Hans Wennborg45172ac2014-11-25 17:23:05 +0000807 // Since we're reusing a cached value, we don't need to update the
808 // OverDefinedCache. The cache will have been properly updated whenever the
809 // cached value was inserted.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000810 return true;
Chris Lattner2c708562009-11-15 20:00:52 +0000811 }
812
Hans Wennborg45172ac2014-11-25 17:23:05 +0000813 // Hold off inserting this value into the Cache in case we have to return
814 // false and come back later.
815 LVILatticeVal Res;
Philip Reames05c435e2016-12-06 03:22:03 +0000816 if (!solveBlockValueImpl(Res, Val, BB))
817 // Work pushed, will revisit
818 return false;
819
820 TheCache.insertResult(Val, BB, Res);
821 return true;
822}
823
824bool LazyValueInfoImpl::solveBlockValueImpl(LVILatticeVal &Res,
825 Value *Val, BasicBlock *BB) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000826
Chris Lattneraf025d32009-11-15 19:59:49 +0000827 Instruction *BBI = dyn_cast<Instruction>(Val);
Philip Reames05c435e2016-12-06 03:22:03 +0000828 if (!BBI || BBI->getParent() != BB)
829 return solveBlockValueNonLocal(Res, Val, BB);
Chris Lattner2c708562009-11-15 20:00:52 +0000830
Philip Reames05c435e2016-12-06 03:22:03 +0000831 if (PHINode *PN = dyn_cast<PHINode>(BBI))
832 return solveBlockValuePHINode(Res, PN, BB);
Owen Anderson80d19f02010-08-18 21:11:37 +0000833
Philip Reames05c435e2016-12-06 03:22:03 +0000834 if (auto *SI = dyn_cast<SelectInst>(BBI))
835 return solveBlockValueSelect(Res, SI, BB);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000836
Philip Reames2ab964e2016-04-27 01:02:25 +0000837 // If this value is a nonnull pointer, record it's range and bailout. Note
838 // that for all other pointer typed values, we terminate the search at the
839 // definition. We could easily extend this to look through geps, bitcasts,
840 // and the like to prove non-nullness, but it's not clear that's worth it
841 // compile time wise. The context-insensative value walk done inside
842 // isKnownNonNull gets most of the profitable cases at much less expense.
843 // This does mean that we have a sensativity to where the defining
844 // instruction is placed, even if it could legally be hoisted much higher.
845 // That is unfortunate.
Igor Laevsky0fa48192015-09-18 13:01:48 +0000846 PointerType *PT = dyn_cast<PointerType>(BBI->getType());
847 if (PT && isKnownNonNull(BBI)) {
848 Res = LVILatticeVal::getNot(ConstantPointerNull::get(PT));
Hans Wennborg45172ac2014-11-25 17:23:05 +0000849 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000850 }
Davide Italianobd543d02016-05-25 22:29:34 +0000851 if (BBI->getType()->isIntegerTy()) {
Craig Topper0e5f1092017-06-03 07:47:08 +0000852 if (auto *CI = dyn_cast<CastInst>(BBI))
853 return solveBlockValueCast(Res, CI, BB);
854
Philip Reames2ab964e2016-04-27 01:02:25 +0000855 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
Philip Reames05c435e2016-12-06 03:22:03 +0000856 if (BO && isa<ConstantInt>(BO->getOperand(1)))
Craig Topper3778c892017-06-02 16:33:13 +0000857 return solveBlockValueBinaryOp(Res, BO, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000858 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000859
Philip Reamesa0c9f6e2016-03-04 22:27:39 +0000860 DEBUG(dbgs() << " compute BB '" << BB->getName()
861 << "' - unknown inst def found.\n");
862 Res = getFromRangeMetadata(BBI);
Hans Wennborg45172ac2014-11-25 17:23:05 +0000863 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000864}
865
866static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
867 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
868 return L->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000869 GetUnderlyingObject(L->getPointerOperand(),
870 L->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000871 }
872 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
873 return S->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000874 GetUnderlyingObject(S->getPointerOperand(),
875 S->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000876 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000877 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
878 if (MI->isVolatile()) return false;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000879
880 // FIXME: check whether it has a valuerange that excludes zero?
881 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
882 if (!Len || Len->isZero()) return false;
883
Eli Friedman7a5fc692011-05-31 20:40:16 +0000884 if (MI->getDestAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000885 if (GetUnderlyingObject(MI->getRawDest(),
886 MI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000887 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000888 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman7a5fc692011-05-31 20:40:16 +0000889 if (MTI->getSourceAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000890 if (GetUnderlyingObject(MTI->getRawSource(),
891 MTI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000892 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000893 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000894 return false;
895}
896
Philip Reames3f83dbe2016-04-27 00:30:55 +0000897/// Return true if the allocation associated with Val is ever dereferenced
898/// within the given basic block. This establishes the fact Val is not null,
899/// but does not imply that the memory at Val is dereferenceable. (Val may
900/// point off the end of the dereferenceable part of the object.)
901static bool isObjectDereferencedInBlock(Value *Val, BasicBlock *BB) {
902 assert(Val->getType()->isPointerTy());
903
904 const DataLayout &DL = BB->getModule()->getDataLayout();
905 Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
906 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
907 // inside InstructionDereferencesPointer either.
908 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1))
909 for (Instruction &I : *BB)
910 if (InstructionDereferencesPointer(&I, UnderlyingVal))
911 return true;
912 return false;
913}
914
Philip Reames92e5e1b2016-09-12 21:46:58 +0000915bool LazyValueInfoImpl::solveBlockValueNonLocal(LVILatticeVal &BBLV,
Owen Anderson64c2c572010-12-20 18:18:16 +0000916 Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000917 LVILatticeVal Result; // Start Undefined.
918
Nick Lewycky55a700b2010-12-18 01:00:40 +0000919 // If this is the entry block, we must be asking about an argument. The
920 // value is overdefined.
921 if (BB == &BB->getParent()->getEntryBlock()) {
922 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
Craig Topper96d6ee852017-04-28 16:57:59 +0000923 // Before giving up, see if we can prove the pointer non-null local to
Philip Reames3f83dbe2016-04-27 00:30:55 +0000924 // this particular block.
925 if (Val->getType()->isPointerTy() &&
926 (isKnownNonNull(Val) || isObjectDereferencedInBlock(Val, BB))) {
Chris Lattner229907c2011-07-18 04:54:35 +0000927 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000928 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
929 } else {
Philip Reames1baaef12016-12-06 03:01:08 +0000930 Result = LVILatticeVal::getOverdefined();
Nick Lewycky55a700b2010-12-18 01:00:40 +0000931 }
Owen Anderson64c2c572010-12-20 18:18:16 +0000932 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000933 return true;
934 }
935
936 // Loop over all of our predecessors, merging what we know from them into
Philip Reamesc80bd042017-02-07 00:25:24 +0000937 // result. If we encounter an unexplored predecessor, we eagerly explore it
938 // in a depth first manner. In practice, this has the effect of discovering
939 // paths we can't analyze eagerly without spending compile times analyzing
940 // other paths. This heuristic benefits from the fact that predecessors are
941 // frequently arranged such that dominating ones come first and we quickly
942 // find a path to function entry. TODO: We should consider explicitly
943 // canonicalizing to make this true rather than relying on this happy
944 // accident.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000945 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000946 LVILatticeVal EdgeResult;
Philip Reamesc80bd042017-02-07 00:25:24 +0000947 if (!getEdgeValue(Val, *PI, BB, EdgeResult))
948 // Explore that input, then return here
949 return false;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000950
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000951 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000952
953 // If we hit overdefined, exit early. The BlockVals entry is already set
954 // to overdefined.
955 if (Result.isOverdefined()) {
956 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +0000957 << "' - overdefined because of pred (non local).\n");
Artur Pilipenkoadcd01f2016-08-09 09:14:29 +0000958 // Before giving up, see if we can prove the pointer non-null local to
Philip Reames3f83dbe2016-04-27 00:30:55 +0000959 // this particular block.
960 if (Val->getType()->isPointerTy() &&
961 isObjectDereferencedInBlock(Val, BB)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000962 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000963 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
964 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000965
Owen Anderson64c2c572010-12-20 18:18:16 +0000966 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000967 return true;
968 }
969 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000970
971 // Return the merged value, which is more precise than 'overdefined'.
972 assert(!Result.isOverdefined());
Owen Anderson64c2c572010-12-20 18:18:16 +0000973 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000974 return true;
975}
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000976
Philip Reames92e5e1b2016-09-12 21:46:58 +0000977bool LazyValueInfoImpl::solveBlockValuePHINode(LVILatticeVal &BBLV,
Owen Anderson64c2c572010-12-20 18:18:16 +0000978 PHINode *PN, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000979 LVILatticeVal Result; // Start Undefined.
980
981 // Loop over all of our predecessors, merging what we know from them into
Philip Reamesc80bd042017-02-07 00:25:24 +0000982 // result. See the comment about the chosen traversal order in
983 // solveBlockValueNonLocal; the same reasoning applies here.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000984 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
985 BasicBlock *PhiBB = PN->getIncomingBlock(i);
986 Value *PhiVal = PN->getIncomingValue(i);
987 LVILatticeVal EdgeResult;
Hal Finkel2400c962014-10-16 00:40:05 +0000988 // Note that we can provide PN as the context value to getEdgeValue, even
989 // though the results will be cached, because PN is the value being used as
990 // the cache key in the caller.
Philip Reamesc80bd042017-02-07 00:25:24 +0000991 if (!getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN))
992 // Explore that input, then return here
993 return false;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000994
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000995 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000996
997 // If we hit overdefined, exit early. The BlockVals entry is already set
998 // to overdefined.
999 if (Result.isOverdefined()) {
1000 DEBUG(dbgs() << " compute BB '" << BB->getName()
Philip Reamesb7571042016-02-02 22:43:08 +00001001 << "' - overdefined because of pred (local).\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001002
Owen Anderson64c2c572010-12-20 18:18:16 +00001003 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +00001004 return true;
1005 }
1006 }
Nick Lewycky55a700b2010-12-18 01:00:40 +00001007
1008 // Return the merged value, which is more precise than 'overdefined'.
1009 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson64c2c572010-12-20 18:18:16 +00001010 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +00001011 return true;
1012}
1013
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001014static LVILatticeVal getValueFromCondition(Value *Val, Value *Cond,
1015 bool isTrueDest = true);
Hal Finkel7e184492014-09-07 20:29:59 +00001016
Philip Reamesd1f829d2016-02-02 21:57:37 +00001017// If we can determine a constraint on the value given conditions assumed by
1018// the program, intersect those constraints with BBLV
Philip Reames92e5e1b2016-09-12 21:46:58 +00001019void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001020 Value *Val, LVILatticeVal &BBLV, Instruction *BBI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001021 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
1022 if (!BBI)
1023 return;
1024
Hal Finkel8a9a7832017-01-11 13:24:24 +00001025 for (auto &AssumeVH : AC->assumptionsFor(Val)) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001026 if (!AssumeVH)
Chandler Carruth66b31302015-01-04 12:03:27 +00001027 continue;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001028 auto *I = cast<CallInst>(AssumeVH);
1029 if (!isValidAssumeForContext(I, BBI, DT))
Hal Finkel7e184492014-09-07 20:29:59 +00001030 continue;
1031
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001032 BBLV = intersect(BBLV, getValueFromCondition(Val, I->getArgOperand(0)));
Hal Finkel7e184492014-09-07 20:29:59 +00001033 }
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001034
1035 // If guards are not used in the module, don't spend time looking for them
1036 auto *GuardDecl = BBI->getModule()->getFunction(
1037 Intrinsic::getName(Intrinsic::experimental_guard));
1038 if (!GuardDecl || GuardDecl->use_empty())
1039 return;
1040
Artur Pilipenko47dc0982016-10-21 15:02:21 +00001041 for (Instruction &I : make_range(BBI->getIterator().getReverse(),
1042 BBI->getParent()->rend())) {
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001043 Value *Cond = nullptr;
Artur Pilipenko47dc0982016-10-21 15:02:21 +00001044 if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(Cond))))
1045 BBLV = intersect(BBLV, getValueFromCondition(Val, Cond));
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001046 }
Hal Finkel7e184492014-09-07 20:29:59 +00001047}
1048
Philip Reames92e5e1b2016-09-12 21:46:58 +00001049bool LazyValueInfoImpl::solveBlockValueSelect(LVILatticeVal &BBLV,
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001050 SelectInst *SI, BasicBlock *BB) {
1051
1052 // Recurse on our inputs if needed
1053 if (!hasBlockValue(SI->getTrueValue(), BB)) {
1054 if (pushBlockValue(std::make_pair(BB, SI->getTrueValue())))
1055 return false;
Philip Reames1baaef12016-12-06 03:01:08 +00001056 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001057 return true;
1058 }
1059 LVILatticeVal TrueVal = getBlockValue(SI->getTrueValue(), BB);
1060 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
1061 // extra slots in the table if we can.
1062 if (TrueVal.isOverdefined()) {
Philip Reames1baaef12016-12-06 03:01:08 +00001063 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001064 return true;
1065 }
1066
1067 if (!hasBlockValue(SI->getFalseValue(), BB)) {
1068 if (pushBlockValue(std::make_pair(BB, SI->getFalseValue())))
1069 return false;
Philip Reames1baaef12016-12-06 03:01:08 +00001070 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001071 return true;
1072 }
1073 LVILatticeVal FalseVal = getBlockValue(SI->getFalseValue(), BB);
1074 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
1075 // extra slots in the table if we can.
1076 if (FalseVal.isOverdefined()) {
Philip Reames1baaef12016-12-06 03:01:08 +00001077 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001078 return true;
1079 }
1080
Philip Reamesadf0e352016-02-26 22:53:59 +00001081 if (TrueVal.isConstantRange() && FalseVal.isConstantRange()) {
Craig Topper2b195fd2017-05-06 03:35:15 +00001082 const ConstantRange &TrueCR = TrueVal.getConstantRange();
1083 const ConstantRange &FalseCR = FalseVal.getConstantRange();
Philip Reamesadf0e352016-02-26 22:53:59 +00001084 Value *LHS = nullptr;
1085 Value *RHS = nullptr;
1086 SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
1087 // Is this a min specifically of our two inputs? (Avoid the risk of
1088 // ValueTracking getting smarter looking back past our immediate inputs.)
1089 if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
1090 LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) {
Philip Reamesb2949622016-12-06 02:54:16 +00001091 ConstantRange ResultCR = [&]() {
1092 switch (SPR.Flavor) {
1093 default:
1094 llvm_unreachable("unexpected minmax type!");
1095 case SPF_SMIN: /// Signed minimum
1096 return TrueCR.smin(FalseCR);
1097 case SPF_UMIN: /// Unsigned minimum
1098 return TrueCR.umin(FalseCR);
1099 case SPF_SMAX: /// Signed maximum
1100 return TrueCR.smax(FalseCR);
1101 case SPF_UMAX: /// Unsigned maximum
1102 return TrueCR.umax(FalseCR);
1103 };
1104 }();
1105 BBLV = LVILatticeVal::getRange(ResultCR);
1106 return true;
Philip Reamesadf0e352016-02-26 22:53:59 +00001107 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001108
Philip Reamesadf0e352016-02-26 22:53:59 +00001109 // TODO: ABS, NABS from the SelectPatternResult
1110 }
1111
Philip Reames854a84c2016-02-12 00:09:18 +00001112 // Can we constrain the facts about the true and false values by using the
1113 // condition itself? This shows up with idioms like e.g. select(a > 5, a, 5).
1114 // TODO: We could potentially refine an overdefined true value above.
Artur Pilipenko2e19f592016-08-02 16:20:48 +00001115 Value *Cond = SI->getCondition();
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001116 TrueVal = intersect(TrueVal,
1117 getValueFromCondition(SI->getTrueValue(), Cond, true));
1118 FalseVal = intersect(FalseVal,
1119 getValueFromCondition(SI->getFalseValue(), Cond, false));
Philip Reames854a84c2016-02-12 00:09:18 +00001120
Artur Pilipenko2e19f592016-08-02 16:20:48 +00001121 // Handle clamp idioms such as:
1122 // %24 = constantrange<0, 17>
1123 // %39 = icmp eq i32 %24, 0
1124 // %40 = add i32 %24, -1
1125 // %siv.next = select i1 %39, i32 16, i32 %40
1126 // %siv.next = constantrange<0, 17> not <-1, 17>
1127 // In general, this can handle any clamp idiom which tests the edge
1128 // condition via an equality or inequality.
1129 if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
Philip Reamesadf0e352016-02-26 22:53:59 +00001130 ICmpInst::Predicate Pred = ICI->getPredicate();
1131 Value *A = ICI->getOperand(0);
1132 if (ConstantInt *CIBase = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
1133 auto addConstants = [](ConstantInt *A, ConstantInt *B) {
1134 assert(A->getType() == B->getType());
1135 return ConstantInt::get(A->getType(), A->getValue() + B->getValue());
1136 };
1137 // See if either input is A + C2, subject to the constraint from the
1138 // condition that A != C when that input is used. We can assume that
1139 // that input doesn't include C + C2.
1140 ConstantInt *CIAdded;
1141 switch (Pred) {
Philip Reames70b39182016-02-27 05:18:30 +00001142 default: break;
Philip Reamesadf0e352016-02-26 22:53:59 +00001143 case ICmpInst::ICMP_EQ:
1144 if (match(SI->getFalseValue(), m_Add(m_Specific(A),
1145 m_ConstantInt(CIAdded)))) {
1146 auto ResNot = addConstants(CIBase, CIAdded);
1147 FalseVal = intersect(FalseVal,
1148 LVILatticeVal::getNot(ResNot));
1149 }
1150 break;
1151 case ICmpInst::ICMP_NE:
1152 if (match(SI->getTrueValue(), m_Add(m_Specific(A),
1153 m_ConstantInt(CIAdded)))) {
1154 auto ResNot = addConstants(CIBase, CIAdded);
1155 TrueVal = intersect(TrueVal,
1156 LVILatticeVal::getNot(ResNot));
1157 }
1158 break;
1159 };
1160 }
1161 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001162
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001163 LVILatticeVal Result; // Start Undefined.
1164 Result.mergeIn(TrueVal, DL);
1165 Result.mergeIn(FalseVal, DL);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +00001166 BBLV = Result;
1167 return true;
1168}
1169
Philip Reames92e5e1b2016-09-12 21:46:58 +00001170bool LazyValueInfoImpl::solveBlockValueCast(LVILatticeVal &BBLV,
Craig Topper0e5f1092017-06-03 07:47:08 +00001171 CastInst *CI,
1172 BasicBlock *BB) {
1173 if (!CI->getOperand(0)->getType()->isSized()) {
Philip Reamese5030e82016-04-26 22:52:30 +00001174 // Without knowing how wide the input is, we can't analyze it in any useful
1175 // way.
Philip Reames1baaef12016-12-06 03:01:08 +00001176 BBLV = LVILatticeVal::getOverdefined();
Philip Reamese5030e82016-04-26 22:52:30 +00001177 return true;
1178 }
Philip Reamesf105db42016-04-26 23:27:33 +00001179
1180 // Filter out casts we don't know how to reason about before attempting to
1181 // recurse on our operand. This can cut a long search short if we know we're
1182 // not going to be able to get any useful information anways.
Craig Topper0e5f1092017-06-03 07:47:08 +00001183 switch (CI->getOpcode()) {
Philip Reamesf105db42016-04-26 23:27:33 +00001184 case Instruction::Trunc:
1185 case Instruction::SExt:
1186 case Instruction::ZExt:
1187 case Instruction::BitCast:
1188 break;
1189 default:
1190 // Unhandled instructions are overdefined.
1191 DEBUG(dbgs() << " compute BB '" << BB->getName()
1192 << "' - overdefined (unknown cast).\n");
Philip Reames1baaef12016-12-06 03:01:08 +00001193 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesf105db42016-04-26 23:27:33 +00001194 return true;
1195 }
1196
Philip Reames38c87c22016-04-26 21:48:16 +00001197 // Figure out the range of the LHS. If that fails, we still apply the
1198 // transfer rule on the full set since we may be able to locally infer
1199 // interesting facts.
Craig Topper0e5f1092017-06-03 07:47:08 +00001200 if (!hasBlockValue(CI->getOperand(0), BB))
1201 if (pushBlockValue(std::make_pair(BB, CI->getOperand(0))))
Philip Reames38c87c22016-04-26 21:48:16 +00001202 // More work to do before applying this transfer rule.
Hans Wennborg45172ac2014-11-25 17:23:05 +00001203 return false;
Philip Reames38c87c22016-04-26 21:48:16 +00001204
1205 const unsigned OperandBitWidth =
Craig Topper0e5f1092017-06-03 07:47:08 +00001206 DL.getTypeSizeInBits(CI->getOperand(0)->getType());
Philip Reames38c87c22016-04-26 21:48:16 +00001207 ConstantRange LHSRange = ConstantRange(OperandBitWidth);
Craig Topper0e5f1092017-06-03 07:47:08 +00001208 if (hasBlockValue(CI->getOperand(0), BB)) {
1209 LVILatticeVal LHSVal = getBlockValue(CI->getOperand(0), BB);
1210 intersectAssumeOrGuardBlockValueConstantRange(CI->getOperand(0), LHSVal,
1211 CI);
Philip Reames38c87c22016-04-26 21:48:16 +00001212 if (LHSVal.isConstantRange())
1213 LHSRange = LHSVal.getConstantRange();
Nick Lewycky55a700b2010-12-18 01:00:40 +00001214 }
1215
Craig Toppera803d5b2017-06-03 07:47:14 +00001216 const unsigned ResultBitWidth = CI->getType()->getIntegerBitWidth();
Philip Reames66715772016-04-25 18:30:31 +00001217
1218 // NOTE: We're currently limited by the set of operations that ConstantRange
1219 // can evaluate symbolically. Enhancing that set will allows us to analyze
1220 // more definitions.
Craig Topper0e5f1092017-06-03 07:47:08 +00001221 BBLV = LVILatticeVal::getRange(LHSRange.castOp(CI->getOpcode(),
1222 ResultBitWidth));
Philip Reames66715772016-04-25 18:30:31 +00001223 return true;
1224}
1225
Philip Reames92e5e1b2016-09-12 21:46:58 +00001226bool LazyValueInfoImpl::solveBlockValueBinaryOp(LVILatticeVal &BBLV,
Craig Topper3778c892017-06-02 16:33:13 +00001227 BinaryOperator *BO,
Philip Reamese5030e82016-04-26 22:52:30 +00001228 BasicBlock *BB) {
Philip Reames66715772016-04-25 18:30:31 +00001229
Craig Topper3778c892017-06-02 16:33:13 +00001230 assert(BO->getOperand(0)->getType()->isSized() &&
Philip Reames053c2a62016-04-26 23:10:35 +00001231 "all operands to binary operators are sized");
Philip Reamesf105db42016-04-26 23:27:33 +00001232
1233 // Filter out operators we don't know how to reason about before attempting to
1234 // recurse on our operand(s). This can cut a long search short if we know
Craig Topper84a9f162017-06-02 16:21:13 +00001235 // we're not going to be able to get any useful information anyways.
Craig Topper3778c892017-06-02 16:33:13 +00001236 switch (BO->getOpcode()) {
Philip Reamesf105db42016-04-26 23:27:33 +00001237 case Instruction::Add:
1238 case Instruction::Sub:
1239 case Instruction::Mul:
1240 case Instruction::UDiv:
1241 case Instruction::Shl:
1242 case Instruction::LShr:
1243 case Instruction::And:
1244 case Instruction::Or:
1245 // continue into the code below
1246 break;
1247 default:
1248 // Unhandled instructions are overdefined.
1249 DEBUG(dbgs() << " compute BB '" << BB->getName()
1250 << "' - overdefined (unknown binary operator).\n");
Philip Reames1baaef12016-12-06 03:01:08 +00001251 BBLV = LVILatticeVal::getOverdefined();
Philip Reamesf105db42016-04-26 23:27:33 +00001252 return true;
1253 };
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001254
Philip Reames053c2a62016-04-26 23:10:35 +00001255 // Figure out the range of the LHS. If that fails, use a conservative range,
1256 // but apply the transfer rule anyways. This lets us pick up facts from
1257 // expressions like "and i32 (call i32 @foo()), 32"
Craig Topper3778c892017-06-02 16:33:13 +00001258 if (!hasBlockValue(BO->getOperand(0), BB))
1259 if (pushBlockValue(std::make_pair(BB, BO->getOperand(0))))
Philip Reames053c2a62016-04-26 23:10:35 +00001260 // More work to do before applying this transfer rule.
1261 return false;
1262
1263 const unsigned OperandBitWidth =
Craig Topper3778c892017-06-02 16:33:13 +00001264 DL.getTypeSizeInBits(BO->getOperand(0)->getType());
Philip Reames053c2a62016-04-26 23:10:35 +00001265 ConstantRange LHSRange = ConstantRange(OperandBitWidth);
Craig Topper3778c892017-06-02 16:33:13 +00001266 if (hasBlockValue(BO->getOperand(0), BB)) {
1267 LVILatticeVal LHSVal = getBlockValue(BO->getOperand(0), BB);
1268 intersectAssumeOrGuardBlockValueConstantRange(BO->getOperand(0), LHSVal,
1269 BO);
Philip Reames053c2a62016-04-26 23:10:35 +00001270 if (LHSVal.isConstantRange())
1271 LHSRange = LHSVal.getConstantRange();
Philip Reames66715772016-04-25 18:30:31 +00001272 }
Philip Reames66715772016-04-25 18:30:31 +00001273
Craig Topper3778c892017-06-02 16:33:13 +00001274 ConstantInt *RHS = cast<ConstantInt>(BO->getOperand(1));
Philip Reames66715772016-04-25 18:30:31 +00001275 ConstantRange RHSRange = ConstantRange(RHS->getValue());
1276
Owen Anderson80d19f02010-08-18 21:11:37 +00001277 // NOTE: We're currently limited by the set of operations that ConstantRange
1278 // can evaluate symbolically. Enhancing that set will allows us to analyze
1279 // more definitions.
Craig Topper3778c892017-06-02 16:33:13 +00001280 Instruction::BinaryOps BinOp = BO->getOpcode();
Philip Reames0e613f72016-12-06 02:36:58 +00001281 BBLV = LVILatticeVal::getRange(LHSRange.binaryOp(BinOp, RHSRange));
Nick Lewycky55a700b2010-12-18 01:00:40 +00001282 return true;
Chris Lattner741c94c2009-11-11 00:22:30 +00001283}
1284
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001285static LVILatticeVal getValueFromICmpCondition(Value *Val, ICmpInst *ICI,
1286 bool isTrueDest) {
Artur Pilipenko21472912016-08-08 14:08:37 +00001287 Value *LHS = ICI->getOperand(0);
1288 Value *RHS = ICI->getOperand(1);
1289 CmpInst::Predicate Predicate = ICI->getPredicate();
1290
1291 if (isa<Constant>(RHS)) {
1292 if (ICI->isEquality() && LHS == Val) {
Hal Finkel7e184492014-09-07 20:29:59 +00001293 // We know that V has the RHS constant if this is a true SETEQ or
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001294 // false SETNE.
Artur Pilipenko21472912016-08-08 14:08:37 +00001295 if (isTrueDest == (Predicate == ICmpInst::ICMP_EQ))
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001296 return LVILatticeVal::get(cast<Constant>(RHS));
Hal Finkel7e184492014-09-07 20:29:59 +00001297 else
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001298 return LVILatticeVal::getNot(cast<Constant>(RHS));
Hal Finkel7e184492014-09-07 20:29:59 +00001299 }
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001300 }
Hal Finkel7e184492014-09-07 20:29:59 +00001301
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001302 if (!Val->getType()->isIntegerTy())
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001303 return LVILatticeVal::getOverdefined();
Hal Finkel7e184492014-09-07 20:29:59 +00001304
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001305 // Use ConstantRange::makeAllowedICmpRegion in order to determine the possible
1306 // range of Val guaranteed by the condition. Recognize comparisons in the from
1307 // of:
1308 // icmp <pred> Val, ...
Artur Pilipenko63562582016-08-12 10:05:11 +00001309 // icmp <pred> (add Val, Offset), ...
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001310 // The latter is the range checking idiom that InstCombine produces. Subtract
1311 // the offset from the allowed range for RHS in this case.
Artur Pilipenkoeed618d2016-08-08 14:33:11 +00001312
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001313 // Val or (add Val, Offset) can be on either hand of the comparison
1314 if (LHS != Val && !match(LHS, m_Add(m_Specific(Val), m_ConstantInt()))) {
1315 std::swap(LHS, RHS);
1316 Predicate = CmpInst::getSwappedPredicate(Predicate);
1317 }
Hal Finkel7e184492014-09-07 20:29:59 +00001318
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001319 ConstantInt *Offset = nullptr;
Artur Pilipenko63562582016-08-12 10:05:11 +00001320 if (LHS != Val)
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001321 match(LHS, m_Add(m_Specific(Val), m_ConstantInt(Offset)));
Hal Finkel7e184492014-09-07 20:29:59 +00001322
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001323 if (LHS == Val || Offset) {
1324 // Calculate the range of values that are allowed by the comparison
1325 ConstantRange RHSRange(RHS->getType()->getIntegerBitWidth(),
1326 /*isFullSet=*/true);
1327 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS))
1328 RHSRange = ConstantRange(CI->getValue());
Artur Pilipenko6669f252016-08-12 10:14:11 +00001329 else if (Instruction *I = dyn_cast<Instruction>(RHS))
1330 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
1331 RHSRange = getConstantRangeFromMetadata(*Ranges);
Artur Pilipenkoc710a462016-08-09 14:50:08 +00001332
1333 // If we're interested in the false dest, invert the condition
1334 CmpInst::Predicate Pred =
1335 isTrueDest ? Predicate : CmpInst::getInversePredicate(Predicate);
1336 ConstantRange TrueValues =
1337 ConstantRange::makeAllowedICmpRegion(Pred, RHSRange);
1338
1339 if (Offset) // Apply the offset from above.
1340 TrueValues = TrueValues.subtract(Offset->getValue());
1341
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001342 return LVILatticeVal::getRange(std::move(TrueValues));
Hal Finkel7e184492014-09-07 20:29:59 +00001343 }
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001344
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001345 return LVILatticeVal::getOverdefined();
Hal Finkel7e184492014-09-07 20:29:59 +00001346}
1347
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001348static LVILatticeVal
1349getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1350 DenseMap<Value*, LVILatticeVal> &Visited);
1351
1352static LVILatticeVal
1353getValueFromConditionImpl(Value *Val, Value *Cond, bool isTrueDest,
1354 DenseMap<Value*, LVILatticeVal> &Visited) {
1355 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
1356 return getValueFromICmpCondition(Val, ICI, isTrueDest);
1357
1358 // Handle conditions in the form of (cond1 && cond2), we know that on the
1359 // true dest path both of the conditions hold.
1360 if (!isTrueDest)
1361 return LVILatticeVal::getOverdefined();
1362
1363 BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond);
1364 if (!BO || BO->getOpcode() != BinaryOperator::And)
1365 return LVILatticeVal::getOverdefined();
1366
1367 auto RHS = getValueFromCondition(Val, BO->getOperand(0), isTrueDest, Visited);
1368 auto LHS = getValueFromCondition(Val, BO->getOperand(1), isTrueDest, Visited);
1369 return intersect(RHS, LHS);
1370}
1371
1372static LVILatticeVal
1373getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest,
1374 DenseMap<Value*, LVILatticeVal> &Visited) {
1375 auto I = Visited.find(Cond);
1376 if (I != Visited.end())
1377 return I->second;
Artur Pilipenkob6230882016-08-12 15:08:15 +00001378
1379 auto Result = getValueFromConditionImpl(Val, Cond, isTrueDest, Visited);
1380 Visited[Cond] = Result;
1381 return Result;
Artur Pilipenkofd223d52016-08-10 15:13:15 +00001382}
1383
1384LVILatticeVal getValueFromCondition(Value *Val, Value *Cond, bool isTrueDest) {
1385 assert(Cond && "precondition");
1386 DenseMap<Value*, LVILatticeVal> Visited;
1387 return getValueFromCondition(Val, Cond, isTrueDest, Visited);
1388}
1389
Nuno Lopese6e04902012-06-28 01:16:18 +00001390/// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
Philip Reames13f73242016-02-01 23:21:11 +00001391/// Val is not constrained on the edge. Result is unspecified if return value
1392/// is false.
Nuno Lopese6e04902012-06-28 01:16:18 +00001393static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1394 BasicBlock *BBTo, LVILatticeVal &Result) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001395 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
Chris Lattner77358782009-11-15 20:02:12 +00001396 // know that v != 0.
Chris Lattner19019ea2009-11-11 22:48:44 +00001397 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
1398 // If this is a conditional branch and only one successor goes to BBTo, then
Sanjay Patel938e2792015-01-09 16:35:37 +00001399 // we may be able to infer something from the condition.
Chris Lattner19019ea2009-11-11 22:48:44 +00001400 if (BI->isConditional() &&
1401 BI->getSuccessor(0) != BI->getSuccessor(1)) {
1402 bool isTrueDest = BI->getSuccessor(0) == BBTo;
1403 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1404 "BBTo isn't a successor of BBFrom");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001405
Chris Lattner19019ea2009-11-11 22:48:44 +00001406 // If V is the condition of the branch itself, then we know exactly what
1407 // it is.
Nick Lewycky55a700b2010-12-18 01:00:40 +00001408 if (BI->getCondition() == Val) {
1409 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson185fe002010-08-10 20:03:09 +00001410 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky55a700b2010-12-18 01:00:40 +00001411 return true;
1412 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001413
Chris Lattner19019ea2009-11-11 22:48:44 +00001414 // If the condition of the branch is an equality comparison, we may be
1415 // able to infer the value.
Artur Pilipenko933c07a2016-08-10 13:38:07 +00001416 Result = getValueFromCondition(Val, BI->getCondition(), isTrueDest);
1417 if (!Result.isOverdefined())
Artur Pilipenko2e19f592016-08-02 16:20:48 +00001418 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001419 }
1420 }
Chris Lattner77358782009-11-15 20:02:12 +00001421
1422 // If the edge was formed by a switch on the value, then we may know exactly
1423 // what it is.
1424 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Nuno Lopes8650fb82012-06-28 16:13:37 +00001425 if (SI->getCondition() != Val)
1426 return false;
1427
1428 bool DefaultCase = SI->getDefaultDest() == BBTo;
1429 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1430 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1431
Chandler Carruth927d8e62017-04-12 07:27:28 +00001432 for (auto Case : SI->cases()) {
1433 ConstantRange EdgeVal(Case.getCaseValue()->getValue());
Manman Renf3fedb62012-09-05 23:45:58 +00001434 if (DefaultCase) {
1435 // It is possible that the default destination is the destination of
1436 // some cases. There is no need to perform difference for those cases.
Chandler Carruth927d8e62017-04-12 07:27:28 +00001437 if (Case.getCaseSuccessor() != BBTo)
Manman Renf3fedb62012-09-05 23:45:58 +00001438 EdgesVals = EdgesVals.difference(EdgeVal);
Chandler Carruth927d8e62017-04-12 07:27:28 +00001439 } else if (Case.getCaseSuccessor() == BBTo)
Nuno Lopesac593802012-05-18 21:02:10 +00001440 EdgesVals = EdgesVals.unionWith(EdgeVal);
Chris Lattner77358782009-11-15 20:02:12 +00001441 }
Benjamin Kramer2337c1f2016-02-20 10:40:34 +00001442 Result = LVILatticeVal::getRange(std::move(EdgesVals));
Nuno Lopes8650fb82012-06-28 16:13:37 +00001443 return true;
Chris Lattner77358782009-11-15 20:02:12 +00001444 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001445 return false;
1446}
1447
Sanjay Patel938e2792015-01-09 16:35:37 +00001448/// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
1449/// the basic block if the edge does not constrain Val.
Philip Reames92e5e1b2016-09-12 21:46:58 +00001450bool LazyValueInfoImpl::getEdgeValue(Value *Val, BasicBlock *BBFrom,
Xin Tong68ea9aa2017-02-24 20:59:26 +00001451 BasicBlock *BBTo, LVILatticeVal &Result,
1452 Instruction *CxtI) {
Nuno Lopese6e04902012-06-28 01:16:18 +00001453 // If already a constant, there is nothing to compute.
1454 if (Constant *VC = dyn_cast<Constant>(Val)) {
1455 Result = LVILatticeVal::get(VC);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001456 return true;
1457 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001458
Philip Reames44456b82016-02-02 03:15:40 +00001459 LVILatticeVal LocalResult;
1460 if (!getEdgeValueLocal(Val, BBFrom, BBTo, LocalResult))
1461 // If we couldn't constrain the value on the edge, LocalResult doesn't
1462 // provide any information.
Philip Reames1baaef12016-12-06 03:01:08 +00001463 LocalResult = LVILatticeVal::getOverdefined();
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001464
Philip Reames44456b82016-02-02 03:15:40 +00001465 if (hasSingleValue(LocalResult)) {
1466 // Can't get any more precise here
1467 Result = LocalResult;
Nuno Lopese6e04902012-06-28 01:16:18 +00001468 return true;
1469 }
1470
1471 if (!hasBlockValue(Val, BBFrom)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +00001472 if (pushBlockValue(std::make_pair(BBFrom, Val)))
1473 return false;
Philip Reames44456b82016-02-02 03:15:40 +00001474 // No new information.
1475 Result = LocalResult;
Hans Wennborg45172ac2014-11-25 17:23:05 +00001476 return true;
Nuno Lopese6e04902012-06-28 01:16:18 +00001477 }
1478
Philip Reames44456b82016-02-02 03:15:40 +00001479 // Try to intersect ranges of the BB and the constraint on the edge.
1480 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001481 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock,
1482 BBFrom->getTerminator());
Hal Finkel2400c962014-10-16 00:40:05 +00001483 // We can use the context instruction (generically the ultimate instruction
1484 // the calling pass is trying to simplify) here, even though the result of
1485 // this function is generally cached when called from the solve* functions
1486 // (and that cached result might be used with queries using a different
1487 // context instruction), because when this function is called from the solve*
1488 // functions, the context instruction is not provided. When called from
Philip Reames92e5e1b2016-09-12 21:46:58 +00001489 // LazyValueInfoImpl::getValueOnEdge, the context instruction is provided,
Hal Finkel2400c962014-10-16 00:40:05 +00001490 // but then the result is not cached.
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001491 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CxtI);
Philip Reames44456b82016-02-02 03:15:40 +00001492
1493 Result = intersect(LocalResult, InBlock);
Nuno Lopese6e04902012-06-28 01:16:18 +00001494 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001495}
1496
Philip Reames92e5e1b2016-09-12 21:46:58 +00001497LVILatticeVal LazyValueInfoImpl::getValueInBlock(Value *V, BasicBlock *BB,
Hal Finkel7e184492014-09-07 20:29:59 +00001498 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001499 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001500 << BB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001501
Hans Wennborg45172ac2014-11-25 17:23:05 +00001502 assert(BlockValueStack.empty() && BlockValueSet.empty());
Philip Reamesbb781b42016-02-10 21:46:32 +00001503 if (!hasBlockValue(V, BB)) {
NAKAMURA Takumibd072a92016-07-25 00:59:46 +00001504 pushBlockValue(std::make_pair(BB, V));
Philip Reamesbb781b42016-02-10 21:46:32 +00001505 solve();
1506 }
Owen Andersonc7ed4dc2010-12-09 06:14:58 +00001507 LVILatticeVal Result = getBlockValue(V, BB);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001508 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001509
1510 DEBUG(dbgs() << " Result = " << Result << "\n");
1511 return Result;
1512}
1513
Philip Reames92e5e1b2016-09-12 21:46:58 +00001514LVILatticeVal LazyValueInfoImpl::getValueAt(Value *V, Instruction *CxtI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001515 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1516 << CxtI->getName() << "'\n");
1517
Philip Reamesbb781b42016-02-10 21:46:32 +00001518 if (auto *C = dyn_cast<Constant>(V))
1519 return LVILatticeVal::get(C);
1520
Philip Reamesd1f829d2016-02-02 21:57:37 +00001521 LVILatticeVal Result = LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +00001522 if (auto *I = dyn_cast<Instruction>(V))
1523 Result = getFromRangeMetadata(I);
Artur Pilipenko2e8f82d2016-08-12 15:52:23 +00001524 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
Philip Reames2c275cc2016-02-02 00:45:30 +00001525
David Greene37e98092009-12-23 20:43:58 +00001526 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001527 return Result;
1528}
Chris Lattner19019ea2009-11-11 22:48:44 +00001529
Philip Reames92e5e1b2016-09-12 21:46:58 +00001530LVILatticeVal LazyValueInfoImpl::
Hal Finkel7e184492014-09-07 20:29:59 +00001531getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1532 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001533 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001534 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001535
Nick Lewycky55a700b2010-12-18 01:00:40 +00001536 LVILatticeVal Result;
Hal Finkel7e184492014-09-07 20:29:59 +00001537 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +00001538 solve();
Hal Finkel7e184492014-09-07 20:29:59 +00001539 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001540 (void)WasFastQuery;
1541 assert(WasFastQuery && "More work to do after problem solved?");
1542 }
1543
David Greene37e98092009-12-23 20:43:58 +00001544 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001545 return Result;
1546}
1547
Philip Reames92e5e1b2016-09-12 21:46:58 +00001548void LazyValueInfoImpl::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Philip Reames9db79482016-09-12 22:38:44 +00001549 BasicBlock *NewSucc) {
1550 TheCache.threadEdgeImpl(OldSucc, NewSucc);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001551}
1552
Chris Lattneraf025d32009-11-15 19:59:49 +00001553//===----------------------------------------------------------------------===//
1554// LazyValueInfo Impl
1555//===----------------------------------------------------------------------===//
1556
Philip Reames92e5e1b2016-09-12 21:46:58 +00001557/// This lazily constructs the LazyValueInfoImpl.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001558static LazyValueInfoImpl &getImpl(void *&PImpl, AssumptionCache *AC,
1559 const DataLayout *DL,
Philip Reames92e5e1b2016-09-12 21:46:58 +00001560 DominatorTree *DT = nullptr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001561 if (!PImpl) {
1562 assert(DL && "getCache() called with a null DataLayout");
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001563 PImpl = new LazyValueInfoImpl(AC, *DL, DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001564 }
Philip Reames92e5e1b2016-09-12 21:46:58 +00001565 return *static_cast<LazyValueInfoImpl*>(PImpl);
Chris Lattneraf025d32009-11-15 19:59:49 +00001566}
1567
Sean Silva687019f2016-06-13 22:01:25 +00001568bool LazyValueInfoWrapperPass::runOnFunction(Function &F) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001569 Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001570 const DataLayout &DL = F.getParent()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001571
1572 DominatorTreeWrapperPass *DTWP =
1573 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Sean Silva687019f2016-06-13 22:01:25 +00001574 Info.DT = DTWP ? &DTWP->getDomTree() : nullptr;
1575 Info.TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chad Rosier43a33062011-12-02 01:26:24 +00001576
Sean Silva687019f2016-06-13 22:01:25 +00001577 if (Info.PImpl)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001578 getImpl(Info.PImpl, Info.AC, &DL, Info.DT).clear();
Hal Finkel7e184492014-09-07 20:29:59 +00001579
Owen Anderson208636f2010-08-18 18:39:01 +00001580 // Fully lazy.
1581 return false;
1582}
1583
Sean Silva687019f2016-06-13 22:01:25 +00001584void LazyValueInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chad Rosier43a33062011-12-02 01:26:24 +00001585 AU.setPreservesAll();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001586 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001587 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chad Rosier43a33062011-12-02 01:26:24 +00001588}
1589
Sean Silva687019f2016-06-13 22:01:25 +00001590LazyValueInfo &LazyValueInfoWrapperPass::getLVI() { return Info; }
1591
1592LazyValueInfo::~LazyValueInfo() { releaseMemory(); }
1593
Chris Lattneraf025d32009-11-15 19:59:49 +00001594void LazyValueInfo::releaseMemory() {
1595 // If the cache was allocated, free it.
1596 if (PImpl) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001597 delete &getImpl(PImpl, AC, nullptr);
Craig Topper9f008862014-04-15 04:59:12 +00001598 PImpl = nullptr;
Chris Lattneraf025d32009-11-15 19:59:49 +00001599 }
1600}
1601
Chandler Carrutha504f2b2017-01-23 06:35:12 +00001602bool LazyValueInfo::invalidate(Function &F, const PreservedAnalyses &PA,
1603 FunctionAnalysisManager::Invalidator &Inv) {
1604 // We need to invalidate if we have either failed to preserve this analyses
1605 // result directly or if any of its dependencies have been invalidated.
1606 auto PAC = PA.getChecker<LazyValueAnalysis>();
1607 if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
1608 (DT && Inv.invalidate<DominatorTreeAnalysis>(F, PA)))
1609 return true;
1610
1611 return false;
1612}
1613
Sean Silva687019f2016-06-13 22:01:25 +00001614void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
1615
1616LazyValueInfo LazyValueAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001617 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
Sean Silva687019f2016-06-13 22:01:25 +00001618 auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
1619 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
1620
Anna Thomasa10e3e42017-03-12 14:06:41 +00001621 return LazyValueInfo(&AC, &F.getParent()->getDataLayout(), &TLI, DT);
Sean Silva687019f2016-06-13 22:01:25 +00001622}
1623
Wei Mif160e342016-09-15 06:28:34 +00001624/// Returns true if we can statically tell that this value will never be a
1625/// "useful" constant. In practice, this means we've got something like an
1626/// alloca or a malloc call for which a comparison against a constant can
1627/// only be guarding dead code. Note that we are potentially giving up some
1628/// precision in dead code (a constant result) in favour of avoiding a
1629/// expensive search for a easily answered common query.
1630static bool isKnownNonConstant(Value *V) {
1631 V = V->stripPointerCasts();
1632 // The return val of alloc cannot be a Constant.
1633 if (isa<AllocaInst>(V))
1634 return true;
1635 return false;
1636}
1637
Hal Finkel7e184492014-09-07 20:29:59 +00001638Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1639 Instruction *CxtI) {
Wei Mif160e342016-09-15 06:28:34 +00001640 // Bail out early if V is known not to be a Constant.
1641 if (isKnownNonConstant(V))
1642 return nullptr;
1643
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001644 const DataLayout &DL = BB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001645 LVILatticeVal Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001646 getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001647
Chris Lattner19019ea2009-11-11 22:48:44 +00001648 if (Result.isConstant())
1649 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001650 if (Result.isConstantRange()) {
Craig Topper2b195fd2017-05-06 03:35:15 +00001651 const ConstantRange &CR = Result.getConstantRange();
Owen Anderson38f6b7f2010-08-27 23:29:38 +00001652 if (const APInt *SingleVal = CR.getSingleElement())
1653 return ConstantInt::get(V->getContext(), *SingleVal);
1654 }
Craig Topper9f008862014-04-15 04:59:12 +00001655 return nullptr;
Chris Lattner19019ea2009-11-11 22:48:44 +00001656}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001657
John Regehre1c481d2016-05-02 19:58:00 +00001658ConstantRange LazyValueInfo::getConstantRange(Value *V, BasicBlock *BB,
NAKAMURA Takumi940cd932016-07-04 01:26:21 +00001659 Instruction *CxtI) {
John Regehre1c481d2016-05-02 19:58:00 +00001660 assert(V->getType()->isIntegerTy());
1661 unsigned Width = V->getType()->getIntegerBitWidth();
1662 const DataLayout &DL = BB->getModule()->getDataLayout();
1663 LVILatticeVal Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001664 getImpl(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
John Regehre1c481d2016-05-02 19:58:00 +00001665 if (Result.isUndefined())
1666 return ConstantRange(Width, /*isFullSet=*/false);
1667 if (Result.isConstantRange())
1668 return Result.getConstantRange();
Artur Pilipenkoa4b6a702016-08-10 12:54:54 +00001669 // We represent ConstantInt constants as constant ranges but other kinds
1670 // of integer constants, i.e. ConstantExpr will be tagged as constants
1671 assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&
1672 "ConstantInt value must be represented as constantrange");
Davide Italianobd543d02016-05-25 22:29:34 +00001673 return ConstantRange(Width, /*isFullSet=*/true);
John Regehre1c481d2016-05-02 19:58:00 +00001674}
1675
Sanjay Patel2a385e22015-01-09 16:47:20 +00001676/// Determine whether the specified value is known to be a
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001677/// constant on the specified edge. Return null if not.
Chris Lattnerd5e25432009-11-12 01:29:10 +00001678Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
Hal Finkel7e184492014-09-07 20:29:59 +00001679 BasicBlock *ToBB,
1680 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001681 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001682 LVILatticeVal Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001683 getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001684
Chris Lattnerd5e25432009-11-12 01:29:10 +00001685 if (Result.isConstant())
1686 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001687 if (Result.isConstantRange()) {
Craig Topper2b195fd2017-05-06 03:35:15 +00001688 const ConstantRange &CR = Result.getConstantRange();
Owen Anderson185fe002010-08-10 20:03:09 +00001689 if (const APInt *SingleVal = CR.getSingleElement())
1690 return ConstantInt::get(V->getContext(), *SingleVal);
1691 }
Craig Topper9f008862014-04-15 04:59:12 +00001692 return nullptr;
Chris Lattnerd5e25432009-11-12 01:29:10 +00001693}
1694
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001695static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C,
1696 LVILatticeVal &Result,
1697 const DataLayout &DL,
1698 TargetLibraryInfo *TLI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001699
Chris Lattner565ee2f2009-11-12 04:36:58 +00001700 // If we know the value is a constant, evaluate the conditional.
Craig Topper9f008862014-04-15 04:59:12 +00001701 Constant *Res = nullptr;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001702 if (Result.isConstant()) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001703 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001704 TLI);
Nick Lewycky11678bd2010-12-15 18:57:18 +00001705 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Hal Finkel7e184492014-09-07 20:29:59 +00001706 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1707 return LazyValueInfo::Unknown;
Chris Lattneraf025d32009-11-15 19:59:49 +00001708 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001709
Owen Anderson185fe002010-08-10 20:03:09 +00001710 if (Result.isConstantRange()) {
Owen Andersonc62f7042010-08-24 07:55:44 +00001711 ConstantInt *CI = dyn_cast<ConstantInt>(C);
Hal Finkel7e184492014-09-07 20:29:59 +00001712 if (!CI) return LazyValueInfo::Unknown;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001713
Craig Topper2b195fd2017-05-06 03:35:15 +00001714 const ConstantRange &CR = Result.getConstantRange();
Owen Anderson185fe002010-08-10 20:03:09 +00001715 if (Pred == ICmpInst::ICMP_EQ) {
1716 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001717 return LazyValueInfo::False;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001718
Owen Anderson185fe002010-08-10 20:03:09 +00001719 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001720 return LazyValueInfo::True;
Owen Anderson185fe002010-08-10 20:03:09 +00001721 } else if (Pred == ICmpInst::ICMP_NE) {
1722 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001723 return LazyValueInfo::True;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001724
Owen Anderson185fe002010-08-10 20:03:09 +00001725 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001726 return LazyValueInfo::False;
Owen Anderson185fe002010-08-10 20:03:09 +00001727 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001728
Owen Anderson185fe002010-08-10 20:03:09 +00001729 // Handle more complex predicates.
Sanjoy Das1f7b8132016-10-02 00:09:57 +00001730 ConstantRange TrueValues = ConstantRange::makeExactICmpRegion(
1731 (ICmpInst::Predicate)Pred, CI->getValue());
Nick Lewycky11678bd2010-12-15 18:57:18 +00001732 if (TrueValues.contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001733 return LazyValueInfo::True;
Nick Lewycky11678bd2010-12-15 18:57:18 +00001734 if (TrueValues.inverse().contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001735 return LazyValueInfo::False;
1736 return LazyValueInfo::Unknown;
Owen Anderson185fe002010-08-10 20:03:09 +00001737 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001738
Chris Lattneraf025d32009-11-15 19:59:49 +00001739 if (Result.isNotConstant()) {
Chris Lattner565ee2f2009-11-12 04:36:58 +00001740 // If this is an equality comparison, we can try to fold it knowing that
1741 // "V != C1".
1742 if (Pred == ICmpInst::ICMP_EQ) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001743 // !C1 == C -> false iff C1 == C.
Chris Lattner565ee2f2009-11-12 04:36:58 +00001744 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001745 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001746 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001747 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001748 return LazyValueInfo::False;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001749 } else if (Pred == ICmpInst::ICMP_NE) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001750 // !C1 != C -> true iff C1 == C.
Chris Lattnerb0c0a0d2009-11-15 20:01:24 +00001751 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001752 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001753 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001754 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001755 return LazyValueInfo::True;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001756 }
Hal Finkel7e184492014-09-07 20:29:59 +00001757 return LazyValueInfo::Unknown;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001758 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001759
Hal Finkel7e184492014-09-07 20:29:59 +00001760 return LazyValueInfo::Unknown;
1761}
1762
Sanjay Patel2a385e22015-01-09 16:47:20 +00001763/// Determine whether the specified value comparison with a constant is known to
1764/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
Hal Finkel7e184492014-09-07 20:29:59 +00001765LazyValueInfo::Tristate
1766LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1767 BasicBlock *FromBB, BasicBlock *ToBB,
1768 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001769 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001770 LVILatticeVal Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001771 getImpl(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001772
1773 return getPredicateResult(Pred, C, Result, DL, TLI);
1774}
1775
1776LazyValueInfo::Tristate
1777LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1778 Instruction *CxtI) {
Wei Mif160e342016-09-15 06:28:34 +00001779 // Is or is not NonNull are common predicates being queried. If
1780 // isKnownNonNull can tell us the result of the predicate, we can
1781 // return it quickly. But this is only a fastpath, and falling
1782 // through would still be correct.
1783 if (V->getType()->isPointerTy() && C->isNullValue() &&
1784 isKnownNonNull(V->stripPointerCasts())) {
1785 if (Pred == ICmpInst::ICMP_EQ)
1786 return LazyValueInfo::False;
1787 else if (Pred == ICmpInst::ICMP_NE)
1788 return LazyValueInfo::True;
1789 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001790 const DataLayout &DL = CxtI->getModule()->getDataLayout();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001791 LVILatticeVal Result = getImpl(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
Philip Reames66ab0f02015-06-16 00:49:59 +00001792 Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1793 if (Ret != Unknown)
1794 return Ret;
Hal Finkel7e184492014-09-07 20:29:59 +00001795
Philip Reamesaeefae02015-11-04 01:47:04 +00001796 // Note: The following bit of code is somewhat distinct from the rest of LVI;
1797 // LVI as a whole tries to compute a lattice value which is conservatively
1798 // correct at a given location. In this case, we have a predicate which we
1799 // weren't able to prove about the merged result, and we're pushing that
1800 // predicate back along each incoming edge to see if we can prove it
1801 // separately for each input. As a motivating example, consider:
1802 // bb1:
1803 // %v1 = ... ; constantrange<1, 5>
1804 // br label %merge
1805 // bb2:
1806 // %v2 = ... ; constantrange<10, 20>
1807 // br label %merge
1808 // merge:
1809 // %phi = phi [%v1, %v2] ; constantrange<1,20>
1810 // %pred = icmp eq i32 %phi, 8
1811 // We can't tell from the lattice value for '%phi' that '%pred' is false
1812 // along each path, but by checking the predicate over each input separately,
1813 // we can.
1814 // We limit the search to one step backwards from the current BB and value.
1815 // We could consider extending this to search further backwards through the
1816 // CFG and/or value graph, but there are non-obvious compile time vs quality
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001817 // tradeoffs.
Philip Reames66ab0f02015-06-16 00:49:59 +00001818 if (CxtI) {
Philip Reamesbb11d622015-08-31 18:31:48 +00001819 BasicBlock *BB = CxtI->getParent();
1820
1821 // Function entry or an unreachable block. Bail to avoid confusing
1822 // analysis below.
1823 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1824 if (PI == PE)
1825 return Unknown;
1826
1827 // If V is a PHI node in the same block as the context, we need to ask
1828 // questions about the predicate as applied to the incoming value along
1829 // each edge. This is useful for eliminating cases where the predicate is
1830 // known along all incoming edges.
1831 if (auto *PHI = dyn_cast<PHINode>(V))
1832 if (PHI->getParent() == BB) {
1833 Tristate Baseline = Unknown;
1834 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1835 Value *Incoming = PHI->getIncomingValue(i);
1836 BasicBlock *PredBB = PHI->getIncomingBlock(i);
NAKAMURA Takumif2529512016-07-04 01:26:27 +00001837 // Note that PredBB may be BB itself.
Philip Reamesbb11d622015-08-31 18:31:48 +00001838 Tristate Result = getPredicateOnEdge(Pred, Incoming, C, PredBB, BB,
1839 CxtI);
NAKAMURA Takumi4cb46e62016-07-04 01:26:33 +00001840
Philip Reamesbb11d622015-08-31 18:31:48 +00001841 // Keep going as long as we've seen a consistent known result for
1842 // all inputs.
1843 Baseline = (i == 0) ? Result /* First iteration */
1844 : (Baseline == Result ? Baseline : Unknown); /* All others */
1845 if (Baseline == Unknown)
1846 break;
1847 }
1848 if (Baseline != Unknown)
1849 return Baseline;
NAKAMURA Takumibd072a92016-07-25 00:59:46 +00001850 }
Philip Reamesbb11d622015-08-31 18:31:48 +00001851
Philip Reames66ab0f02015-06-16 00:49:59 +00001852 // For a comparison where the V is outside this block, it's possible
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001853 // that we've branched on it before. Look to see if the value is known
Philip Reames66ab0f02015-06-16 00:49:59 +00001854 // on all incoming edges.
Philip Reamesbb11d622015-08-31 18:31:48 +00001855 if (!isa<Instruction>(V) ||
1856 cast<Instruction>(V)->getParent() != BB) {
Philip Reames66ab0f02015-06-16 00:49:59 +00001857 // For predecessor edge, determine if the comparison is true or false
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001858 // on that edge. If they're all true or all false, we can conclude
Philip Reames66ab0f02015-06-16 00:49:59 +00001859 // the value of the comparison in this block.
1860 Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1861 if (Baseline != Unknown) {
1862 // Check that all remaining incoming values match the first one.
1863 while (++PI != PE) {
1864 Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1865 if (Ret != Baseline) break;
1866 }
1867 // If we terminated early, then one of the values didn't match.
1868 if (PI == PE) {
1869 return Baseline;
1870 }
1871 }
1872 }
1873 }
1874 return Unknown;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001875}
1876
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001877void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky11678bd2010-12-15 18:57:18 +00001878 BasicBlock *NewSucc) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001879 if (PImpl) {
1880 const DataLayout &DL = PredBB->getModule()->getDataLayout();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001881 getImpl(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001882 }
Owen Anderson208636f2010-08-18 18:39:01 +00001883}
1884
1885void LazyValueInfo::eraseBlock(BasicBlock *BB) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001886 if (PImpl) {
1887 const DataLayout &DL = BB->getModule()->getDataLayout();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001888 getImpl(PImpl, AC, &DL, DT).eraseBlock(BB);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001889 }
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001890}
Anna Thomase27b39a2017-03-22 19:27:12 +00001891
1892
1893void LazyValueInfo::printCache(Function &F, raw_ostream &OS) {
1894 if (PImpl) {
1895 getImpl(PImpl, AC, DL, DT).printCache(F, OS);
1896 }
1897}
1898
1899namespace {
1900// Printer class for LazyValueInfo results.
1901class LazyValueInfoPrinter : public FunctionPass {
1902public:
1903 static char ID; // Pass identification, replacement for typeid
1904 LazyValueInfoPrinter() : FunctionPass(ID) {
1905 initializeLazyValueInfoPrinterPass(*PassRegistry::getPassRegistry());
1906 }
1907
1908 void getAnalysisUsage(AnalysisUsage &AU) const override {
1909 AU.setPreservesAll();
1910 AU.addRequired<LazyValueInfoWrapperPass>();
1911 }
1912
1913 bool runOnFunction(Function &F) override {
1914 dbgs() << "LVI for function '" << F.getName() << "':\n";
1915 auto &LVI = getAnalysis<LazyValueInfoWrapperPass>().getLVI();
1916 LVI.printCache(F, dbgs());
1917 return false;
1918 }
1919};
1920}
1921
1922char LazyValueInfoPrinter::ID = 0;
1923INITIALIZE_PASS_BEGIN(LazyValueInfoPrinter, "print-lazy-value-info",
1924 "Lazy Value Info Printer Pass", false, false)
1925INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
1926INITIALIZE_PASS_END(LazyValueInfoPrinter, "print-lazy-value-info",
1927 "Lazy Value Info Printer Pass", false, false)