blob: 3d8f4bf9e106022f8feffc75f2c63699e766378c [file] [log] [blame]
Hans Wennborgc5ec73d2014-11-21 18:58:23 +00001//===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===//
Chris Lattner741c94c2009-11-11 00:22:30 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interface for lazy computation of value constraint
11// information.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/LazyValueInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/STLExtras.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000018#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000020#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohmana4fcd242010-12-15 20:02:24 +000021#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000022#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000023#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
Hal Finkel7e184492014-09-07 20:29:59 +000026#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Instructions.h"
28#include "llvm/IR/IntrinsicInst.h"
Philip Reameseb3e9da2015-10-29 03:57:17 +000029#include "llvm/IR/LLVMContext.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000030#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000031#include "llvm/IR/ValueHandle.h"
Chris Lattnerb584d1e2009-11-12 01:22:16 +000032#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Support/raw_ostream.h"
Bill Wendling4ec081a2012-01-11 23:43:34 +000034#include <map>
Nick Lewycky55a700b2010-12-18 01:00:40 +000035#include <stack>
Chris Lattner741c94c2009-11-11 00:22:30 +000036using namespace llvm;
Benjamin Kramerd9d80b12012-03-02 15:34:43 +000037using namespace PatternMatch;
Chris Lattner741c94c2009-11-11 00:22:30 +000038
Chandler Carruthf1221bd2014-04-22 02:48:03 +000039#define DEBUG_TYPE "lazy-value-info"
40
Chris Lattner741c94c2009-11-11 00:22:30 +000041char LazyValueInfo::ID = 0;
Chad Rosier43a33062011-12-02 01:26:24 +000042INITIALIZE_PASS_BEGIN(LazyValueInfo, "lazy-value-info",
43 "Lazy Value Information Analysis", false, true)
Chandler Carruth66b31302015-01-04 12:03:27 +000044INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthb98f63d2015-01-15 10:41:28 +000045INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chad Rosier43a33062011-12-02 01:26:24 +000046INITIALIZE_PASS_END(LazyValueInfo, "lazy-value-info",
Owen Andersondf7a4f22010-10-07 22:25:06 +000047 "Lazy Value Information Analysis", false, true)
Chris Lattner741c94c2009-11-11 00:22:30 +000048
49namespace llvm {
50 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfo(); }
51}
52
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000053
54//===----------------------------------------------------------------------===//
55// LVILatticeVal
56//===----------------------------------------------------------------------===//
57
Sanjay Patel2a385e22015-01-09 16:47:20 +000058/// This is the information tracked by LazyValueInfo for each value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000059///
60/// FIXME: This is basically just for bringup, this can be made a lot more rich
61/// in the future.
62///
63namespace {
64class LVILatticeVal {
65 enum LatticeValueTy {
Sanjay Patel2a385e22015-01-09 16:47:20 +000066 /// This Value has no known value yet.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000067 undefined,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000068
Sanjay Patel2a385e22015-01-09 16:47:20 +000069 /// This Value has a specific constant value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000070 constant,
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000071
Sanjay Patel2a385e22015-01-09 16:47:20 +000072 /// This Value is known to not have the specified value.
Chris Lattner565ee2f2009-11-12 04:36:58 +000073 notconstant,
Chad Rosier43a33062011-12-02 01:26:24 +000074
Sanjay Patel2a385e22015-01-09 16:47:20 +000075 /// The Value falls within this range.
Owen Anderson0f306a42010-08-05 22:59:19 +000076 constantrange,
Chad Rosier43a33062011-12-02 01:26:24 +000077
Sanjay Patel2a385e22015-01-09 16:47:20 +000078 /// This value is not known to be constant, and we know that it has a value.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000079 overdefined
80 };
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000081
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000082 /// Val: This stores the current lattice value along with the Constant* for
Chris Lattner565ee2f2009-11-12 04:36:58 +000083 /// the constant if this is a 'constant' or 'notconstant' value.
Owen Andersonc3a14132010-08-05 22:10:46 +000084 LatticeValueTy Tag;
85 Constant *Val;
Owen Anderson0f306a42010-08-05 22:59:19 +000086 ConstantRange Range;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +000087
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000088public:
Craig Topper9f008862014-04-15 04:59:12 +000089 LVILatticeVal() : Tag(undefined), Val(nullptr), Range(1, true) {}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +000090
Chris Lattner19019ea2009-11-11 22:48:44 +000091 static LVILatticeVal get(Constant *C) {
92 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +000093 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +000094 Res.markConstant(C);
Chris Lattner19019ea2009-11-11 22:48:44 +000095 return Res;
96 }
Chris Lattner565ee2f2009-11-12 04:36:58 +000097 static LVILatticeVal getNot(Constant *C) {
98 LVILatticeVal Res;
Nick Lewycky11678bd2010-12-15 18:57:18 +000099 if (!isa<UndefValue>(C))
Owen Anderson185fe002010-08-10 20:03:09 +0000100 Res.markNotConstant(C);
Chris Lattner565ee2f2009-11-12 04:36:58 +0000101 return Res;
102 }
Owen Anderson5f1dd092010-08-10 23:20:01 +0000103 static LVILatticeVal getRange(ConstantRange CR) {
104 LVILatticeVal Res;
105 Res.markConstantRange(CR);
106 return Res;
107 }
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000108 static LVILatticeVal getOverdefined() {
109 LVILatticeVal Res;
110 Res.markOverdefined();
111 return Res;
112 }
113
Owen Anderson0f306a42010-08-05 22:59:19 +0000114 bool isUndefined() const { return Tag == undefined; }
115 bool isConstant() const { return Tag == constant; }
116 bool isNotConstant() const { return Tag == notconstant; }
117 bool isConstantRange() const { return Tag == constantrange; }
118 bool isOverdefined() const { return Tag == overdefined; }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000119
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000120 Constant *getConstant() const {
121 assert(isConstant() && "Cannot get the constant of a non-constant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000122 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000123 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000124
Chris Lattner565ee2f2009-11-12 04:36:58 +0000125 Constant *getNotConstant() const {
126 assert(isNotConstant() && "Cannot get the constant of a non-notconstant!");
Owen Andersonc3a14132010-08-05 22:10:46 +0000127 return Val;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000128 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000129
Owen Anderson0f306a42010-08-05 22:59:19 +0000130 ConstantRange getConstantRange() const {
131 assert(isConstantRange() &&
132 "Cannot get the constant-range of a non-constant-range!");
133 return Range;
134 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000135
Sanjay Patel2a385e22015-01-09 16:47:20 +0000136 /// Return true if this is a change in status.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000137 bool markOverdefined() {
138 if (isOverdefined())
139 return false;
Owen Andersonc3a14132010-08-05 22:10:46 +0000140 Tag = overdefined;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000141 return true;
142 }
143
Sanjay Patel2a385e22015-01-09 16:47:20 +0000144 /// Return true if this is a change in status.
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000145 bool markConstant(Constant *V) {
Nick Lewycky11678bd2010-12-15 18:57:18 +0000146 assert(V && "Marking constant with NULL");
147 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
148 return markConstantRange(ConstantRange(CI->getValue()));
149 if (isa<UndefValue>(V))
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000150 return false;
Nick Lewycky11678bd2010-12-15 18:57:18 +0000151
152 assert((!isConstant() || getConstant() == V) &&
153 "Marking constant with different value");
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000154 assert(isUndefined());
Owen Andersonc3a14132010-08-05 22:10:46 +0000155 Tag = constant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000156 Val = V;
Chris Lattner19019ea2009-11-11 22:48:44 +0000157 return true;
158 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000159
Sanjay Patel2a385e22015-01-09 16:47:20 +0000160 /// Return true if this is a change in status.
Chris Lattner565ee2f2009-11-12 04:36:58 +0000161 bool markNotConstant(Constant *V) {
Chris Lattner565ee2f2009-11-12 04:36:58 +0000162 assert(V && "Marking constant with NULL");
Nick Lewycky11678bd2010-12-15 18:57:18 +0000163 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
164 return markConstantRange(ConstantRange(CI->getValue()+1, CI->getValue()));
165 if (isa<UndefValue>(V))
166 return false;
167
168 assert((!isConstant() || getConstant() != V) &&
169 "Marking constant !constant with same value");
170 assert((!isNotConstant() || getNotConstant() == V) &&
171 "Marking !constant with different value");
172 assert(isUndefined() || isConstant());
173 Tag = notconstant;
Owen Andersonc3a14132010-08-05 22:10:46 +0000174 Val = V;
Chris Lattner565ee2f2009-11-12 04:36:58 +0000175 return true;
176 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000177
Sanjay Patel2a385e22015-01-09 16:47:20 +0000178 /// Return true if this is a change in status.
Owen Anderson0f306a42010-08-05 22:59:19 +0000179 bool markConstantRange(const ConstantRange NewR) {
180 if (isConstantRange()) {
181 if (NewR.isEmptySet())
182 return markOverdefined();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000183
Nuno Lopese6e04902012-06-28 01:16:18 +0000184 bool changed = Range != NewR;
Owen Anderson0f306a42010-08-05 22:59:19 +0000185 Range = NewR;
186 return changed;
187 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000188
Owen Anderson0f306a42010-08-05 22:59:19 +0000189 assert(isUndefined());
190 if (NewR.isEmptySet())
191 return markOverdefined();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000192
Owen Anderson0f306a42010-08-05 22:59:19 +0000193 Tag = constantrange;
194 Range = NewR;
195 return true;
196 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000197
Sanjay Patel2a385e22015-01-09 16:47:20 +0000198 /// Merge the specified lattice value into this one, updating this
Chris Lattner19019ea2009-11-11 22:48:44 +0000199 /// one and returning true if anything changed.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000200 bool mergeIn(const LVILatticeVal &RHS, const DataLayout &DL) {
Chris Lattner19019ea2009-11-11 22:48:44 +0000201 if (RHS.isUndefined() || isOverdefined()) return false;
202 if (RHS.isOverdefined()) return markOverdefined();
203
Nick Lewycky11678bd2010-12-15 18:57:18 +0000204 if (isUndefined()) {
205 Tag = RHS.Tag;
206 Val = RHS.Val;
207 Range = RHS.Range;
208 return true;
Chris Lattner22db4b52009-11-12 04:57:13 +0000209 }
210
Nick Lewycky11678bd2010-12-15 18:57:18 +0000211 if (isConstant()) {
212 if (RHS.isConstant()) {
213 if (Val == RHS.Val)
214 return false;
215 return markOverdefined();
216 }
217
218 if (RHS.isNotConstant()) {
219 if (Val == RHS.Val)
220 return markOverdefined();
221
222 // Unless we can prove that the two Constants are different, we must
223 // move to overdefined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000224 if (ConstantInt *Res =
225 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
226 CmpInst::ICMP_NE, getConstant(), RHS.getNotConstant(), DL)))
Nick Lewycky11678bd2010-12-15 18:57:18 +0000227 if (Res->isOne())
228 return markNotConstant(RHS.getNotConstant());
229
230 return markOverdefined();
231 }
232
233 // RHS is a ConstantRange, LHS is a non-integer Constant.
234
235 // FIXME: consider the case where RHS is a range [1, 0) and LHS is
236 // a function. The correct result is to pick up RHS.
237
Chris Lattner19019ea2009-11-11 22:48:44 +0000238 return markOverdefined();
Nick Lewycky11678bd2010-12-15 18:57:18 +0000239 }
240
241 if (isNotConstant()) {
242 if (RHS.isConstant()) {
243 if (Val == RHS.Val)
244 return markOverdefined();
245
246 // Unless we can prove that the two Constants are different, we must
247 // move to overdefined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000248 if (ConstantInt *Res =
249 dyn_cast<ConstantInt>(ConstantFoldCompareInstOperands(
250 CmpInst::ICMP_NE, getNotConstant(), RHS.getConstant(), DL)))
Nick Lewycky11678bd2010-12-15 18:57:18 +0000251 if (Res->isOne())
252 return false;
253
254 return markOverdefined();
255 }
256
257 if (RHS.isNotConstant()) {
258 if (Val == RHS.Val)
259 return false;
260 return markOverdefined();
261 }
262
263 return markOverdefined();
264 }
265
266 assert(isConstantRange() && "New LVILattice type?");
267 if (!RHS.isConstantRange())
268 return markOverdefined();
269
270 ConstantRange NewR = Range.unionWith(RHS.getConstantRange());
271 if (NewR.isFullSet())
272 return markOverdefined();
273 return markConstantRange(NewR);
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000274 }
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000275};
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000276
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000277} // end anonymous namespace.
278
Chris Lattner19019ea2009-11-11 22:48:44 +0000279namespace llvm {
Chandler Carruth2b1ba482011-04-18 18:49:44 +0000280raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val)
281 LLVM_ATTRIBUTE_USED;
Chris Lattner19019ea2009-11-11 22:48:44 +0000282raw_ostream &operator<<(raw_ostream &OS, const LVILatticeVal &Val) {
283 if (Val.isUndefined())
284 return OS << "undefined";
285 if (Val.isOverdefined())
286 return OS << "overdefined";
Chris Lattner565ee2f2009-11-12 04:36:58 +0000287
288 if (Val.isNotConstant())
289 return OS << "notconstant<" << *Val.getNotConstant() << '>';
Owen Anderson8afac042010-08-09 20:50:46 +0000290 else if (Val.isConstantRange())
291 return OS << "constantrange<" << Val.getConstantRange().getLower() << ", "
292 << Val.getConstantRange().getUpper() << '>';
Chris Lattner19019ea2009-11-11 22:48:44 +0000293 return OS << "constant<" << *Val.getConstant() << '>';
294}
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000295}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000296
Philip Reamesd1f829d2016-02-02 21:57:37 +0000297static LVILatticeVal intersect(LVILatticeVal A, LVILatticeVal B);
298
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000299//===----------------------------------------------------------------------===//
Chris Lattneraf025d32009-11-15 19:59:49 +0000300// LazyValueInfoCache Decl
Chris Lattnerfde1f8d2009-11-11 02:08:33 +0000301//===----------------------------------------------------------------------===//
302
Chris Lattneraf025d32009-11-15 19:59:49 +0000303namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000304 /// A callback value handle updates the cache when values are erased.
Owen Anderson118ac802011-01-05 21:15:29 +0000305 class LazyValueInfoCache;
David Blaikie774b5842015-08-03 22:30:24 +0000306 struct LVIValueHandle final : public CallbackVH {
Owen Anderson118ac802011-01-05 21:15:29 +0000307 LazyValueInfoCache *Parent;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000308
Owen Anderson118ac802011-01-05 21:15:29 +0000309 LVIValueHandle(Value *V, LazyValueInfoCache *P)
310 : CallbackVH(V), Parent(P) { }
Craig Toppere9ba7592014-03-05 07:30:04 +0000311
312 void deleted() override;
313 void allUsesReplacedWith(Value *V) override {
Owen Anderson118ac802011-01-05 21:15:29 +0000314 deleted();
315 }
316 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000317}
Owen Anderson118ac802011-01-05 21:15:29 +0000318
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000319namespace {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000320 /// This is the cache kept by LazyValueInfo which
Chris Lattneraf025d32009-11-15 19:59:49 +0000321 /// maintains information about queries across the clients' queries.
322 class LazyValueInfoCache {
Sanjay Patel2a385e22015-01-09 16:47:20 +0000323 /// This is all of the cached block information for exactly one Value*.
324 /// The entries are sorted by the BasicBlock* of the
Chris Lattneraf025d32009-11-15 19:59:49 +0000325 /// entries, allowing us to do a lookup with a binary search.
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000326 /// Over-defined lattice values are recorded in OverDefinedCache to reduce
327 /// memory overhead.
Bruno Cardoso Lopes1846ea32015-08-18 16:54:36 +0000328 typedef SmallDenseMap<AssertingVH<BasicBlock>, LVILatticeVal, 4>
329 ValueCacheEntryTy;
Chris Lattneraf025d32009-11-15 19:59:49 +0000330
Sanjay Patel2a385e22015-01-09 16:47:20 +0000331 /// This is all of the cached information for all values,
Owen Anderson6f060af2011-01-05 23:26:22 +0000332 /// mapped from Value* to key information.
Bill Wendling58c75692012-01-12 01:41:03 +0000333 std::map<LVIValueHandle, ValueCacheEntryTy> ValueCache;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000334
Sanjay Patel2a385e22015-01-09 16:47:20 +0000335 /// This tracks, on a per-block basis, the set of values that are
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000336 /// over-defined at the end of that block.
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000337 typedef DenseMap<AssertingVH<BasicBlock>, SmallPtrSet<Value *, 4>>
338 OverDefinedCacheTy;
339 OverDefinedCacheTy OverDefinedCache;
Benjamin Kramer36647082011-12-03 15:16:45 +0000340
Sanjay Patel2a385e22015-01-09 16:47:20 +0000341 /// Keep track of all blocks that we have ever seen, so we
Benjamin Kramer36647082011-12-03 15:16:45 +0000342 /// don't spend time removing unused blocks from our caches.
343 DenseSet<AssertingVH<BasicBlock> > SeenBlocks;
344
Sanjay Patel2a385e22015-01-09 16:47:20 +0000345 /// This stack holds the state of the value solver during a query.
346 /// It basically emulates the callstack of the naive
Owen Anderson6f060af2011-01-05 23:26:22 +0000347 /// recursive value lookup process.
348 std::stack<std::pair<BasicBlock*, Value*> > BlockValueStack;
Hal Finkel7e184492014-09-07 20:29:59 +0000349
Sanjay Patel2a385e22015-01-09 16:47:20 +0000350 /// Keeps track of which block-value pairs are in BlockValueStack.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000351 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
352
Sanjay Patel2a385e22015-01-09 16:47:20 +0000353 /// Push BV onto BlockValueStack unless it's already in there.
354 /// Returns true on success.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000355 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
Benjamin Kramer4e3b9032015-02-27 21:43:14 +0000356 if (!BlockValueSet.insert(BV).second)
Hans Wennborg45172ac2014-11-25 17:23:05 +0000357 return false; // It's already in the stack.
358
Philip Reames44456b82016-02-02 03:15:40 +0000359 DEBUG(dbgs() << "PUSH: " << *BV.second << " in " << BV.first->getName()
360 << "\n");
Hans Wennborg45172ac2014-11-25 17:23:05 +0000361 BlockValueStack.push(BV);
Hans Wennborg45172ac2014-11-25 17:23:05 +0000362 return true;
363 }
364
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000365 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
366 const DataLayout &DL; ///< A mandatory DataLayout
367 DominatorTree *DT; ///< An optional DT pointer.
368
Owen Anderson118ac802011-01-05 21:15:29 +0000369 friend struct LVIValueHandle;
Owen Anderson6f060af2011-01-05 23:26:22 +0000370
Hans Wennborg45172ac2014-11-25 17:23:05 +0000371 void insertResult(Value *Val, BasicBlock *BB, const LVILatticeVal &Result) {
372 SeenBlocks.insert(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000373
374 // Insert over-defined values into their own cache to reduce memory
375 // overhead.
Hans Wennborg45172ac2014-11-25 17:23:05 +0000376 if (Result.isOverdefined())
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000377 OverDefinedCache[BB].insert(Val);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000378 else
379 lookup(Val)[BB] = Result;
Hans Wennborg45172ac2014-11-25 17:23:05 +0000380 }
Owen Andersonc1561b82010-07-30 23:59:40 +0000381
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000382 LVILatticeVal getBlockValue(Value *Val, BasicBlock *BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000383 bool getEdgeValue(Value *V, BasicBlock *F, BasicBlock *T,
Hal Finkel7e184492014-09-07 20:29:59 +0000384 LVILatticeVal &Result,
385 Instruction *CxtI = nullptr);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000386 bool hasBlockValue(Value *Val, BasicBlock *BB);
387
388 // These methods process one work item and may add more. A false value
389 // returned means that the work item was not completely processed and must
390 // be revisited after going through the new items.
391 bool solveBlockValue(Value *Val, BasicBlock *BB);
Owen Anderson64c2c572010-12-20 18:18:16 +0000392 bool solveBlockValueNonLocal(LVILatticeVal &BBLV,
393 Value *Val, BasicBlock *BB);
394 bool solveBlockValuePHINode(LVILatticeVal &BBLV,
395 PHINode *PN, BasicBlock *BB);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000396 bool solveBlockValueSelect(LVILatticeVal &BBLV,
397 SelectInst *S, BasicBlock *BB);
Owen Anderson64c2c572010-12-20 18:18:16 +0000398 bool solveBlockValueConstantRange(LVILatticeVal &BBLV,
399 Instruction *BBI, BasicBlock *BB);
Philip Reamesd1f829d2016-02-02 21:57:37 +0000400 void intersectAssumeBlockValueConstantRange(Value *Val, LVILatticeVal &BBLV,
Hal Finkel7e184492014-09-07 20:29:59 +0000401 Instruction *BBI);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000402
403 void solve();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000404
Nick Lewycky11678bd2010-12-15 18:57:18 +0000405 ValueCacheEntryTy &lookup(Value *V) {
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000406 return ValueCache[LVIValueHandle(V, this)];
407 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000408
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000409 bool isOverdefined(Value *V, BasicBlock *BB) const {
410 auto ODI = OverDefinedCache.find(BB);
411
412 if (ODI == OverDefinedCache.end())
413 return false;
414
415 return ODI->second.count(V);
416 }
417
418 bool hasCachedValueInfo(Value *V, BasicBlock *BB) {
419 if (isOverdefined(V, BB))
420 return true;
421
422 LVIValueHandle ValHandle(V, this);
423 auto I = ValueCache.find(ValHandle);
424 if (I == ValueCache.end())
425 return false;
426
427 return I->second.count(BB);
428 }
429
430 LVILatticeVal getCachedValueInfo(Value *V, BasicBlock *BB) {
431 if (isOverdefined(V, BB))
432 return LVILatticeVal::getOverdefined();
433
434 return lookup(V)[BB];
435 }
436
Chris Lattneraf025d32009-11-15 19:59:49 +0000437 public:
Sanjay Patel2a385e22015-01-09 16:47:20 +0000438 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000439 /// value for the specified Value* at the end of the specified block.
Hal Finkel7e184492014-09-07 20:29:59 +0000440 LVILatticeVal getValueInBlock(Value *V, BasicBlock *BB,
441 Instruction *CxtI = nullptr);
442
Sanjay Patel2a385e22015-01-09 16:47:20 +0000443 /// This is the query interface to determine the lattice
Hal Finkel7e184492014-09-07 20:29:59 +0000444 /// value for the specified Value* at the specified instruction (generally
445 /// from an assume intrinsic).
446 LVILatticeVal getValueAt(Value *V, Instruction *CxtI);
Chris Lattneraf025d32009-11-15 19:59:49 +0000447
Sanjay Patel2a385e22015-01-09 16:47:20 +0000448 /// This is the query interface to determine the lattice
Chris Lattneraf025d32009-11-15 19:59:49 +0000449 /// value for the specified Value* that is true on the specified edge.
Hal Finkel7e184492014-09-07 20:29:59 +0000450 LVILatticeVal getValueOnEdge(Value *V, BasicBlock *FromBB,BasicBlock *ToBB,
451 Instruction *CxtI = nullptr);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000452
Sanjay Patel2a385e22015-01-09 16:47:20 +0000453 /// This is the update interface to inform the cache that an edge from
454 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
Owen Andersonaa7f66b2010-07-26 18:48:03 +0000455 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000456
Sanjay Patel2a385e22015-01-09 16:47:20 +0000457 /// This is part of the update interface to inform the cache
Owen Anderson208636f2010-08-18 18:39:01 +0000458 /// that a block has been deleted.
459 void eraseBlock(BasicBlock *BB);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000460
Owen Anderson208636f2010-08-18 18:39:01 +0000461 /// clear - Empty the cache.
462 void clear() {
Benjamin Kramerbbf3c602011-12-03 15:19:55 +0000463 SeenBlocks.clear();
Owen Anderson208636f2010-08-18 18:39:01 +0000464 ValueCache.clear();
465 OverDefinedCache.clear();
466 }
Hal Finkel7e184492014-09-07 20:29:59 +0000467
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000468 LazyValueInfoCache(AssumptionCache *AC, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000469 DominatorTree *DT = nullptr)
470 : AC(AC), DL(DL), DT(DT) {}
Chris Lattneraf025d32009-11-15 19:59:49 +0000471 };
472} // end anonymous namespace
473
Owen Anderson118ac802011-01-05 21:15:29 +0000474void LVIValueHandle::deleted() {
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000475 SmallVector<AssertingVH<BasicBlock>, 4> ToErase;
476 for (auto &I : Parent->OverDefinedCache) {
477 SmallPtrSetImpl<Value *> &ValueSet = I.second;
478 if (ValueSet.count(getValPtr()))
479 ValueSet.erase(getValPtr());
480 if (ValueSet.empty())
481 ToErase.push_back(I.first);
482 }
483 for (auto &BB : ToErase)
484 Parent->OverDefinedCache.erase(BB);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000485
Owen Anderson7b974a42010-08-11 22:36:04 +0000486 // This erasure deallocates *this, so it MUST happen after we're done
487 // using any and all members of *this.
488 Parent->ValueCache.erase(*this);
Owen Andersonc1561b82010-07-30 23:59:40 +0000489}
490
Owen Anderson208636f2010-08-18 18:39:01 +0000491void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
Benjamin Kramer36647082011-12-03 15:16:45 +0000492 // Shortcut if we have never seen this block.
493 DenseSet<AssertingVH<BasicBlock> >::iterator I = SeenBlocks.find(BB);
494 if (I == SeenBlocks.end())
495 return;
496 SeenBlocks.erase(I);
497
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000498 auto ODI = OverDefinedCache.find(BB);
499 if (ODI != OverDefinedCache.end())
500 OverDefinedCache.erase(ODI);
Owen Anderson208636f2010-08-18 18:39:01 +0000501
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +0000502 for (auto I = ValueCache.begin(), E = ValueCache.end(); I != E; ++I)
Owen Anderson208636f2010-08-18 18:39:01 +0000503 I->second.erase(BB);
504}
Owen Andersonc1561b82010-07-30 23:59:40 +0000505
Nick Lewycky55a700b2010-12-18 01:00:40 +0000506void LazyValueInfoCache::solve() {
Owen Anderson6f060af2011-01-05 23:26:22 +0000507 while (!BlockValueStack.empty()) {
508 std::pair<BasicBlock*, Value*> &e = BlockValueStack.top();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000509 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
510
Nuno Lopese6e04902012-06-28 01:16:18 +0000511 if (solveBlockValue(e.second, e.first)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000512 // The work item was completely processed.
513 assert(BlockValueStack.top() == e && "Nothing should have been pushed!");
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000514 assert(hasCachedValueInfo(e.second, e.first) &&
515 "Result should be in cache!");
Hans Wennborg45172ac2014-11-25 17:23:05 +0000516
Philip Reames44456b82016-02-02 03:15:40 +0000517 DEBUG(dbgs() << "POP " << *e.second << " in " << e.first->getName()
518 << " = " << lookup(e.second)[e.first] << "\n");
519
Owen Anderson6f060af2011-01-05 23:26:22 +0000520 BlockValueStack.pop();
Hans Wennborg45172ac2014-11-25 17:23:05 +0000521 BlockValueSet.erase(e);
522 } else {
523 // More work needs to be done before revisiting.
524 assert(BlockValueStack.top() != e && "Stack should have been pushed!");
Nuno Lopese6e04902012-06-28 01:16:18 +0000525 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000526 }
527}
528
529bool LazyValueInfoCache::hasBlockValue(Value *Val, BasicBlock *BB) {
530 // If already a constant, there is nothing to compute.
531 if (isa<Constant>(Val))
532 return true;
533
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000534 return hasCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000535}
536
Owen Andersonc7ed4dc2010-12-09 06:14:58 +0000537LVILatticeVal LazyValueInfoCache::getBlockValue(Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000538 // If already a constant, there is nothing to compute.
539 if (Constant *VC = dyn_cast<Constant>(Val))
540 return LVILatticeVal::get(VC);
541
Benjamin Kramer36647082011-12-03 15:16:45 +0000542 SeenBlocks.insert(BB);
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000543 return getCachedValueInfo(Val, BB);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000544}
545
Philip Reameseb3e9da2015-10-29 03:57:17 +0000546static LVILatticeVal getFromRangeMetadata(Instruction *BBI) {
547 switch (BBI->getOpcode()) {
548 default: break;
549 case Instruction::Load:
550 case Instruction::Call:
551 case Instruction::Invoke:
552 if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
Philip Reames70efccd2015-10-29 04:21:49 +0000553 if (isa<IntegerType>(BBI->getType())) {
Philip Reameseb3e9da2015-10-29 03:57:17 +0000554 ConstantRange Result = getConstantRangeFromMetadata(*Ranges);
555 return LVILatticeVal::getRange(Result);
556 }
557 break;
558 };
Philip Reamesd1f829d2016-02-02 21:57:37 +0000559 // Nothing known - will be intersected with other facts
560 return LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +0000561}
562
Nick Lewycky55a700b2010-12-18 01:00:40 +0000563bool LazyValueInfoCache::solveBlockValue(Value *Val, BasicBlock *BB) {
564 if (isa<Constant>(Val))
565 return true;
566
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000567 if (hasCachedValueInfo(Val, BB)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000568 // If we have a cached value, use that.
569 DEBUG(dbgs() << " reuse BB '" << BB->getName()
Akira Hatanaka2992bee2015-12-11 00:49:47 +0000570 << "' val=" << getCachedValueInfo(Val, BB) << '\n');
Nick Lewycky55a700b2010-12-18 01:00:40 +0000571
Hans Wennborg45172ac2014-11-25 17:23:05 +0000572 // Since we're reusing a cached value, we don't need to update the
573 // OverDefinedCache. The cache will have been properly updated whenever the
574 // cached value was inserted.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000575 return true;
Chris Lattner2c708562009-11-15 20:00:52 +0000576 }
577
Hans Wennborg45172ac2014-11-25 17:23:05 +0000578 // Hold off inserting this value into the Cache in case we have to return
579 // false and come back later.
580 LVILatticeVal Res;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000581
Chris Lattneraf025d32009-11-15 19:59:49 +0000582 Instruction *BBI = dyn_cast<Instruction>(Val);
Craig Topper9f008862014-04-15 04:59:12 +0000583 if (!BBI || BBI->getParent() != BB) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000584 if (!solveBlockValueNonLocal(Res, Val, BB))
585 return false;
586 insertResult(Val, BB, Res);
587 return true;
Chris Lattneraf025d32009-11-15 19:59:49 +0000588 }
Chris Lattner2c708562009-11-15 20:00:52 +0000589
Nick Lewycky55a700b2010-12-18 01:00:40 +0000590 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000591 if (!solveBlockValuePHINode(Res, PN, BB))
592 return false;
593 insertResult(Val, BB, Res);
594 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000595 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000596
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000597 if (auto *SI = dyn_cast<SelectInst>(BBI)) {
598 if (!solveBlockValueSelect(Res, SI, BB))
599 return false;
600 insertResult(Val, BB, Res);
601 return true;
602 }
603
Igor Laevsky0fa48192015-09-18 13:01:48 +0000604 // If this value is a nonnull pointer, record it's range and bailout.
605 PointerType *PT = dyn_cast<PointerType>(BBI->getType());
606 if (PT && isKnownNonNull(BBI)) {
607 Res = LVILatticeVal::getNot(ConstantPointerNull::get(PT));
Hans Wennborg45172ac2014-11-25 17:23:05 +0000608 insertResult(Val, BB, Res);
609 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000610 }
611
Philip Reamesd1f829d2016-02-02 21:57:37 +0000612 // If this is an instruction which supports range metadata, intersect the
613 // implied range.
614 Res = intersect(Res, getFromRangeMetadata(BBI));
Philip Reameseb3e9da2015-10-29 03:57:17 +0000615
Owen Anderson80d19f02010-08-18 21:11:37 +0000616 // We can only analyze the definitions of certain classes of instructions
617 // (integral binops and casts at the moment), so bail if this isn't one.
Chris Lattneraf025d32009-11-15 19:59:49 +0000618 LVILatticeVal Result;
Owen Anderson80d19f02010-08-18 21:11:37 +0000619 if ((!isa<BinaryOperator>(BBI) && !isa<CastInst>(BBI)) ||
620 !BBI->getType()->isIntegerTy()) {
621 DEBUG(dbgs() << " compute BB '" << BB->getName()
622 << "' - overdefined because inst def found.\n");
Hans Wennborg45172ac2014-11-25 17:23:05 +0000623 Res.markOverdefined();
624 insertResult(Val, BB, Res);
625 return true;
Owen Anderson80d19f02010-08-18 21:11:37 +0000626 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000627
Owen Anderson80d19f02010-08-18 21:11:37 +0000628 // FIXME: We're currently limited to binops with a constant RHS. This should
629 // be improved.
630 BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI);
631 if (BO && !isa<ConstantInt>(BO->getOperand(1))) {
632 DEBUG(dbgs() << " compute BB '" << BB->getName()
633 << "' - overdefined because inst def found.\n");
634
Hans Wennborg45172ac2014-11-25 17:23:05 +0000635 Res.markOverdefined();
636 insertResult(Val, BB, Res);
637 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000638 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000639
Hans Wennborg45172ac2014-11-25 17:23:05 +0000640 if (!solveBlockValueConstantRange(Res, BBI, BB))
641 return false;
642 insertResult(Val, BB, Res);
643 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000644}
645
646static bool InstructionDereferencesPointer(Instruction *I, Value *Ptr) {
647 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
648 return L->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000649 GetUnderlyingObject(L->getPointerOperand(),
650 L->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000651 }
652 if (StoreInst *S = dyn_cast<StoreInst>(I)) {
653 return S->getPointerAddressSpace() == 0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000654 GetUnderlyingObject(S->getPointerOperand(),
655 S->getModule()->getDataLayout()) == Ptr;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000656 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000657 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
658 if (MI->isVolatile()) return false;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000659
660 // FIXME: check whether it has a valuerange that excludes zero?
661 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
662 if (!Len || Len->isZero()) return false;
663
Eli Friedman7a5fc692011-05-31 20:40:16 +0000664 if (MI->getDestAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000665 if (GetUnderlyingObject(MI->getRawDest(),
666 MI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000667 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000668 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Eli Friedman7a5fc692011-05-31 20:40:16 +0000669 if (MTI->getSourceAddressSpace() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000670 if (GetUnderlyingObject(MTI->getRawSource(),
671 MTI->getModule()->getDataLayout()) == Ptr)
Eli Friedman7a5fc692011-05-31 20:40:16 +0000672 return true;
Nick Lewycky367f98f2011-01-15 09:16:12 +0000673 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000674 return false;
675}
676
Owen Anderson64c2c572010-12-20 18:18:16 +0000677bool LazyValueInfoCache::solveBlockValueNonLocal(LVILatticeVal &BBLV,
678 Value *Val, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000679 LVILatticeVal Result; // Start Undefined.
680
681 // If this is a pointer, and there's a load from that pointer in this BB,
682 // then we know that the pointer can't be NULL.
683 bool NotNull = false;
684 if (Val->getType()->isPointerTy()) {
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000685 if (isKnownNonNull(Val)) {
Nick Lewycky367f98f2011-01-15 09:16:12 +0000686 NotNull = true;
687 } else {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000688 const DataLayout &DL = BB->getModule()->getDataLayout();
689 Value *UnderlyingVal = GetUnderlyingObject(Val, DL);
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000690 // If 'GetUnderlyingObject' didn't converge, skip it. It won't converge
691 // inside InstructionDereferencesPointer either.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000692 if (UnderlyingVal == GetUnderlyingObject(UnderlyingVal, DL, 1)) {
Hans Wennborgcbb18e32014-11-21 19:07:46 +0000693 for (Instruction &I : *BB) {
694 if (InstructionDereferencesPointer(&I, UnderlyingVal)) {
Nick Lewyckyc86037f2012-10-26 04:43:47 +0000695 NotNull = true;
696 break;
697 }
Nick Lewycky367f98f2011-01-15 09:16:12 +0000698 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000699 }
700 }
701 }
702
703 // If this is the entry block, we must be asking about an argument. The
704 // value is overdefined.
705 if (BB == &BB->getParent()->getEntryBlock()) {
706 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
707 if (NotNull) {
Chris Lattner229907c2011-07-18 04:54:35 +0000708 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000709 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
710 } else {
711 Result.markOverdefined();
712 }
Owen Anderson64c2c572010-12-20 18:18:16 +0000713 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000714 return true;
715 }
716
717 // Loop over all of our predecessors, merging what we know from them into
718 // result.
719 bool EdgesMissing = false;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000720 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000721 LVILatticeVal EdgeResult;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000722 EdgesMissing |= !getEdgeValue(Val, *PI, BB, EdgeResult);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000723 if (EdgesMissing)
724 continue;
725
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000726 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000727
728 // If we hit overdefined, exit early. The BlockVals entry is already set
729 // to overdefined.
730 if (Result.isOverdefined()) {
731 DEBUG(dbgs() << " compute BB '" << BB->getName()
732 << "' - overdefined because of pred.\n");
733 // If we previously determined that this is a pointer that can't be null
734 // then return that rather than giving up entirely.
735 if (NotNull) {
Chris Lattner229907c2011-07-18 04:54:35 +0000736 PointerType *PTy = cast<PointerType>(Val->getType());
Nick Lewycky55a700b2010-12-18 01:00:40 +0000737 Result = LVILatticeVal::getNot(ConstantPointerNull::get(PTy));
738 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000739
Owen Anderson64c2c572010-12-20 18:18:16 +0000740 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000741 return true;
742 }
743 }
744 if (EdgesMissing)
745 return false;
746
747 // Return the merged value, which is more precise than 'overdefined'.
748 assert(!Result.isOverdefined());
Owen Anderson64c2c572010-12-20 18:18:16 +0000749 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000750 return true;
751}
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000752
Owen Anderson64c2c572010-12-20 18:18:16 +0000753bool LazyValueInfoCache::solveBlockValuePHINode(LVILatticeVal &BBLV,
754 PHINode *PN, BasicBlock *BB) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000755 LVILatticeVal Result; // Start Undefined.
756
757 // Loop over all of our predecessors, merging what we know from them into
758 // result.
759 bool EdgesMissing = false;
760 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
761 BasicBlock *PhiBB = PN->getIncomingBlock(i);
762 Value *PhiVal = PN->getIncomingValue(i);
763 LVILatticeVal EdgeResult;
Hal Finkel2400c962014-10-16 00:40:05 +0000764 // Note that we can provide PN as the context value to getEdgeValue, even
765 // though the results will be cached, because PN is the value being used as
766 // the cache key in the caller.
Hal Finkel7e184492014-09-07 20:29:59 +0000767 EdgesMissing |= !getEdgeValue(PhiVal, PhiBB, BB, EdgeResult, PN);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000768 if (EdgesMissing)
769 continue;
770
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000771 Result.mergeIn(EdgeResult, DL);
Nick Lewycky55a700b2010-12-18 01:00:40 +0000772
773 // If we hit overdefined, exit early. The BlockVals entry is already set
774 // to overdefined.
775 if (Result.isOverdefined()) {
776 DEBUG(dbgs() << " compute BB '" << BB->getName()
777 << "' - overdefined because of pred.\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000778
Owen Anderson64c2c572010-12-20 18:18:16 +0000779 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000780 return true;
781 }
782 }
783 if (EdgesMissing)
784 return false;
785
786 // Return the merged value, which is more precise than 'overdefined'.
787 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
Owen Anderson64c2c572010-12-20 18:18:16 +0000788 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000789 return true;
790}
791
Hal Finkel7e184492014-09-07 20:29:59 +0000792static bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
793 LVILatticeVal &Result,
794 bool isTrueDest = true);
795
Philip Reamesd1f829d2016-02-02 21:57:37 +0000796// If we can determine a constraint on the value given conditions assumed by
797// the program, intersect those constraints with BBLV
798void LazyValueInfoCache::intersectAssumeBlockValueConstantRange(Value *Val,
Hans Wennborgc5ec73d2014-11-21 18:58:23 +0000799 LVILatticeVal &BBLV,
800 Instruction *BBI) {
Hal Finkel7e184492014-09-07 20:29:59 +0000801 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
802 if (!BBI)
803 return;
804
Chandler Carruth66b31302015-01-04 12:03:27 +0000805 for (auto &AssumeVH : AC->assumptions()) {
806 if (!AssumeVH)
807 continue;
808 auto *I = cast<CallInst>(AssumeVH);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000809 if (!isValidAssumeForContext(I, BBI, DT))
Hal Finkel7e184492014-09-07 20:29:59 +0000810 continue;
811
812 Value *C = I->getArgOperand(0);
813 if (ICmpInst *ICI = dyn_cast<ICmpInst>(C)) {
814 LVILatticeVal Result;
Philip Reamesd1f829d2016-02-02 21:57:37 +0000815 if (getValueFromFromCondition(Val, ICI, Result))
816 BBLV = intersect(BBLV, Result);
Hal Finkel7e184492014-09-07 20:29:59 +0000817 }
818 }
819}
820
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000821bool LazyValueInfoCache::solveBlockValueSelect(LVILatticeVal &BBLV,
822 SelectInst *SI, BasicBlock *BB) {
823
824 // Recurse on our inputs if needed
825 if (!hasBlockValue(SI->getTrueValue(), BB)) {
826 if (pushBlockValue(std::make_pair(BB, SI->getTrueValue())))
827 return false;
828 BBLV.markOverdefined();
829 return true;
830 }
831 LVILatticeVal TrueVal = getBlockValue(SI->getTrueValue(), BB);
832 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
833 // extra slots in the table if we can.
834 if (TrueVal.isOverdefined()) {
835 BBLV.markOverdefined();
836 return true;
837 }
838
839 if (!hasBlockValue(SI->getFalseValue(), BB)) {
840 if (pushBlockValue(std::make_pair(BB, SI->getFalseValue())))
841 return false;
842 BBLV.markOverdefined();
843 return true;
844 }
845 LVILatticeVal FalseVal = getBlockValue(SI->getFalseValue(), BB);
846 // If we hit overdefined, don't ask more queries. We want to avoid poisoning
847 // extra slots in the table if we can.
848 if (FalseVal.isOverdefined()) {
849 BBLV.markOverdefined();
850 return true;
851 }
852
853 LVILatticeVal Result; // Start Undefined.
854 Result.mergeIn(TrueVal, DL);
855 Result.mergeIn(FalseVal, DL);
Philip Reamesc0bdb0c2016-02-01 22:57:53 +0000856 BBLV = Result;
857 return true;
858}
859
Owen Anderson64c2c572010-12-20 18:18:16 +0000860bool LazyValueInfoCache::solveBlockValueConstantRange(LVILatticeVal &BBLV,
861 Instruction *BBI,
Nick Lewycky55a700b2010-12-18 01:00:40 +0000862 BasicBlock *BB) {
Owen Anderson80d19f02010-08-18 21:11:37 +0000863 // Figure out the range of the LHS. If that fails, bail.
Nick Lewycky55a700b2010-12-18 01:00:40 +0000864 if (!hasBlockValue(BBI->getOperand(0), BB)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +0000865 if (pushBlockValue(std::make_pair(BB, BBI->getOperand(0))))
866 return false;
867 BBLV.markOverdefined();
868 return true;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000869 }
870
Nick Lewycky55a700b2010-12-18 01:00:40 +0000871 LVILatticeVal LHSVal = getBlockValue(BBI->getOperand(0), BB);
Philip Reamesd1f829d2016-02-02 21:57:37 +0000872 intersectAssumeBlockValueConstantRange(BBI->getOperand(0), LHSVal, BBI);
Owen Anderson80d19f02010-08-18 21:11:37 +0000873 if (!LHSVal.isConstantRange()) {
Owen Anderson64c2c572010-12-20 18:18:16 +0000874 BBLV.markOverdefined();
Nick Lewycky55a700b2010-12-18 01:00:40 +0000875 return true;
Owen Anderson80d19f02010-08-18 21:11:37 +0000876 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000877
Owen Anderson80d19f02010-08-18 21:11:37 +0000878 ConstantRange LHSRange = LHSVal.getConstantRange();
879 ConstantRange RHSRange(1);
Chris Lattner229907c2011-07-18 04:54:35 +0000880 IntegerType *ResultTy = cast<IntegerType>(BBI->getType());
Owen Anderson80d19f02010-08-18 21:11:37 +0000881 if (isa<BinaryOperator>(BBI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +0000882 if (ConstantInt *RHS = dyn_cast<ConstantInt>(BBI->getOperand(1))) {
883 RHSRange = ConstantRange(RHS->getValue());
884 } else {
Owen Anderson64c2c572010-12-20 18:18:16 +0000885 BBLV.markOverdefined();
Nick Lewycky55a700b2010-12-18 01:00:40 +0000886 return true;
Owen Andersonc62f7042010-08-24 07:55:44 +0000887 }
Owen Anderson80d19f02010-08-18 21:11:37 +0000888 }
Nick Lewycky55a700b2010-12-18 01:00:40 +0000889
Owen Anderson80d19f02010-08-18 21:11:37 +0000890 // NOTE: We're currently limited by the set of operations that ConstantRange
891 // can evaluate symbolically. Enhancing that set will allows us to analyze
892 // more definitions.
Owen Anderson64c2c572010-12-20 18:18:16 +0000893 LVILatticeVal Result;
Owen Anderson80d19f02010-08-18 21:11:37 +0000894 switch (BBI->getOpcode()) {
895 case Instruction::Add:
896 Result.markConstantRange(LHSRange.add(RHSRange));
897 break;
898 case Instruction::Sub:
899 Result.markConstantRange(LHSRange.sub(RHSRange));
900 break;
901 case Instruction::Mul:
902 Result.markConstantRange(LHSRange.multiply(RHSRange));
903 break;
904 case Instruction::UDiv:
905 Result.markConstantRange(LHSRange.udiv(RHSRange));
906 break;
907 case Instruction::Shl:
908 Result.markConstantRange(LHSRange.shl(RHSRange));
909 break;
910 case Instruction::LShr:
911 Result.markConstantRange(LHSRange.lshr(RHSRange));
912 break;
913 case Instruction::Trunc:
914 Result.markConstantRange(LHSRange.truncate(ResultTy->getBitWidth()));
915 break;
916 case Instruction::SExt:
917 Result.markConstantRange(LHSRange.signExtend(ResultTy->getBitWidth()));
918 break;
919 case Instruction::ZExt:
920 Result.markConstantRange(LHSRange.zeroExtend(ResultTy->getBitWidth()));
921 break;
922 case Instruction::BitCast:
923 Result.markConstantRange(LHSRange);
924 break;
Nick Lewyckyad48e012010-09-07 05:39:02 +0000925 case Instruction::And:
926 Result.markConstantRange(LHSRange.binaryAnd(RHSRange));
927 break;
928 case Instruction::Or:
929 Result.markConstantRange(LHSRange.binaryOr(RHSRange));
930 break;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000931
Owen Anderson80d19f02010-08-18 21:11:37 +0000932 // Unhandled instructions are overdefined.
933 default:
934 DEBUG(dbgs() << " compute BB '" << BB->getName()
935 << "' - overdefined because inst def found.\n");
936 Result.markOverdefined();
937 break;
938 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000939
Owen Anderson64c2c572010-12-20 18:18:16 +0000940 BBLV = Result;
Nick Lewycky55a700b2010-12-18 01:00:40 +0000941 return true;
Chris Lattner741c94c2009-11-11 00:22:30 +0000942}
943
Hal Finkel7e184492014-09-07 20:29:59 +0000944bool getValueFromFromCondition(Value *Val, ICmpInst *ICI,
945 LVILatticeVal &Result, bool isTrueDest) {
946 if (ICI && isa<Constant>(ICI->getOperand(1))) {
947 if (ICI->isEquality() && ICI->getOperand(0) == Val) {
948 // We know that V has the RHS constant if this is a true SETEQ or
949 // false SETNE.
950 if (isTrueDest == (ICI->getPredicate() == ICmpInst::ICMP_EQ))
951 Result = LVILatticeVal::get(cast<Constant>(ICI->getOperand(1)));
952 else
953 Result = LVILatticeVal::getNot(cast<Constant>(ICI->getOperand(1)));
954 return true;
955 }
956
957 // Recognize the range checking idiom that InstCombine produces.
958 // (X-C1) u< C2 --> [C1, C1+C2)
959 ConstantInt *NegOffset = nullptr;
960 if (ICI->getPredicate() == ICmpInst::ICMP_ULT)
961 match(ICI->getOperand(0), m_Add(m_Specific(Val),
962 m_ConstantInt(NegOffset)));
963
964 ConstantInt *CI = dyn_cast<ConstantInt>(ICI->getOperand(1));
965 if (CI && (ICI->getOperand(0) == Val || NegOffset)) {
Sanjoy Das7182d362015-03-18 00:41:24 +0000966 // Calculate the range of values that are allowed by the comparison
Hal Finkel7e184492014-09-07 20:29:59 +0000967 ConstantRange CmpRange(CI->getValue());
968 ConstantRange TrueValues =
Sanjoy Das7182d362015-03-18 00:41:24 +0000969 ConstantRange::makeAllowedICmpRegion(ICI->getPredicate(), CmpRange);
Hal Finkel7e184492014-09-07 20:29:59 +0000970
971 if (NegOffset) // Apply the offset from above.
972 TrueValues = TrueValues.subtract(NegOffset->getValue());
973
974 // If we're interested in the false dest, invert the condition.
975 if (!isTrueDest) TrueValues = TrueValues.inverse();
976
977 Result = LVILatticeVal::getRange(TrueValues);
978 return true;
979 }
980 }
981
982 return false;
983}
984
Nuno Lopese6e04902012-06-28 01:16:18 +0000985/// \brief Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
Philip Reames13f73242016-02-01 23:21:11 +0000986/// Val is not constrained on the edge. Result is unspecified if return value
987/// is false.
Nuno Lopese6e04902012-06-28 01:16:18 +0000988static bool getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
989 BasicBlock *BBTo, LVILatticeVal &Result) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +0000990 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
Chris Lattner77358782009-11-15 20:02:12 +0000991 // know that v != 0.
Chris Lattner19019ea2009-11-11 22:48:44 +0000992 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
993 // If this is a conditional branch and only one successor goes to BBTo, then
Sanjay Patel938e2792015-01-09 16:35:37 +0000994 // we may be able to infer something from the condition.
Chris Lattner19019ea2009-11-11 22:48:44 +0000995 if (BI->isConditional() &&
996 BI->getSuccessor(0) != BI->getSuccessor(1)) {
997 bool isTrueDest = BI->getSuccessor(0) == BBTo;
998 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
999 "BBTo isn't a successor of BBFrom");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001000
Chris Lattner19019ea2009-11-11 22:48:44 +00001001 // If V is the condition of the branch itself, then we know exactly what
1002 // it is.
Nick Lewycky55a700b2010-12-18 01:00:40 +00001003 if (BI->getCondition() == Val) {
1004 Result = LVILatticeVal::get(ConstantInt::get(
Owen Anderson185fe002010-08-10 20:03:09 +00001005 Type::getInt1Ty(Val->getContext()), isTrueDest));
Nick Lewycky55a700b2010-12-18 01:00:40 +00001006 return true;
1007 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001008
Chris Lattner19019ea2009-11-11 22:48:44 +00001009 // If the condition of the branch is an equality comparison, we may be
1010 // able to infer the value.
Sanjay Pateld7291152015-01-09 16:28:15 +00001011 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
1012 if (getValueFromFromCondition(Val, ICI, Result, isTrueDest))
1013 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001014 }
1015 }
Chris Lattner77358782009-11-15 20:02:12 +00001016
1017 // If the edge was formed by a switch on the value, then we may know exactly
1018 // what it is.
1019 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
Nuno Lopes8650fb82012-06-28 16:13:37 +00001020 if (SI->getCondition() != Val)
1021 return false;
1022
1023 bool DefaultCase = SI->getDefaultDest() == BBTo;
1024 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1025 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1026
Hans Wennborgcbb18e32014-11-21 19:07:46 +00001027 for (SwitchInst::CaseIt i : SI->cases()) {
Nuno Lopes8650fb82012-06-28 16:13:37 +00001028 ConstantRange EdgeVal(i.getCaseValue()->getValue());
Manman Renf3fedb62012-09-05 23:45:58 +00001029 if (DefaultCase) {
1030 // It is possible that the default destination is the destination of
1031 // some cases. There is no need to perform difference for those cases.
1032 if (i.getCaseSuccessor() != BBTo)
1033 EdgesVals = EdgesVals.difference(EdgeVal);
1034 } else if (i.getCaseSuccessor() == BBTo)
Nuno Lopesac593802012-05-18 21:02:10 +00001035 EdgesVals = EdgesVals.unionWith(EdgeVal);
Chris Lattner77358782009-11-15 20:02:12 +00001036 }
Nuno Lopes8650fb82012-06-28 16:13:37 +00001037 Result = LVILatticeVal::getRange(EdgesVals);
1038 return true;
Chris Lattner77358782009-11-15 20:02:12 +00001039 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001040 return false;
1041}
1042
Philip Reames44456b82016-02-02 03:15:40 +00001043/// Returns true if this lattice value represents at most one possible value.
1044/// This is as precise as any lattice value can get while still representing
1045/// reachable code.
1046static bool hasSingleValue(LVILatticeVal Val) {
1047 if (Val.isConstantRange() &&
1048 Val.getConstantRange().isSingleElement())
1049 // Integer constants are single element ranges
1050 return true;
1051 if (Val.isConstant())
1052 // Non integer constants
1053 return true;
1054 return false;
1055}
1056
1057/// Combine two sets of facts about the same value into a single set of
1058/// facts. Note that this method is not suitable for merging facts along
1059/// different paths in a CFG; that's what the mergeIn function is for. This
1060/// is for merging facts gathered about the same value at the same location
1061/// through two independent means.
1062/// Notes:
1063/// * This method does not promise to return the most precise possible lattice
1064/// value implied by A and B. It is allowed to return any lattice element
1065/// which is at least as strong as *either* A or B (unless our facts
1066/// conflict, see below).
1067/// * Due to unreachable code, the intersection of two lattice values could be
1068/// contradictory. If this happens, we return some valid lattice value so as
1069/// not confuse the rest of LVI. Ideally, we'd always return Undefined, but
1070/// we do not make this guarantee. TODO: This would be a useful enhancement.
1071static LVILatticeVal intersect(LVILatticeVal A, LVILatticeVal B) {
1072 // Undefined is the strongest state. It means the value is known to be along
1073 // an unreachable path.
1074 if (A.isUndefined())
1075 return A;
1076 if (B.isUndefined())
1077 return B;
1078
1079 // If we gave up for one, but got a useable fact from the other, use it.
1080 if (A.isOverdefined())
1081 return B;
1082 if (B.isOverdefined())
1083 return A;
1084
1085 // Can't get any more precise than constants.
1086 if (hasSingleValue(A))
1087 return A;
1088 if (hasSingleValue(B))
1089 return B;
1090
1091 // Could be either constant range or not constant here.
1092 if (!A.isConstantRange() || !B.isConstantRange()) {
1093 // TODO: Arbitrary choice, could be improved
1094 return A;
1095 }
1096
1097 // Intersect two constant ranges
1098 ConstantRange Range =
1099 A.getConstantRange().intersectWith(B.getConstantRange());
1100 // Note: An empty range is implicitly converted to overdefined internally.
1101 // TODO: We could instead use Undefined here since we've proven a conflict
1102 // and thus know this path must be unreachable.
1103 return LVILatticeVal::getRange(Range);
1104}
1105
Sanjay Patel938e2792015-01-09 16:35:37 +00001106/// \brief Compute the value of Val on the edge BBFrom -> BBTo or the value at
1107/// the basic block if the edge does not constrain Val.
Nuno Lopese6e04902012-06-28 01:16:18 +00001108bool LazyValueInfoCache::getEdgeValue(Value *Val, BasicBlock *BBFrom,
Hal Finkel7e184492014-09-07 20:29:59 +00001109 BasicBlock *BBTo, LVILatticeVal &Result,
1110 Instruction *CxtI) {
Nuno Lopese6e04902012-06-28 01:16:18 +00001111 // If already a constant, there is nothing to compute.
1112 if (Constant *VC = dyn_cast<Constant>(Val)) {
1113 Result = LVILatticeVal::get(VC);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001114 return true;
1115 }
Nuno Lopese6e04902012-06-28 01:16:18 +00001116
Philip Reames44456b82016-02-02 03:15:40 +00001117 LVILatticeVal LocalResult;
1118 if (!getEdgeValueLocal(Val, BBFrom, BBTo, LocalResult))
1119 // If we couldn't constrain the value on the edge, LocalResult doesn't
1120 // provide any information.
1121 LocalResult.markOverdefined();
1122
1123 if (hasSingleValue(LocalResult)) {
1124 // Can't get any more precise here
1125 Result = LocalResult;
Nuno Lopese6e04902012-06-28 01:16:18 +00001126 return true;
1127 }
1128
1129 if (!hasBlockValue(Val, BBFrom)) {
Hans Wennborg45172ac2014-11-25 17:23:05 +00001130 if (pushBlockValue(std::make_pair(BBFrom, Val)))
1131 return false;
Philip Reames44456b82016-02-02 03:15:40 +00001132 // No new information.
1133 Result = LocalResult;
Hans Wennborg45172ac2014-11-25 17:23:05 +00001134 return true;
Nuno Lopese6e04902012-06-28 01:16:18 +00001135 }
1136
Philip Reames44456b82016-02-02 03:15:40 +00001137 // Try to intersect ranges of the BB and the constraint on the edge.
1138 LVILatticeVal InBlock = getBlockValue(Val, BBFrom);
Philip Reamesd1f829d2016-02-02 21:57:37 +00001139 intersectAssumeBlockValueConstantRange(Val, InBlock, BBFrom->getTerminator());
Hal Finkel2400c962014-10-16 00:40:05 +00001140 // We can use the context instruction (generically the ultimate instruction
1141 // the calling pass is trying to simplify) here, even though the result of
1142 // this function is generally cached when called from the solve* functions
1143 // (and that cached result might be used with queries using a different
1144 // context instruction), because when this function is called from the solve*
1145 // functions, the context instruction is not provided. When called from
1146 // LazyValueInfoCache::getValueOnEdge, the context instruction is provided,
1147 // but then the result is not cached.
Philip Reamesd1f829d2016-02-02 21:57:37 +00001148 intersectAssumeBlockValueConstantRange(Val, InBlock, CxtI);
Philip Reames44456b82016-02-02 03:15:40 +00001149
1150 Result = intersect(LocalResult, InBlock);
Nuno Lopese6e04902012-06-28 01:16:18 +00001151 return true;
Chris Lattner19019ea2009-11-11 22:48:44 +00001152}
1153
Hal Finkel7e184492014-09-07 20:29:59 +00001154LVILatticeVal LazyValueInfoCache::getValueInBlock(Value *V, BasicBlock *BB,
1155 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001156 DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001157 << BB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001158
Hans Wennborg45172ac2014-11-25 17:23:05 +00001159 assert(BlockValueStack.empty() && BlockValueSet.empty());
1160 pushBlockValue(std::make_pair(BB, V));
1161
Nick Lewycky55a700b2010-12-18 01:00:40 +00001162 solve();
Owen Andersonc7ed4dc2010-12-09 06:14:58 +00001163 LVILatticeVal Result = getBlockValue(V, BB);
Philip Reamesd1f829d2016-02-02 21:57:37 +00001164 intersectAssumeBlockValueConstantRange(V, Result, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001165
1166 DEBUG(dbgs() << " Result = " << Result << "\n");
1167 return Result;
1168}
1169
1170LVILatticeVal LazyValueInfoCache::getValueAt(Value *V, Instruction *CxtI) {
1171 DEBUG(dbgs() << "LVI Getting value " << *V << " at '"
1172 << CxtI->getName() << "'\n");
1173
Philip Reamesd1f829d2016-02-02 21:57:37 +00001174 LVILatticeVal Result = LVILatticeVal::getOverdefined();
Philip Reameseb3e9da2015-10-29 03:57:17 +00001175 if (auto *I = dyn_cast<Instruction>(V))
1176 Result = getFromRangeMetadata(I);
Philip Reamesd1f829d2016-02-02 21:57:37 +00001177 intersectAssumeBlockValueConstantRange(V, Result, CxtI);
Philip Reames2c275cc2016-02-02 00:45:30 +00001178
David Greene37e98092009-12-23 20:43:58 +00001179 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001180 return Result;
1181}
Chris Lattner19019ea2009-11-11 22:48:44 +00001182
Chris Lattneraf025d32009-11-15 19:59:49 +00001183LVILatticeVal LazyValueInfoCache::
Hal Finkel7e184492014-09-07 20:29:59 +00001184getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1185 Instruction *CxtI) {
David Greene37e98092009-12-23 20:43:58 +00001186 DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
Chris Lattneraf025d32009-11-15 19:59:49 +00001187 << FromBB->getName() << "' to '" << ToBB->getName() << "'\n");
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001188
Nick Lewycky55a700b2010-12-18 01:00:40 +00001189 LVILatticeVal Result;
Hal Finkel7e184492014-09-07 20:29:59 +00001190 if (!getEdgeValue(V, FromBB, ToBB, Result, CxtI)) {
Nick Lewycky55a700b2010-12-18 01:00:40 +00001191 solve();
Hal Finkel7e184492014-09-07 20:29:59 +00001192 bool WasFastQuery = getEdgeValue(V, FromBB, ToBB, Result, CxtI);
Nick Lewycky55a700b2010-12-18 01:00:40 +00001193 (void)WasFastQuery;
1194 assert(WasFastQuery && "More work to do after problem solved?");
1195 }
1196
David Greene37e98092009-12-23 20:43:58 +00001197 DEBUG(dbgs() << " Result = " << Result << "\n");
Chris Lattneraf025d32009-11-15 19:59:49 +00001198 return Result;
1199}
1200
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001201void LazyValueInfoCache::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1202 BasicBlock *NewSucc) {
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001203 // When an edge in the graph has been threaded, values that we could not
1204 // determine a value for before (i.e. were marked overdefined) may be
1205 // possible to solve now. We do NOT try to proactively update these values.
1206 // Instead, we clear their entries from the cache, and allow lazy updating to
1207 // recompute them when needed.
1208
Hans Wennborgc5ec73d2014-11-21 18:58:23 +00001209 // The updating process is fairly simple: we need to drop cached info
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001210 // for all values that were marked overdefined in OldSucc, and for those same
1211 // values in any successor of OldSucc (except NewSucc) in which they were
1212 // also marked overdefined.
1213 std::vector<BasicBlock*> worklist;
1214 worklist.push_back(OldSucc);
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001215
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001216 auto I = OverDefinedCache.find(OldSucc);
1217 if (I == OverDefinedCache.end())
1218 return; // Nothing to process here.
Bruno Cardoso Lopes7a1483e2015-08-21 21:18:26 +00001219 SmallVector<Value *, 4> ValsToClear(I->second.begin(), I->second.end());
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001220
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001221 // Use a worklist to perform a depth-first search of OldSucc's successors.
1222 // NOTE: We do not need a visited list since any blocks we have already
1223 // visited will have had their overdefined markers cleared already, and we
1224 // thus won't loop to their successors.
1225 while (!worklist.empty()) {
1226 BasicBlock *ToUpdate = worklist.back();
1227 worklist.pop_back();
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001228
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001229 // Skip blocks only accessible through NewSucc.
1230 if (ToUpdate == NewSucc) continue;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001231
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001232 bool changed = false;
Bruno Cardoso Lopes7a1483e2015-08-21 21:18:26 +00001233 for (Value *V : ValsToClear) {
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001234 // If a value was marked overdefined in OldSucc, and is here too...
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001235 auto OI = OverDefinedCache.find(ToUpdate);
1236 if (OI == OverDefinedCache.end())
1237 continue;
1238 SmallPtrSetImpl<Value *> &ValueSet = OI->second;
1239 if (!ValueSet.count(V))
1240 continue;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001241
Bruno Cardoso Lopes6ac4ea42015-08-18 16:34:27 +00001242 ValueSet.erase(V);
1243 if (ValueSet.empty())
1244 OverDefinedCache.erase(OI);
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001245
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001246 // If we removed anything, then we potentially need to update
Owen Andersonaac5a722010-07-27 23:58:11 +00001247 // blocks successors too.
1248 changed = true;
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001249 }
Nick Lewycky55a700b2010-12-18 01:00:40 +00001250
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001251 if (!changed) continue;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001252
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001253 worklist.insert(worklist.end(), succ_begin(ToUpdate), succ_end(ToUpdate));
1254 }
1255}
1256
Chris Lattneraf025d32009-11-15 19:59:49 +00001257//===----------------------------------------------------------------------===//
1258// LazyValueInfo Impl
1259//===----------------------------------------------------------------------===//
1260
Sanjay Patel2a385e22015-01-09 16:47:20 +00001261/// This lazily constructs the LazyValueInfoCache.
Chandler Carruth66b31302015-01-04 12:03:27 +00001262static LazyValueInfoCache &getCache(void *&PImpl, AssumptionCache *AC,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001263 const DataLayout *DL,
Hal Finkel7e184492014-09-07 20:29:59 +00001264 DominatorTree *DT = nullptr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001265 if (!PImpl) {
1266 assert(DL && "getCache() called with a null DataLayout");
1267 PImpl = new LazyValueInfoCache(AC, *DL, DT);
1268 }
Chris Lattneraf025d32009-11-15 19:59:49 +00001269 return *static_cast<LazyValueInfoCache*>(PImpl);
1270}
1271
Owen Anderson208636f2010-08-18 18:39:01 +00001272bool LazyValueInfo::runOnFunction(Function &F) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001273 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001274 const DataLayout &DL = F.getParent()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001275
1276 DominatorTreeWrapperPass *DTWP =
1277 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1278 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Chad Rosier43a33062011-12-02 01:26:24 +00001279
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001280 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chad Rosier43a33062011-12-02 01:26:24 +00001281
Hal Finkel7e184492014-09-07 20:29:59 +00001282 if (PImpl)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001283 getCache(PImpl, AC, &DL, DT).clear();
Hal Finkel7e184492014-09-07 20:29:59 +00001284
Owen Anderson208636f2010-08-18 18:39:01 +00001285 // Fully lazy.
1286 return false;
1287}
1288
Chad Rosier43a33062011-12-02 01:26:24 +00001289void LazyValueInfo::getAnalysisUsage(AnalysisUsage &AU) const {
1290 AU.setPreservesAll();
Chandler Carruth66b31302015-01-04 12:03:27 +00001291 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001292 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chad Rosier43a33062011-12-02 01:26:24 +00001293}
1294
Chris Lattneraf025d32009-11-15 19:59:49 +00001295void LazyValueInfo::releaseMemory() {
1296 // If the cache was allocated, free it.
1297 if (PImpl) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001298 delete &getCache(PImpl, AC, nullptr);
Craig Topper9f008862014-04-15 04:59:12 +00001299 PImpl = nullptr;
Chris Lattneraf025d32009-11-15 19:59:49 +00001300 }
1301}
1302
Hal Finkel7e184492014-09-07 20:29:59 +00001303Constant *LazyValueInfo::getConstant(Value *V, BasicBlock *BB,
1304 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001305 const DataLayout &DL = BB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001306 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001307 getCache(PImpl, AC, &DL, DT).getValueInBlock(V, BB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001308
Chris Lattner19019ea2009-11-11 22:48:44 +00001309 if (Result.isConstant())
1310 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001311 if (Result.isConstantRange()) {
Owen Anderson38f6b7f2010-08-27 23:29:38 +00001312 ConstantRange CR = Result.getConstantRange();
1313 if (const APInt *SingleVal = CR.getSingleElement())
1314 return ConstantInt::get(V->getContext(), *SingleVal);
1315 }
Craig Topper9f008862014-04-15 04:59:12 +00001316 return nullptr;
Chris Lattner19019ea2009-11-11 22:48:44 +00001317}
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001318
Sanjay Patel2a385e22015-01-09 16:47:20 +00001319/// Determine whether the specified value is known to be a
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001320/// constant on the specified edge. Return null if not.
Chris Lattnerd5e25432009-11-12 01:29:10 +00001321Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
Hal Finkel7e184492014-09-07 20:29:59 +00001322 BasicBlock *ToBB,
1323 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001324 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001325 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001326 getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Chandler Carruth66b31302015-01-04 12:03:27 +00001327
Chris Lattnerd5e25432009-11-12 01:29:10 +00001328 if (Result.isConstant())
1329 return Result.getConstant();
Nick Lewycky11678bd2010-12-15 18:57:18 +00001330 if (Result.isConstantRange()) {
Owen Anderson185fe002010-08-10 20:03:09 +00001331 ConstantRange CR = Result.getConstantRange();
1332 if (const APInt *SingleVal = CR.getSingleElement())
1333 return ConstantInt::get(V->getContext(), *SingleVal);
1334 }
Craig Topper9f008862014-04-15 04:59:12 +00001335 return nullptr;
Chris Lattnerd5e25432009-11-12 01:29:10 +00001336}
1337
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001338static LazyValueInfo::Tristate getPredicateResult(unsigned Pred, Constant *C,
1339 LVILatticeVal &Result,
1340 const DataLayout &DL,
1341 TargetLibraryInfo *TLI) {
Hal Finkel7e184492014-09-07 20:29:59 +00001342
Chris Lattner565ee2f2009-11-12 04:36:58 +00001343 // If we know the value is a constant, evaluate the conditional.
Craig Topper9f008862014-04-15 04:59:12 +00001344 Constant *Res = nullptr;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001345 if (Result.isConstant()) {
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001346 Res = ConstantFoldCompareInstOperands(Pred, Result.getConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001347 TLI);
Nick Lewycky11678bd2010-12-15 18:57:18 +00001348 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
Hal Finkel7e184492014-09-07 20:29:59 +00001349 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1350 return LazyValueInfo::Unknown;
Chris Lattneraf025d32009-11-15 19:59:49 +00001351 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001352
Owen Anderson185fe002010-08-10 20:03:09 +00001353 if (Result.isConstantRange()) {
Owen Andersonc62f7042010-08-24 07:55:44 +00001354 ConstantInt *CI = dyn_cast<ConstantInt>(C);
Hal Finkel7e184492014-09-07 20:29:59 +00001355 if (!CI) return LazyValueInfo::Unknown;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001356
Owen Anderson185fe002010-08-10 20:03:09 +00001357 ConstantRange CR = Result.getConstantRange();
1358 if (Pred == ICmpInst::ICMP_EQ) {
1359 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001360 return LazyValueInfo::False;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001361
Owen Anderson185fe002010-08-10 20:03:09 +00001362 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001363 return LazyValueInfo::True;
Owen Anderson185fe002010-08-10 20:03:09 +00001364 } else if (Pred == ICmpInst::ICMP_NE) {
1365 if (!CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001366 return LazyValueInfo::True;
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001367
Owen Anderson185fe002010-08-10 20:03:09 +00001368 if (CR.isSingleElement() && CR.contains(CI->getValue()))
Hal Finkel7e184492014-09-07 20:29:59 +00001369 return LazyValueInfo::False;
Owen Anderson185fe002010-08-10 20:03:09 +00001370 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001371
Owen Anderson185fe002010-08-10 20:03:09 +00001372 // Handle more complex predicates.
Nick Lewycky11678bd2010-12-15 18:57:18 +00001373 ConstantRange TrueValues =
1374 ICmpInst::makeConstantRange((ICmpInst::Predicate)Pred, CI->getValue());
1375 if (TrueValues.contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001376 return LazyValueInfo::True;
Nick Lewycky11678bd2010-12-15 18:57:18 +00001377 if (TrueValues.inverse().contains(CR))
Hal Finkel7e184492014-09-07 20:29:59 +00001378 return LazyValueInfo::False;
1379 return LazyValueInfo::Unknown;
Owen Anderson185fe002010-08-10 20:03:09 +00001380 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001381
Chris Lattneraf025d32009-11-15 19:59:49 +00001382 if (Result.isNotConstant()) {
Chris Lattner565ee2f2009-11-12 04:36:58 +00001383 // If this is an equality comparison, we can try to fold it knowing that
1384 // "V != C1".
1385 if (Pred == ICmpInst::ICMP_EQ) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001386 // !C1 == C -> false iff C1 == C.
Chris Lattner565ee2f2009-11-12 04:36:58 +00001387 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001388 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001389 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001390 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001391 return LazyValueInfo::False;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001392 } else if (Pred == ICmpInst::ICMP_NE) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001393 // !C1 != C -> true iff C1 == C.
Chris Lattnerb0c0a0d2009-11-15 20:01:24 +00001394 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00001395 Result.getNotConstant(), C, DL,
Chad Rosier43a33062011-12-02 01:26:24 +00001396 TLI);
Chris Lattner565ee2f2009-11-12 04:36:58 +00001397 if (Res->isNullValue())
Hal Finkel7e184492014-09-07 20:29:59 +00001398 return LazyValueInfo::True;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001399 }
Hal Finkel7e184492014-09-07 20:29:59 +00001400 return LazyValueInfo::Unknown;
Chris Lattner565ee2f2009-11-12 04:36:58 +00001401 }
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001402
Hal Finkel7e184492014-09-07 20:29:59 +00001403 return LazyValueInfo::Unknown;
1404}
1405
Sanjay Patel2a385e22015-01-09 16:47:20 +00001406/// Determine whether the specified value comparison with a constant is known to
1407/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
Hal Finkel7e184492014-09-07 20:29:59 +00001408LazyValueInfo::Tristate
1409LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1410 BasicBlock *FromBB, BasicBlock *ToBB,
1411 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001412 const DataLayout &DL = FromBB->getModule()->getDataLayout();
Hal Finkel7e184492014-09-07 20:29:59 +00001413 LVILatticeVal Result =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001414 getCache(PImpl, AC, &DL, DT).getValueOnEdge(V, FromBB, ToBB, CxtI);
Hal Finkel7e184492014-09-07 20:29:59 +00001415
1416 return getPredicateResult(Pred, C, Result, DL, TLI);
1417}
1418
1419LazyValueInfo::Tristate
1420LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1421 Instruction *CxtI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001422 const DataLayout &DL = CxtI->getModule()->getDataLayout();
1423 LVILatticeVal Result = getCache(PImpl, AC, &DL, DT).getValueAt(V, CxtI);
Philip Reames66ab0f02015-06-16 00:49:59 +00001424 Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1425 if (Ret != Unknown)
1426 return Ret;
Hal Finkel7e184492014-09-07 20:29:59 +00001427
Philip Reamesaeefae02015-11-04 01:47:04 +00001428 // Note: The following bit of code is somewhat distinct from the rest of LVI;
1429 // LVI as a whole tries to compute a lattice value which is conservatively
1430 // correct at a given location. In this case, we have a predicate which we
1431 // weren't able to prove about the merged result, and we're pushing that
1432 // predicate back along each incoming edge to see if we can prove it
1433 // separately for each input. As a motivating example, consider:
1434 // bb1:
1435 // %v1 = ... ; constantrange<1, 5>
1436 // br label %merge
1437 // bb2:
1438 // %v2 = ... ; constantrange<10, 20>
1439 // br label %merge
1440 // merge:
1441 // %phi = phi [%v1, %v2] ; constantrange<1,20>
1442 // %pred = icmp eq i32 %phi, 8
1443 // We can't tell from the lattice value for '%phi' that '%pred' is false
1444 // along each path, but by checking the predicate over each input separately,
1445 // we can.
1446 // We limit the search to one step backwards from the current BB and value.
1447 // We could consider extending this to search further backwards through the
1448 // CFG and/or value graph, but there are non-obvious compile time vs quality
1449 // tradeoffs.
Philip Reames66ab0f02015-06-16 00:49:59 +00001450 if (CxtI) {
Philip Reamesbb11d622015-08-31 18:31:48 +00001451 BasicBlock *BB = CxtI->getParent();
1452
1453 // Function entry or an unreachable block. Bail to avoid confusing
1454 // analysis below.
1455 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1456 if (PI == PE)
1457 return Unknown;
1458
1459 // If V is a PHI node in the same block as the context, we need to ask
1460 // questions about the predicate as applied to the incoming value along
1461 // each edge. This is useful for eliminating cases where the predicate is
1462 // known along all incoming edges.
1463 if (auto *PHI = dyn_cast<PHINode>(V))
1464 if (PHI->getParent() == BB) {
1465 Tristate Baseline = Unknown;
1466 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1467 Value *Incoming = PHI->getIncomingValue(i);
1468 BasicBlock *PredBB = PHI->getIncomingBlock(i);
1469 // Note that PredBB may be BB itself.
1470 Tristate Result = getPredicateOnEdge(Pred, Incoming, C, PredBB, BB,
1471 CxtI);
1472
1473 // Keep going as long as we've seen a consistent known result for
1474 // all inputs.
1475 Baseline = (i == 0) ? Result /* First iteration */
1476 : (Baseline == Result ? Baseline : Unknown); /* All others */
1477 if (Baseline == Unknown)
1478 break;
1479 }
1480 if (Baseline != Unknown)
1481 return Baseline;
1482 }
1483
Philip Reames66ab0f02015-06-16 00:49:59 +00001484 // For a comparison where the V is outside this block, it's possible
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001485 // that we've branched on it before. Look to see if the value is known
Philip Reames66ab0f02015-06-16 00:49:59 +00001486 // on all incoming edges.
Philip Reamesbb11d622015-08-31 18:31:48 +00001487 if (!isa<Instruction>(V) ||
1488 cast<Instruction>(V)->getParent() != BB) {
Philip Reames66ab0f02015-06-16 00:49:59 +00001489 // For predecessor edge, determine if the comparison is true or false
Bruno Cardoso Lopes51fd2422015-07-28 15:53:21 +00001490 // on that edge. If they're all true or all false, we can conclude
Philip Reames66ab0f02015-06-16 00:49:59 +00001491 // the value of the comparison in this block.
1492 Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1493 if (Baseline != Unknown) {
1494 // Check that all remaining incoming values match the first one.
1495 while (++PI != PE) {
1496 Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1497 if (Ret != Baseline) break;
1498 }
1499 // If we terminated early, then one of the values didn't match.
1500 if (PI == PE) {
1501 return Baseline;
1502 }
1503 }
1504 }
1505 }
1506 return Unknown;
Chris Lattnerfde1f8d2009-11-11 02:08:33 +00001507}
1508
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001509void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
Nick Lewycky11678bd2010-12-15 18:57:18 +00001510 BasicBlock *NewSucc) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001511 if (PImpl) {
1512 const DataLayout &DL = PredBB->getModule()->getDataLayout();
1513 getCache(PImpl, AC, &DL, DT).threadEdge(PredBB, OldSucc, NewSucc);
1514 }
Owen Anderson208636f2010-08-18 18:39:01 +00001515}
1516
1517void LazyValueInfo::eraseBlock(BasicBlock *BB) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001518 if (PImpl) {
1519 const DataLayout &DL = BB->getModule()->getDataLayout();
1520 getCache(PImpl, AC, &DL, DT).eraseBlock(BB);
1521 }
Owen Andersonaa7f66b2010-07-26 18:48:03 +00001522}