blob: f329e3a5084b3b7aa968ae0cb5dbe45aade0a645 [file] [log] [blame]
Chris Lattner965c7692008-06-02 01:18:21 +00001//===- ValueTracking.cpp - Walk computations to compute properties --------===//
2//
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 contains routines that help analyze properties that chains of
11// computations have.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/ValueTracking.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000017#include "llvm/Analysis/AssumptionCache.h"
Dan Gohman949ab782010-12-15 20:10:26 +000018#include "llvm/Analysis/InstructionSimplify.h"
Benjamin Kramerfd4777c2013-09-24 16:37:51 +000019#include "llvm/Analysis/MemoryBuiltins.h"
Nick Lewyckyec373542014-05-20 05:13:21 +000020#include "llvm/IR/CallSite.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000021#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/DataLayout.h"
Hal Finkel60db0582014-09-07 18:57:58 +000024#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000025#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/GlobalAlias.h"
27#include "llvm/IR/GlobalVariable.h"
28#include "llvm/IR/Instructions.h"
29#include "llvm/IR/IntrinsicInst.h"
30#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/Metadata.h"
32#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000033#include "llvm/IR/PatternMatch.h"
Matt Arsenaultf1a7e622014-07-15 01:55:03 +000034#include "llvm/Support/Debug.h"
Chris Lattner965c7692008-06-02 01:18:21 +000035#include "llvm/Support/MathExtras.h"
Chris Lattner64496902008-06-04 04:46:14 +000036#include <cstring>
Chris Lattner965c7692008-06-02 01:18:21 +000037using namespace llvm;
Duncan Sandsd3951082011-01-25 09:38:29 +000038using namespace llvm::PatternMatch;
39
40const unsigned MaxDepth = 6;
41
Philip Reames1c292272015-03-10 22:43:20 +000042/// Enable an experimental feature to leverage information about dominating
43/// conditions to compute known bits. The individual options below control how
44/// hard we search. The defaults are choosen to be fairly aggressive. If you
45/// run into compile time problems when testing, scale them back and report
46/// your findings.
47static cl::opt<bool> EnableDomConditions("value-tracking-dom-conditions",
48 cl::Hidden, cl::init(false));
49
50// This is expensive, so we only do it for the top level query value.
51// (TODO: evaluate cost vs profit, consider higher thresholds)
52static cl::opt<unsigned> DomConditionsMaxDepth("dom-conditions-max-depth",
53 cl::Hidden, cl::init(1));
54
55/// How many dominating blocks should be scanned looking for dominating
56/// conditions?
57static cl::opt<unsigned> DomConditionsMaxDomBlocks("dom-conditions-dom-blocks",
58 cl::Hidden,
59 cl::init(20000));
60
61// Controls the number of uses of the value searched for possible
62// dominating comparisons.
63static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
64 cl::Hidden, cl::init(2000));
65
66// If true, don't consider only compares whose only use is a branch.
67static cl::opt<bool> DomConditionsSingleCmpUse("dom-conditions-single-cmp-use",
68 cl::Hidden, cl::init(false));
69
Sanjay Patelaee84212014-11-04 16:27:42 +000070/// Returns the bitwidth of the given scalar or pointer type (if unknown returns
71/// 0). For vector types, returns the element type's bitwidth.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000072static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
Duncan Sandsd3951082011-01-25 09:38:29 +000073 if (unsigned BitWidth = Ty->getScalarSizeInBits())
74 return BitWidth;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +000075
Mehdi Aminia28d91d2015-03-10 02:37:25 +000076 return DL.getPointerTypeSizeInBits(Ty);
Duncan Sandsd3951082011-01-25 09:38:29 +000077}
Chris Lattner965c7692008-06-02 01:18:21 +000078
Hal Finkel60db0582014-09-07 18:57:58 +000079// Many of these functions have internal versions that take an assumption
80// exclusion set. This is because of the potential for mutual recursion to
81// cause computeKnownBits to repeatedly visit the same assume intrinsic. The
82// classic case of this is assume(x = y), which will attempt to determine
83// bits in x from bits in y, which will attempt to determine bits in y from
84// bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
85// isKnownNonZero, which calls computeKnownBits and ComputeSignBit and
86// isKnownToBeAPowerOfTwo (all of which can call computeKnownBits), and so on.
87typedef SmallPtrSet<const Value *, 8> ExclInvsSet;
88
Benjamin Kramercfd8d902014-09-12 08:56:53 +000089namespace {
Hal Finkel60db0582014-09-07 18:57:58 +000090// Simplifying using an assume can only be done in a particular control-flow
91// context (the context instruction provides that context). If an assume and
92// the context instruction are not in the same block then the DT helps in
93// figuring out if we can use it.
94struct Query {
95 ExclInvsSet ExclInvs;
Chandler Carruth66b31302015-01-04 12:03:27 +000096 AssumptionCache *AC;
Hal Finkel60db0582014-09-07 18:57:58 +000097 const Instruction *CxtI;
98 const DominatorTree *DT;
99
Chandler Carruth66b31302015-01-04 12:03:27 +0000100 Query(AssumptionCache *AC = nullptr, const Instruction *CxtI = nullptr,
Hal Finkel60db0582014-09-07 18:57:58 +0000101 const DominatorTree *DT = nullptr)
Chandler Carruth66b31302015-01-04 12:03:27 +0000102 : AC(AC), CxtI(CxtI), DT(DT) {}
Hal Finkel60db0582014-09-07 18:57:58 +0000103
104 Query(const Query &Q, const Value *NewExcl)
Chandler Carruth66b31302015-01-04 12:03:27 +0000105 : ExclInvs(Q.ExclInvs), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000106 ExclInvs.insert(NewExcl);
107 }
108};
Benjamin Kramercfd8d902014-09-12 08:56:53 +0000109} // end anonymous namespace
Hal Finkel60db0582014-09-07 18:57:58 +0000110
Sanjay Patel547e9752014-11-04 16:09:50 +0000111// Given the provided Value and, potentially, a context instruction, return
Hal Finkel60db0582014-09-07 18:57:58 +0000112// the preferred context instruction (if any).
113static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
114 // If we've been provided with a context instruction, then use that (provided
115 // it has been inserted).
116 if (CxtI && CxtI->getParent())
117 return CxtI;
118
119 // If the value is really an already-inserted instruction, then use that.
120 CxtI = dyn_cast<Instruction>(V);
121 if (CxtI && CxtI->getParent())
122 return CxtI;
123
124 return nullptr;
125}
126
127static void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000128 const DataLayout &DL, unsigned Depth,
129 const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000130
131void llvm::computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000132 const DataLayout &DL, unsigned Depth,
Chandler Carruth66b31302015-01-04 12:03:27 +0000133 AssumptionCache *AC, const Instruction *CxtI,
Hal Finkel60db0582014-09-07 18:57:58 +0000134 const DominatorTree *DT) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000135 ::computeKnownBits(V, KnownZero, KnownOne, DL, Depth,
Chandler Carruth66b31302015-01-04 12:03:27 +0000136 Query(AC, safeCxtI(V, CxtI), DT));
Hal Finkel60db0582014-09-07 18:57:58 +0000137}
138
139static void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000140 const DataLayout &DL, unsigned Depth,
141 const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000142
143void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000144 const DataLayout &DL, unsigned Depth,
Chandler Carruth66b31302015-01-04 12:03:27 +0000145 AssumptionCache *AC, const Instruction *CxtI,
Hal Finkel60db0582014-09-07 18:57:58 +0000146 const DominatorTree *DT) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000147 ::ComputeSignBit(V, KnownZero, KnownOne, DL, Depth,
Chandler Carruth66b31302015-01-04 12:03:27 +0000148 Query(AC, safeCxtI(V, CxtI), DT));
Hal Finkel60db0582014-09-07 18:57:58 +0000149}
150
151static bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000152 const Query &Q, const DataLayout &DL);
Hal Finkel60db0582014-09-07 18:57:58 +0000153
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000154bool llvm::isKnownToBeAPowerOfTwo(Value *V, const DataLayout &DL, bool OrZero,
Chandler Carruth66b31302015-01-04 12:03:27 +0000155 unsigned Depth, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000156 const Instruction *CxtI,
157 const DominatorTree *DT) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000158 return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
159 Query(AC, safeCxtI(V, CxtI), DT), DL);
160}
161
162static bool isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
163 const Query &Q);
164
165bool llvm::isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
166 AssumptionCache *AC, const Instruction *CxtI,
167 const DominatorTree *DT) {
168 return ::isKnownNonZero(V, DL, Depth, Query(AC, safeCxtI(V, CxtI), DT));
169}
170
171static bool MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
172 unsigned Depth, const Query &Q);
173
174bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
175 unsigned Depth, AssumptionCache *AC,
176 const Instruction *CxtI, const DominatorTree *DT) {
177 return ::MaskedValueIsZero(V, Mask, DL, Depth,
178 Query(AC, safeCxtI(V, CxtI), DT));
179}
180
181static unsigned ComputeNumSignBits(Value *V, const DataLayout &DL,
182 unsigned Depth, const Query &Q);
183
184unsigned llvm::ComputeNumSignBits(Value *V, const DataLayout &DL,
185 unsigned Depth, AssumptionCache *AC,
186 const Instruction *CxtI,
187 const DominatorTree *DT) {
188 return ::ComputeNumSignBits(V, DL, Depth, Query(AC, safeCxtI(V, CxtI), DT));
Hal Finkel60db0582014-09-07 18:57:58 +0000189}
190
Jay Foada0653a32014-05-14 21:14:37 +0000191static void computeKnownBitsAddSub(bool Add, Value *Op0, Value *Op1, bool NSW,
192 APInt &KnownZero, APInt &KnownOne,
193 APInt &KnownZero2, APInt &KnownOne2,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000194 const DataLayout &DL, unsigned Depth,
Hal Finkel60db0582014-09-07 18:57:58 +0000195 const Query &Q) {
196 if (!Add) {
197 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
198 // We know that the top bits of C-X are clear if X contains less bits
199 // than C (i.e. no wrap-around can happen). For example, 20-X is
200 // positive if we can prove that X is >= 0 and < 16.
201 if (!CLHS->getValue().isNegative()) {
202 unsigned BitWidth = KnownZero.getBitWidth();
203 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
204 // NLZ can't be BitWidth with no sign bit
205 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000206 computeKnownBits(Op1, KnownZero2, KnownOne2, DL, Depth + 1, Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000207
208 // If all of the MaskV bits are known to be zero, then we know the
209 // output top bits are zero, because we now know that the output is
210 // from [0-C].
211 if ((KnownZero2 & MaskV) == MaskV) {
212 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
213 // Top bits known zero.
214 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
215 }
216 }
217 }
218 }
219
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000220 unsigned BitWidth = KnownZero.getBitWidth();
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000221
David Majnemer97ddca32014-08-22 00:40:43 +0000222 // If an initial sequence of bits in the result is not needed, the
223 // corresponding bits in the operands are not needed.
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000224 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000225 computeKnownBits(Op0, LHSKnownZero, LHSKnownOne, DL, Depth + 1, Q);
226 computeKnownBits(Op1, KnownZero2, KnownOne2, DL, Depth + 1, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000227
David Majnemer97ddca32014-08-22 00:40:43 +0000228 // Carry in a 1 for a subtract, rather than a 0.
229 APInt CarryIn(BitWidth, 0);
230 if (!Add) {
231 // Sum = LHS + ~RHS + 1
232 std::swap(KnownZero2, KnownOne2);
233 CarryIn.setBit(0);
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000234 }
235
David Majnemer97ddca32014-08-22 00:40:43 +0000236 APInt PossibleSumZero = ~LHSKnownZero + ~KnownZero2 + CarryIn;
237 APInt PossibleSumOne = LHSKnownOne + KnownOne2 + CarryIn;
238
239 // Compute known bits of the carry.
240 APInt CarryKnownZero = ~(PossibleSumZero ^ LHSKnownZero ^ KnownZero2);
241 APInt CarryKnownOne = PossibleSumOne ^ LHSKnownOne ^ KnownOne2;
242
243 // Compute set of known bits (where all three relevant bits are known).
244 APInt LHSKnown = LHSKnownZero | LHSKnownOne;
245 APInt RHSKnown = KnownZero2 | KnownOne2;
246 APInt CarryKnown = CarryKnownZero | CarryKnownOne;
247 APInt Known = LHSKnown & RHSKnown & CarryKnown;
248
249 assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
250 "known bits of sum differ");
251
252 // Compute known bits of the result.
253 KnownZero = ~PossibleSumOne & Known;
254 KnownOne = PossibleSumOne & Known;
255
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000256 // Are we still trying to solve for the sign bit?
David Majnemer97ddca32014-08-22 00:40:43 +0000257 if (!Known.isNegative()) {
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000258 if (NSW) {
David Majnemer97ddca32014-08-22 00:40:43 +0000259 // Adding two non-negative numbers, or subtracting a negative number from
260 // a non-negative one, can't wrap into negative.
261 if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
262 KnownZero |= APInt::getSignBit(BitWidth);
263 // Adding two negative numbers, or subtracting a non-negative number from
264 // a negative one, can't wrap into non-negative.
265 else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
266 KnownOne |= APInt::getSignBit(BitWidth);
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000267 }
268 }
269}
270
Jay Foada0653a32014-05-14 21:14:37 +0000271static void computeKnownBitsMul(Value *Op0, Value *Op1, bool NSW,
272 APInt &KnownZero, APInt &KnownOne,
273 APInt &KnownZero2, APInt &KnownOne2,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000274 const DataLayout &DL, unsigned Depth,
Hal Finkel60db0582014-09-07 18:57:58 +0000275 const Query &Q) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000276 unsigned BitWidth = KnownZero.getBitWidth();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000277 computeKnownBits(Op1, KnownZero, KnownOne, DL, Depth + 1, Q);
278 computeKnownBits(Op0, KnownZero2, KnownOne2, DL, Depth + 1, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000279
280 bool isKnownNegative = false;
281 bool isKnownNonNegative = false;
282 // If the multiplication is known not to overflow, compute the sign bit.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000283 if (NSW) {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000284 if (Op0 == Op1) {
285 // The product of a number with itself is non-negative.
286 isKnownNonNegative = true;
287 } else {
288 bool isKnownNonNegativeOp1 = KnownZero.isNegative();
289 bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
290 bool isKnownNegativeOp1 = KnownOne.isNegative();
291 bool isKnownNegativeOp0 = KnownOne2.isNegative();
292 // The product of two numbers with the same sign is non-negative.
293 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
294 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
295 // The product of a negative number and a non-negative number is either
296 // negative or zero.
297 if (!isKnownNonNegative)
298 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000299 isKnownNonZero(Op0, DL, Depth, Q)) ||
Nick Lewyckyfa306072012-03-18 23:28:48 +0000300 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000301 isKnownNonZero(Op1, DL, Depth, Q));
Nick Lewyckyfa306072012-03-18 23:28:48 +0000302 }
303 }
304
305 // If low bits are zero in either operand, output low known-0 bits.
306 // Also compute a conserative estimate for high known-0 bits.
307 // More trickiness is possible, but this is sufficient for the
308 // interesting case of alignment computation.
309 KnownOne.clearAllBits();
310 unsigned TrailZ = KnownZero.countTrailingOnes() +
311 KnownZero2.countTrailingOnes();
312 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
313 KnownZero2.countLeadingOnes(),
314 BitWidth) - BitWidth;
315
316 TrailZ = std::min(TrailZ, BitWidth);
317 LeadZ = std::min(LeadZ, BitWidth);
318 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
319 APInt::getHighBitsSet(BitWidth, LeadZ);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000320
321 // Only make use of no-wrap flags if we failed to compute the sign bit
322 // directly. This matters if the multiplication always overflows, in
323 // which case we prefer to follow the result of the direct computation,
324 // though as the program is invoking undefined behaviour we can choose
325 // whatever we like here.
326 if (isKnownNonNegative && !KnownOne.isNegative())
327 KnownZero.setBit(BitWidth - 1);
328 else if (isKnownNegative && !KnownZero.isNegative())
329 KnownOne.setBit(BitWidth - 1);
330}
331
Jingyue Wu37fcb592014-06-19 16:50:16 +0000332void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
333 APInt &KnownZero) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000334 unsigned BitWidth = KnownZero.getBitWidth();
Rafael Espindola53190532012-03-30 15:52:11 +0000335 unsigned NumRanges = Ranges.getNumOperands() / 2;
336 assert(NumRanges >= 1);
337
338 // Use the high end of the ranges to find leading zeros.
339 unsigned MinLeadingZeros = BitWidth;
340 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000341 ConstantInt *Lower =
342 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
343 ConstantInt *Upper =
344 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
Rafael Espindola53190532012-03-30 15:52:11 +0000345 ConstantRange Range(Lower->getValue(), Upper->getValue());
346 if (Range.isWrappedSet())
347 MinLeadingZeros = 0; // -1 has no zeros
348 unsigned LeadingZeros = (Upper->getValue() - 1).countLeadingZeros();
349 MinLeadingZeros = std::min(LeadingZeros, MinLeadingZeros);
350 }
351
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000352 KnownZero = APInt::getHighBitsSet(BitWidth, MinLeadingZeros);
Rafael Espindola53190532012-03-30 15:52:11 +0000353}
Jay Foad5a29c362014-05-15 12:12:55 +0000354
Hal Finkel60db0582014-09-07 18:57:58 +0000355static bool isEphemeralValueOf(Instruction *I, const Value *E) {
356 SmallVector<const Value *, 16> WorkSet(1, I);
357 SmallPtrSet<const Value *, 32> Visited;
358 SmallPtrSet<const Value *, 16> EphValues;
359
360 while (!WorkSet.empty()) {
361 const Value *V = WorkSet.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +0000362 if (!Visited.insert(V).second)
Hal Finkel60db0582014-09-07 18:57:58 +0000363 continue;
364
365 // If all uses of this value are ephemeral, then so is this value.
366 bool FoundNEUse = false;
367 for (const User *I : V->users())
368 if (!EphValues.count(I)) {
369 FoundNEUse = true;
370 break;
371 }
372
373 if (!FoundNEUse) {
374 if (V == E)
375 return true;
376
377 EphValues.insert(V);
378 if (const User *U = dyn_cast<User>(V))
379 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
380 J != JE; ++J) {
381 if (isSafeToSpeculativelyExecute(*J))
382 WorkSet.push_back(*J);
383 }
384 }
385 }
386
387 return false;
388}
389
390// Is this an intrinsic that cannot be speculated but also cannot trap?
391static bool isAssumeLikeIntrinsic(const Instruction *I) {
392 if (const CallInst *CI = dyn_cast<CallInst>(I))
393 if (Function *F = CI->getCalledFunction())
394 switch (F->getIntrinsicID()) {
395 default: break;
396 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
397 case Intrinsic::assume:
398 case Intrinsic::dbg_declare:
399 case Intrinsic::dbg_value:
400 case Intrinsic::invariant_start:
401 case Intrinsic::invariant_end:
402 case Intrinsic::lifetime_start:
403 case Intrinsic::lifetime_end:
404 case Intrinsic::objectsize:
405 case Intrinsic::ptr_annotation:
406 case Intrinsic::var_annotation:
407 return true;
408 }
409
410 return false;
411}
412
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000413static bool isValidAssumeForContext(Value *V, const Query &Q) {
Hal Finkel60db0582014-09-07 18:57:58 +0000414 Instruction *Inv = cast<Instruction>(V);
415
416 // There are two restrictions on the use of an assume:
417 // 1. The assume must dominate the context (or the control flow must
418 // reach the assume whenever it reaches the context).
419 // 2. The context must not be in the assume's set of ephemeral values
420 // (otherwise we will use the assume to prove that the condition
421 // feeding the assume is trivially true, thus causing the removal of
422 // the assume).
423
424 if (Q.DT) {
425 if (Q.DT->dominates(Inv, Q.CxtI)) {
426 return true;
427 } else if (Inv->getParent() == Q.CxtI->getParent()) {
428 // The context comes first, but they're both in the same block. Make sure
429 // there is nothing in between that might interrupt the control flow.
430 for (BasicBlock::const_iterator I =
431 std::next(BasicBlock::const_iterator(Q.CxtI)),
432 IE(Inv); I != IE; ++I)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000433 if (!isSafeToSpeculativelyExecute(I) && !isAssumeLikeIntrinsic(I))
Hal Finkel60db0582014-09-07 18:57:58 +0000434 return false;
435
436 return !isEphemeralValueOf(Inv, Q.CxtI);
437 }
438
439 return false;
440 }
441
442 // When we don't have a DT, we do a limited search...
443 if (Inv->getParent() == Q.CxtI->getParent()->getSinglePredecessor()) {
444 return true;
445 } else if (Inv->getParent() == Q.CxtI->getParent()) {
446 // Search forward from the assume until we reach the context (or the end
447 // of the block); the common case is that the assume will come first.
448 for (BasicBlock::iterator I = std::next(BasicBlock::iterator(Inv)),
449 IE = Inv->getParent()->end(); I != IE; ++I)
450 if (I == Q.CxtI)
451 return true;
452
453 // The context must come first...
454 for (BasicBlock::const_iterator I =
455 std::next(BasicBlock::const_iterator(Q.CxtI)),
456 IE(Inv); I != IE; ++I)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000457 if (!isSafeToSpeculativelyExecute(I) && !isAssumeLikeIntrinsic(I))
Hal Finkel60db0582014-09-07 18:57:58 +0000458 return false;
459
460 return !isEphemeralValueOf(Inv, Q.CxtI);
461 }
462
463 return false;
464}
465
466bool llvm::isValidAssumeForContext(const Instruction *I,
467 const Instruction *CxtI,
Hal Finkel60db0582014-09-07 18:57:58 +0000468 const DominatorTree *DT) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000469 return ::isValidAssumeForContext(const_cast<Instruction *>(I),
470 Query(nullptr, CxtI, DT));
Hal Finkel60db0582014-09-07 18:57:58 +0000471}
472
473template<typename LHS, typename RHS>
474inline match_combine_or<CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>,
475 CmpClass_match<RHS, LHS, ICmpInst, ICmpInst::Predicate>>
476m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
477 return m_CombineOr(m_ICmp(Pred, L, R), m_ICmp(Pred, R, L));
478}
479
480template<typename LHS, typename RHS>
481inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::And>,
482 BinaryOp_match<RHS, LHS, Instruction::And>>
483m_c_And(const LHS &L, const RHS &R) {
484 return m_CombineOr(m_And(L, R), m_And(R, L));
485}
486
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000487template<typename LHS, typename RHS>
488inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Or>,
489 BinaryOp_match<RHS, LHS, Instruction::Or>>
490m_c_Or(const LHS &L, const RHS &R) {
491 return m_CombineOr(m_Or(L, R), m_Or(R, L));
492}
493
494template<typename LHS, typename RHS>
495inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Xor>,
496 BinaryOp_match<RHS, LHS, Instruction::Xor>>
497m_c_Xor(const LHS &L, const RHS &R) {
498 return m_CombineOr(m_Xor(L, R), m_Xor(R, L));
499}
500
Philip Reames1c292272015-03-10 22:43:20 +0000501/// Compute known bits in 'V' under the assumption that the condition 'Cmp' is
502/// true (at the context instruction.) This is mostly a utility function for
503/// the prototype dominating conditions reasoning below.
504static void computeKnownBitsFromTrueCondition(Value *V, ICmpInst *Cmp,
505 APInt &KnownZero,
506 APInt &KnownOne,
507 const DataLayout &DL,
508 unsigned Depth, const Query &Q) {
509 Value *LHS = Cmp->getOperand(0);
510 Value *RHS = Cmp->getOperand(1);
511 // TODO: We could potentially be more aggressive here. This would be worth
512 // evaluating. If we can, explore commoning this code with the assume
513 // handling logic.
514 if (LHS != V && RHS != V)
515 return;
516
517 const unsigned BitWidth = KnownZero.getBitWidth();
518
519 switch (Cmp->getPredicate()) {
520 default:
521 // We know nothing from this condition
522 break;
523 // TODO: implement unsigned bound from below (known one bits)
524 // TODO: common condition check implementations with assumes
525 // TODO: implement other patterns from assume (e.g. V & B == A)
526 case ICmpInst::ICMP_SGT:
527 if (LHS == V) {
528 APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
529 computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
530 if (KnownOneTemp.isAllOnesValue() || KnownZeroTemp.isNegative()) {
531 // We know that the sign bit is zero.
532 KnownZero |= APInt::getSignBit(BitWidth);
533 }
534 }
535 break;
536 case ICmpInst::ICMP_EQ:
537 if (LHS == V)
538 computeKnownBits(RHS, KnownZero, KnownOne, DL, Depth + 1, Q);
539 else if (RHS == V)
540 computeKnownBits(LHS, KnownZero, KnownOne, DL, Depth + 1, Q);
541 else
542 llvm_unreachable("missing use?");
543 break;
544 case ICmpInst::ICMP_ULE:
545 if (LHS == V) {
546 APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
547 computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
548 // The known zero bits carry over
549 unsigned SignBits = KnownZeroTemp.countLeadingOnes();
550 KnownZero |= APInt::getHighBitsSet(BitWidth, SignBits);
551 }
552 break;
553 case ICmpInst::ICMP_ULT:
554 if (LHS == V) {
555 APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
556 computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
557 // Whatever high bits in rhs are zero are known to be zero (if rhs is a
558 // power of 2, then one more).
559 unsigned SignBits = KnownZeroTemp.countLeadingOnes();
560 if (isKnownToBeAPowerOfTwo(RHS, false, Depth + 1, Query(Q, Cmp), DL))
561 SignBits++;
562 KnownZero |= APInt::getHighBitsSet(BitWidth, SignBits);
563 }
564 break;
565 };
566}
567
568/// Compute known bits in 'V' from conditions which are known to be true along
569/// all paths leading to the context instruction. In particular, look for
570/// cases where one branch of an interesting condition dominates the context
571/// instruction. This does not do general dataflow.
572/// NOTE: This code is EXPERIMENTAL and currently off by default.
573static void computeKnownBitsFromDominatingCondition(Value *V, APInt &KnownZero,
574 APInt &KnownOne,
575 const DataLayout &DL,
576 unsigned Depth,
577 const Query &Q) {
578 // Need both the dominator tree and the query location to do anything useful
579 if (!Q.DT || !Q.CxtI)
580 return;
581 Instruction *Cxt = const_cast<Instruction *>(Q.CxtI);
582
583 // Avoid useless work
584 if (auto VI = dyn_cast<Instruction>(V))
585 if (VI->getParent() == Cxt->getParent())
586 return;
587
588 // Note: We currently implement two options. It's not clear which of these
589 // will survive long term, we need data for that.
590 // Option 1 - Try walking the dominator tree looking for conditions which
591 // might apply. This works well for local conditions (loop guards, etc..),
592 // but not as well for things far from the context instruction (presuming a
593 // low max blocks explored). If we can set an high enough limit, this would
594 // be all we need.
595 // Option 2 - We restrict out search to those conditions which are uses of
596 // the value we're interested in. This is independent of dom structure,
597 // but is slightly less powerful without looking through lots of use chains.
598 // It does handle conditions far from the context instruction (e.g. early
599 // function exits on entry) really well though.
600
601 // Option 1 - Search the dom tree
602 unsigned NumBlocksExplored = 0;
603 BasicBlock *Current = Cxt->getParent();
604 while (true) {
605 // Stop searching if we've gone too far up the chain
606 if (NumBlocksExplored >= DomConditionsMaxDomBlocks)
607 break;
608 NumBlocksExplored++;
609
610 if (!Q.DT->getNode(Current)->getIDom())
611 break;
612 Current = Q.DT->getNode(Current)->getIDom()->getBlock();
613 if (!Current)
614 // found function entry
615 break;
616
617 BranchInst *BI = dyn_cast<BranchInst>(Current->getTerminator());
618 if (!BI || BI->isUnconditional())
619 continue;
620 ICmpInst *Cmp = dyn_cast<ICmpInst>(BI->getCondition());
621 if (!Cmp)
622 continue;
623
624 // We're looking for conditions that are guaranteed to hold at the context
625 // instruction. Finding a condition where one path dominates the context
626 // isn't enough because both the true and false cases could merge before
627 // the context instruction we're actually interested in. Instead, we need
628 // to ensure that the taken *edge* dominates the context instruction.
629 BasicBlock *BB0 = BI->getSuccessor(0);
630 BasicBlockEdge Edge(BI->getParent(), BB0);
631 if (!Edge.isSingleEdge() || !Q.DT->dominates(Edge, Q.CxtI->getParent()))
632 continue;
633
634 computeKnownBitsFromTrueCondition(V, Cmp, KnownZero, KnownOne, DL, Depth,
635 Q);
636 }
637
638 // Option 2 - Search the other uses of V
639 unsigned NumUsesExplored = 0;
640 for (auto U : V->users()) {
641 // Avoid massive lists
642 if (NumUsesExplored >= DomConditionsMaxUses)
643 break;
644 NumUsesExplored++;
645 // Consider only compare instructions uniquely controlling a branch
646 ICmpInst *Cmp = dyn_cast<ICmpInst>(U);
647 if (!Cmp)
648 continue;
649
650 if (DomConditionsSingleCmpUse && !Cmp->hasOneUse())
651 continue;
652
653 for (auto *CmpU : Cmp->users()) {
654 BranchInst *BI = dyn_cast<BranchInst>(CmpU);
655 if (!BI || BI->isUnconditional())
656 continue;
657 // We're looking for conditions that are guaranteed to hold at the
658 // context instruction. Finding a condition where one path dominates
659 // the context isn't enough because both the true and false cases could
660 // merge before the context instruction we're actually interested in.
661 // Instead, we need to ensure that the taken *edge* dominates the context
662 // instruction.
663 BasicBlock *BB0 = BI->getSuccessor(0);
664 BasicBlockEdge Edge(BI->getParent(), BB0);
665 if (!Edge.isSingleEdge() || !Q.DT->dominates(Edge, Q.CxtI->getParent()))
666 continue;
667
668 computeKnownBitsFromTrueCondition(V, Cmp, KnownZero, KnownOne, DL, Depth,
669 Q);
670 }
671 }
672}
673
Hal Finkel60db0582014-09-07 18:57:58 +0000674static void computeKnownBitsFromAssume(Value *V, APInt &KnownZero,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000675 APInt &KnownOne, const DataLayout &DL,
Hal Finkel60db0582014-09-07 18:57:58 +0000676 unsigned Depth, const Query &Q) {
677 // Use of assumptions is context-sensitive. If we don't have a context, we
678 // cannot use them!
Chandler Carruth66b31302015-01-04 12:03:27 +0000679 if (!Q.AC || !Q.CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000680 return;
681
682 unsigned BitWidth = KnownZero.getBitWidth();
683
Chandler Carruth66b31302015-01-04 12:03:27 +0000684 for (auto &AssumeVH : Q.AC->assumptions()) {
685 if (!AssumeVH)
686 continue;
687 CallInst *I = cast<CallInst>(AssumeVH);
Chandler Carruth75c11b82015-01-04 23:13:57 +0000688 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
Chandler Carruth66b31302015-01-04 12:03:27 +0000689 "Got assumption for the wrong function!");
Hal Finkel60db0582014-09-07 18:57:58 +0000690 if (Q.ExclInvs.count(I))
691 continue;
692
Philip Reames00d3b272014-11-24 23:44:28 +0000693 // Warning: This loop can end up being somewhat performance sensetive.
694 // We're running this loop for once for each value queried resulting in a
695 // runtime of ~O(#assumes * #values).
696
697 assert(isa<IntrinsicInst>(I) &&
698 dyn_cast<IntrinsicInst>(I)->getIntrinsicID() == Intrinsic::assume &&
699 "must be an assume intrinsic");
700
701 Value *Arg = I->getArgOperand(0);
702
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000703 if (Arg == V && isValidAssumeForContext(I, Q)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000704 assert(BitWidth == 1 && "assume operand is not i1?");
705 KnownZero.clearAllBits();
706 KnownOne.setAllBits();
707 return;
708 }
709
David Majnemer9b609752014-12-12 23:59:29 +0000710 // The remaining tests are all recursive, so bail out if we hit the limit.
711 if (Depth == MaxDepth)
712 continue;
713
Hal Finkel60db0582014-09-07 18:57:58 +0000714 Value *A, *B;
715 auto m_V = m_CombineOr(m_Specific(V),
716 m_CombineOr(m_PtrToInt(m_Specific(V)),
717 m_BitCast(m_Specific(V))));
718
719 CmpInst::Predicate Pred;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000720 ConstantInt *C;
Hal Finkel60db0582014-09-07 18:57:58 +0000721 // assume(v = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000722 if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000723 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000724 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
725 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
726 KnownZero |= RHSKnownZero;
727 KnownOne |= RHSKnownOne;
728 // assume(v & b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000729 } else if (match(Arg,
730 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
731 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000732 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
733 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
734 APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
735 computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
736
737 // For those bits in the mask that are known to be one, we can propagate
738 // known bits from the RHS to V.
739 KnownZero |= RHSKnownZero & MaskKnownOne;
740 KnownOne |= RHSKnownOne & MaskKnownOne;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000741 // assume(~(v & b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000742 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
743 m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000744 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000745 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
746 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
747 APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
748 computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
749
750 // For those bits in the mask that are known to be one, we can propagate
751 // inverted known bits from the RHS to V.
752 KnownZero |= RHSKnownOne & MaskKnownOne;
753 KnownOne |= RHSKnownZero & MaskKnownOne;
754 // assume(v | b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000755 } else if (match(Arg,
756 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
757 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000758 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
759 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
760 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
761 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
762
763 // For those bits in B that are known to be zero, we can propagate known
764 // bits from the RHS to V.
765 KnownZero |= RHSKnownZero & BKnownZero;
766 KnownOne |= RHSKnownOne & BKnownZero;
767 // assume(~(v | b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000768 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
769 m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000770 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000771 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
772 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
773 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
774 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
775
776 // For those bits in B that are known to be zero, we can propagate
777 // inverted known bits from the RHS to V.
778 KnownZero |= RHSKnownOne & BKnownZero;
779 KnownOne |= RHSKnownZero & BKnownZero;
780 // assume(v ^ b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000781 } else if (match(Arg,
782 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
783 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000784 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
785 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
786 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
787 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
788
789 // For those bits in B that are known to be zero, we can propagate known
790 // bits from the RHS to V. For those bits in B that are known to be one,
791 // we can propagate inverted known bits from the RHS to V.
792 KnownZero |= RHSKnownZero & BKnownZero;
793 KnownOne |= RHSKnownOne & BKnownZero;
794 KnownZero |= RHSKnownOne & BKnownOne;
795 KnownOne |= RHSKnownZero & BKnownOne;
796 // assume(~(v ^ b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000797 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
798 m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000799 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000800 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
801 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
802 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
803 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
804
805 // For those bits in B that are known to be zero, we can propagate
806 // inverted known bits from the RHS to V. For those bits in B that are
807 // known to be one, we can propagate known bits from the RHS to V.
808 KnownZero |= RHSKnownOne & BKnownZero;
809 KnownOne |= RHSKnownZero & BKnownZero;
810 KnownZero |= RHSKnownZero & BKnownOne;
811 KnownOne |= RHSKnownOne & BKnownOne;
812 // assume(v << c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000813 } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
814 m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000815 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000816 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
817 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
818 // For those bits in RHS that are known, we can propagate them to known
819 // bits in V shifted to the right by C.
820 KnownZero |= RHSKnownZero.lshr(C->getZExtValue());
821 KnownOne |= RHSKnownOne.lshr(C->getZExtValue());
822 // assume(~(v << c) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000823 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
824 m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000825 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000826 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
827 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
828 // For those bits in RHS that are known, we can propagate them inverted
829 // to known bits in V shifted to the right by C.
830 KnownZero |= RHSKnownOne.lshr(C->getZExtValue());
831 KnownOne |= RHSKnownZero.lshr(C->getZExtValue());
832 // assume(v >> c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000833 } else if (match(Arg,
834 m_c_ICmp(Pred, m_CombineOr(m_LShr(m_V, m_ConstantInt(C)),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000835 m_AShr(m_V, m_ConstantInt(C))),
836 m_Value(A))) &&
837 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000838 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
839 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
840 // For those bits in RHS that are known, we can propagate them to known
841 // bits in V shifted to the right by C.
842 KnownZero |= RHSKnownZero << C->getZExtValue();
843 KnownOne |= RHSKnownOne << C->getZExtValue();
844 // assume(~(v >> c) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000845 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_CombineOr(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000846 m_LShr(m_V, m_ConstantInt(C)),
847 m_AShr(m_V, m_ConstantInt(C)))),
Philip Reames00d3b272014-11-24 23:44:28 +0000848 m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000849 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000850 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
851 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
852 // For those bits in RHS that are known, we can propagate them inverted
853 // to known bits in V shifted to the right by C.
854 KnownZero |= RHSKnownOne << C->getZExtValue();
855 KnownOne |= RHSKnownZero << C->getZExtValue();
856 // assume(v >=_s c) where c is non-negative
Philip Reames00d3b272014-11-24 23:44:28 +0000857 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000858 Pred == ICmpInst::ICMP_SGE && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000859 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
860 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
861
862 if (RHSKnownZero.isNegative()) {
863 // We know that the sign bit is zero.
864 KnownZero |= APInt::getSignBit(BitWidth);
865 }
866 // assume(v >_s c) where c is at least -1.
Philip Reames00d3b272014-11-24 23:44:28 +0000867 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000868 Pred == ICmpInst::ICMP_SGT && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000869 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
870 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
871
872 if (RHSKnownOne.isAllOnesValue() || RHSKnownZero.isNegative()) {
873 // We know that the sign bit is zero.
874 KnownZero |= APInt::getSignBit(BitWidth);
875 }
876 // assume(v <=_s c) where c is negative
Philip Reames00d3b272014-11-24 23:44:28 +0000877 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000878 Pred == ICmpInst::ICMP_SLE && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000879 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
880 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
881
882 if (RHSKnownOne.isNegative()) {
883 // We know that the sign bit is one.
884 KnownOne |= APInt::getSignBit(BitWidth);
885 }
886 // assume(v <_s c) where c is non-positive
Philip Reames00d3b272014-11-24 23:44:28 +0000887 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000888 Pred == ICmpInst::ICMP_SLT && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000889 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
890 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
891
892 if (RHSKnownZero.isAllOnesValue() || RHSKnownOne.isNegative()) {
893 // We know that the sign bit is one.
894 KnownOne |= APInt::getSignBit(BitWidth);
895 }
896 // assume(v <=_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000897 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000898 Pred == ICmpInst::ICMP_ULE && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000899 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
900 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
901
902 // Whatever high bits in c are zero are known to be zero.
903 KnownZero |=
904 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
905 // assume(v <_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000906 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000907 Pred == ICmpInst::ICMP_ULT && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000908 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
909 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
910
911 // Whatever high bits in c are zero are known to be zero (if c is a power
912 // of 2, then one more).
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000913 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I), DL))
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000914 KnownZero |=
915 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes()+1);
916 else
917 KnownZero |=
918 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
Hal Finkel60db0582014-09-07 18:57:58 +0000919 }
920 }
921}
922
Jay Foada0653a32014-05-14 21:14:37 +0000923/// Determine which bits of V are known to be either zero or one and return
924/// them in the KnownZero/KnownOne bit sets.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000925///
Chris Lattner965c7692008-06-02 01:18:21 +0000926/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
927/// we cannot optimize based on the assumption that it is zero without changing
928/// it to be an explicit zero. If we don't change it to zero, other code could
929/// optimized based on the contradictory assumption that it is non-zero.
930/// Because instcombine aggressively folds operations with undef args anyway,
931/// this won't lose us code quality.
Chris Lattner4bc28252009-09-08 00:06:16 +0000932///
933/// This function is defined on values with integer type, values with pointer
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000934/// type, and vectors of integers. In the case
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000935/// where V is a vector, known zero, and known one values are the
Chris Lattner4bc28252009-09-08 00:06:16 +0000936/// same width as the vector element, and the bit is set only if it is true
937/// for all of the elements in the vector.
Hal Finkel60db0582014-09-07 18:57:58 +0000938void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000939 const DataLayout &DL, unsigned Depth, const Query &Q) {
Chris Lattner965c7692008-06-02 01:18:21 +0000940 assert(V && "No Value?");
Dan Gohmanbf0002e2009-05-21 02:28:33 +0000941 assert(Depth <= MaxDepth && "Limit Search Depth");
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000942 unsigned BitWidth = KnownZero.getBitWidth();
943
Nadav Rotem3924cb02011-12-05 06:29:09 +0000944 assert((V->getType()->isIntOrIntVectorTy() ||
945 V->getType()->getScalarType()->isPointerTy()) &&
946 "Not integer or pointer type!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000947 assert((DL.getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000948 (!V->getType()->isIntOrIntVectorTy() ||
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000949 V->getType()->getScalarSizeInBits() == BitWidth) &&
Nadav Rotem3924cb02011-12-05 06:29:09 +0000950 KnownZero.getBitWidth() == BitWidth &&
Chris Lattner965c7692008-06-02 01:18:21 +0000951 KnownOne.getBitWidth() == BitWidth &&
Jay Foade48d9e82014-05-14 08:00:07 +0000952 "V, KnownOne and KnownZero should have same BitWidth");
Chris Lattner965c7692008-06-02 01:18:21 +0000953
954 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
955 // We know all of the bits for a constant!
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000956 KnownOne = CI->getValue();
957 KnownZero = ~KnownOne;
Chris Lattner965c7692008-06-02 01:18:21 +0000958 return;
959 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000960 // Null and aggregate-zero are all-zeros.
961 if (isa<ConstantPointerNull>(V) ||
962 isa<ConstantAggregateZero>(V)) {
Jay Foad25a5e4c2010-12-01 08:53:58 +0000963 KnownOne.clearAllBits();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000964 KnownZero = APInt::getAllOnesValue(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +0000965 return;
966 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000967 // Handle a constant vector by taking the intersection of the known bits of
Chris Lattner8213c8a2012-02-06 21:56:39 +0000968 // each element. There is no real need to handle ConstantVector here, because
969 // we don't handle undef in any particularly useful way.
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000970 if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
971 // We know that CDS must be a vector of integers. Take the intersection of
972 // each element.
973 KnownZero.setAllBits(); KnownOne.setAllBits();
974 APInt Elt(KnownZero.getBitWidth(), 0);
Chris Lattner9be59592012-01-25 01:27:20 +0000975 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000976 Elt = CDS->getElementAsInteger(i);
977 KnownZero &= ~Elt;
Craig Topper1bef2c82012-12-22 19:15:35 +0000978 KnownOne &= Elt;
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000979 }
980 return;
981 }
Craig Topper1bef2c82012-12-22 19:15:35 +0000982
Chris Lattner965c7692008-06-02 01:18:21 +0000983 // The address of an aligned GlobalValue has trailing zeros.
Michael Kupersteinbe8032c2014-12-23 11:33:41 +0000984 if (auto *GO = dyn_cast<GlobalObject>(V)) {
985 unsigned Align = GO->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000986 if (Align == 0) {
Michael Kupersteinbe8032c2014-12-23 11:33:41 +0000987 if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
Eli Friedmane7ab1a22011-11-28 22:48:22 +0000988 Type *ObjectType = GVar->getType()->getElementType();
Nick Lewycky1d57ee32012-03-07 02:27:53 +0000989 if (ObjectType->isSized()) {
990 // If the object is defined in the current Module, we'll be giving
991 // it the preferred alignment. Otherwise, we have to assume that it
992 // may only have the minimum ABI alignment.
993 if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000994 Align = DL.getPreferredAlignment(GVar);
Nick Lewycky1d57ee32012-03-07 02:27:53 +0000995 else
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000996 Align = DL.getABITypeAlignment(ObjectType);
Nick Lewycky1d57ee32012-03-07 02:27:53 +0000997 }
Eli Friedmane7ab1a22011-11-28 22:48:22 +0000998 }
Dan Gohmana72f8562009-08-11 15:50:03 +0000999 }
Chris Lattner965c7692008-06-02 01:18:21 +00001000 if (Align > 0)
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001001 KnownZero = APInt::getLowBitsSet(BitWidth,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001002 countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +00001003 else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001004 KnownZero.clearAllBits();
1005 KnownOne.clearAllBits();
Chris Lattner965c7692008-06-02 01:18:21 +00001006 return;
1007 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001008
Chris Lattner83791ce2011-05-23 00:03:39 +00001009 if (Argument *A = dyn_cast<Argument>(V)) {
Hal Finkelccc70902014-07-22 16:58:55 +00001010 unsigned Align = A->getType()->isPointerTy() ? A->getParamAlignment() : 0;
Duncan Sands271ea6c2012-10-04 13:36:31 +00001011
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001012 if (!Align && A->hasStructRetAttr()) {
Duncan Sands271ea6c2012-10-04 13:36:31 +00001013 // An sret parameter has at least the ABI alignment of the return type.
1014 Type *EltTy = cast<PointerType>(A->getType())->getElementType();
1015 if (EltTy->isSized())
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001016 Align = DL.getABITypeAlignment(EltTy);
Duncan Sands271ea6c2012-10-04 13:36:31 +00001017 }
1018
1019 if (Align)
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001020 KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
David Majnemer8df46c92015-01-03 02:33:25 +00001021 else
1022 KnownZero.clearAllBits();
1023 KnownOne.clearAllBits();
Hal Finkel60db0582014-09-07 18:57:58 +00001024
1025 // Don't give up yet... there might be an assumption that provides more
1026 // information...
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001027 computeKnownBitsFromAssume(V, KnownZero, KnownOne, DL, Depth, Q);
Philip Reames1c292272015-03-10 22:43:20 +00001028
1029 // Or a dominating condition for that matter
1030 if (EnableDomConditions && Depth <= DomConditionsMaxDepth)
1031 computeKnownBitsFromDominatingCondition(V, KnownZero, KnownOne, DL,
1032 Depth, Q);
Chris Lattner83791ce2011-05-23 00:03:39 +00001033 return;
1034 }
Chris Lattner965c7692008-06-02 01:18:21 +00001035
Chris Lattner83791ce2011-05-23 00:03:39 +00001036 // Start out not knowing anything.
1037 KnownZero.clearAllBits(); KnownOne.clearAllBits();
Chris Lattner965c7692008-06-02 01:18:21 +00001038
Michael Kupersteinbe8032c2014-12-23 11:33:41 +00001039 // Limit search depth.
1040 // All recursive calls that increase depth must come after this.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001041 if (Depth == MaxDepth)
Michael Kupersteinbe8032c2014-12-23 11:33:41 +00001042 return;
1043
1044 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1045 // the bits of its aliasee.
1046 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1047 if (!GA->mayBeOverridden())
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001048 computeKnownBits(GA->getAliasee(), KnownZero, KnownOne, DL, Depth + 1, Q);
Michael Kupersteinbe8032c2014-12-23 11:33:41 +00001049 return;
1050 }
Chris Lattner965c7692008-06-02 01:18:21 +00001051
Hal Finkel60db0582014-09-07 18:57:58 +00001052 // Check whether a nearby assume intrinsic can determine some known bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001053 computeKnownBitsFromAssume(V, KnownZero, KnownOne, DL, Depth, Q);
Hal Finkel60db0582014-09-07 18:57:58 +00001054
Philip Reames1c292272015-03-10 22:43:20 +00001055 // Check whether there's a dominating condition which implies something about
1056 // this value at the given context.
1057 if (EnableDomConditions && Depth <= DomConditionsMaxDepth)
1058 computeKnownBitsFromDominatingCondition(V, KnownZero, KnownOne, DL, Depth,
1059 Q);
1060
Dan Gohman80ca01c2009-07-17 20:47:02 +00001061 Operator *I = dyn_cast<Operator>(V);
Chris Lattner965c7692008-06-02 01:18:21 +00001062 if (!I) return;
1063
1064 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohman80ca01c2009-07-17 20:47:02 +00001065 switch (I->getOpcode()) {
Chris Lattner965c7692008-06-02 01:18:21 +00001066 default: break;
Rafael Espindola53190532012-03-30 15:52:11 +00001067 case Instruction::Load:
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001068 if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
Jingyue Wu37fcb592014-06-19 16:50:16 +00001069 computeKnownBitsFromRangeMetadata(*MD, KnownZero);
Jay Foad5a29c362014-05-15 12:12:55 +00001070 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001071 case Instruction::And: {
1072 // If either the LHS or the RHS are Zero, the result is zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001073 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
1074 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001075
Chris Lattner965c7692008-06-02 01:18:21 +00001076 // Output known-1 bits are only known if set in both the LHS & RHS.
1077 KnownOne &= KnownOne2;
1078 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1079 KnownZero |= KnownZero2;
Jay Foad5a29c362014-05-15 12:12:55 +00001080 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001081 }
1082 case Instruction::Or: {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001083 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
1084 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001085
Chris Lattner965c7692008-06-02 01:18:21 +00001086 // Output known-0 bits are only known if clear in both the LHS & RHS.
1087 KnownZero &= KnownZero2;
1088 // Output known-1 are known to be set if set in either the LHS | RHS.
1089 KnownOne |= KnownOne2;
Jay Foad5a29c362014-05-15 12:12:55 +00001090 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001091 }
1092 case Instruction::Xor: {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001093 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
1094 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001095
Chris Lattner965c7692008-06-02 01:18:21 +00001096 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1097 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1098 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1099 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1100 KnownZero = KnownZeroOut;
Jay Foad5a29c362014-05-15 12:12:55 +00001101 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001102 }
1103 case Instruction::Mul: {
Nick Lewyckyfa306072012-03-18 23:28:48 +00001104 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001105 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, KnownZero,
1106 KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001107 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001108 }
1109 case Instruction::UDiv: {
1110 // For the purposes of computing leading zeros we can conservatively
1111 // treat a udiv as a logical right shift by the power of 2 known to
1112 // be less than the denominator.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001113 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001114 unsigned LeadZ = KnownZero2.countLeadingOnes();
1115
Jay Foad25a5e4c2010-12-01 08:53:58 +00001116 KnownOne2.clearAllBits();
1117 KnownZero2.clearAllBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001118 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001119 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1120 if (RHSUnknownLeadingOnes != BitWidth)
1121 LeadZ = std::min(BitWidth,
1122 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1123
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001124 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
Jay Foad5a29c362014-05-15 12:12:55 +00001125 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001126 }
1127 case Instruction::Select:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001128 computeKnownBits(I->getOperand(2), KnownZero, KnownOne, DL, Depth + 1, Q);
1129 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001130
1131 // Only known if known in both the LHS and RHS.
1132 KnownOne &= KnownOne2;
1133 KnownZero &= KnownZero2;
Jay Foad5a29c362014-05-15 12:12:55 +00001134 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001135 case Instruction::FPTrunc:
1136 case Instruction::FPExt:
1137 case Instruction::FPToUI:
1138 case Instruction::FPToSI:
1139 case Instruction::SIToFP:
1140 case Instruction::UIToFP:
Jay Foad5a29c362014-05-15 12:12:55 +00001141 break; // Can't work with floating point.
Chris Lattner965c7692008-06-02 01:18:21 +00001142 case Instruction::PtrToInt:
1143 case Instruction::IntToPtr:
Matt Arsenaultf1a7e622014-07-15 01:55:03 +00001144 case Instruction::AddrSpaceCast: // Pointers could be different sizes.
Chris Lattner965c7692008-06-02 01:18:21 +00001145 // FALL THROUGH and handle them the same as zext/trunc.
1146 case Instruction::ZExt:
1147 case Instruction::Trunc: {
Chris Lattner229907c2011-07-18 04:54:35 +00001148 Type *SrcTy = I->getOperand(0)->getType();
Nadav Rotem15198e92012-10-26 17:17:05 +00001149
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001150 unsigned SrcBitWidth;
Chris Lattner965c7692008-06-02 01:18:21 +00001151 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1152 // which fall through here.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001153 SrcBitWidth = DL.getTypeSizeInBits(SrcTy->getScalarType());
Nadav Rotem15198e92012-10-26 17:17:05 +00001154
1155 assert(SrcBitWidth && "SrcBitWidth can't be zero");
Jay Foad583abbc2010-12-07 08:25:19 +00001156 KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
1157 KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001158 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
Jay Foad583abbc2010-12-07 08:25:19 +00001159 KnownZero = KnownZero.zextOrTrunc(BitWidth);
1160 KnownOne = KnownOne.zextOrTrunc(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +00001161 // Any top bits are known to be zero.
1162 if (BitWidth > SrcBitWidth)
1163 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001164 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001165 }
1166 case Instruction::BitCast: {
Chris Lattner229907c2011-07-18 04:54:35 +00001167 Type *SrcTy = I->getOperand(0)->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00001168 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattneredb84072009-07-02 16:04:08 +00001169 // TODO: For now, not handling conversions like:
1170 // (bitcast i64 %x to <2 x i32>)
Duncan Sands19d0b472010-02-16 11:11:14 +00001171 !I->getType()->isVectorTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001172 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
Jay Foad5a29c362014-05-15 12:12:55 +00001173 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001174 }
1175 break;
1176 }
1177 case Instruction::SExt: {
1178 // Compute the bits in the result that are not present in the input.
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001179 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Craig Topper1bef2c82012-12-22 19:15:35 +00001180
Jay Foad583abbc2010-12-07 08:25:19 +00001181 KnownZero = KnownZero.trunc(SrcBitWidth);
1182 KnownOne = KnownOne.trunc(SrcBitWidth);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001183 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
Jay Foad583abbc2010-12-07 08:25:19 +00001184 KnownZero = KnownZero.zext(BitWidth);
1185 KnownOne = KnownOne.zext(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +00001186
1187 // If the sign bit of the input is known set or clear, then we know the
1188 // top bits of the result.
1189 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
1190 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1191 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
1192 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001193 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001194 }
1195 case Instruction::Shl:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001196 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Chris Lattner965c7692008-06-02 01:18:21 +00001197 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1198 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001199 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001200 KnownZero <<= ShiftAmt;
1201 KnownOne <<= ShiftAmt;
1202 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Chris Lattner965c7692008-06-02 01:18:21 +00001203 }
1204 break;
1205 case Instruction::LShr:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001206 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Chris Lattner965c7692008-06-02 01:18:21 +00001207 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1208 // Compute the new bits that are at the top now.
1209 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Craig Topper1bef2c82012-12-22 19:15:35 +00001210
Chris Lattner965c7692008-06-02 01:18:21 +00001211 // Unsigned shift right.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001212 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001213 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
1214 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
1215 // high bits known zero.
1216 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Chris Lattner965c7692008-06-02 01:18:21 +00001217 }
1218 break;
1219 case Instruction::AShr:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001220 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Chris Lattner965c7692008-06-02 01:18:21 +00001221 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1222 // Compute the new bits that are at the top now.
Chris Lattnerc86e67e2011-01-04 18:19:15 +00001223 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
Craig Topper1bef2c82012-12-22 19:15:35 +00001224
Chris Lattner965c7692008-06-02 01:18:21 +00001225 // Signed shift right.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001226 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001227 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
1228 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Craig Topper1bef2c82012-12-22 19:15:35 +00001229
Chris Lattner965c7692008-06-02 01:18:21 +00001230 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1231 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
1232 KnownZero |= HighBits;
1233 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
1234 KnownOne |= HighBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001235 }
1236 break;
1237 case Instruction::Sub: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001238 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001239 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001240 KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
1241 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001242 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001243 }
Chris Lattner965c7692008-06-02 01:18:21 +00001244 case Instruction::Add: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001245 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001246 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001247 KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
1248 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001249 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001250 }
1251 case Instruction::SRem:
1252 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001253 APInt RA = Rem->getValue().abs();
1254 if (RA.isPowerOf2()) {
1255 APInt LowBits = RA - 1;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001256 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1,
1257 Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001258
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001259 // The low bits of the first operand are unchanged by the srem.
1260 KnownZero = KnownZero2 & LowBits;
1261 KnownOne = KnownOne2 & LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001262
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001263 // If the first operand is non-negative or has all low bits zero, then
1264 // the upper bits are all zero.
1265 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1266 KnownZero |= ~LowBits;
1267
1268 // If the first operand is negative and not all low bits are zero, then
1269 // the upper bits are all one.
1270 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
1271 KnownOne |= ~LowBits;
1272
Craig Topper1bef2c82012-12-22 19:15:35 +00001273 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001274 }
1275 }
Nick Lewyckye4679792011-03-07 01:50:10 +00001276
1277 // The sign bit is the LHS's sign bit, except when the result of the
1278 // remainder is zero.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001279 if (KnownZero.isNonNegative()) {
Nick Lewyckye4679792011-03-07 01:50:10 +00001280 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001281 computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, DL,
1282 Depth + 1, Q);
Nick Lewyckye4679792011-03-07 01:50:10 +00001283 // If it's known zero, our sign bit is also zero.
1284 if (LHSKnownZero.isNegative())
Duncan Sands34c48692012-04-30 11:56:58 +00001285 KnownZero.setBit(BitWidth - 1);
Nick Lewyckye4679792011-03-07 01:50:10 +00001286 }
1287
Chris Lattner965c7692008-06-02 01:18:21 +00001288 break;
1289 case Instruction::URem: {
1290 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1291 APInt RA = Rem->getValue();
1292 if (RA.isPowerOf2()) {
1293 APInt LowBits = (RA - 1);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001294 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1,
1295 Q);
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001296 KnownZero |= ~LowBits;
1297 KnownOne &= LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001298 break;
1299 }
1300 }
1301
1302 // Since the result is less than or equal to either operand, any leading
1303 // zero bits in either operand must also exist in the result.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001304 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1305 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001306
Chris Lattner4612ae12009-01-20 18:22:57 +00001307 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
Chris Lattner965c7692008-06-02 01:18:21 +00001308 KnownZero2.countLeadingOnes());
Jay Foad25a5e4c2010-12-01 08:53:58 +00001309 KnownOne.clearAllBits();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001310 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
Chris Lattner965c7692008-06-02 01:18:21 +00001311 break;
1312 }
1313
Victor Hernandeza3aaf852009-10-17 01:18:07 +00001314 case Instruction::Alloca: {
Victor Hernandez8acf2952009-10-23 21:09:37 +00001315 AllocaInst *AI = cast<AllocaInst>(V);
Chris Lattner965c7692008-06-02 01:18:21 +00001316 unsigned Align = AI->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001317 if (Align == 0)
1318 Align = DL.getABITypeAlignment(AI->getType()->getElementType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001319
Chris Lattner965c7692008-06-02 01:18:21 +00001320 if (Align > 0)
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001321 KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +00001322 break;
1323 }
1324 case Instruction::GetElementPtr: {
1325 // Analyze all of the subscripts of this getelementptr instruction
1326 // to determine if we can prove known low zero bits.
Chris Lattner965c7692008-06-02 01:18:21 +00001327 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001328 computeKnownBits(I->getOperand(0), LocalKnownZero, LocalKnownOne, DL,
1329 Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001330 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1331
1332 gep_type_iterator GTI = gep_type_begin(I);
1333 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1334 Value *Index = I->getOperand(i);
Chris Lattner229907c2011-07-18 04:54:35 +00001335 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001336 // Handle struct member offset arithmetic.
Matt Arsenault74742a12013-08-19 21:43:16 +00001337
1338 // Handle case when index is vector zeroinitializer
1339 Constant *CIndex = cast<Constant>(Index);
1340 if (CIndex->isZeroValue())
1341 continue;
1342
1343 if (CIndex->getType()->isVectorTy())
1344 Index = CIndex->getSplatValue();
1345
Chris Lattner965c7692008-06-02 01:18:21 +00001346 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001347 const StructLayout *SL = DL.getStructLayout(STy);
Chris Lattner965c7692008-06-02 01:18:21 +00001348 uint64_t Offset = SL->getElementOffset(Idx);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001349 TrailZ = std::min<unsigned>(TrailZ,
1350 countTrailingZeros(Offset));
Chris Lattner965c7692008-06-02 01:18:21 +00001351 } else {
1352 // Handle array index arithmetic.
Chris Lattner229907c2011-07-18 04:54:35 +00001353 Type *IndexedTy = GTI.getIndexedType();
Jay Foad5a29c362014-05-15 12:12:55 +00001354 if (!IndexedTy->isSized()) {
1355 TrailZ = 0;
1356 break;
1357 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001358 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001359 uint64_t TypeSize = DL.getTypeAllocSize(IndexedTy);
Chris Lattner965c7692008-06-02 01:18:21 +00001360 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001361 computeKnownBits(Index, LocalKnownZero, LocalKnownOne, DL, Depth + 1,
1362 Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001363 TrailZ = std::min(TrailZ,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001364 unsigned(countTrailingZeros(TypeSize) +
Chris Lattner4612ae12009-01-20 18:22:57 +00001365 LocalKnownZero.countTrailingOnes()));
Chris Lattner965c7692008-06-02 01:18:21 +00001366 }
1367 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001368
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001369 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
Chris Lattner965c7692008-06-02 01:18:21 +00001370 break;
1371 }
1372 case Instruction::PHI: {
1373 PHINode *P = cast<PHINode>(I);
1374 // Handle the case of a simple two-predecessor recurrence PHI.
1375 // There's a lot more that could theoretically be done here, but
1376 // this is sufficient to catch some interesting cases.
1377 if (P->getNumIncomingValues() == 2) {
1378 for (unsigned i = 0; i != 2; ++i) {
1379 Value *L = P->getIncomingValue(i);
1380 Value *R = P->getIncomingValue(!i);
Dan Gohman80ca01c2009-07-17 20:47:02 +00001381 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner965c7692008-06-02 01:18:21 +00001382 if (!LU)
1383 continue;
Dan Gohman80ca01c2009-07-17 20:47:02 +00001384 unsigned Opcode = LU->getOpcode();
Chris Lattner965c7692008-06-02 01:18:21 +00001385 // Check for operations that have the property that if
1386 // both their operands have low zero bits, the result
1387 // will have low zero bits.
1388 if (Opcode == Instruction::Add ||
1389 Opcode == Instruction::Sub ||
1390 Opcode == Instruction::And ||
1391 Opcode == Instruction::Or ||
1392 Opcode == Instruction::Mul) {
1393 Value *LL = LU->getOperand(0);
1394 Value *LR = LU->getOperand(1);
1395 // Find a recurrence.
1396 if (LL == I)
1397 L = LR;
1398 else if (LR == I)
1399 L = LL;
1400 else
1401 break;
1402 // Ok, we have a PHI of the form L op= R. Check for low
1403 // zero bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001404 computeKnownBits(R, KnownZero2, KnownOne2, DL, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001405
1406 // We need to take the minimum number of known bits
1407 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001408 computeKnownBits(L, KnownZero3, KnownOne3, DL, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001409
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001410 KnownZero = APInt::getLowBitsSet(BitWidth,
David Greeneaebd9e02008-10-27 23:24:03 +00001411 std::min(KnownZero2.countTrailingOnes(),
1412 KnownZero3.countTrailingOnes()));
Chris Lattner965c7692008-06-02 01:18:21 +00001413 break;
1414 }
1415 }
1416 }
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001417
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001418 // Unreachable blocks may have zero-operand PHI nodes.
1419 if (P->getNumIncomingValues() == 0)
Jay Foad5a29c362014-05-15 12:12:55 +00001420 break;
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001421
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001422 // Otherwise take the unions of the known bit sets of the operands,
1423 // taking conservative care to avoid excessive recursion.
1424 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
Duncan Sands7dc3d472011-03-08 12:39:03 +00001425 // Skip if every incoming value references to ourself.
Nuno Lopes0d44a502012-07-03 21:15:40 +00001426 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
Duncan Sands7dc3d472011-03-08 12:39:03 +00001427 break;
1428
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001429 KnownZero = APInt::getAllOnesValue(BitWidth);
1430 KnownOne = APInt::getAllOnesValue(BitWidth);
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001431 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) {
1432 // Skip direct self references.
1433 if (P->getIncomingValue(i) == P) continue;
1434
1435 KnownZero2 = APInt(BitWidth, 0);
1436 KnownOne2 = APInt(BitWidth, 0);
1437 // Recurse, but cap the recursion to one level, because we don't
1438 // want to waste time spinning around in loops.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001439 computeKnownBits(P->getIncomingValue(i), KnownZero2, KnownOne2, DL,
1440 MaxDepth - 1, Q);
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001441 KnownZero &= KnownZero2;
1442 KnownOne &= KnownOne2;
1443 // If all bits have been ruled out, there's no need to check
1444 // more operands.
1445 if (!KnownZero && !KnownOne)
1446 break;
1447 }
1448 }
Chris Lattner965c7692008-06-02 01:18:21 +00001449 break;
1450 }
1451 case Instruction::Call:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001452 case Instruction::Invoke:
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001453 if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
Jingyue Wu37fcb592014-06-19 16:50:16 +00001454 computeKnownBitsFromRangeMetadata(*MD, KnownZero);
1455 // If a range metadata is attached to this IntrinsicInst, intersect the
1456 // explicit range specified by the metadata and the implicit range of
1457 // the intrinsic.
Chris Lattner965c7692008-06-02 01:18:21 +00001458 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1459 switch (II->getIntrinsicID()) {
1460 default: break;
Chris Lattner965c7692008-06-02 01:18:21 +00001461 case Intrinsic::ctlz:
1462 case Intrinsic::cttz: {
1463 unsigned LowBits = Log2_32(BitWidth)+1;
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001464 // If this call is undefined for 0, the result will be less than 2^n.
1465 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1466 LowBits -= 1;
Jingyue Wu37fcb592014-06-19 16:50:16 +00001467 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001468 break;
1469 }
1470 case Intrinsic::ctpop: {
1471 unsigned LowBits = Log2_32(BitWidth)+1;
Jingyue Wu37fcb592014-06-19 16:50:16 +00001472 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
Chris Lattner965c7692008-06-02 01:18:21 +00001473 break;
1474 }
Chad Rosierb3628842011-05-26 23:13:19 +00001475 case Intrinsic::x86_sse42_crc32_64_64:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001476 KnownZero |= APInt::getHighBitsSet(64, 32);
Evan Cheng2a746bf2011-05-22 18:25:30 +00001477 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001478 }
1479 }
1480 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001481 case Instruction::ExtractValue:
1482 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
1483 ExtractValueInst *EVI = cast<ExtractValueInst>(I);
1484 if (EVI->getNumIndices() != 1) break;
1485 if (EVI->getIndices()[0] == 0) {
1486 switch (II->getIntrinsicID()) {
1487 default: break;
1488 case Intrinsic::uadd_with_overflow:
1489 case Intrinsic::sadd_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001490 computeKnownBitsAddSub(true, II->getArgOperand(0),
1491 II->getArgOperand(1), false, KnownZero,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001492 KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001493 break;
1494 case Intrinsic::usub_with_overflow:
1495 case Intrinsic::ssub_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001496 computeKnownBitsAddSub(false, II->getArgOperand(0),
1497 II->getArgOperand(1), false, KnownZero,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001498 KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001499 break;
Nick Lewyckyfa306072012-03-18 23:28:48 +00001500 case Intrinsic::umul_with_overflow:
1501 case Intrinsic::smul_with_overflow:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001502 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
1503 KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
1504 Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001505 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001506 }
1507 }
1508 }
Chris Lattner965c7692008-06-02 01:18:21 +00001509 }
Jay Foad5a29c362014-05-15 12:12:55 +00001510
1511 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001512}
1513
Sanjay Patelaee84212014-11-04 16:27:42 +00001514/// Determine whether the sign bit is known to be zero or one.
1515/// Convenience wrapper around computeKnownBits.
Hal Finkel60db0582014-09-07 18:57:58 +00001516void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001517 const DataLayout &DL, unsigned Depth, const Query &Q) {
1518 unsigned BitWidth = getBitWidth(V->getType(), DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001519 if (!BitWidth) {
1520 KnownZero = false;
1521 KnownOne = false;
1522 return;
1523 }
1524 APInt ZeroBits(BitWidth, 0);
1525 APInt OneBits(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001526 computeKnownBits(V, ZeroBits, OneBits, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001527 KnownOne = OneBits[BitWidth - 1];
1528 KnownZero = ZeroBits[BitWidth - 1];
1529}
1530
Sanjay Patelaee84212014-11-04 16:27:42 +00001531/// Return true if the given value is known to have exactly one
Duncan Sandsd3951082011-01-25 09:38:29 +00001532/// bit set when defined. For vectors return true if every element is known to
Sanjay Patelaee84212014-11-04 16:27:42 +00001533/// be a power of two when defined. Supports values with integer or pointer
Duncan Sandsd3951082011-01-25 09:38:29 +00001534/// types and vectors of integers.
Hal Finkel60db0582014-09-07 18:57:58 +00001535bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001536 const Query &Q, const DataLayout &DL) {
Duncan Sandsba286d72011-10-26 20:55:21 +00001537 if (Constant *C = dyn_cast<Constant>(V)) {
1538 if (C->isNullValue())
1539 return OrZero;
1540 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1541 return CI->getValue().isPowerOf2();
1542 // TODO: Handle vector constants.
1543 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001544
1545 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1546 // it is shifted off the end then the result is undefined.
1547 if (match(V, m_Shl(m_One(), m_Value())))
1548 return true;
1549
1550 // (signbit) >>l X is clearly a power of two if the one is not shifted off the
1551 // bottom. If it is shifted off the bottom then the result is undefined.
Duncan Sands4b397fc2011-02-01 08:50:33 +00001552 if (match(V, m_LShr(m_SignBit(), m_Value())))
Duncan Sandsd3951082011-01-25 09:38:29 +00001553 return true;
1554
1555 // The remaining tests are all recursive, so bail out if we hit the limit.
1556 if (Depth++ == MaxDepth)
1557 return false;
1558
Craig Topper9f008862014-04-15 04:59:12 +00001559 Value *X = nullptr, *Y = nullptr;
Duncan Sands985ba632011-10-28 18:30:05 +00001560 // A shift of a power of two is a power of two or zero.
1561 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
1562 match(V, m_Shr(m_Value(X), m_Value()))))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001563 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q, DL);
Duncan Sands985ba632011-10-28 18:30:05 +00001564
Duncan Sandsd3951082011-01-25 09:38:29 +00001565 if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001566 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q, DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001567
1568 if (SelectInst *SI = dyn_cast<SelectInst>(V))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001569 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q, DL) &&
1570 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q, DL);
Duncan Sandsba286d72011-10-26 20:55:21 +00001571
Duncan Sandsba286d72011-10-26 20:55:21 +00001572 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1573 // A power of two and'd with anything is a power of two or zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001574 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q, DL) ||
1575 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q, DL))
Duncan Sandsba286d72011-10-26 20:55:21 +00001576 return true;
1577 // X & (-X) is always a power of two or zero.
1578 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1579 return true;
1580 return false;
1581 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001582
David Majnemerb7d54092013-07-30 21:01:36 +00001583 // Adding a power-of-two or zero to the same power-of-two or zero yields
1584 // either the original power-of-two, a larger power-of-two or zero.
1585 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1586 OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
1587 if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1588 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1589 match(X, m_And(m_Value(), m_Specific(Y))))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001590 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q, DL))
David Majnemerb7d54092013-07-30 21:01:36 +00001591 return true;
1592 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1593 match(Y, m_And(m_Value(), m_Specific(X))))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001594 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q, DL))
David Majnemerb7d54092013-07-30 21:01:36 +00001595 return true;
1596
1597 unsigned BitWidth = V->getType()->getScalarSizeInBits();
1598 APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001599 computeKnownBits(X, LHSZeroBits, LHSOneBits, DL, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001600
1601 APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001602 computeKnownBits(Y, RHSZeroBits, RHSOneBits, DL, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001603 // If i8 V is a power of two or zero:
1604 // ZeroBits: 1 1 1 0 1 1 1 1
1605 // ~ZeroBits: 0 0 0 1 0 0 0 0
1606 if ((~(LHSZeroBits & RHSZeroBits)).isPowerOf2())
1607 // If OrZero isn't set, we cannot give back a zero result.
1608 // Make sure either the LHS or RHS has a bit set.
1609 if (OrZero || RHSOneBits.getBoolValue() || LHSOneBits.getBoolValue())
1610 return true;
1611 }
1612 }
David Majnemerbeab5672013-05-18 19:30:37 +00001613
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001614 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewyckyf0469af2011-03-21 21:40:32 +00001615 // is a power of two only if the first operand is a power of two and not
1616 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001617 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1618 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
Hal Finkel60db0582014-09-07 18:57:58 +00001619 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001620 Depth, Q, DL);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001621 }
1622
Duncan Sandsd3951082011-01-25 09:38:29 +00001623 return false;
1624}
1625
Chandler Carruth80d3e562012-12-07 02:08:58 +00001626/// \brief Test whether a GEP's result is known to be non-null.
1627///
1628/// Uses properties inherent in a GEP to try to determine whether it is known
1629/// to be non-null.
1630///
1631/// Currently this routine does not support vector GEPs.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001632static bool isGEPKnownNonNull(GEPOperator *GEP, const DataLayout &DL,
Hal Finkel60db0582014-09-07 18:57:58 +00001633 unsigned Depth, const Query &Q) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001634 if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1635 return false;
1636
1637 // FIXME: Support vector-GEPs.
1638 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1639
1640 // If the base pointer is non-null, we cannot walk to a null address with an
1641 // inbounds GEP in address space zero.
Hal Finkel60db0582014-09-07 18:57:58 +00001642 if (isKnownNonZero(GEP->getPointerOperand(), DL, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001643 return true;
1644
Chandler Carruth80d3e562012-12-07 02:08:58 +00001645 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1646 // If so, then the GEP cannot produce a null pointer, as doing so would
1647 // inherently violate the inbounds contract within address space zero.
1648 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1649 GTI != GTE; ++GTI) {
1650 // Struct types are easy -- they must always be indexed by a constant.
1651 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1652 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1653 unsigned ElementIdx = OpC->getZExtValue();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001654 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth80d3e562012-12-07 02:08:58 +00001655 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1656 if (ElementOffset > 0)
1657 return true;
1658 continue;
1659 }
1660
1661 // If we have a zero-sized type, the index doesn't matter. Keep looping.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001662 if (DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
Chandler Carruth80d3e562012-12-07 02:08:58 +00001663 continue;
1664
1665 // Fast path the constant operand case both for efficiency and so we don't
1666 // increment Depth when just zipping down an all-constant GEP.
1667 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1668 if (!OpC->isZero())
1669 return true;
1670 continue;
1671 }
1672
1673 // We post-increment Depth here because while isKnownNonZero increments it
1674 // as well, when we pop back up that increment won't persist. We don't want
1675 // to recurse 10k times just because we have 10k GEP operands. We don't
1676 // bail completely out because we want to handle constant GEPs regardless
1677 // of depth.
1678 if (Depth++ >= MaxDepth)
1679 continue;
1680
Hal Finkel60db0582014-09-07 18:57:58 +00001681 if (isKnownNonZero(GTI.getOperand(), DL, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001682 return true;
1683 }
1684
1685 return false;
1686}
1687
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001688/// Does the 'Range' metadata (which must be a valid MD_range operand list)
1689/// ensure that the value it's attached to is never Value? 'RangeType' is
1690/// is the type of the value described by the range.
1691static bool rangeMetadataExcludesValue(MDNode* Ranges,
1692 const APInt& Value) {
1693 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1694 assert(NumRanges >= 1);
1695 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001696 ConstantInt *Lower =
1697 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1698 ConstantInt *Upper =
1699 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001700 ConstantRange Range(Lower->getValue(), Upper->getValue());
1701 if (Range.contains(Value))
1702 return false;
1703 }
1704 return true;
1705}
1706
Sanjay Patelaee84212014-11-04 16:27:42 +00001707/// Return true if the given value is known to be non-zero when defined.
1708/// For vectors return true if every element is known to be non-zero when
1709/// defined. Supports values with integer or pointer type and vectors of
1710/// integers.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001711bool isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
Hal Finkel60db0582014-09-07 18:57:58 +00001712 const Query &Q) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001713 if (Constant *C = dyn_cast<Constant>(V)) {
1714 if (C->isNullValue())
1715 return false;
1716 if (isa<ConstantInt>(C))
1717 // Must be non-zero due to null test above.
1718 return true;
1719 // TODO: Handle vectors
1720 return false;
1721 }
1722
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001723 if (Instruction* I = dyn_cast<Instruction>(V)) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001724 if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001725 // If the possible ranges don't contain zero, then the value is
1726 // definitely non-zero.
1727 if (IntegerType* Ty = dyn_cast<IntegerType>(V->getType())) {
1728 const APInt ZeroValue(Ty->getBitWidth(), 0);
1729 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
1730 return true;
1731 }
1732 }
1733 }
1734
Duncan Sandsd3951082011-01-25 09:38:29 +00001735 // The remaining tests are all recursive, so bail out if we hit the limit.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001736 if (Depth++ >= MaxDepth)
Duncan Sandsd3951082011-01-25 09:38:29 +00001737 return false;
1738
Chandler Carruth80d3e562012-12-07 02:08:58 +00001739 // Check for pointer simplifications.
1740 if (V->getType()->isPointerTy()) {
Manman Ren12171122013-03-18 21:23:25 +00001741 if (isKnownNonNull(V))
1742 return true;
Chandler Carruth80d3e562012-12-07 02:08:58 +00001743 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001744 if (isGEPKnownNonNull(GEP, DL, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001745 return true;
1746 }
1747
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001748 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001749
1750 // X | Y != 0 if X != 0 or Y != 0.
Craig Topper9f008862014-04-15 04:59:12 +00001751 Value *X = nullptr, *Y = nullptr;
Duncan Sandsd3951082011-01-25 09:38:29 +00001752 if (match(V, m_Or(m_Value(X), m_Value(Y))))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001753 return isKnownNonZero(X, DL, Depth, Q) || isKnownNonZero(Y, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001754
1755 // ext X != 0 if X != 0.
1756 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001757 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001758
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001759 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd3951082011-01-25 09:38:29 +00001760 // if the lowest bit is shifted off the end.
1761 if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001762 // shl nuw can't remove any non-zero bits.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001763 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001764 if (BO->hasNoUnsignedWrap())
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001765 return isKnownNonZero(X, DL, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001766
Duncan Sandsd3951082011-01-25 09:38:29 +00001767 APInt KnownZero(BitWidth, 0);
1768 APInt KnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001769 computeKnownBits(X, KnownZero, KnownOne, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001770 if (KnownOne[0])
1771 return true;
1772 }
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001773 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd3951082011-01-25 09:38:29 +00001774 // defined if the sign bit is shifted off the end.
1775 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001776 // shr exact can only shift out zero bits.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001777 PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001778 if (BO->isExact())
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001779 return isKnownNonZero(X, DL, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001780
Duncan Sandsd3951082011-01-25 09:38:29 +00001781 bool XKnownNonNegative, XKnownNegative;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001782 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001783 if (XKnownNegative)
1784 return true;
1785 }
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001786 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001787 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001788 return isKnownNonZero(X, DL, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001789 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001790 // X + Y.
1791 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1792 bool XKnownNonNegative, XKnownNegative;
1793 bool YKnownNonNegative, YKnownNegative;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001794 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, DL, Depth, Q);
1795 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001796
1797 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001798 // zero unless both X and Y are zero.
Duncan Sandsd3951082011-01-25 09:38:29 +00001799 if (XKnownNonNegative && YKnownNonNegative)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001800 if (isKnownNonZero(X, DL, Depth, Q) || isKnownNonZero(Y, DL, Depth, Q))
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001801 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00001802
1803 // If X and Y are both negative (as signed values) then their sum is not
1804 // zero unless both X and Y equal INT_MIN.
1805 if (BitWidth && XKnownNegative && YKnownNegative) {
1806 APInt KnownZero(BitWidth, 0);
1807 APInt KnownOne(BitWidth, 0);
1808 APInt Mask = APInt::getSignedMaxValue(BitWidth);
1809 // The sign bit of X is set. If some other bit is set then X is not equal
1810 // to INT_MIN.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001811 computeKnownBits(X, KnownZero, KnownOne, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001812 if ((KnownOne & Mask) != 0)
1813 return true;
1814 // The sign bit of Y is set. If some other bit is set then Y is not equal
1815 // to INT_MIN.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001816 computeKnownBits(Y, KnownZero, KnownOne, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001817 if ((KnownOne & Mask) != 0)
1818 return true;
1819 }
1820
1821 // The sum of a non-negative number and a power of two is not zero.
Hal Finkel60db0582014-09-07 18:57:58 +00001822 if (XKnownNonNegative &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001823 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q, DL))
Duncan Sandsd3951082011-01-25 09:38:29 +00001824 return true;
Hal Finkel60db0582014-09-07 18:57:58 +00001825 if (YKnownNonNegative &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001826 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q, DL))
Duncan Sandsd3951082011-01-25 09:38:29 +00001827 return true;
1828 }
Duncan Sands7cb61e52011-10-27 19:16:21 +00001829 // X * Y.
1830 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
1831 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1832 // If X and Y are non-zero then so is X * Y as long as the multiplication
1833 // does not overflow.
1834 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001835 isKnownNonZero(X, DL, Depth, Q) && isKnownNonZero(Y, DL, Depth, Q))
Duncan Sands7cb61e52011-10-27 19:16:21 +00001836 return true;
1837 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001838 // (C ? X : Y) != 0 if X != 0 and Y != 0.
1839 else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001840 if (isKnownNonZero(SI->getTrueValue(), DL, Depth, Q) &&
1841 isKnownNonZero(SI->getFalseValue(), DL, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001842 return true;
1843 }
1844
1845 if (!BitWidth) return false;
1846 APInt KnownZero(BitWidth, 0);
1847 APInt KnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001848 computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001849 return KnownOne != 0;
1850}
1851
Sanjay Patelaee84212014-11-04 16:27:42 +00001852/// Return true if 'V & Mask' is known to be zero. We use this predicate to
1853/// simplify operations downstream. Mask is known to be zero for bits that V
1854/// cannot have.
Chris Lattner4bc28252009-09-08 00:06:16 +00001855///
1856/// This function is defined on values with integer type, values with pointer
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001857/// type, and vectors of integers. In the case
Chris Lattner4bc28252009-09-08 00:06:16 +00001858/// where V is a vector, the mask, known zero, and known one values are the
1859/// same width as the vector element, and the bit is set only if it is true
1860/// for all of the elements in the vector.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001861bool MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
1862 unsigned Depth, const Query &Q) {
Chris Lattner965c7692008-06-02 01:18:21 +00001863 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001864 computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001865 return (KnownZero & Mask) == Mask;
1866}
1867
1868
1869
Sanjay Patelaee84212014-11-04 16:27:42 +00001870/// Return the number of times the sign bit of the register is replicated into
1871/// the other bits. We know that at least 1 bit is always equal to the sign bit
1872/// (itself), but other cases can give us information. For example, immediately
1873/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
1874/// other, so we return 3.
Chris Lattner965c7692008-06-02 01:18:21 +00001875///
1876/// 'Op' must have a scalar integer type.
1877///
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001878unsigned ComputeNumSignBits(Value *V, const DataLayout &DL, unsigned Depth,
1879 const Query &Q) {
1880 unsigned TyBits = DL.getTypeSizeInBits(V->getType()->getScalarType());
Chris Lattner965c7692008-06-02 01:18:21 +00001881 unsigned Tmp, Tmp2;
1882 unsigned FirstAnswer = 1;
1883
Jay Foada0653a32014-05-14 21:14:37 +00001884 // Note that ConstantInt is handled by the general computeKnownBits case
Chris Lattner2e01a692008-06-02 18:39:07 +00001885 // below.
1886
Chris Lattner965c7692008-06-02 01:18:21 +00001887 if (Depth == 6)
1888 return 1; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00001889
Dan Gohman80ca01c2009-07-17 20:47:02 +00001890 Operator *U = dyn_cast<Operator>(V);
1891 switch (Operator::getOpcode(V)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001892 default: break;
1893 case Instruction::SExt:
Mon P Wangbb3eac92009-12-02 04:59:58 +00001894 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001895 return ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q) + Tmp;
Craig Topper1bef2c82012-12-22 19:15:35 +00001896
Nadav Rotemc99a3872015-03-06 00:23:58 +00001897 case Instruction::SDiv: {
Nadav Rotem029c5c72015-03-03 21:39:02 +00001898 const APInt *Denominator;
1899 // sdiv X, C -> adds log(C) sign bits.
1900 if (match(U->getOperand(1), m_APInt(Denominator))) {
1901
1902 // Ignore non-positive denominator.
1903 if (!Denominator->isStrictlyPositive())
1904 break;
1905
1906 // Calculate the incoming numerator bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001907 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
Nadav Rotem029c5c72015-03-03 21:39:02 +00001908
1909 // Add floor(log(C)) bits to the numerator bits.
1910 return std::min(TyBits, NumBits + Denominator->logBase2());
1911 }
1912 break;
Nadav Rotemc99a3872015-03-06 00:23:58 +00001913 }
1914
1915 case Instruction::SRem: {
1916 const APInt *Denominator;
Sanjoy Dase561fee2015-03-25 22:33:53 +00001917 // srem X, C -> we know that the result is within [-C+1,C) when C is a
1918 // positive constant. This let us put a lower bound on the number of sign
1919 // bits.
Nadav Rotemc99a3872015-03-06 00:23:58 +00001920 if (match(U->getOperand(1), m_APInt(Denominator))) {
1921
1922 // Ignore non-positive denominator.
1923 if (!Denominator->isStrictlyPositive())
1924 break;
1925
1926 // Calculate the incoming numerator bits. SRem by a positive constant
1927 // can't lower the number of sign bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001928 unsigned NumrBits =
1929 ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
Nadav Rotemc99a3872015-03-06 00:23:58 +00001930
1931 // Calculate the leading sign bit constraints by examining the
Sanjoy Dase561fee2015-03-25 22:33:53 +00001932 // denominator. Given that the denominator is positive, there are two
1933 // cases:
1934 //
1935 // 1. the numerator is positive. The result range is [0,C) and [0,C) u<
1936 // (1 << ceilLogBase2(C)).
1937 //
1938 // 2. the numerator is negative. Then the result range is (-C,0] and
1939 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
1940 //
1941 // Thus a lower bound on the number of sign bits is `TyBits -
1942 // ceilLogBase2(C)`.
Nadav Rotemc99a3872015-03-06 00:23:58 +00001943
Sanjoy Dase561fee2015-03-25 22:33:53 +00001944 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
Nadav Rotemc99a3872015-03-06 00:23:58 +00001945 return std::max(NumrBits, ResBits);
1946 }
1947 break;
1948 }
Nadav Rotem029c5c72015-03-03 21:39:02 +00001949
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001950 case Instruction::AShr: {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001951 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001952 // ashr X, C -> adds C sign bits. Vectors too.
1953 const APInt *ShAmt;
1954 if (match(U->getOperand(1), m_APInt(ShAmt))) {
1955 Tmp += ShAmt->getZExtValue();
Chris Lattner965c7692008-06-02 01:18:21 +00001956 if (Tmp > TyBits) Tmp = TyBits;
1957 }
1958 return Tmp;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001959 }
1960 case Instruction::Shl: {
1961 const APInt *ShAmt;
1962 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner965c7692008-06-02 01:18:21 +00001963 // shl destroys sign bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001964 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001965 Tmp2 = ShAmt->getZExtValue();
1966 if (Tmp2 >= TyBits || // Bad shift.
1967 Tmp2 >= Tmp) break; // Shifted all sign bits out.
1968 return Tmp - Tmp2;
Chris Lattner965c7692008-06-02 01:18:21 +00001969 }
1970 break;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001971 }
Chris Lattner965c7692008-06-02 01:18:21 +00001972 case Instruction::And:
1973 case Instruction::Or:
1974 case Instruction::Xor: // NOT is handled here.
1975 // Logical binary ops preserve the number of sign bits at the worst.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001976 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001977 if (Tmp != 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001978 Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001979 FirstAnswer = std::min(Tmp, Tmp2);
1980 // We computed what we know about the sign bits as our first
1981 // answer. Now proceed to the generic code that uses
Jay Foada0653a32014-05-14 21:14:37 +00001982 // computeKnownBits, and pick whichever answer is better.
Chris Lattner965c7692008-06-02 01:18:21 +00001983 }
1984 break;
1985
1986 case Instruction::Select:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001987 Tmp = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001988 if (Tmp == 1) return 1; // Early out.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001989 Tmp2 = ComputeNumSignBits(U->getOperand(2), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001990 return std::min(Tmp, Tmp2);
Craig Topper1bef2c82012-12-22 19:15:35 +00001991
Chris Lattner965c7692008-06-02 01:18:21 +00001992 case Instruction::Add:
1993 // Add can have at most one carry bit. Thus we know that the output
1994 // is, at worst, one more bit than the inputs.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001995 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001996 if (Tmp == 1) return 1; // Early out.
Craig Topper1bef2c82012-12-22 19:15:35 +00001997
Chris Lattner965c7692008-06-02 01:18:21 +00001998 // Special case decrementing a value (ADD X, -1):
David Majnemera55027f2014-12-26 09:20:17 +00001999 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
Chris Lattner965c7692008-06-02 01:18:21 +00002000 if (CRHS->isAllOnesValue()) {
2001 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002002 computeKnownBits(U->getOperand(0), KnownZero, KnownOne, DL, Depth + 1,
2003 Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002004
Chris Lattner965c7692008-06-02 01:18:21 +00002005 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2006 // sign bits set.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00002007 if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002008 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002009
Chris Lattner965c7692008-06-02 01:18:21 +00002010 // If we are subtracting one from a positive number, there is no carry
2011 // out of the result.
2012 if (KnownZero.isNegative())
2013 return Tmp;
2014 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002015
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002016 Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002017 if (Tmp2 == 1) return 1;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002018 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002019
Chris Lattner965c7692008-06-02 01:18:21 +00002020 case Instruction::Sub:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002021 Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002022 if (Tmp2 == 1) return 1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002023
Chris Lattner965c7692008-06-02 01:18:21 +00002024 // Handle NEG.
David Majnemera55027f2014-12-26 09:20:17 +00002025 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
Chris Lattner965c7692008-06-02 01:18:21 +00002026 if (CLHS->isNullValue()) {
2027 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002028 computeKnownBits(U->getOperand(1), KnownZero, KnownOne, DL, Depth + 1,
2029 Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002030 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2031 // sign bits set.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00002032 if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002033 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002034
Chris Lattner965c7692008-06-02 01:18:21 +00002035 // If the input is known to be positive (the sign bit is known clear),
2036 // the output of the NEG has the same number of sign bits as the input.
2037 if (KnownZero.isNegative())
2038 return Tmp2;
Craig Topper1bef2c82012-12-22 19:15:35 +00002039
Chris Lattner965c7692008-06-02 01:18:21 +00002040 // Otherwise, we treat this like a SUB.
2041 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002042
Chris Lattner965c7692008-06-02 01:18:21 +00002043 // Sub can have at most one carry bit. Thus we know that the output
2044 // is, at worst, one more bit than the inputs.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002045 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002046 if (Tmp == 1) return 1; // Early out.
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002047 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002048
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002049 case Instruction::PHI: {
2050 PHINode *PN = cast<PHINode>(U);
David Majnemer6ee8d172015-01-04 07:06:53 +00002051 unsigned NumIncomingValues = PN->getNumIncomingValues();
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002052 // Don't analyze large in-degree PHIs.
David Majnemer6ee8d172015-01-04 07:06:53 +00002053 if (NumIncomingValues > 4) break;
2054 // Unreachable blocks may have zero-operand PHI nodes.
2055 if (NumIncomingValues == 0) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002056
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002057 // Take the minimum of all incoming values. This can't infinitely loop
2058 // because of our depth threshold.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002059 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), DL, Depth + 1, Q);
David Majnemer6ee8d172015-01-04 07:06:53 +00002060 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002061 if (Tmp == 1) return Tmp;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002062 Tmp = std::min(
2063 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), DL, Depth + 1, Q));
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002064 }
2065 return Tmp;
2066 }
2067
Chris Lattner965c7692008-06-02 01:18:21 +00002068 case Instruction::Trunc:
2069 // FIXME: it's tricky to do anything useful for this, but it is an important
2070 // case for targets like X86.
2071 break;
2072 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002073
Chris Lattner965c7692008-06-02 01:18:21 +00002074 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2075 // use this information.
2076 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00002077 APInt Mask;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002078 computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002079
Chris Lattner965c7692008-06-02 01:18:21 +00002080 if (KnownZero.isNegative()) { // sign bit is 0
2081 Mask = KnownZero;
2082 } else if (KnownOne.isNegative()) { // sign bit is 1;
2083 Mask = KnownOne;
2084 } else {
2085 // Nothing known.
2086 return FirstAnswer;
2087 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002088
Chris Lattner965c7692008-06-02 01:18:21 +00002089 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2090 // the number of identical bits in the top of the input value.
2091 Mask = ~Mask;
2092 Mask <<= Mask.getBitWidth()-TyBits;
2093 // Return # leading zeros. We use 'min' here in case Val was zero before
2094 // shifting. We don't want to return '64' as for an i32 "0".
2095 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
2096}
Chris Lattnera12a6de2008-06-02 01:29:46 +00002097
Sanjay Patelaee84212014-11-04 16:27:42 +00002098/// This function computes the integer multiple of Base that equals V.
2099/// If successful, it returns true and returns the multiple in
2100/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez47444882009-11-10 08:28:35 +00002101/// through SExt instructions only if LookThroughSExt is true.
2102bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman6a976bb2009-11-18 00:58:27 +00002103 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez47444882009-11-10 08:28:35 +00002104 const unsigned MaxDepth = 6;
2105
Dan Gohman6a976bb2009-11-18 00:58:27 +00002106 assert(V && "No Value?");
Victor Hernandez47444882009-11-10 08:28:35 +00002107 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002108 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez47444882009-11-10 08:28:35 +00002109
Chris Lattner229907c2011-07-18 04:54:35 +00002110 Type *T = V->getType();
Victor Hernandez47444882009-11-10 08:28:35 +00002111
Dan Gohman6a976bb2009-11-18 00:58:27 +00002112 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez47444882009-11-10 08:28:35 +00002113
2114 if (Base == 0)
2115 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002116
Victor Hernandez47444882009-11-10 08:28:35 +00002117 if (Base == 1) {
2118 Multiple = V;
2119 return true;
2120 }
2121
2122 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2123 Constant *BaseVal = ConstantInt::get(T, Base);
2124 if (CO && CO == BaseVal) {
2125 // Multiple is 1.
2126 Multiple = ConstantInt::get(T, 1);
2127 return true;
2128 }
2129
2130 if (CI && CI->getZExtValue() % Base == 0) {
2131 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
Craig Topper1bef2c82012-12-22 19:15:35 +00002132 return true;
Victor Hernandez47444882009-11-10 08:28:35 +00002133 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002134
Victor Hernandez47444882009-11-10 08:28:35 +00002135 if (Depth == MaxDepth) return false; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002136
Victor Hernandez47444882009-11-10 08:28:35 +00002137 Operator *I = dyn_cast<Operator>(V);
2138 if (!I) return false;
2139
2140 switch (I->getOpcode()) {
2141 default: break;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002142 case Instruction::SExt:
Victor Hernandez47444882009-11-10 08:28:35 +00002143 if (!LookThroughSExt) return false;
2144 // otherwise fall through to ZExt
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002145 case Instruction::ZExt:
Dan Gohman6a976bb2009-11-18 00:58:27 +00002146 return ComputeMultiple(I->getOperand(0), Base, Multiple,
2147 LookThroughSExt, Depth+1);
Victor Hernandez47444882009-11-10 08:28:35 +00002148 case Instruction::Shl:
2149 case Instruction::Mul: {
2150 Value *Op0 = I->getOperand(0);
2151 Value *Op1 = I->getOperand(1);
2152
2153 if (I->getOpcode() == Instruction::Shl) {
2154 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2155 if (!Op1CI) return false;
2156 // Turn Op0 << Op1 into Op0 * 2^Op1
2157 APInt Op1Int = Op1CI->getValue();
2158 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foad15084f02010-11-30 09:02:01 +00002159 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002160 API.setBit(BitToSet);
Jay Foad15084f02010-11-30 09:02:01 +00002161 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez47444882009-11-10 08:28:35 +00002162 }
2163
Craig Topper9f008862014-04-15 04:59:12 +00002164 Value *Mul0 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002165 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2166 if (Constant *Op1C = dyn_cast<Constant>(Op1))
2167 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002168 if (Op1C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002169 MulC->getType()->getPrimitiveSizeInBits())
2170 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002171 if (Op1C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002172 MulC->getType()->getPrimitiveSizeInBits())
2173 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002174
Chris Lattner72d283c2010-09-05 17:20:46 +00002175 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2176 Multiple = ConstantExpr::getMul(MulC, Op1C);
2177 return true;
2178 }
Victor Hernandez47444882009-11-10 08:28:35 +00002179
2180 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2181 if (Mul0CI->getValue() == 1) {
2182 // V == Base * Op1, so return Op1
2183 Multiple = Op1;
2184 return true;
2185 }
2186 }
2187
Craig Topper9f008862014-04-15 04:59:12 +00002188 Value *Mul1 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002189 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2190 if (Constant *Op0C = dyn_cast<Constant>(Op0))
2191 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002192 if (Op0C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002193 MulC->getType()->getPrimitiveSizeInBits())
2194 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002195 if (Op0C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002196 MulC->getType()->getPrimitiveSizeInBits())
2197 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002198
Chris Lattner72d283c2010-09-05 17:20:46 +00002199 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2200 Multiple = ConstantExpr::getMul(MulC, Op0C);
2201 return true;
2202 }
Victor Hernandez47444882009-11-10 08:28:35 +00002203
2204 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2205 if (Mul1CI->getValue() == 1) {
2206 // V == Base * Op0, so return Op0
2207 Multiple = Op0;
2208 return true;
2209 }
2210 }
Victor Hernandez47444882009-11-10 08:28:35 +00002211 }
2212 }
2213
2214 // We could not determine if V is a multiple of Base.
2215 return false;
2216}
2217
Sanjay Patelaee84212014-11-04 16:27:42 +00002218/// Return true if we can prove that the specified FP value is never equal to
2219/// -0.0.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002220///
2221/// NOTE: this function will need to be revisited when we support non-default
2222/// rounding modes!
2223///
2224bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
2225 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2226 return !CFP->getValueAPF().isNegZero();
Craig Topper1bef2c82012-12-22 19:15:35 +00002227
Sanjay Patel40eaa8d2015-02-25 18:00:15 +00002228 // FIXME: Magic number! At the least, this should be given a name because it's
2229 // used similarly in CannotBeOrderedLessThanZero(). A better fix may be to
2230 // expose it as a parameter, so it can be used for testing / experimenting.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002231 if (Depth == 6)
Sanjay Patel40eaa8d2015-02-25 18:00:15 +00002232 return false; // Limit search depth.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002233
Dan Gohman80ca01c2009-07-17 20:47:02 +00002234 const Operator *I = dyn_cast<Operator>(V);
Craig Topper9f008862014-04-15 04:59:12 +00002235 if (!I) return false;
Michael Ilseman0f128372012-12-06 00:07:09 +00002236
2237 // Check if the nsz fast-math flag is set
2238 if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
2239 if (FPO->hasNoSignedZeros())
2240 return true;
2241
Chris Lattnera12a6de2008-06-02 01:29:46 +00002242 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Jakub Staszakb7129f22013-03-06 00:16:16 +00002243 if (I->getOpcode() == Instruction::FAdd)
2244 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
2245 if (CFP->isNullValue())
2246 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002247
Chris Lattnera12a6de2008-06-02 01:29:46 +00002248 // sitofp and uitofp turn into +0.0 for zero.
2249 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2250 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002251
Chris Lattnera12a6de2008-06-02 01:29:46 +00002252 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2253 // sqrt(-0.0) = -0.0, no other negative results are possible.
2254 if (II->getIntrinsicID() == Intrinsic::sqrt)
Gabor Greif1abbde32010-06-23 23:38:07 +00002255 return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
Craig Topper1bef2c82012-12-22 19:15:35 +00002256
Chris Lattnera12a6de2008-06-02 01:29:46 +00002257 if (const CallInst *CI = dyn_cast<CallInst>(I))
2258 if (const Function *F = CI->getCalledFunction()) {
2259 if (F->isDeclaration()) {
Daniel Dunbarca414c72009-07-26 08:34:35 +00002260 // abs(x) != -0.0
2261 if (F->getName() == "abs") return true;
Dale Johannesenf6a987b2009-09-25 20:54:50 +00002262 // fabs[lf](x) != -0.0
2263 if (F->getName() == "fabs") return true;
2264 if (F->getName() == "fabsf") return true;
2265 if (F->getName() == "fabsl") return true;
2266 if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
2267 F->getName() == "sqrtl")
Gabor Greif1abbde32010-06-23 23:38:07 +00002268 return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
Chris Lattnera12a6de2008-06-02 01:29:46 +00002269 }
2270 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002271
Chris Lattnera12a6de2008-06-02 01:29:46 +00002272 return false;
2273}
2274
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002275bool llvm::CannotBeOrderedLessThanZero(const Value *V, unsigned Depth) {
2276 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2277 return !CFP->getValueAPF().isNegative() || CFP->getValueAPF().isZero();
2278
Sanjay Patel40eaa8d2015-02-25 18:00:15 +00002279 // FIXME: Magic number! At the least, this should be given a name because it's
2280 // used similarly in CannotBeNegativeZero(). A better fix may be to
2281 // expose it as a parameter, so it can be used for testing / experimenting.
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002282 if (Depth == 6)
2283 return false; // Limit search depth.
2284
2285 const Operator *I = dyn_cast<Operator>(V);
2286 if (!I) return false;
2287
2288 switch (I->getOpcode()) {
2289 default: break;
2290 case Instruction::FMul:
2291 // x*x is always non-negative or a NaN.
2292 if (I->getOperand(0) == I->getOperand(1))
2293 return true;
2294 // Fall through
2295 case Instruction::FAdd:
2296 case Instruction::FDiv:
2297 case Instruction::FRem:
2298 return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1) &&
2299 CannotBeOrderedLessThanZero(I->getOperand(1), Depth+1);
2300 case Instruction::FPExt:
2301 case Instruction::FPTrunc:
2302 // Widening/narrowing never change sign.
2303 return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
2304 case Instruction::Call:
2305 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2306 switch (II->getIntrinsicID()) {
2307 default: break;
2308 case Intrinsic::exp:
2309 case Intrinsic::exp2:
2310 case Intrinsic::fabs:
2311 case Intrinsic::sqrt:
2312 return true;
2313 case Intrinsic::powi:
2314 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
2315 // powi(x,n) is non-negative if n is even.
2316 if (CI->getBitWidth() <= 64 && CI->getSExtValue() % 2u == 0)
2317 return true;
2318 }
2319 return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
2320 case Intrinsic::fma:
2321 case Intrinsic::fmuladd:
2322 // x*x+y is non-negative if y is non-negative.
2323 return I->getOperand(0) == I->getOperand(1) &&
2324 CannotBeOrderedLessThanZero(I->getOperand(2), Depth+1);
2325 }
2326 break;
2327 }
2328 return false;
2329}
2330
Sanjay Patelaee84212014-11-04 16:27:42 +00002331/// If the specified value can be set by repeating the same byte in memory,
2332/// return the i8 value that it is represented with. This is
Chris Lattner9cb10352010-12-26 20:15:01 +00002333/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2334/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
2335/// byte store (e.g. i16 0x1234), return null.
2336Value *llvm::isBytewiseValue(Value *V) {
2337 // All byte-wide stores are splatable, even of arbitrary variables.
2338 if (V->getType()->isIntegerTy(8)) return V;
Chris Lattneracf6b072011-02-19 19:35:49 +00002339
2340 // Handle 'null' ConstantArrayZero etc.
2341 if (Constant *C = dyn_cast<Constant>(V))
2342 if (C->isNullValue())
2343 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
Craig Topper1bef2c82012-12-22 19:15:35 +00002344
Chris Lattner9cb10352010-12-26 20:15:01 +00002345 // Constant float and double values can be handled as integer values if the
Craig Topper1bef2c82012-12-22 19:15:35 +00002346 // corresponding integer value is "byteable". An important case is 0.0.
Chris Lattner9cb10352010-12-26 20:15:01 +00002347 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2348 if (CFP->getType()->isFloatTy())
2349 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2350 if (CFP->getType()->isDoubleTy())
2351 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2352 // Don't handle long double formats, which have strange constraints.
2353 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002354
Benjamin Kramer17d90152015-02-07 19:29:02 +00002355 // We can handle constant integers that are multiple of 8 bits.
Chris Lattner9cb10352010-12-26 20:15:01 +00002356 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Benjamin Kramer17d90152015-02-07 19:29:02 +00002357 if (CI->getBitWidth() % 8 == 0) {
2358 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
Craig Topper1bef2c82012-12-22 19:15:35 +00002359
Benjamin Kramerb4b51502015-03-25 16:49:59 +00002360 if (!CI->getValue().isSplat(8))
Benjamin Kramer17d90152015-02-07 19:29:02 +00002361 return nullptr;
2362 return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
Chris Lattner9cb10352010-12-26 20:15:01 +00002363 }
2364 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002365
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002366 // A ConstantDataArray/Vector is splatable if all its members are equal and
2367 // also splatable.
2368 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2369 Value *Elt = CA->getElementAsConstant(0);
2370 Value *Val = isBytewiseValue(Elt);
Chris Lattner9cb10352010-12-26 20:15:01 +00002371 if (!Val)
Craig Topper9f008862014-04-15 04:59:12 +00002372 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002373
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002374 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2375 if (CA->getElementAsConstant(I) != Elt)
Craig Topper9f008862014-04-15 04:59:12 +00002376 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002377
Chris Lattner9cb10352010-12-26 20:15:01 +00002378 return Val;
2379 }
Chad Rosier8abf65a2011-12-06 00:19:08 +00002380
Chris Lattner9cb10352010-12-26 20:15:01 +00002381 // Conceptually, we could handle things like:
2382 // %a = zext i8 %X to i16
2383 // %b = shl i16 %a, 8
2384 // %c = or i16 %a, %b
2385 // but until there is an example that actually needs this, it doesn't seem
2386 // worth worrying about.
Craig Topper9f008862014-04-15 04:59:12 +00002387 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00002388}
2389
2390
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002391// This is the recursive version of BuildSubAggregate. It takes a few different
2392// arguments. Idxs is the index within the nested struct From that we are
2393// looking at now (which is of type IndexedType). IdxSkip is the number of
2394// indices from Idxs that should be left out when inserting into the resulting
2395// struct. To is the result struct built so far, new insertvalue instructions
2396// build on that.
Chris Lattner229907c2011-07-18 04:54:35 +00002397static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Craig Topper2cd5ff82013-07-11 16:22:38 +00002398 SmallVectorImpl<unsigned> &Idxs,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002399 unsigned IdxSkip,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002400 Instruction *InsertBefore) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +00002401 llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002402 if (STy) {
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002403 // Save the original To argument so we can modify it
2404 Value *OrigTo = To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002405 // General case, the type indexed by Idxs is a struct
2406 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2407 // Process each struct element recursively
2408 Idxs.push_back(i);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002409 Value *PrevTo = To;
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002410 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002411 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002412 Idxs.pop_back();
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002413 if (!To) {
2414 // Couldn't find any inserted value for this index? Cleanup
2415 while (PrevTo != OrigTo) {
2416 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
2417 PrevTo = Del->getAggregateOperand();
2418 Del->eraseFromParent();
2419 }
2420 // Stop processing elements
2421 break;
2422 }
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002423 }
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002424 // If we successfully found a value for each of our subaggregates
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002425 if (To)
2426 return To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002427 }
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002428 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
2429 // the struct's elements had a value that was inserted directly. In the latter
2430 // case, perhaps we can't determine each of the subelements individually, but
2431 // we might be able to find the complete struct somewhere.
Craig Topper1bef2c82012-12-22 19:15:35 +00002432
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002433 // Find the value that is at that particular spot
Jay Foad57aa6362011-07-13 10:26:04 +00002434 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002435
2436 if (!V)
Craig Topper9f008862014-04-15 04:59:12 +00002437 return nullptr;
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002438
2439 // Insert the value in the new (sub) aggregrate
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002440 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
Jay Foad57aa6362011-07-13 10:26:04 +00002441 "tmp", InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002442}
2443
2444// This helper takes a nested struct and extracts a part of it (which is again a
2445// struct) into a new value. For example, given the struct:
2446// { a, { b, { c, d }, e } }
2447// and the indices "1, 1" this returns
2448// { c, d }.
2449//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002450// It does this by inserting an insertvalue for each element in the resulting
2451// struct, as opposed to just inserting a single struct. This will only work if
2452// each of the elements of the substruct are known (ie, inserted into From by an
2453// insertvalue instruction somewhere).
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002454//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002455// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foad57aa6362011-07-13 10:26:04 +00002456static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002457 Instruction *InsertBefore) {
Matthijs Kooijman69801d42008-06-16 13:28:31 +00002458 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattner229907c2011-07-18 04:54:35 +00002459 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foad57aa6362011-07-13 10:26:04 +00002460 idx_range);
Owen Andersonb292b8c2009-07-30 23:03:37 +00002461 Value *To = UndefValue::get(IndexedType);
Jay Foad57aa6362011-07-13 10:26:04 +00002462 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002463 unsigned IdxSkip = Idxs.size();
2464
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002465 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002466}
2467
Sanjay Patelaee84212014-11-04 16:27:42 +00002468/// Given an aggregrate and an sequence of indices, see if
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002469/// the scalar value indexed is already around as a register, for example if it
2470/// were inserted directly into the aggregrate.
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002471///
2472/// If InsertBefore is not null, this function will duplicate (modified)
2473/// insertvalues when a part of a nested struct is extracted.
Jay Foad57aa6362011-07-13 10:26:04 +00002474Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
2475 Instruction *InsertBefore) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002476 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002477 // recursion).
Jay Foad57aa6362011-07-13 10:26:04 +00002478 if (idx_range.empty())
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002479 return V;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002480 // We have indices, so V should have an indexable type.
2481 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
2482 "Not looking at a struct or array?");
2483 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
2484 "Invalid indices for type?");
Owen Andersonf1f17432009-07-06 22:37:39 +00002485
Chris Lattner67058832012-01-25 06:48:06 +00002486 if (Constant *C = dyn_cast<Constant>(V)) {
2487 C = C->getAggregateElement(idx_range[0]);
Craig Topper9f008862014-04-15 04:59:12 +00002488 if (!C) return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00002489 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
2490 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002491
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002492 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002493 // Loop the indices for the insertvalue instruction in parallel with the
2494 // requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00002495 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002496 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
2497 i != e; ++i, ++req_idx) {
Jay Foad57aa6362011-07-13 10:26:04 +00002498 if (req_idx == idx_range.end()) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002499 // We can't handle this without inserting insertvalues
2500 if (!InsertBefore)
Craig Topper9f008862014-04-15 04:59:12 +00002501 return nullptr;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002502
2503 // The requested index identifies a part of a nested aggregate. Handle
2504 // this specially. For example,
2505 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
2506 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
2507 // %C = extractvalue {i32, { i32, i32 } } %B, 1
2508 // This can be changed into
2509 // %A = insertvalue {i32, i32 } undef, i32 10, 0
2510 // %C = insertvalue {i32, i32 } %A, i32 11, 1
2511 // which allows the unused 0,0 element from the nested struct to be
2512 // removed.
2513 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
2514 InsertBefore);
Duncan Sandsdb356ee2008-06-19 08:47:31 +00002515 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002516
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002517 // This insert value inserts something else than what we are looking for.
2518 // See if the (aggregrate) value inserted into has the value we are
2519 // looking for, then.
2520 if (*req_idx != *i)
Jay Foad57aa6362011-07-13 10:26:04 +00002521 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002522 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002523 }
2524 // If we end up here, the indices of the insertvalue match with those
2525 // requested (though possibly only partially). Now we recursively look at
2526 // the inserted value, passing any remaining indices.
Jay Foad57aa6362011-07-13 10:26:04 +00002527 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002528 makeArrayRef(req_idx, idx_range.end()),
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002529 InsertBefore);
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002530 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002531
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002532 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002533 // If we're extracting a value from an aggregrate that was extracted from
2534 // something else, we can extract from that something else directly instead.
2535 // However, we will need to chain I's indices with the requested indices.
Craig Topper1bef2c82012-12-22 19:15:35 +00002536
2537 // Calculate the number of indices required
Jay Foad57aa6362011-07-13 10:26:04 +00002538 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002539 // Allocate some space to put the new indices in
Matthijs Kooijman8369c672008-06-17 08:24:37 +00002540 SmallVector<unsigned, 5> Idxs;
2541 Idxs.reserve(size);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002542 // Add indices from the extract value instruction
Jay Foad57aa6362011-07-13 10:26:04 +00002543 Idxs.append(I->idx_begin(), I->idx_end());
Craig Topper1bef2c82012-12-22 19:15:35 +00002544
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002545 // Add requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00002546 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002547
Craig Topper1bef2c82012-12-22 19:15:35 +00002548 assert(Idxs.size() == size
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002549 && "Number of indices added not correct?");
Craig Topper1bef2c82012-12-22 19:15:35 +00002550
Jay Foad57aa6362011-07-13 10:26:04 +00002551 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002552 }
2553 // Otherwise, we don't know (such as, extracting from a function return value
2554 // or load instruction)
Craig Topper9f008862014-04-15 04:59:12 +00002555 return nullptr;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002556}
Evan Chengda3db112008-06-30 07:31:25 +00002557
Sanjay Patelaee84212014-11-04 16:27:42 +00002558/// Analyze the specified pointer to see if it can be expressed as a base
2559/// pointer plus a constant offset. Return the base and offset to the caller.
Chris Lattnere28618d2010-11-30 22:25:26 +00002560Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002561 const DataLayout &DL) {
2562 unsigned BitWidth = DL.getPointerTypeSizeInBits(Ptr->getType());
Nuno Lopes368c4d02012-12-31 20:48:35 +00002563 APInt ByteOffset(BitWidth, 0);
2564 while (1) {
2565 if (Ptr->getType()->isVectorTy())
2566 break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002567
Nuno Lopes368c4d02012-12-31 20:48:35 +00002568 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002569 APInt GEPOffset(BitWidth, 0);
2570 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
2571 break;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00002572
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002573 ByteOffset += GEPOffset;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00002574
Nuno Lopes368c4d02012-12-31 20:48:35 +00002575 Ptr = GEP->getPointerOperand();
Matt Arsenaultfd78d0c2014-07-14 22:39:22 +00002576 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
2577 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002578 Ptr = cast<Operator>(Ptr)->getOperand(0);
2579 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
2580 if (GA->mayBeOverridden())
2581 break;
2582 Ptr = GA->getAliasee();
Chris Lattnere28618d2010-11-30 22:25:26 +00002583 } else {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002584 break;
Chris Lattnere28618d2010-11-30 22:25:26 +00002585 }
2586 }
Nuno Lopes368c4d02012-12-31 20:48:35 +00002587 Offset = ByteOffset.getSExtValue();
2588 return Ptr;
Chris Lattnere28618d2010-11-30 22:25:26 +00002589}
2590
2591
Sanjay Patelaee84212014-11-04 16:27:42 +00002592/// This function computes the length of a null-terminated C string pointed to
2593/// by V. If successful, it returns true and returns the string in Str.
2594/// If unsuccessful, it returns false.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002595bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
2596 uint64_t Offset, bool TrimAtNul) {
2597 assert(V);
Evan Chengda3db112008-06-30 07:31:25 +00002598
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002599 // Look through bitcast instructions and geps.
2600 V = V->stripPointerCasts();
Craig Topper1bef2c82012-12-22 19:15:35 +00002601
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00002602 // If the value is a GEP instruction or constant expression, treat it as an
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002603 // offset.
2604 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Evan Chengda3db112008-06-30 07:31:25 +00002605 // Make sure the GEP has exactly three arguments.
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002606 if (GEP->getNumOperands() != 3)
2607 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002608
Evan Chengda3db112008-06-30 07:31:25 +00002609 // Make sure the index-ee is a pointer to array of i8.
Chris Lattner229907c2011-07-18 04:54:35 +00002610 PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
2611 ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
Craig Topper9f008862014-04-15 04:59:12 +00002612 if (!AT || !AT->getElementType()->isIntegerTy(8))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002613 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002614
Evan Chengda3db112008-06-30 07:31:25 +00002615 // Check to make sure that the first operand of the GEP is an integer and
2616 // has value 0 so that we are sure we're indexing into the initializer.
Dan Gohman0b4df042010-04-14 22:20:45 +00002617 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
Craig Topper9f008862014-04-15 04:59:12 +00002618 if (!FirstIdx || !FirstIdx->isZero())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002619 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002620
Evan Chengda3db112008-06-30 07:31:25 +00002621 // If the second index isn't a ConstantInt, then this is a variable index
2622 // into the array. If this occurs, we can't say anything meaningful about
2623 // the string.
2624 uint64_t StartIdx = 0;
Dan Gohman0b4df042010-04-14 22:20:45 +00002625 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Chengda3db112008-06-30 07:31:25 +00002626 StartIdx = CI->getZExtValue();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002627 else
2628 return false;
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00002629 return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx + Offset,
2630 TrimAtNul);
Evan Chengda3db112008-06-30 07:31:25 +00002631 }
Nick Lewycky46209882011-10-20 00:34:35 +00002632
Evan Chengda3db112008-06-30 07:31:25 +00002633 // The GEP instruction, constant or instruction, must reference a global
2634 // variable that is a constant and is initialized. The referenced constant
2635 // initializer is the array that we'll use for optimization.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002636 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00002637 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002638 return false;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002639
Nick Lewycky46209882011-10-20 00:34:35 +00002640 // Handle the all-zeros case
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002641 if (GV->getInitializer()->isNullValue()) {
Evan Chengda3db112008-06-30 07:31:25 +00002642 // This is a degenerate case. The initializer is constant zero so the
2643 // length of the string must be zero.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002644 Str = "";
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002645 return true;
2646 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002647
Evan Chengda3db112008-06-30 07:31:25 +00002648 // Must be a Constant Array
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002649 const ConstantDataArray *Array =
2650 dyn_cast<ConstantDataArray>(GV->getInitializer());
Craig Topper9f008862014-04-15 04:59:12 +00002651 if (!Array || !Array->isString())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002652 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002653
Evan Chengda3db112008-06-30 07:31:25 +00002654 // Get the number of elements in the array
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002655 uint64_t NumElts = Array->getType()->getArrayNumElements();
2656
2657 // Start out with the entire array in the StringRef.
2658 Str = Array->getAsString();
2659
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002660 if (Offset > NumElts)
2661 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002662
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002663 // Skip over 'offset' bytes.
2664 Str = Str.substr(Offset);
Craig Topper1bef2c82012-12-22 19:15:35 +00002665
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002666 if (TrimAtNul) {
2667 // Trim off the \0 and anything after it. If the array is not nul
2668 // terminated, we just return the whole end of string. The client may know
2669 // some other way that the string is length-bound.
2670 Str = Str.substr(0, Str.find('\0'));
2671 }
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002672 return true;
Evan Chengda3db112008-06-30 07:31:25 +00002673}
Eric Christopher4899cbc2010-03-05 06:58:57 +00002674
2675// These next two are very similar to the above, but also look through PHI
2676// nodes.
2677// TODO: See if we can integrate these two together.
2678
Sanjay Patelaee84212014-11-04 16:27:42 +00002679/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00002680/// the specified pointer, return 'len+1'. If we can't, return 0.
Craig Topper71b7b682014-08-21 05:55:13 +00002681static uint64_t GetStringLengthH(Value *V, SmallPtrSetImpl<PHINode*> &PHIs) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00002682 // Look through noop bitcast instructions.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002683 V = V->stripPointerCasts();
Eric Christopher4899cbc2010-03-05 06:58:57 +00002684
2685 // If this is a PHI node, there are two cases: either we have already seen it
2686 // or we haven't.
2687 if (PHINode *PN = dyn_cast<PHINode>(V)) {
David Blaikie70573dc2014-11-19 07:49:26 +00002688 if (!PHIs.insert(PN).second)
Eric Christopher4899cbc2010-03-05 06:58:57 +00002689 return ~0ULL; // already in the set.
2690
2691 // If it was new, see if all the input strings are the same length.
2692 uint64_t LenSoFar = ~0ULL;
2693 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2694 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
2695 if (Len == 0) return 0; // Unknown length -> unknown.
2696
2697 if (Len == ~0ULL) continue;
2698
2699 if (Len != LenSoFar && LenSoFar != ~0ULL)
2700 return 0; // Disagree -> unknown.
2701 LenSoFar = Len;
2702 }
2703
2704 // Success, all agree.
2705 return LenSoFar;
2706 }
2707
2708 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
2709 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
2710 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
2711 if (Len1 == 0) return 0;
2712 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
2713 if (Len2 == 0) return 0;
2714 if (Len1 == ~0ULL) return Len2;
2715 if (Len2 == ~0ULL) return Len1;
2716 if (Len1 != Len2) return 0;
2717 return Len1;
2718 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002719
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002720 // Otherwise, see if we can read the string.
2721 StringRef StrData;
2722 if (!getConstantStringInfo(V, StrData))
Eric Christopher4899cbc2010-03-05 06:58:57 +00002723 return 0;
2724
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002725 return StrData.size()+1;
Eric Christopher4899cbc2010-03-05 06:58:57 +00002726}
2727
Sanjay Patelaee84212014-11-04 16:27:42 +00002728/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00002729/// the specified pointer, return 'len+1'. If we can't, return 0.
2730uint64_t llvm::GetStringLength(Value *V) {
2731 if (!V->getType()->isPointerTy()) return 0;
2732
2733 SmallPtrSet<PHINode*, 32> PHIs;
2734 uint64_t Len = GetStringLengthH(V, PHIs);
2735 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
2736 // an empty string as a length.
2737 return Len == ~0ULL ? 1 : Len;
2738}
Dan Gohmana4fcd242010-12-15 20:02:24 +00002739
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002740Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
2741 unsigned MaxLookup) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00002742 if (!V->getType()->isPointerTy())
2743 return V;
2744 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
2745 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2746 V = GEP->getPointerOperand();
Matt Arsenault70f4db882014-07-15 00:56:40 +00002747 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
2748 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00002749 V = cast<Operator>(V)->getOperand(0);
2750 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2751 if (GA->mayBeOverridden())
2752 return V;
2753 V = GA->getAliasee();
2754 } else {
Dan Gohman05b18f12010-12-15 20:49:55 +00002755 // See if InstructionSimplify knows any relevant tricks.
2756 if (Instruction *I = dyn_cast<Instruction>(V))
Chandler Carruth66b31302015-01-04 12:03:27 +00002757 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002758 if (Value *Simplified = SimplifyInstruction(I, DL, nullptr)) {
Dan Gohman05b18f12010-12-15 20:49:55 +00002759 V = Simplified;
2760 continue;
2761 }
2762
Dan Gohmana4fcd242010-12-15 20:02:24 +00002763 return V;
2764 }
2765 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
2766 }
2767 return V;
2768}
Nick Lewycky3e334a42011-06-27 04:20:45 +00002769
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002770void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
2771 const DataLayout &DL, unsigned MaxLookup) {
Dan Gohmaned7c24e22012-05-10 18:57:38 +00002772 SmallPtrSet<Value *, 4> Visited;
2773 SmallVector<Value *, 4> Worklist;
2774 Worklist.push_back(V);
2775 do {
2776 Value *P = Worklist.pop_back_val();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002777 P = GetUnderlyingObject(P, DL, MaxLookup);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00002778
David Blaikie70573dc2014-11-19 07:49:26 +00002779 if (!Visited.insert(P).second)
Dan Gohmaned7c24e22012-05-10 18:57:38 +00002780 continue;
2781
2782 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
2783 Worklist.push_back(SI->getTrueValue());
2784 Worklist.push_back(SI->getFalseValue());
2785 continue;
2786 }
2787
2788 if (PHINode *PN = dyn_cast<PHINode>(P)) {
2789 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2790 Worklist.push_back(PN->getIncomingValue(i));
2791 continue;
2792 }
2793
2794 Objects.push_back(P);
2795 } while (!Worklist.empty());
2796}
2797
Sanjay Patelaee84212014-11-04 16:27:42 +00002798/// Return true if the only users of this pointer are lifetime markers.
Nick Lewycky3e334a42011-06-27 04:20:45 +00002799bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00002800 for (const User *U : V->users()) {
2801 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Nick Lewycky3e334a42011-06-27 04:20:45 +00002802 if (!II) return false;
2803
2804 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2805 II->getIntrinsicID() != Intrinsic::lifetime_end)
2806 return false;
2807 }
2808 return true;
2809}
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002810
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002811bool llvm::isSafeToSpeculativelyExecute(const Value *V) {
Dan Gohman7ac046a2012-01-04 23:01:09 +00002812 const Operator *Inst = dyn_cast<Operator>(V);
2813 if (!Inst)
2814 return false;
2815
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002816 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
2817 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
2818 if (C->canTrap())
2819 return false;
2820
2821 switch (Inst->getOpcode()) {
2822 default:
2823 return true;
2824 case Instruction::UDiv:
David Majnemerf20d7c42014-11-04 23:49:08 +00002825 case Instruction::URem: {
2826 // x / y is undefined if y == 0.
2827 const APInt *V;
2828 if (match(Inst->getOperand(1), m_APInt(V)))
2829 return *V != 0;
2830 return false;
2831 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002832 case Instruction::SDiv:
2833 case Instruction::SRem: {
David Majnemerf20d7c42014-11-04 23:49:08 +00002834 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
David Majnemer8a6578a2015-02-01 19:10:19 +00002835 const APInt *Numerator, *Denominator;
2836 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
2837 return false;
2838 // We cannot hoist this division if the denominator is 0.
2839 if (*Denominator == 0)
2840 return false;
2841 // It's safe to hoist if the denominator is not 0 or -1.
2842 if (*Denominator != -1)
2843 return true;
2844 // At this point we know that the denominator is -1. It is safe to hoist as
2845 // long we know that the numerator is not INT_MIN.
2846 if (match(Inst->getOperand(0), m_APInt(Numerator)))
2847 return !Numerator->isMinSignedValue();
2848 // The numerator *might* be MinSignedValue.
David Majnemerf20d7c42014-11-04 23:49:08 +00002849 return false;
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002850 }
2851 case Instruction::Load: {
2852 const LoadInst *LI = cast<LoadInst>(Inst);
Kostya Serebryany0b458282013-11-21 07:29:28 +00002853 if (!LI->isUnordered() ||
2854 // Speculative load may create a race that did not exist in the source.
2855 LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002856 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002857 const DataLayout &DL = LI->getModule()->getDataLayout();
2858 return LI->getPointerOperand()->isDereferenceablePointer(DL);
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002859 }
Nick Lewyckyb4039f62011-12-21 05:52:02 +00002860 case Instruction::Call: {
Michael Liao736bac62014-11-06 19:05:57 +00002861 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
2862 switch (II->getIntrinsicID()) {
2863 // These synthetic intrinsics have no side-effects and just mark
2864 // information about their operands.
2865 // FIXME: There are other no-op synthetic instructions that potentially
2866 // should be considered at least *safe* to speculate...
2867 case Intrinsic::dbg_declare:
2868 case Intrinsic::dbg_value:
2869 return true;
Chandler Carruth28192c92012-04-07 19:22:18 +00002870
Michael Liao736bac62014-11-06 19:05:57 +00002871 case Intrinsic::bswap:
2872 case Intrinsic::ctlz:
2873 case Intrinsic::ctpop:
2874 case Intrinsic::cttz:
2875 case Intrinsic::objectsize:
2876 case Intrinsic::sadd_with_overflow:
2877 case Intrinsic::smul_with_overflow:
2878 case Intrinsic::ssub_with_overflow:
2879 case Intrinsic::uadd_with_overflow:
2880 case Intrinsic::umul_with_overflow:
2881 case Intrinsic::usub_with_overflow:
2882 return true;
2883 // Sqrt should be OK, since the llvm sqrt intrinsic isn't defined to set
2884 // errno like libm sqrt would.
2885 case Intrinsic::sqrt:
2886 case Intrinsic::fma:
2887 case Intrinsic::fmuladd:
2888 case Intrinsic::fabs:
2889 case Intrinsic::minnum:
2890 case Intrinsic::maxnum:
2891 return true;
2892 // TODO: some fp intrinsics are marked as having the same error handling
2893 // as libm. They're safe to speculate when they won't error.
2894 // TODO: are convert_{from,to}_fp16 safe?
2895 // TODO: can we list target-specific intrinsics here?
2896 default: break;
2897 }
2898 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002899 return false; // The called function could have undefined behavior or
Nick Lewyckyb4039f62011-12-21 05:52:02 +00002900 // side-effects, even if marked readnone nounwind.
2901 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002902 case Instruction::VAArg:
2903 case Instruction::Alloca:
2904 case Instruction::Invoke:
2905 case Instruction::PHI:
2906 case Instruction::Store:
2907 case Instruction::Ret:
2908 case Instruction::Br:
2909 case Instruction::IndirectBr:
2910 case Instruction::Switch:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002911 case Instruction::Unreachable:
2912 case Instruction::Fence:
2913 case Instruction::LandingPad:
2914 case Instruction::AtomicRMW:
2915 case Instruction::AtomicCmpXchg:
2916 case Instruction::Resume:
2917 return false; // Misc instructions which have effects
2918 }
2919}
Dan Gohman1b0f79d2013-01-31 02:40:59 +00002920
Sanjay Patelaee84212014-11-04 16:27:42 +00002921/// Return true if we know that the specified value is never null.
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00002922bool llvm::isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI) {
Dan Gohman1b0f79d2013-01-31 02:40:59 +00002923 // Alloca never returns null, malloc might.
2924 if (isa<AllocaInst>(V)) return true;
2925
Nick Lewyckyd52b1522014-05-20 01:23:40 +00002926 // A byval, inalloca, or nonnull argument is never null.
Dan Gohman1b0f79d2013-01-31 02:40:59 +00002927 if (const Argument *A = dyn_cast<Argument>(V))
Nick Lewyckyd52b1522014-05-20 01:23:40 +00002928 return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
Dan Gohman1b0f79d2013-01-31 02:40:59 +00002929
2930 // Global values are not null unless extern weak.
2931 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2932 return !GV->hasExternalWeakLinkage();
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00002933
Philip Reamescdb72f32014-10-20 22:40:55 +00002934 // A Load tagged w/nonnull metadata is never null.
2935 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
Philip Reames5a3f5f72014-10-21 00:13:20 +00002936 return LI->getMetadata(LLVMContext::MD_nonnull);
Philip Reamescdb72f32014-10-20 22:40:55 +00002937
Nick Lewyckyec373542014-05-20 05:13:21 +00002938 if (ImmutableCallSite CS = V)
Hal Finkelb0407ba2014-07-18 15:51:28 +00002939 if (CS.isReturnNonNull())
Nick Lewyckyec373542014-05-20 05:13:21 +00002940 return true;
2941
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00002942 // operator new never returns null.
2943 if (isOperatorNewLikeFn(V, TLI, /*LookThroughBitCast=*/true))
2944 return true;
2945
Dan Gohman1b0f79d2013-01-31 02:40:59 +00002946 return false;
2947}
David Majnemer491331a2015-01-02 07:29:43 +00002948
2949OverflowResult llvm::computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002950 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00002951 AssumptionCache *AC,
David Majnemer491331a2015-01-02 07:29:43 +00002952 const Instruction *CxtI,
2953 const DominatorTree *DT) {
2954 // Multiplying n * m significant bits yields a result of n + m significant
2955 // bits. If the total number of significant bits does not exceed the
2956 // result bit width (minus 1), there is no overflow.
2957 // This means if we have enough leading zero bits in the operands
2958 // we can guarantee that the result does not overflow.
2959 // Ref: "Hacker's Delight" by Henry Warren
2960 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
2961 APInt LHSKnownZero(BitWidth, 0);
David Majnemerc8a576b2015-01-02 07:29:47 +00002962 APInt LHSKnownOne(BitWidth, 0);
David Majnemer491331a2015-01-02 07:29:43 +00002963 APInt RHSKnownZero(BitWidth, 0);
David Majnemerc8a576b2015-01-02 07:29:47 +00002964 APInt RHSKnownOne(BitWidth, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00002965 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
2966 DT);
2967 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
2968 DT);
David Majnemer491331a2015-01-02 07:29:43 +00002969 // Note that underestimating the number of zero bits gives a more
2970 // conservative answer.
2971 unsigned ZeroBits = LHSKnownZero.countLeadingOnes() +
2972 RHSKnownZero.countLeadingOnes();
2973 // First handle the easy case: if we have enough zero bits there's
2974 // definitely no overflow.
2975 if (ZeroBits >= BitWidth)
2976 return OverflowResult::NeverOverflows;
2977
2978 // Get the largest possible values for each operand.
2979 APInt LHSMax = ~LHSKnownZero;
2980 APInt RHSMax = ~RHSKnownZero;
2981
2982 // We know the multiply operation doesn't overflow if the maximum values for
2983 // each operand will not overflow after we multiply them together.
David Majnemerc8a576b2015-01-02 07:29:47 +00002984 bool MaxOverflow;
2985 LHSMax.umul_ov(RHSMax, MaxOverflow);
2986 if (!MaxOverflow)
2987 return OverflowResult::NeverOverflows;
David Majnemer491331a2015-01-02 07:29:43 +00002988
David Majnemerc8a576b2015-01-02 07:29:47 +00002989 // We know it always overflows if multiplying the smallest possible values for
2990 // the operands also results in overflow.
2991 bool MinOverflow;
2992 LHSKnownOne.umul_ov(RHSKnownOne, MinOverflow);
2993 if (MinOverflow)
2994 return OverflowResult::AlwaysOverflows;
2995
2996 return OverflowResult::MayOverflow;
David Majnemer491331a2015-01-02 07:29:43 +00002997}
David Majnemer5310c1e2015-01-07 00:39:50 +00002998
2999OverflowResult llvm::computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003000 const DataLayout &DL,
David Majnemer5310c1e2015-01-07 00:39:50 +00003001 AssumptionCache *AC,
3002 const Instruction *CxtI,
3003 const DominatorTree *DT) {
3004 bool LHSKnownNonNegative, LHSKnownNegative;
3005 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0,
3006 AC, CxtI, DT);
3007 if (LHSKnownNonNegative || LHSKnownNegative) {
3008 bool RHSKnownNonNegative, RHSKnownNegative;
3009 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0,
3010 AC, CxtI, DT);
3011
3012 if (LHSKnownNegative && RHSKnownNegative) {
3013 // The sign bit is set in both cases: this MUST overflow.
3014 // Create a simple add instruction, and insert it into the struct.
3015 return OverflowResult::AlwaysOverflows;
3016 }
3017
3018 if (LHSKnownNonNegative && RHSKnownNonNegative) {
3019 // The sign bit is clear in both cases: this CANNOT overflow.
3020 // Create a simple add instruction, and insert it into the struct.
3021 return OverflowResult::NeverOverflows;
3022 }
3023 }
3024
3025 return OverflowResult::MayOverflow;
3026}