blob: c70a8087d868419e7c8a2e15e65fe721bf26d8e3 [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"
Adam Nemete2b885c2015-04-23 20:09:20 +000020#include "llvm/Analysis/LoopInfo.h"
Nick Lewyckyec373542014-05-20 05:13:21 +000021#include "llvm/IR/CallSite.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000022#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Constants.h"
24#include "llvm/IR/DataLayout.h"
Hal Finkel60db0582014-09-07 18:57:58 +000025#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000026#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/GlobalAlias.h"
28#include "llvm/IR/GlobalVariable.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/IntrinsicInst.h"
31#include "llvm/IR/LLVMContext.h"
32#include "llvm/IR/Metadata.h"
33#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000034#include "llvm/IR/PatternMatch.h"
Philip Reames5461d452015-04-23 17:36:48 +000035#include "llvm/IR/Statepoint.h"
Matt Arsenaultf1a7e622014-07-15 01:55:03 +000036#include "llvm/Support/Debug.h"
Chris Lattner965c7692008-06-02 01:18:21 +000037#include "llvm/Support/MathExtras.h"
Chris Lattner64496902008-06-04 04:46:14 +000038#include <cstring>
Chris Lattner965c7692008-06-02 01:18:21 +000039using namespace llvm;
Duncan Sandsd3951082011-01-25 09:38:29 +000040using namespace llvm::PatternMatch;
41
42const unsigned MaxDepth = 6;
43
Philip Reames1c292272015-03-10 22:43:20 +000044/// Enable an experimental feature to leverage information about dominating
45/// conditions to compute known bits. The individual options below control how
46/// hard we search. The defaults are choosen to be fairly aggressive. If you
47/// run into compile time problems when testing, scale them back and report
48/// your findings.
49static cl::opt<bool> EnableDomConditions("value-tracking-dom-conditions",
50 cl::Hidden, cl::init(false));
51
52// This is expensive, so we only do it for the top level query value.
53// (TODO: evaluate cost vs profit, consider higher thresholds)
54static cl::opt<unsigned> DomConditionsMaxDepth("dom-conditions-max-depth",
55 cl::Hidden, cl::init(1));
56
57/// How many dominating blocks should be scanned looking for dominating
58/// conditions?
59static cl::opt<unsigned> DomConditionsMaxDomBlocks("dom-conditions-dom-blocks",
60 cl::Hidden,
61 cl::init(20000));
62
63// Controls the number of uses of the value searched for possible
64// dominating comparisons.
65static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
66 cl::Hidden, cl::init(2000));
67
68// If true, don't consider only compares whose only use is a branch.
69static cl::opt<bool> DomConditionsSingleCmpUse("dom-conditions-single-cmp-use",
70 cl::Hidden, cl::init(false));
71
Sanjay Patelaee84212014-11-04 16:27:42 +000072/// Returns the bitwidth of the given scalar or pointer type (if unknown returns
73/// 0). For vector types, returns the element type's bitwidth.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000074static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
Duncan Sandsd3951082011-01-25 09:38:29 +000075 if (unsigned BitWidth = Ty->getScalarSizeInBits())
76 return BitWidth;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +000077
Mehdi Aminia28d91d2015-03-10 02:37:25 +000078 return DL.getPointerTypeSizeInBits(Ty);
Duncan Sandsd3951082011-01-25 09:38:29 +000079}
Chris Lattner965c7692008-06-02 01:18:21 +000080
Hal Finkel60db0582014-09-07 18:57:58 +000081// Many of these functions have internal versions that take an assumption
82// exclusion set. This is because of the potential for mutual recursion to
83// cause computeKnownBits to repeatedly visit the same assume intrinsic. The
84// classic case of this is assume(x = y), which will attempt to determine
85// bits in x from bits in y, which will attempt to determine bits in y from
86// bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
87// isKnownNonZero, which calls computeKnownBits and ComputeSignBit and
88// isKnownToBeAPowerOfTwo (all of which can call computeKnownBits), and so on.
89typedef SmallPtrSet<const Value *, 8> ExclInvsSet;
90
Benjamin Kramercfd8d902014-09-12 08:56:53 +000091namespace {
Hal Finkel60db0582014-09-07 18:57:58 +000092// Simplifying using an assume can only be done in a particular control-flow
93// context (the context instruction provides that context). If an assume and
94// the context instruction are not in the same block then the DT helps in
95// figuring out if we can use it.
96struct Query {
97 ExclInvsSet ExclInvs;
Chandler Carruth66b31302015-01-04 12:03:27 +000098 AssumptionCache *AC;
Hal Finkel60db0582014-09-07 18:57:58 +000099 const Instruction *CxtI;
100 const DominatorTree *DT;
101
Chandler Carruth66b31302015-01-04 12:03:27 +0000102 Query(AssumptionCache *AC = nullptr, const Instruction *CxtI = nullptr,
Hal Finkel60db0582014-09-07 18:57:58 +0000103 const DominatorTree *DT = nullptr)
Chandler Carruth66b31302015-01-04 12:03:27 +0000104 : AC(AC), CxtI(CxtI), DT(DT) {}
Hal Finkel60db0582014-09-07 18:57:58 +0000105
106 Query(const Query &Q, const Value *NewExcl)
Chandler Carruth66b31302015-01-04 12:03:27 +0000107 : ExclInvs(Q.ExclInvs), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000108 ExclInvs.insert(NewExcl);
109 }
110};
Benjamin Kramercfd8d902014-09-12 08:56:53 +0000111} // end anonymous namespace
Hal Finkel60db0582014-09-07 18:57:58 +0000112
Sanjay Patel547e9752014-11-04 16:09:50 +0000113// Given the provided Value and, potentially, a context instruction, return
Hal Finkel60db0582014-09-07 18:57:58 +0000114// the preferred context instruction (if any).
115static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
116 // If we've been provided with a context instruction, then use that (provided
117 // it has been inserted).
118 if (CxtI && CxtI->getParent())
119 return CxtI;
120
121 // If the value is really an already-inserted instruction, then use that.
122 CxtI = dyn_cast<Instruction>(V);
123 if (CxtI && CxtI->getParent())
124 return CxtI;
125
126 return nullptr;
127}
128
129static void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000130 const DataLayout &DL, unsigned Depth,
131 const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000132
133void llvm::computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000134 const DataLayout &DL, unsigned Depth,
Chandler Carruth66b31302015-01-04 12:03:27 +0000135 AssumptionCache *AC, const Instruction *CxtI,
Hal Finkel60db0582014-09-07 18:57:58 +0000136 const DominatorTree *DT) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000137 ::computeKnownBits(V, KnownZero, KnownOne, DL, Depth,
Chandler Carruth66b31302015-01-04 12:03:27 +0000138 Query(AC, safeCxtI(V, CxtI), DT));
Hal Finkel60db0582014-09-07 18:57:58 +0000139}
140
Jingyue Wuca321902015-05-14 23:53:19 +0000141bool llvm::haveNoCommonBitsSet(Value *LHS, Value *RHS, const DataLayout &DL,
142 AssumptionCache *AC, const Instruction *CxtI,
143 const DominatorTree *DT) {
144 assert(LHS->getType() == RHS->getType() &&
145 "LHS and RHS should have the same type");
146 assert(LHS->getType()->isIntOrIntVectorTy() &&
147 "LHS and RHS should be integers");
148 IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
149 APInt LHSKnownZero(IT->getBitWidth(), 0), LHSKnownOne(IT->getBitWidth(), 0);
150 APInt RHSKnownZero(IT->getBitWidth(), 0), RHSKnownOne(IT->getBitWidth(), 0);
151 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, 0, AC, CxtI, DT);
152 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, 0, AC, CxtI, DT);
153 return (LHSKnownZero | RHSKnownZero).isAllOnesValue();
154}
155
Hal Finkel60db0582014-09-07 18:57:58 +0000156static void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000157 const DataLayout &DL, unsigned Depth,
158 const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000159
160void llvm::ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000161 const DataLayout &DL, unsigned Depth,
Chandler Carruth66b31302015-01-04 12:03:27 +0000162 AssumptionCache *AC, const Instruction *CxtI,
Hal Finkel60db0582014-09-07 18:57:58 +0000163 const DominatorTree *DT) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000164 ::ComputeSignBit(V, KnownZero, KnownOne, DL, Depth,
Chandler Carruth66b31302015-01-04 12:03:27 +0000165 Query(AC, safeCxtI(V, CxtI), DT));
Hal Finkel60db0582014-09-07 18:57:58 +0000166}
167
168static bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000169 const Query &Q, const DataLayout &DL);
Hal Finkel60db0582014-09-07 18:57:58 +0000170
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000171bool llvm::isKnownToBeAPowerOfTwo(Value *V, const DataLayout &DL, bool OrZero,
Chandler Carruth66b31302015-01-04 12:03:27 +0000172 unsigned Depth, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000173 const Instruction *CxtI,
174 const DominatorTree *DT) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000175 return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
176 Query(AC, safeCxtI(V, CxtI), DT), DL);
177}
178
179static bool isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
180 const Query &Q);
181
182bool llvm::isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
183 AssumptionCache *AC, const Instruction *CxtI,
184 const DominatorTree *DT) {
185 return ::isKnownNonZero(V, DL, Depth, Query(AC, safeCxtI(V, CxtI), DT));
186}
187
188static bool MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
189 unsigned Depth, const Query &Q);
190
191bool llvm::MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
192 unsigned Depth, AssumptionCache *AC,
193 const Instruction *CxtI, const DominatorTree *DT) {
194 return ::MaskedValueIsZero(V, Mask, DL, Depth,
195 Query(AC, safeCxtI(V, CxtI), DT));
196}
197
198static unsigned ComputeNumSignBits(Value *V, const DataLayout &DL,
199 unsigned Depth, const Query &Q);
200
201unsigned llvm::ComputeNumSignBits(Value *V, const DataLayout &DL,
202 unsigned Depth, AssumptionCache *AC,
203 const Instruction *CxtI,
204 const DominatorTree *DT) {
205 return ::ComputeNumSignBits(V, DL, Depth, Query(AC, safeCxtI(V, CxtI), DT));
Hal Finkel60db0582014-09-07 18:57:58 +0000206}
207
Jay Foada0653a32014-05-14 21:14:37 +0000208static void computeKnownBitsAddSub(bool Add, Value *Op0, Value *Op1, bool NSW,
209 APInt &KnownZero, APInt &KnownOne,
210 APInt &KnownZero2, APInt &KnownOne2,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000211 const DataLayout &DL, unsigned Depth,
Hal Finkel60db0582014-09-07 18:57:58 +0000212 const Query &Q) {
213 if (!Add) {
214 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(Op0)) {
215 // We know that the top bits of C-X are clear if X contains less bits
216 // than C (i.e. no wrap-around can happen). For example, 20-X is
217 // positive if we can prove that X is >= 0 and < 16.
218 if (!CLHS->getValue().isNegative()) {
219 unsigned BitWidth = KnownZero.getBitWidth();
220 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
221 // NLZ can't be BitWidth with no sign bit
222 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000223 computeKnownBits(Op1, KnownZero2, KnownOne2, DL, Depth + 1, Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000224
225 // If all of the MaskV bits are known to be zero, then we know the
226 // output top bits are zero, because we now know that the output is
227 // from [0-C].
228 if ((KnownZero2 & MaskV) == MaskV) {
229 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
230 // Top bits known zero.
231 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
232 }
233 }
234 }
235 }
236
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000237 unsigned BitWidth = KnownZero.getBitWidth();
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000238
David Majnemer97ddca32014-08-22 00:40:43 +0000239 // If an initial sequence of bits in the result is not needed, the
240 // corresponding bits in the operands are not needed.
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000241 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000242 computeKnownBits(Op0, LHSKnownZero, LHSKnownOne, DL, Depth + 1, Q);
243 computeKnownBits(Op1, KnownZero2, KnownOne2, DL, Depth + 1, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000244
David Majnemer97ddca32014-08-22 00:40:43 +0000245 // Carry in a 1 for a subtract, rather than a 0.
246 APInt CarryIn(BitWidth, 0);
247 if (!Add) {
248 // Sum = LHS + ~RHS + 1
249 std::swap(KnownZero2, KnownOne2);
250 CarryIn.setBit(0);
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000251 }
252
David Majnemer97ddca32014-08-22 00:40:43 +0000253 APInt PossibleSumZero = ~LHSKnownZero + ~KnownZero2 + CarryIn;
254 APInt PossibleSumOne = LHSKnownOne + KnownOne2 + CarryIn;
255
256 // Compute known bits of the carry.
257 APInt CarryKnownZero = ~(PossibleSumZero ^ LHSKnownZero ^ KnownZero2);
258 APInt CarryKnownOne = PossibleSumOne ^ LHSKnownOne ^ KnownOne2;
259
260 // Compute set of known bits (where all three relevant bits are known).
261 APInt LHSKnown = LHSKnownZero | LHSKnownOne;
262 APInt RHSKnown = KnownZero2 | KnownOne2;
263 APInt CarryKnown = CarryKnownZero | CarryKnownOne;
264 APInt Known = LHSKnown & RHSKnown & CarryKnown;
265
266 assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
267 "known bits of sum differ");
268
269 // Compute known bits of the result.
270 KnownZero = ~PossibleSumOne & Known;
271 KnownOne = PossibleSumOne & Known;
272
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000273 // Are we still trying to solve for the sign bit?
David Majnemer97ddca32014-08-22 00:40:43 +0000274 if (!Known.isNegative()) {
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000275 if (NSW) {
David Majnemer97ddca32014-08-22 00:40:43 +0000276 // Adding two non-negative numbers, or subtracting a negative number from
277 // a non-negative one, can't wrap into negative.
278 if (LHSKnownZero.isNegative() && KnownZero2.isNegative())
279 KnownZero |= APInt::getSignBit(BitWidth);
280 // Adding two negative numbers, or subtracting a non-negative number from
281 // a negative one, can't wrap into non-negative.
282 else if (LHSKnownOne.isNegative() && KnownOne2.isNegative())
283 KnownOne |= APInt::getSignBit(BitWidth);
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000284 }
285 }
286}
287
Jay Foada0653a32014-05-14 21:14:37 +0000288static void computeKnownBitsMul(Value *Op0, Value *Op1, bool NSW,
289 APInt &KnownZero, APInt &KnownOne,
290 APInt &KnownZero2, APInt &KnownOne2,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000291 const DataLayout &DL, unsigned Depth,
Hal Finkel60db0582014-09-07 18:57:58 +0000292 const Query &Q) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000293 unsigned BitWidth = KnownZero.getBitWidth();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000294 computeKnownBits(Op1, KnownZero, KnownOne, DL, Depth + 1, Q);
295 computeKnownBits(Op0, KnownZero2, KnownOne2, DL, Depth + 1, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000296
297 bool isKnownNegative = false;
298 bool isKnownNonNegative = false;
299 // If the multiplication is known not to overflow, compute the sign bit.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000300 if (NSW) {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000301 if (Op0 == Op1) {
302 // The product of a number with itself is non-negative.
303 isKnownNonNegative = true;
304 } else {
305 bool isKnownNonNegativeOp1 = KnownZero.isNegative();
306 bool isKnownNonNegativeOp0 = KnownZero2.isNegative();
307 bool isKnownNegativeOp1 = KnownOne.isNegative();
308 bool isKnownNegativeOp0 = KnownOne2.isNegative();
309 // The product of two numbers with the same sign is non-negative.
310 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
311 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
312 // The product of a negative number and a non-negative number is either
313 // negative or zero.
314 if (!isKnownNonNegative)
315 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000316 isKnownNonZero(Op0, DL, Depth, Q)) ||
Nick Lewyckyfa306072012-03-18 23:28:48 +0000317 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000318 isKnownNonZero(Op1, DL, Depth, Q));
Nick Lewyckyfa306072012-03-18 23:28:48 +0000319 }
320 }
321
322 // If low bits are zero in either operand, output low known-0 bits.
323 // Also compute a conserative estimate for high known-0 bits.
324 // More trickiness is possible, but this is sufficient for the
325 // interesting case of alignment computation.
326 KnownOne.clearAllBits();
327 unsigned TrailZ = KnownZero.countTrailingOnes() +
328 KnownZero2.countTrailingOnes();
329 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
330 KnownZero2.countLeadingOnes(),
331 BitWidth) - BitWidth;
332
333 TrailZ = std::min(TrailZ, BitWidth);
334 LeadZ = std::min(LeadZ, BitWidth);
335 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
336 APInt::getHighBitsSet(BitWidth, LeadZ);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000337
338 // Only make use of no-wrap flags if we failed to compute the sign bit
339 // directly. This matters if the multiplication always overflows, in
340 // which case we prefer to follow the result of the direct computation,
341 // though as the program is invoking undefined behaviour we can choose
342 // whatever we like here.
343 if (isKnownNonNegative && !KnownOne.isNegative())
344 KnownZero.setBit(BitWidth - 1);
345 else if (isKnownNegative && !KnownZero.isNegative())
346 KnownOne.setBit(BitWidth - 1);
347}
348
Jingyue Wu37fcb592014-06-19 16:50:16 +0000349void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
350 APInt &KnownZero) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000351 unsigned BitWidth = KnownZero.getBitWidth();
Rafael Espindola53190532012-03-30 15:52:11 +0000352 unsigned NumRanges = Ranges.getNumOperands() / 2;
353 assert(NumRanges >= 1);
354
355 // Use the high end of the ranges to find leading zeros.
356 unsigned MinLeadingZeros = BitWidth;
357 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000358 ConstantInt *Lower =
359 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
360 ConstantInt *Upper =
361 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
Rafael Espindola53190532012-03-30 15:52:11 +0000362 ConstantRange Range(Lower->getValue(), Upper->getValue());
363 if (Range.isWrappedSet())
364 MinLeadingZeros = 0; // -1 has no zeros
365 unsigned LeadingZeros = (Upper->getValue() - 1).countLeadingZeros();
366 MinLeadingZeros = std::min(LeadingZeros, MinLeadingZeros);
367 }
368
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000369 KnownZero = APInt::getHighBitsSet(BitWidth, MinLeadingZeros);
Rafael Espindola53190532012-03-30 15:52:11 +0000370}
Jay Foad5a29c362014-05-15 12:12:55 +0000371
Hal Finkel60db0582014-09-07 18:57:58 +0000372static bool isEphemeralValueOf(Instruction *I, const Value *E) {
373 SmallVector<const Value *, 16> WorkSet(1, I);
374 SmallPtrSet<const Value *, 32> Visited;
375 SmallPtrSet<const Value *, 16> EphValues;
376
377 while (!WorkSet.empty()) {
378 const Value *V = WorkSet.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +0000379 if (!Visited.insert(V).second)
Hal Finkel60db0582014-09-07 18:57:58 +0000380 continue;
381
382 // If all uses of this value are ephemeral, then so is this value.
383 bool FoundNEUse = false;
384 for (const User *I : V->users())
385 if (!EphValues.count(I)) {
386 FoundNEUse = true;
387 break;
388 }
389
390 if (!FoundNEUse) {
391 if (V == E)
392 return true;
393
394 EphValues.insert(V);
395 if (const User *U = dyn_cast<User>(V))
396 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
397 J != JE; ++J) {
398 if (isSafeToSpeculativelyExecute(*J))
399 WorkSet.push_back(*J);
400 }
401 }
402 }
403
404 return false;
405}
406
407// Is this an intrinsic that cannot be speculated but also cannot trap?
408static bool isAssumeLikeIntrinsic(const Instruction *I) {
409 if (const CallInst *CI = dyn_cast<CallInst>(I))
410 if (Function *F = CI->getCalledFunction())
411 switch (F->getIntrinsicID()) {
412 default: break;
413 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
414 case Intrinsic::assume:
415 case Intrinsic::dbg_declare:
416 case Intrinsic::dbg_value:
417 case Intrinsic::invariant_start:
418 case Intrinsic::invariant_end:
419 case Intrinsic::lifetime_start:
420 case Intrinsic::lifetime_end:
421 case Intrinsic::objectsize:
422 case Intrinsic::ptr_annotation:
423 case Intrinsic::var_annotation:
424 return true;
425 }
426
427 return false;
428}
429
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000430static bool isValidAssumeForContext(Value *V, const Query &Q) {
Hal Finkel60db0582014-09-07 18:57:58 +0000431 Instruction *Inv = cast<Instruction>(V);
432
433 // There are two restrictions on the use of an assume:
434 // 1. The assume must dominate the context (or the control flow must
435 // reach the assume whenever it reaches the context).
436 // 2. The context must not be in the assume's set of ephemeral values
437 // (otherwise we will use the assume to prove that the condition
438 // feeding the assume is trivially true, thus causing the removal of
439 // the assume).
440
441 if (Q.DT) {
442 if (Q.DT->dominates(Inv, Q.CxtI)) {
443 return true;
444 } else if (Inv->getParent() == Q.CxtI->getParent()) {
445 // The context comes first, but they're both in the same block. Make sure
446 // there is nothing in between that might interrupt the control flow.
447 for (BasicBlock::const_iterator I =
448 std::next(BasicBlock::const_iterator(Q.CxtI)),
449 IE(Inv); I != IE; ++I)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000450 if (!isSafeToSpeculativelyExecute(I) && !isAssumeLikeIntrinsic(I))
Hal Finkel60db0582014-09-07 18:57:58 +0000451 return false;
452
453 return !isEphemeralValueOf(Inv, Q.CxtI);
454 }
455
456 return false;
457 }
458
459 // When we don't have a DT, we do a limited search...
460 if (Inv->getParent() == Q.CxtI->getParent()->getSinglePredecessor()) {
461 return true;
462 } else if (Inv->getParent() == Q.CxtI->getParent()) {
463 // Search forward from the assume until we reach the context (or the end
464 // of the block); the common case is that the assume will come first.
465 for (BasicBlock::iterator I = std::next(BasicBlock::iterator(Inv)),
466 IE = Inv->getParent()->end(); I != IE; ++I)
467 if (I == Q.CxtI)
468 return true;
469
470 // The context must come first...
471 for (BasicBlock::const_iterator I =
472 std::next(BasicBlock::const_iterator(Q.CxtI)),
473 IE(Inv); I != IE; ++I)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000474 if (!isSafeToSpeculativelyExecute(I) && !isAssumeLikeIntrinsic(I))
Hal Finkel60db0582014-09-07 18:57:58 +0000475 return false;
476
477 return !isEphemeralValueOf(Inv, Q.CxtI);
478 }
479
480 return false;
481}
482
483bool llvm::isValidAssumeForContext(const Instruction *I,
484 const Instruction *CxtI,
Hal Finkel60db0582014-09-07 18:57:58 +0000485 const DominatorTree *DT) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000486 return ::isValidAssumeForContext(const_cast<Instruction *>(I),
487 Query(nullptr, CxtI, DT));
Hal Finkel60db0582014-09-07 18:57:58 +0000488}
489
490template<typename LHS, typename RHS>
491inline match_combine_or<CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>,
492 CmpClass_match<RHS, LHS, ICmpInst, ICmpInst::Predicate>>
493m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
494 return m_CombineOr(m_ICmp(Pred, L, R), m_ICmp(Pred, R, L));
495}
496
497template<typename LHS, typename RHS>
498inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::And>,
499 BinaryOp_match<RHS, LHS, Instruction::And>>
500m_c_And(const LHS &L, const RHS &R) {
501 return m_CombineOr(m_And(L, R), m_And(R, L));
502}
503
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000504template<typename LHS, typename RHS>
505inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Or>,
506 BinaryOp_match<RHS, LHS, Instruction::Or>>
507m_c_Or(const LHS &L, const RHS &R) {
508 return m_CombineOr(m_Or(L, R), m_Or(R, L));
509}
510
511template<typename LHS, typename RHS>
512inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Xor>,
513 BinaryOp_match<RHS, LHS, Instruction::Xor>>
514m_c_Xor(const LHS &L, const RHS &R) {
515 return m_CombineOr(m_Xor(L, R), m_Xor(R, L));
516}
517
Philip Reames1c292272015-03-10 22:43:20 +0000518/// Compute known bits in 'V' under the assumption that the condition 'Cmp' is
519/// true (at the context instruction.) This is mostly a utility function for
520/// the prototype dominating conditions reasoning below.
521static void computeKnownBitsFromTrueCondition(Value *V, ICmpInst *Cmp,
522 APInt &KnownZero,
523 APInt &KnownOne,
524 const DataLayout &DL,
525 unsigned Depth, const Query &Q) {
526 Value *LHS = Cmp->getOperand(0);
527 Value *RHS = Cmp->getOperand(1);
528 // TODO: We could potentially be more aggressive here. This would be worth
529 // evaluating. If we can, explore commoning this code with the assume
530 // handling logic.
531 if (LHS != V && RHS != V)
532 return;
533
534 const unsigned BitWidth = KnownZero.getBitWidth();
535
536 switch (Cmp->getPredicate()) {
537 default:
538 // We know nothing from this condition
539 break;
540 // TODO: implement unsigned bound from below (known one bits)
541 // TODO: common condition check implementations with assumes
542 // TODO: implement other patterns from assume (e.g. V & B == A)
543 case ICmpInst::ICMP_SGT:
544 if (LHS == V) {
545 APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
546 computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
547 if (KnownOneTemp.isAllOnesValue() || KnownZeroTemp.isNegative()) {
548 // We know that the sign bit is zero.
549 KnownZero |= APInt::getSignBit(BitWidth);
550 }
551 }
552 break;
553 case ICmpInst::ICMP_EQ:
554 if (LHS == V)
555 computeKnownBits(RHS, KnownZero, KnownOne, DL, Depth + 1, Q);
556 else if (RHS == V)
557 computeKnownBits(LHS, KnownZero, KnownOne, DL, Depth + 1, Q);
558 else
559 llvm_unreachable("missing use?");
560 break;
561 case ICmpInst::ICMP_ULE:
562 if (LHS == V) {
563 APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
564 computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
565 // The known zero bits carry over
566 unsigned SignBits = KnownZeroTemp.countLeadingOnes();
567 KnownZero |= APInt::getHighBitsSet(BitWidth, SignBits);
568 }
569 break;
570 case ICmpInst::ICMP_ULT:
571 if (LHS == V) {
572 APInt KnownZeroTemp(BitWidth, 0), KnownOneTemp(BitWidth, 0);
573 computeKnownBits(RHS, KnownZeroTemp, KnownOneTemp, DL, Depth + 1, Q);
574 // Whatever high bits in rhs are zero are known to be zero (if rhs is a
575 // power of 2, then one more).
576 unsigned SignBits = KnownZeroTemp.countLeadingOnes();
577 if (isKnownToBeAPowerOfTwo(RHS, false, Depth + 1, Query(Q, Cmp), DL))
578 SignBits++;
579 KnownZero |= APInt::getHighBitsSet(BitWidth, SignBits);
580 }
581 break;
582 };
583}
584
585/// Compute known bits in 'V' from conditions which are known to be true along
586/// all paths leading to the context instruction. In particular, look for
587/// cases where one branch of an interesting condition dominates the context
588/// instruction. This does not do general dataflow.
589/// NOTE: This code is EXPERIMENTAL and currently off by default.
590static void computeKnownBitsFromDominatingCondition(Value *V, APInt &KnownZero,
591 APInt &KnownOne,
592 const DataLayout &DL,
593 unsigned Depth,
594 const Query &Q) {
595 // Need both the dominator tree and the query location to do anything useful
596 if (!Q.DT || !Q.CxtI)
597 return;
598 Instruction *Cxt = const_cast<Instruction *>(Q.CxtI);
599
600 // Avoid useless work
601 if (auto VI = dyn_cast<Instruction>(V))
602 if (VI->getParent() == Cxt->getParent())
603 return;
604
605 // Note: We currently implement two options. It's not clear which of these
606 // will survive long term, we need data for that.
607 // Option 1 - Try walking the dominator tree looking for conditions which
608 // might apply. This works well for local conditions (loop guards, etc..),
609 // but not as well for things far from the context instruction (presuming a
610 // low max blocks explored). If we can set an high enough limit, this would
611 // be all we need.
612 // Option 2 - We restrict out search to those conditions which are uses of
613 // the value we're interested in. This is independent of dom structure,
614 // but is slightly less powerful without looking through lots of use chains.
615 // It does handle conditions far from the context instruction (e.g. early
616 // function exits on entry) really well though.
617
618 // Option 1 - Search the dom tree
619 unsigned NumBlocksExplored = 0;
620 BasicBlock *Current = Cxt->getParent();
621 while (true) {
622 // Stop searching if we've gone too far up the chain
623 if (NumBlocksExplored >= DomConditionsMaxDomBlocks)
624 break;
625 NumBlocksExplored++;
626
627 if (!Q.DT->getNode(Current)->getIDom())
628 break;
629 Current = Q.DT->getNode(Current)->getIDom()->getBlock();
630 if (!Current)
631 // found function entry
632 break;
633
634 BranchInst *BI = dyn_cast<BranchInst>(Current->getTerminator());
635 if (!BI || BI->isUnconditional())
636 continue;
637 ICmpInst *Cmp = dyn_cast<ICmpInst>(BI->getCondition());
638 if (!Cmp)
639 continue;
640
641 // We're looking for conditions that are guaranteed to hold at the context
642 // instruction. Finding a condition where one path dominates the context
643 // isn't enough because both the true and false cases could merge before
644 // the context instruction we're actually interested in. Instead, we need
645 // to ensure that the taken *edge* dominates the context instruction.
646 BasicBlock *BB0 = BI->getSuccessor(0);
647 BasicBlockEdge Edge(BI->getParent(), BB0);
648 if (!Edge.isSingleEdge() || !Q.DT->dominates(Edge, Q.CxtI->getParent()))
649 continue;
650
651 computeKnownBitsFromTrueCondition(V, Cmp, KnownZero, KnownOne, DL, Depth,
652 Q);
653 }
654
655 // Option 2 - Search the other uses of V
656 unsigned NumUsesExplored = 0;
657 for (auto U : V->users()) {
658 // Avoid massive lists
659 if (NumUsesExplored >= DomConditionsMaxUses)
660 break;
661 NumUsesExplored++;
662 // Consider only compare instructions uniquely controlling a branch
663 ICmpInst *Cmp = dyn_cast<ICmpInst>(U);
664 if (!Cmp)
665 continue;
666
667 if (DomConditionsSingleCmpUse && !Cmp->hasOneUse())
668 continue;
669
670 for (auto *CmpU : Cmp->users()) {
671 BranchInst *BI = dyn_cast<BranchInst>(CmpU);
672 if (!BI || BI->isUnconditional())
673 continue;
674 // We're looking for conditions that are guaranteed to hold at the
675 // context instruction. Finding a condition where one path dominates
676 // the context isn't enough because both the true and false cases could
677 // merge before the context instruction we're actually interested in.
678 // Instead, we need to ensure that the taken *edge* dominates the context
679 // instruction.
680 BasicBlock *BB0 = BI->getSuccessor(0);
681 BasicBlockEdge Edge(BI->getParent(), BB0);
682 if (!Edge.isSingleEdge() || !Q.DT->dominates(Edge, Q.CxtI->getParent()))
683 continue;
684
685 computeKnownBitsFromTrueCondition(V, Cmp, KnownZero, KnownOne, DL, Depth,
686 Q);
687 }
688 }
689}
690
Hal Finkel60db0582014-09-07 18:57:58 +0000691static void computeKnownBitsFromAssume(Value *V, APInt &KnownZero,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000692 APInt &KnownOne, const DataLayout &DL,
Hal Finkel60db0582014-09-07 18:57:58 +0000693 unsigned Depth, const Query &Q) {
694 // Use of assumptions is context-sensitive. If we don't have a context, we
695 // cannot use them!
Chandler Carruth66b31302015-01-04 12:03:27 +0000696 if (!Q.AC || !Q.CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000697 return;
698
699 unsigned BitWidth = KnownZero.getBitWidth();
700
Chandler Carruth66b31302015-01-04 12:03:27 +0000701 for (auto &AssumeVH : Q.AC->assumptions()) {
702 if (!AssumeVH)
703 continue;
704 CallInst *I = cast<CallInst>(AssumeVH);
Chandler Carruth75c11b82015-01-04 23:13:57 +0000705 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
Chandler Carruth66b31302015-01-04 12:03:27 +0000706 "Got assumption for the wrong function!");
Hal Finkel60db0582014-09-07 18:57:58 +0000707 if (Q.ExclInvs.count(I))
708 continue;
709
Philip Reames00d3b272014-11-24 23:44:28 +0000710 // Warning: This loop can end up being somewhat performance sensetive.
711 // We're running this loop for once for each value queried resulting in a
712 // runtime of ~O(#assumes * #values).
713
Benjamin Kramer619c4e52015-04-10 11:24:51 +0000714 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
Philip Reames00d3b272014-11-24 23:44:28 +0000715 "must be an assume intrinsic");
Benjamin Kramer619c4e52015-04-10 11:24:51 +0000716
Philip Reames00d3b272014-11-24 23:44:28 +0000717 Value *Arg = I->getArgOperand(0);
718
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000719 if (Arg == V && isValidAssumeForContext(I, Q)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000720 assert(BitWidth == 1 && "assume operand is not i1?");
721 KnownZero.clearAllBits();
722 KnownOne.setAllBits();
723 return;
724 }
725
David Majnemer9b609752014-12-12 23:59:29 +0000726 // The remaining tests are all recursive, so bail out if we hit the limit.
727 if (Depth == MaxDepth)
728 continue;
729
Hal Finkel60db0582014-09-07 18:57:58 +0000730 Value *A, *B;
731 auto m_V = m_CombineOr(m_Specific(V),
732 m_CombineOr(m_PtrToInt(m_Specific(V)),
733 m_BitCast(m_Specific(V))));
734
735 CmpInst::Predicate Pred;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000736 ConstantInt *C;
Hal Finkel60db0582014-09-07 18:57:58 +0000737 // assume(v = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000738 if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000739 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000740 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
741 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
742 KnownZero |= RHSKnownZero;
743 KnownOne |= RHSKnownOne;
744 // assume(v & b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000745 } else if (match(Arg,
746 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
747 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000748 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
749 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
750 APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
751 computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
752
753 // For those bits in the mask that are known to be one, we can propagate
754 // known bits from the RHS to V.
755 KnownZero |= RHSKnownZero & MaskKnownOne;
756 KnownOne |= RHSKnownOne & MaskKnownOne;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000757 // assume(~(v & b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000758 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
759 m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000760 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000761 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
762 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
763 APInt MaskKnownZero(BitWidth, 0), MaskKnownOne(BitWidth, 0);
764 computeKnownBits(B, MaskKnownZero, MaskKnownOne, DL, Depth+1, Query(Q, I));
765
766 // For those bits in the mask that are known to be one, we can propagate
767 // inverted known bits from the RHS to V.
768 KnownZero |= RHSKnownOne & MaskKnownOne;
769 KnownOne |= RHSKnownZero & MaskKnownOne;
770 // assume(v | b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000771 } else if (match(Arg,
772 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
773 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000774 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
775 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
776 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
777 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
778
779 // For those bits in B that are known to be zero, we can propagate known
780 // bits from the RHS to V.
781 KnownZero |= RHSKnownZero & BKnownZero;
782 KnownOne |= RHSKnownOne & BKnownZero;
783 // assume(~(v | b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000784 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
785 m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000786 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000787 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
788 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
789 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
790 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
791
792 // For those bits in B that are known to be zero, we can propagate
793 // inverted known bits from the RHS to V.
794 KnownZero |= RHSKnownOne & BKnownZero;
795 KnownOne |= RHSKnownZero & BKnownZero;
796 // assume(v ^ b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000797 } else if (match(Arg,
798 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
799 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 known
806 // bits from the RHS to V. For those bits in B that are known to be one,
807 // we can propagate inverted known bits from the RHS to V.
808 KnownZero |= RHSKnownZero & BKnownZero;
809 KnownOne |= RHSKnownOne & BKnownZero;
810 KnownZero |= RHSKnownOne & BKnownOne;
811 KnownOne |= RHSKnownZero & BKnownOne;
812 // assume(~(v ^ b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000813 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
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 APInt BKnownZero(BitWidth, 0), BKnownOne(BitWidth, 0);
819 computeKnownBits(B, BKnownZero, BKnownOne, DL, Depth+1, Query(Q, I));
820
821 // For those bits in B that are known to be zero, we can propagate
822 // inverted known bits from the RHS to V. For those bits in B that are
823 // known to be one, we can propagate known bits from the RHS to V.
824 KnownZero |= RHSKnownOne & BKnownZero;
825 KnownOne |= RHSKnownZero & BKnownZero;
826 KnownZero |= RHSKnownZero & BKnownOne;
827 KnownOne |= RHSKnownOne & BKnownOne;
828 // assume(v << c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000829 } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
830 m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000831 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000832 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
833 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
834 // For those bits in RHS that are known, we can propagate them to known
835 // bits in V shifted to the right by C.
836 KnownZero |= RHSKnownZero.lshr(C->getZExtValue());
837 KnownOne |= RHSKnownOne.lshr(C->getZExtValue());
838 // assume(~(v << c) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000839 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
840 m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000841 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000842 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
843 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
844 // For those bits in RHS that are known, we can propagate them inverted
845 // to known bits in V shifted to the right by C.
846 KnownZero |= RHSKnownOne.lshr(C->getZExtValue());
847 KnownOne |= RHSKnownZero.lshr(C->getZExtValue());
848 // assume(v >> c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000849 } else if (match(Arg,
850 m_c_ICmp(Pred, m_CombineOr(m_LShr(m_V, m_ConstantInt(C)),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000851 m_AShr(m_V, m_ConstantInt(C))),
852 m_Value(A))) &&
853 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000854 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
855 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
856 // For those bits in RHS that are known, we can propagate them to known
857 // bits in V shifted to the right by C.
858 KnownZero |= RHSKnownZero << C->getZExtValue();
859 KnownOne |= RHSKnownOne << C->getZExtValue();
860 // assume(~(v >> c) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000861 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_CombineOr(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000862 m_LShr(m_V, m_ConstantInt(C)),
863 m_AShr(m_V, m_ConstantInt(C)))),
Philip Reames00d3b272014-11-24 23:44:28 +0000864 m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000865 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000866 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
867 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
868 // For those bits in RHS that are known, we can propagate them inverted
869 // to known bits in V shifted to the right by C.
870 KnownZero |= RHSKnownOne << C->getZExtValue();
871 KnownOne |= RHSKnownZero << C->getZExtValue();
872 // assume(v >=_s c) where c is non-negative
Philip Reames00d3b272014-11-24 23:44:28 +0000873 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000874 Pred == ICmpInst::ICMP_SGE && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000875 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
876 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
877
878 if (RHSKnownZero.isNegative()) {
879 // We know that the sign bit is zero.
880 KnownZero |= APInt::getSignBit(BitWidth);
881 }
882 // assume(v >_s c) where c is at least -1.
Philip Reames00d3b272014-11-24 23:44:28 +0000883 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000884 Pred == ICmpInst::ICMP_SGT && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000885 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
886 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
887
888 if (RHSKnownOne.isAllOnesValue() || RHSKnownZero.isNegative()) {
889 // We know that the sign bit is zero.
890 KnownZero |= APInt::getSignBit(BitWidth);
891 }
892 // assume(v <=_s c) where c is negative
Philip Reames00d3b272014-11-24 23:44:28 +0000893 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000894 Pred == ICmpInst::ICMP_SLE && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000895 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
896 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
897
898 if (RHSKnownOne.isNegative()) {
899 // We know that the sign bit is one.
900 KnownOne |= APInt::getSignBit(BitWidth);
901 }
902 // assume(v <_s c) where c is non-positive
Philip Reames00d3b272014-11-24 23:44:28 +0000903 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000904 Pred == ICmpInst::ICMP_SLT && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000905 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
906 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
907
908 if (RHSKnownZero.isAllOnesValue() || RHSKnownOne.isNegative()) {
909 // We know that the sign bit is one.
910 KnownOne |= APInt::getSignBit(BitWidth);
911 }
912 // assume(v <=_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000913 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000914 Pred == ICmpInst::ICMP_ULE && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000915 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
916 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
917
918 // Whatever high bits in c are zero are known to be zero.
919 KnownZero |=
920 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
921 // assume(v <_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000922 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000923 Pred == ICmpInst::ICMP_ULT && isValidAssumeForContext(I, Q)) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000924 APInt RHSKnownZero(BitWidth, 0), RHSKnownOne(BitWidth, 0);
925 computeKnownBits(A, RHSKnownZero, RHSKnownOne, DL, Depth+1, Query(Q, I));
926
927 // Whatever high bits in c are zero are known to be zero (if c is a power
928 // of 2, then one more).
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000929 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I), DL))
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000930 KnownZero |=
931 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes()+1);
932 else
933 KnownZero |=
934 APInt::getHighBitsSet(BitWidth, RHSKnownZero.countLeadingOnes());
Hal Finkel60db0582014-09-07 18:57:58 +0000935 }
936 }
937}
938
Jay Foada0653a32014-05-14 21:14:37 +0000939/// Determine which bits of V are known to be either zero or one and return
940/// them in the KnownZero/KnownOne bit sets.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000941///
Chris Lattner965c7692008-06-02 01:18:21 +0000942/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
943/// we cannot optimize based on the assumption that it is zero without changing
944/// it to be an explicit zero. If we don't change it to zero, other code could
945/// optimized based on the contradictory assumption that it is non-zero.
946/// Because instcombine aggressively folds operations with undef args anyway,
947/// this won't lose us code quality.
Chris Lattner4bc28252009-09-08 00:06:16 +0000948///
949/// This function is defined on values with integer type, values with pointer
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000950/// type, and vectors of integers. In the case
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000951/// where V is a vector, known zero, and known one values are the
Chris Lattner4bc28252009-09-08 00:06:16 +0000952/// same width as the vector element, and the bit is set only if it is true
953/// for all of the elements in the vector.
Hal Finkel60db0582014-09-07 18:57:58 +0000954void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000955 const DataLayout &DL, unsigned Depth, const Query &Q) {
Chris Lattner965c7692008-06-02 01:18:21 +0000956 assert(V && "No Value?");
Dan Gohmanbf0002e2009-05-21 02:28:33 +0000957 assert(Depth <= MaxDepth && "Limit Search Depth");
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000958 unsigned BitWidth = KnownZero.getBitWidth();
959
Nadav Rotem3924cb02011-12-05 06:29:09 +0000960 assert((V->getType()->isIntOrIntVectorTy() ||
961 V->getType()->getScalarType()->isPointerTy()) &&
962 "Not integer or pointer type!");
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000963 assert((DL.getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000964 (!V->getType()->isIntOrIntVectorTy() ||
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000965 V->getType()->getScalarSizeInBits() == BitWidth) &&
Nadav Rotem3924cb02011-12-05 06:29:09 +0000966 KnownZero.getBitWidth() == BitWidth &&
Chris Lattner965c7692008-06-02 01:18:21 +0000967 KnownOne.getBitWidth() == BitWidth &&
Jay Foade48d9e82014-05-14 08:00:07 +0000968 "V, KnownOne and KnownZero should have same BitWidth");
Chris Lattner965c7692008-06-02 01:18:21 +0000969
970 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
971 // We know all of the bits for a constant!
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000972 KnownOne = CI->getValue();
973 KnownZero = ~KnownOne;
Chris Lattner965c7692008-06-02 01:18:21 +0000974 return;
975 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000976 // Null and aggregate-zero are all-zeros.
977 if (isa<ConstantPointerNull>(V) ||
978 isa<ConstantAggregateZero>(V)) {
Jay Foad25a5e4c2010-12-01 08:53:58 +0000979 KnownOne.clearAllBits();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000980 KnownZero = APInt::getAllOnesValue(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +0000981 return;
982 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000983 // Handle a constant vector by taking the intersection of the known bits of
Chris Lattner8213c8a2012-02-06 21:56:39 +0000984 // each element. There is no real need to handle ConstantVector here, because
985 // we don't handle undef in any particularly useful way.
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000986 if (ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
987 // We know that CDS must be a vector of integers. Take the intersection of
988 // each element.
989 KnownZero.setAllBits(); KnownOne.setAllBits();
990 APInt Elt(KnownZero.getBitWidth(), 0);
Chris Lattner9be59592012-01-25 01:27:20 +0000991 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000992 Elt = CDS->getElementAsInteger(i);
993 KnownZero &= ~Elt;
Craig Topper1bef2c82012-12-22 19:15:35 +0000994 KnownOne &= Elt;
Chris Lattnerf7eb5432012-01-24 07:54:10 +0000995 }
996 return;
997 }
Craig Topper1bef2c82012-12-22 19:15:35 +0000998
Chris Lattner965c7692008-06-02 01:18:21 +0000999 // The address of an aligned GlobalValue has trailing zeros.
Michael Kupersteinbe8032c2014-12-23 11:33:41 +00001000 if (auto *GO = dyn_cast<GlobalObject>(V)) {
1001 unsigned Align = GO->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001002 if (Align == 0) {
Michael Kupersteinbe8032c2014-12-23 11:33:41 +00001003 if (auto *GVar = dyn_cast<GlobalVariable>(GO)) {
Eli Friedmane7ab1a22011-11-28 22:48:22 +00001004 Type *ObjectType = GVar->getType()->getElementType();
Nick Lewycky1d57ee32012-03-07 02:27:53 +00001005 if (ObjectType->isSized()) {
1006 // If the object is defined in the current Module, we'll be giving
1007 // it the preferred alignment. Otherwise, we have to assume that it
1008 // may only have the minimum ABI alignment.
1009 if (!GVar->isDeclaration() && !GVar->isWeakForLinker())
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001010 Align = DL.getPreferredAlignment(GVar);
Nick Lewycky1d57ee32012-03-07 02:27:53 +00001011 else
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001012 Align = DL.getABITypeAlignment(ObjectType);
Nick Lewycky1d57ee32012-03-07 02:27:53 +00001013 }
Eli Friedmane7ab1a22011-11-28 22:48:22 +00001014 }
Dan Gohmana72f8562009-08-11 15:50:03 +00001015 }
Chris Lattner965c7692008-06-02 01:18:21 +00001016 if (Align > 0)
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001017 KnownZero = APInt::getLowBitsSet(BitWidth,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001018 countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +00001019 else
Jay Foad25a5e4c2010-12-01 08:53:58 +00001020 KnownZero.clearAllBits();
1021 KnownOne.clearAllBits();
Chris Lattner965c7692008-06-02 01:18:21 +00001022 return;
1023 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001024
Chris Lattner83791ce2011-05-23 00:03:39 +00001025 if (Argument *A = dyn_cast<Argument>(V)) {
Hal Finkelccc70902014-07-22 16:58:55 +00001026 unsigned Align = A->getType()->isPointerTy() ? A->getParamAlignment() : 0;
Duncan Sands271ea6c2012-10-04 13:36:31 +00001027
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001028 if (!Align && A->hasStructRetAttr()) {
Duncan Sands271ea6c2012-10-04 13:36:31 +00001029 // An sret parameter has at least the ABI alignment of the return type.
1030 Type *EltTy = cast<PointerType>(A->getType())->getElementType();
1031 if (EltTy->isSized())
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001032 Align = DL.getABITypeAlignment(EltTy);
Duncan Sands271ea6c2012-10-04 13:36:31 +00001033 }
1034
1035 if (Align)
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001036 KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
David Majnemer8df46c92015-01-03 02:33:25 +00001037 else
1038 KnownZero.clearAllBits();
1039 KnownOne.clearAllBits();
Hal Finkel60db0582014-09-07 18:57:58 +00001040
1041 // Don't give up yet... there might be an assumption that provides more
1042 // information...
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001043 computeKnownBitsFromAssume(V, KnownZero, KnownOne, DL, Depth, Q);
Philip Reames1c292272015-03-10 22:43:20 +00001044
1045 // Or a dominating condition for that matter
1046 if (EnableDomConditions && Depth <= DomConditionsMaxDepth)
1047 computeKnownBitsFromDominatingCondition(V, KnownZero, KnownOne, DL,
1048 Depth, Q);
Chris Lattner83791ce2011-05-23 00:03:39 +00001049 return;
1050 }
Chris Lattner965c7692008-06-02 01:18:21 +00001051
Chris Lattner83791ce2011-05-23 00:03:39 +00001052 // Start out not knowing anything.
1053 KnownZero.clearAllBits(); KnownOne.clearAllBits();
Chris Lattner965c7692008-06-02 01:18:21 +00001054
Michael Kupersteinbe8032c2014-12-23 11:33:41 +00001055 // Limit search depth.
1056 // All recursive calls that increase depth must come after this.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001057 if (Depth == MaxDepth)
Michael Kupersteinbe8032c2014-12-23 11:33:41 +00001058 return;
1059
1060 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1061 // the bits of its aliasee.
1062 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1063 if (!GA->mayBeOverridden())
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001064 computeKnownBits(GA->getAliasee(), KnownZero, KnownOne, DL, Depth + 1, Q);
Michael Kupersteinbe8032c2014-12-23 11:33:41 +00001065 return;
1066 }
Chris Lattner965c7692008-06-02 01:18:21 +00001067
Hal Finkel60db0582014-09-07 18:57:58 +00001068 // Check whether a nearby assume intrinsic can determine some known bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001069 computeKnownBitsFromAssume(V, KnownZero, KnownOne, DL, Depth, Q);
Hal Finkel60db0582014-09-07 18:57:58 +00001070
Philip Reames1c292272015-03-10 22:43:20 +00001071 // Check whether there's a dominating condition which implies something about
1072 // this value at the given context.
1073 if (EnableDomConditions && Depth <= DomConditionsMaxDepth)
1074 computeKnownBitsFromDominatingCondition(V, KnownZero, KnownOne, DL, Depth,
1075 Q);
1076
Dan Gohman80ca01c2009-07-17 20:47:02 +00001077 Operator *I = dyn_cast<Operator>(V);
Chris Lattner965c7692008-06-02 01:18:21 +00001078 if (!I) return;
1079
1080 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohman80ca01c2009-07-17 20:47:02 +00001081 switch (I->getOpcode()) {
Chris Lattner965c7692008-06-02 01:18:21 +00001082 default: break;
Rafael Espindola53190532012-03-30 15:52:11 +00001083 case Instruction::Load:
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001084 if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
Jingyue Wu37fcb592014-06-19 16:50:16 +00001085 computeKnownBitsFromRangeMetadata(*MD, KnownZero);
Jay Foad5a29c362014-05-15 12:12:55 +00001086 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001087 case Instruction::And: {
1088 // If either the LHS or the RHS are Zero, the result is zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001089 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
1090 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001091
Chris Lattner965c7692008-06-02 01:18:21 +00001092 // Output known-1 bits are only known if set in both the LHS & RHS.
1093 KnownOne &= KnownOne2;
1094 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1095 KnownZero |= KnownZero2;
Jay Foad5a29c362014-05-15 12:12:55 +00001096 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001097 }
1098 case Instruction::Or: {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001099 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
1100 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001101
Chris Lattner965c7692008-06-02 01:18:21 +00001102 // Output known-0 bits are only known if clear in both the LHS & RHS.
1103 KnownZero &= KnownZero2;
1104 // Output known-1 are known to be set if set in either the LHS | RHS.
1105 KnownOne |= KnownOne2;
Jay Foad5a29c362014-05-15 12:12:55 +00001106 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001107 }
1108 case Instruction::Xor: {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001109 computeKnownBits(I->getOperand(1), KnownZero, KnownOne, DL, Depth + 1, Q);
1110 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001111
Chris Lattner965c7692008-06-02 01:18:21 +00001112 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1113 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1114 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1115 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1116 KnownZero = KnownZeroOut;
Jay Foad5a29c362014-05-15 12:12:55 +00001117 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001118 }
1119 case Instruction::Mul: {
Nick Lewyckyfa306072012-03-18 23:28:48 +00001120 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001121 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, KnownZero,
1122 KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001123 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001124 }
1125 case Instruction::UDiv: {
1126 // For the purposes of computing leading zeros we can conservatively
1127 // treat a udiv as a logical right shift by the power of 2 known to
1128 // be less than the denominator.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001129 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001130 unsigned LeadZ = KnownZero2.countLeadingOnes();
1131
Jay Foad25a5e4c2010-12-01 08:53:58 +00001132 KnownOne2.clearAllBits();
1133 KnownZero2.clearAllBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001134 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001135 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1136 if (RHSUnknownLeadingOnes != BitWidth)
1137 LeadZ = std::min(BitWidth,
1138 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1139
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001140 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
Jay Foad5a29c362014-05-15 12:12:55 +00001141 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001142 }
1143 case Instruction::Select:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001144 computeKnownBits(I->getOperand(2), KnownZero, KnownOne, DL, Depth + 1, Q);
1145 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001146
1147 // Only known if known in both the LHS and RHS.
1148 KnownOne &= KnownOne2;
1149 KnownZero &= KnownZero2;
Jay Foad5a29c362014-05-15 12:12:55 +00001150 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001151 case Instruction::FPTrunc:
1152 case Instruction::FPExt:
1153 case Instruction::FPToUI:
1154 case Instruction::FPToSI:
1155 case Instruction::SIToFP:
1156 case Instruction::UIToFP:
Jay Foad5a29c362014-05-15 12:12:55 +00001157 break; // Can't work with floating point.
Chris Lattner965c7692008-06-02 01:18:21 +00001158 case Instruction::PtrToInt:
1159 case Instruction::IntToPtr:
Matt Arsenaultf1a7e622014-07-15 01:55:03 +00001160 case Instruction::AddrSpaceCast: // Pointers could be different sizes.
Chris Lattner965c7692008-06-02 01:18:21 +00001161 // FALL THROUGH and handle them the same as zext/trunc.
1162 case Instruction::ZExt:
1163 case Instruction::Trunc: {
Chris Lattner229907c2011-07-18 04:54:35 +00001164 Type *SrcTy = I->getOperand(0)->getType();
Nadav Rotem15198e92012-10-26 17:17:05 +00001165
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001166 unsigned SrcBitWidth;
Chris Lattner965c7692008-06-02 01:18:21 +00001167 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1168 // which fall through here.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001169 SrcBitWidth = DL.getTypeSizeInBits(SrcTy->getScalarType());
Nadav Rotem15198e92012-10-26 17:17:05 +00001170
1171 assert(SrcBitWidth && "SrcBitWidth can't be zero");
Jay Foad583abbc2010-12-07 08:25:19 +00001172 KnownZero = KnownZero.zextOrTrunc(SrcBitWidth);
1173 KnownOne = KnownOne.zextOrTrunc(SrcBitWidth);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001174 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
Jay Foad583abbc2010-12-07 08:25:19 +00001175 KnownZero = KnownZero.zextOrTrunc(BitWidth);
1176 KnownOne = KnownOne.zextOrTrunc(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +00001177 // Any top bits are known to be zero.
1178 if (BitWidth > SrcBitWidth)
1179 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001180 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001181 }
1182 case Instruction::BitCast: {
Chris Lattner229907c2011-07-18 04:54:35 +00001183 Type *SrcTy = I->getOperand(0)->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00001184 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattneredb84072009-07-02 16:04:08 +00001185 // TODO: For now, not handling conversions like:
1186 // (bitcast i64 %x to <2 x i32>)
Duncan Sands19d0b472010-02-16 11:11:14 +00001187 !I->getType()->isVectorTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001188 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
Jay Foad5a29c362014-05-15 12:12:55 +00001189 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001190 }
1191 break;
1192 }
1193 case Instruction::SExt: {
1194 // Compute the bits in the result that are not present in the input.
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001195 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Craig Topper1bef2c82012-12-22 19:15:35 +00001196
Jay Foad583abbc2010-12-07 08:25:19 +00001197 KnownZero = KnownZero.trunc(SrcBitWidth);
1198 KnownOne = KnownOne.trunc(SrcBitWidth);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001199 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
Jay Foad583abbc2010-12-07 08:25:19 +00001200 KnownZero = KnownZero.zext(BitWidth);
1201 KnownOne = KnownOne.zext(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +00001202
1203 // If the sign bit of the input is known set or clear, then we know the
1204 // top bits of the result.
1205 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
1206 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1207 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
1208 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001209 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001210 }
1211 case Instruction::Shl:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001212 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Chris Lattner965c7692008-06-02 01:18:21 +00001213 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1214 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001215 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001216 KnownZero <<= ShiftAmt;
1217 KnownOne <<= ShiftAmt;
1218 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Chris Lattner965c7692008-06-02 01:18:21 +00001219 }
1220 break;
1221 case Instruction::LShr:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001222 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Chris Lattner965c7692008-06-02 01:18:21 +00001223 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1224 // Compute the new bits that are at the top now.
1225 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Craig Topper1bef2c82012-12-22 19:15:35 +00001226
Chris Lattner965c7692008-06-02 01:18:21 +00001227 // Unsigned shift right.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001228 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001229 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
1230 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
1231 // high bits known zero.
1232 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Chris Lattner965c7692008-06-02 01:18:21 +00001233 }
1234 break;
1235 case Instruction::AShr:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001236 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Chris Lattner965c7692008-06-02 01:18:21 +00001237 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1238 // Compute the new bits that are at the top now.
Chris Lattnerc86e67e2011-01-04 18:19:15 +00001239 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth-1);
Craig Topper1bef2c82012-12-22 19:15:35 +00001240
Chris Lattner965c7692008-06-02 01:18:21 +00001241 // Signed shift right.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001242 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001243 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
1244 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Craig Topper1bef2c82012-12-22 19:15:35 +00001245
Chris Lattner965c7692008-06-02 01:18:21 +00001246 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1247 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
1248 KnownZero |= HighBits;
1249 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
1250 KnownOne |= HighBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001251 }
1252 break;
1253 case Instruction::Sub: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001254 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001255 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001256 KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
1257 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001258 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001259 }
Chris Lattner965c7692008-06-02 01:18:21 +00001260 case Instruction::Add: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001261 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001262 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001263 KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
1264 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001265 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001266 }
1267 case Instruction::SRem:
1268 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001269 APInt RA = Rem->getValue().abs();
1270 if (RA.isPowerOf2()) {
1271 APInt LowBits = RA - 1;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001272 computeKnownBits(I->getOperand(0), KnownZero2, KnownOne2, DL, Depth + 1,
1273 Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001274
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001275 // The low bits of the first operand are unchanged by the srem.
1276 KnownZero = KnownZero2 & LowBits;
1277 KnownOne = KnownOne2 & LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001278
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001279 // If the first operand is non-negative or has all low bits zero, then
1280 // the upper bits are all zero.
1281 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1282 KnownZero |= ~LowBits;
1283
1284 // If the first operand is negative and not all low bits are zero, then
1285 // the upper bits are all one.
1286 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
1287 KnownOne |= ~LowBits;
1288
Craig Topper1bef2c82012-12-22 19:15:35 +00001289 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001290 }
1291 }
Nick Lewyckye4679792011-03-07 01:50:10 +00001292
1293 // The sign bit is the LHS's sign bit, except when the result of the
1294 // remainder is zero.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001295 if (KnownZero.isNonNegative()) {
Nick Lewyckye4679792011-03-07 01:50:10 +00001296 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001297 computeKnownBits(I->getOperand(0), LHSKnownZero, LHSKnownOne, DL,
1298 Depth + 1, Q);
Nick Lewyckye4679792011-03-07 01:50:10 +00001299 // If it's known zero, our sign bit is also zero.
1300 if (LHSKnownZero.isNegative())
Duncan Sands34c48692012-04-30 11:56:58 +00001301 KnownZero.setBit(BitWidth - 1);
Nick Lewyckye4679792011-03-07 01:50:10 +00001302 }
1303
Chris Lattner965c7692008-06-02 01:18:21 +00001304 break;
1305 case Instruction::URem: {
1306 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1307 APInt RA = Rem->getValue();
1308 if (RA.isPowerOf2()) {
1309 APInt LowBits = (RA - 1);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001310 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1,
1311 Q);
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001312 KnownZero |= ~LowBits;
1313 KnownOne &= LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001314 break;
1315 }
1316 }
1317
1318 // Since the result is less than or equal to either operand, any leading
1319 // zero bits in either operand must also exist in the result.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001320 computeKnownBits(I->getOperand(0), KnownZero, KnownOne, DL, Depth + 1, Q);
1321 computeKnownBits(I->getOperand(1), KnownZero2, KnownOne2, DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001322
Chris Lattner4612ae12009-01-20 18:22:57 +00001323 unsigned Leaders = std::max(KnownZero.countLeadingOnes(),
Chris Lattner965c7692008-06-02 01:18:21 +00001324 KnownZero2.countLeadingOnes());
Jay Foad25a5e4c2010-12-01 08:53:58 +00001325 KnownOne.clearAllBits();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001326 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
Chris Lattner965c7692008-06-02 01:18:21 +00001327 break;
1328 }
1329
Victor Hernandeza3aaf852009-10-17 01:18:07 +00001330 case Instruction::Alloca: {
Victor Hernandez8acf2952009-10-23 21:09:37 +00001331 AllocaInst *AI = cast<AllocaInst>(V);
Chris Lattner965c7692008-06-02 01:18:21 +00001332 unsigned Align = AI->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001333 if (Align == 0)
1334 Align = DL.getABITypeAlignment(AI->getType()->getElementType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001335
Chris Lattner965c7692008-06-02 01:18:21 +00001336 if (Align > 0)
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001337 KnownZero = APInt::getLowBitsSet(BitWidth, countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +00001338 break;
1339 }
1340 case Instruction::GetElementPtr: {
1341 // Analyze all of the subscripts of this getelementptr instruction
1342 // to determine if we can prove known low zero bits.
Chris Lattner965c7692008-06-02 01:18:21 +00001343 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001344 computeKnownBits(I->getOperand(0), LocalKnownZero, LocalKnownOne, DL,
1345 Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001346 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1347
1348 gep_type_iterator GTI = gep_type_begin(I);
1349 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1350 Value *Index = I->getOperand(i);
Chris Lattner229907c2011-07-18 04:54:35 +00001351 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001352 // Handle struct member offset arithmetic.
Matt Arsenault74742a12013-08-19 21:43:16 +00001353
1354 // Handle case when index is vector zeroinitializer
1355 Constant *CIndex = cast<Constant>(Index);
1356 if (CIndex->isZeroValue())
1357 continue;
1358
1359 if (CIndex->getType()->isVectorTy())
1360 Index = CIndex->getSplatValue();
1361
Chris Lattner965c7692008-06-02 01:18:21 +00001362 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001363 const StructLayout *SL = DL.getStructLayout(STy);
Chris Lattner965c7692008-06-02 01:18:21 +00001364 uint64_t Offset = SL->getElementOffset(Idx);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001365 TrailZ = std::min<unsigned>(TrailZ,
1366 countTrailingZeros(Offset));
Chris Lattner965c7692008-06-02 01:18:21 +00001367 } else {
1368 // Handle array index arithmetic.
Chris Lattner229907c2011-07-18 04:54:35 +00001369 Type *IndexedTy = GTI.getIndexedType();
Jay Foad5a29c362014-05-15 12:12:55 +00001370 if (!IndexedTy->isSized()) {
1371 TrailZ = 0;
1372 break;
1373 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001374 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001375 uint64_t TypeSize = DL.getTypeAllocSize(IndexedTy);
Chris Lattner965c7692008-06-02 01:18:21 +00001376 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001377 computeKnownBits(Index, LocalKnownZero, LocalKnownOne, DL, Depth + 1,
1378 Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001379 TrailZ = std::min(TrailZ,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001380 unsigned(countTrailingZeros(TypeSize) +
Chris Lattner4612ae12009-01-20 18:22:57 +00001381 LocalKnownZero.countTrailingOnes()));
Chris Lattner965c7692008-06-02 01:18:21 +00001382 }
1383 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001384
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001385 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ);
Chris Lattner965c7692008-06-02 01:18:21 +00001386 break;
1387 }
1388 case Instruction::PHI: {
1389 PHINode *P = cast<PHINode>(I);
1390 // Handle the case of a simple two-predecessor recurrence PHI.
1391 // There's a lot more that could theoretically be done here, but
1392 // this is sufficient to catch some interesting cases.
1393 if (P->getNumIncomingValues() == 2) {
1394 for (unsigned i = 0; i != 2; ++i) {
1395 Value *L = P->getIncomingValue(i);
1396 Value *R = P->getIncomingValue(!i);
Dan Gohman80ca01c2009-07-17 20:47:02 +00001397 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner965c7692008-06-02 01:18:21 +00001398 if (!LU)
1399 continue;
Dan Gohman80ca01c2009-07-17 20:47:02 +00001400 unsigned Opcode = LU->getOpcode();
Chris Lattner965c7692008-06-02 01:18:21 +00001401 // Check for operations that have the property that if
1402 // both their operands have low zero bits, the result
1403 // will have low zero bits.
1404 if (Opcode == Instruction::Add ||
1405 Opcode == Instruction::Sub ||
1406 Opcode == Instruction::And ||
1407 Opcode == Instruction::Or ||
1408 Opcode == Instruction::Mul) {
1409 Value *LL = LU->getOperand(0);
1410 Value *LR = LU->getOperand(1);
1411 // Find a recurrence.
1412 if (LL == I)
1413 L = LR;
1414 else if (LR == I)
1415 L = LL;
1416 else
1417 break;
1418 // Ok, we have a PHI of the form L op= R. Check for low
1419 // zero bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001420 computeKnownBits(R, KnownZero2, KnownOne2, DL, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001421
1422 // We need to take the minimum number of known bits
1423 APInt KnownZero3(KnownZero), KnownOne3(KnownOne);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001424 computeKnownBits(L, KnownZero3, KnownOne3, DL, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001425
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001426 KnownZero = APInt::getLowBitsSet(BitWidth,
David Greeneaebd9e02008-10-27 23:24:03 +00001427 std::min(KnownZero2.countTrailingOnes(),
1428 KnownZero3.countTrailingOnes()));
Chris Lattner965c7692008-06-02 01:18:21 +00001429 break;
1430 }
1431 }
1432 }
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001433
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001434 // Unreachable blocks may have zero-operand PHI nodes.
1435 if (P->getNumIncomingValues() == 0)
Jay Foad5a29c362014-05-15 12:12:55 +00001436 break;
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001437
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001438 // Otherwise take the unions of the known bit sets of the operands,
1439 // taking conservative care to avoid excessive recursion.
1440 if (Depth < MaxDepth - 1 && !KnownZero && !KnownOne) {
Duncan Sands7dc3d472011-03-08 12:39:03 +00001441 // Skip if every incoming value references to ourself.
Nuno Lopes0d44a502012-07-03 21:15:40 +00001442 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
Duncan Sands7dc3d472011-03-08 12:39:03 +00001443 break;
1444
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001445 KnownZero = APInt::getAllOnesValue(BitWidth);
1446 KnownOne = APInt::getAllOnesValue(BitWidth);
Pete Cooper833f34d2015-05-12 20:05:31 +00001447 for (Value *IncValue : P->incoming_values()) {
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001448 // Skip direct self references.
Pete Cooper833f34d2015-05-12 20:05:31 +00001449 if (IncValue == P) continue;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001450
1451 KnownZero2 = APInt(BitWidth, 0);
1452 KnownOne2 = APInt(BitWidth, 0);
1453 // Recurse, but cap the recursion to one level, because we don't
1454 // want to waste time spinning around in loops.
Pete Cooper833f34d2015-05-12 20:05:31 +00001455 computeKnownBits(IncValue, KnownZero2, KnownOne2, DL,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001456 MaxDepth - 1, Q);
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001457 KnownZero &= KnownZero2;
1458 KnownOne &= KnownOne2;
1459 // If all bits have been ruled out, there's no need to check
1460 // more operands.
1461 if (!KnownZero && !KnownOne)
1462 break;
1463 }
1464 }
Chris Lattner965c7692008-06-02 01:18:21 +00001465 break;
1466 }
1467 case Instruction::Call:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001468 case Instruction::Invoke:
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001469 if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
Jingyue Wu37fcb592014-06-19 16:50:16 +00001470 computeKnownBitsFromRangeMetadata(*MD, KnownZero);
1471 // If a range metadata is attached to this IntrinsicInst, intersect the
1472 // explicit range specified by the metadata and the implicit range of
1473 // the intrinsic.
Chris Lattner965c7692008-06-02 01:18:21 +00001474 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1475 switch (II->getIntrinsicID()) {
1476 default: break;
Chris Lattner965c7692008-06-02 01:18:21 +00001477 case Intrinsic::ctlz:
1478 case Intrinsic::cttz: {
1479 unsigned LowBits = Log2_32(BitWidth)+1;
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001480 // If this call is undefined for 0, the result will be less than 2^n.
1481 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1482 LowBits -= 1;
Jingyue Wu37fcb592014-06-19 16:50:16 +00001483 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001484 break;
1485 }
1486 case Intrinsic::ctpop: {
1487 unsigned LowBits = Log2_32(BitWidth)+1;
Jingyue Wu37fcb592014-06-19 16:50:16 +00001488 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
Chris Lattner965c7692008-06-02 01:18:21 +00001489 break;
1490 }
Chad Rosierb3628842011-05-26 23:13:19 +00001491 case Intrinsic::x86_sse42_crc32_64_64:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001492 KnownZero |= APInt::getHighBitsSet(64, 32);
Evan Cheng2a746bf2011-05-22 18:25:30 +00001493 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001494 }
1495 }
1496 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001497 case Instruction::ExtractValue:
1498 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
1499 ExtractValueInst *EVI = cast<ExtractValueInst>(I);
1500 if (EVI->getNumIndices() != 1) break;
1501 if (EVI->getIndices()[0] == 0) {
1502 switch (II->getIntrinsicID()) {
1503 default: break;
1504 case Intrinsic::uadd_with_overflow:
1505 case Intrinsic::sadd_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001506 computeKnownBitsAddSub(true, II->getArgOperand(0),
1507 II->getArgOperand(1), false, KnownZero,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001508 KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001509 break;
1510 case Intrinsic::usub_with_overflow:
1511 case Intrinsic::ssub_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001512 computeKnownBitsAddSub(false, II->getArgOperand(0),
1513 II->getArgOperand(1), false, KnownZero,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001514 KnownOne, KnownZero2, KnownOne2, DL, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001515 break;
Nick Lewyckyfa306072012-03-18 23:28:48 +00001516 case Intrinsic::umul_with_overflow:
1517 case Intrinsic::smul_with_overflow:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001518 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
1519 KnownZero, KnownOne, KnownZero2, KnownOne2, DL,
1520 Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001521 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001522 }
1523 }
1524 }
Chris Lattner965c7692008-06-02 01:18:21 +00001525 }
Jay Foad5a29c362014-05-15 12:12:55 +00001526
1527 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001528}
1529
Sanjay Patelaee84212014-11-04 16:27:42 +00001530/// Determine whether the sign bit is known to be zero or one.
1531/// Convenience wrapper around computeKnownBits.
Hal Finkel60db0582014-09-07 18:57:58 +00001532void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001533 const DataLayout &DL, unsigned Depth, const Query &Q) {
1534 unsigned BitWidth = getBitWidth(V->getType(), DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001535 if (!BitWidth) {
1536 KnownZero = false;
1537 KnownOne = false;
1538 return;
1539 }
1540 APInt ZeroBits(BitWidth, 0);
1541 APInt OneBits(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001542 computeKnownBits(V, ZeroBits, OneBits, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001543 KnownOne = OneBits[BitWidth - 1];
1544 KnownZero = ZeroBits[BitWidth - 1];
1545}
1546
Sanjay Patelaee84212014-11-04 16:27:42 +00001547/// Return true if the given value is known to have exactly one
Duncan Sandsd3951082011-01-25 09:38:29 +00001548/// bit set when defined. For vectors return true if every element is known to
Sanjay Patelaee84212014-11-04 16:27:42 +00001549/// be a power of two when defined. Supports values with integer or pointer
Duncan Sandsd3951082011-01-25 09:38:29 +00001550/// types and vectors of integers.
Hal Finkel60db0582014-09-07 18:57:58 +00001551bool isKnownToBeAPowerOfTwo(Value *V, bool OrZero, unsigned Depth,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001552 const Query &Q, const DataLayout &DL) {
Duncan Sandsba286d72011-10-26 20:55:21 +00001553 if (Constant *C = dyn_cast<Constant>(V)) {
1554 if (C->isNullValue())
1555 return OrZero;
1556 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1557 return CI->getValue().isPowerOf2();
1558 // TODO: Handle vector constants.
1559 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001560
1561 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1562 // it is shifted off the end then the result is undefined.
1563 if (match(V, m_Shl(m_One(), m_Value())))
1564 return true;
1565
1566 // (signbit) >>l X is clearly a power of two if the one is not shifted off the
1567 // bottom. If it is shifted off the bottom then the result is undefined.
Duncan Sands4b397fc2011-02-01 08:50:33 +00001568 if (match(V, m_LShr(m_SignBit(), m_Value())))
Duncan Sandsd3951082011-01-25 09:38:29 +00001569 return true;
1570
1571 // The remaining tests are all recursive, so bail out if we hit the limit.
1572 if (Depth++ == MaxDepth)
1573 return false;
1574
Craig Topper9f008862014-04-15 04:59:12 +00001575 Value *X = nullptr, *Y = nullptr;
Duncan Sands985ba632011-10-28 18:30:05 +00001576 // A shift of a power of two is a power of two or zero.
1577 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
1578 match(V, m_Shr(m_Value(X), m_Value()))))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001579 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q, DL);
Duncan Sands985ba632011-10-28 18:30:05 +00001580
Duncan Sandsd3951082011-01-25 09:38:29 +00001581 if (ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001582 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q, DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001583
1584 if (SelectInst *SI = dyn_cast<SelectInst>(V))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001585 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q, DL) &&
1586 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q, DL);
Duncan Sandsba286d72011-10-26 20:55:21 +00001587
Duncan Sandsba286d72011-10-26 20:55:21 +00001588 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1589 // A power of two and'd with anything is a power of two or zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001590 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q, DL) ||
1591 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q, DL))
Duncan Sandsba286d72011-10-26 20:55:21 +00001592 return true;
1593 // X & (-X) is always a power of two or zero.
1594 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1595 return true;
1596 return false;
1597 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001598
David Majnemerb7d54092013-07-30 21:01:36 +00001599 // Adding a power-of-two or zero to the same power-of-two or zero yields
1600 // either the original power-of-two, a larger power-of-two or zero.
1601 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1602 OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
1603 if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1604 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1605 match(X, m_And(m_Value(), m_Specific(Y))))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001606 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q, DL))
David Majnemerb7d54092013-07-30 21:01:36 +00001607 return true;
1608 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1609 match(Y, m_And(m_Value(), m_Specific(X))))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001610 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q, DL))
David Majnemerb7d54092013-07-30 21:01:36 +00001611 return true;
1612
1613 unsigned BitWidth = V->getType()->getScalarSizeInBits();
1614 APInt LHSZeroBits(BitWidth, 0), LHSOneBits(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001615 computeKnownBits(X, LHSZeroBits, LHSOneBits, DL, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001616
1617 APInt RHSZeroBits(BitWidth, 0), RHSOneBits(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001618 computeKnownBits(Y, RHSZeroBits, RHSOneBits, DL, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001619 // If i8 V is a power of two or zero:
1620 // ZeroBits: 1 1 1 0 1 1 1 1
1621 // ~ZeroBits: 0 0 0 1 0 0 0 0
1622 if ((~(LHSZeroBits & RHSZeroBits)).isPowerOf2())
1623 // If OrZero isn't set, we cannot give back a zero result.
1624 // Make sure either the LHS or RHS has a bit set.
1625 if (OrZero || RHSOneBits.getBoolValue() || LHSOneBits.getBoolValue())
1626 return true;
1627 }
1628 }
David Majnemerbeab5672013-05-18 19:30:37 +00001629
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001630 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewyckyf0469af2011-03-21 21:40:32 +00001631 // is a power of two only if the first operand is a power of two and not
1632 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001633 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1634 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
Hal Finkel60db0582014-09-07 18:57:58 +00001635 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001636 Depth, Q, DL);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001637 }
1638
Duncan Sandsd3951082011-01-25 09:38:29 +00001639 return false;
1640}
1641
Chandler Carruth80d3e562012-12-07 02:08:58 +00001642/// \brief Test whether a GEP's result is known to be non-null.
1643///
1644/// Uses properties inherent in a GEP to try to determine whether it is known
1645/// to be non-null.
1646///
1647/// Currently this routine does not support vector GEPs.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001648static bool isGEPKnownNonNull(GEPOperator *GEP, const DataLayout &DL,
Hal Finkel60db0582014-09-07 18:57:58 +00001649 unsigned Depth, const Query &Q) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001650 if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1651 return false;
1652
1653 // FIXME: Support vector-GEPs.
1654 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1655
1656 // If the base pointer is non-null, we cannot walk to a null address with an
1657 // inbounds GEP in address space zero.
Hal Finkel60db0582014-09-07 18:57:58 +00001658 if (isKnownNonZero(GEP->getPointerOperand(), DL, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001659 return true;
1660
Chandler Carruth80d3e562012-12-07 02:08:58 +00001661 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1662 // If so, then the GEP cannot produce a null pointer, as doing so would
1663 // inherently violate the inbounds contract within address space zero.
1664 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1665 GTI != GTE; ++GTI) {
1666 // Struct types are easy -- they must always be indexed by a constant.
1667 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1668 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1669 unsigned ElementIdx = OpC->getZExtValue();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001670 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruth80d3e562012-12-07 02:08:58 +00001671 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1672 if (ElementOffset > 0)
1673 return true;
1674 continue;
1675 }
1676
1677 // If we have a zero-sized type, the index doesn't matter. Keep looping.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001678 if (DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
Chandler Carruth80d3e562012-12-07 02:08:58 +00001679 continue;
1680
1681 // Fast path the constant operand case both for efficiency and so we don't
1682 // increment Depth when just zipping down an all-constant GEP.
1683 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1684 if (!OpC->isZero())
1685 return true;
1686 continue;
1687 }
1688
1689 // We post-increment Depth here because while isKnownNonZero increments it
1690 // as well, when we pop back up that increment won't persist. We don't want
1691 // to recurse 10k times just because we have 10k GEP operands. We don't
1692 // bail completely out because we want to handle constant GEPs regardless
1693 // of depth.
1694 if (Depth++ >= MaxDepth)
1695 continue;
1696
Hal Finkel60db0582014-09-07 18:57:58 +00001697 if (isKnownNonZero(GTI.getOperand(), DL, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001698 return true;
1699 }
1700
1701 return false;
1702}
1703
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001704/// Does the 'Range' metadata (which must be a valid MD_range operand list)
1705/// ensure that the value it's attached to is never Value? 'RangeType' is
1706/// is the type of the value described by the range.
1707static bool rangeMetadataExcludesValue(MDNode* Ranges,
1708 const APInt& Value) {
1709 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1710 assert(NumRanges >= 1);
1711 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001712 ConstantInt *Lower =
1713 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1714 ConstantInt *Upper =
1715 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001716 ConstantRange Range(Lower->getValue(), Upper->getValue());
1717 if (Range.contains(Value))
1718 return false;
1719 }
1720 return true;
1721}
1722
Sanjay Patelaee84212014-11-04 16:27:42 +00001723/// Return true if the given value is known to be non-zero when defined.
1724/// For vectors return true if every element is known to be non-zero when
1725/// defined. Supports values with integer or pointer type and vectors of
1726/// integers.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001727bool isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth,
Hal Finkel60db0582014-09-07 18:57:58 +00001728 const Query &Q) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001729 if (Constant *C = dyn_cast<Constant>(V)) {
1730 if (C->isNullValue())
1731 return false;
1732 if (isa<ConstantInt>(C))
1733 // Must be non-zero due to null test above.
1734 return true;
1735 // TODO: Handle vectors
1736 return false;
1737 }
1738
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001739 if (Instruction* I = dyn_cast<Instruction>(V)) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001740 if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001741 // If the possible ranges don't contain zero, then the value is
1742 // definitely non-zero.
1743 if (IntegerType* Ty = dyn_cast<IntegerType>(V->getType())) {
1744 const APInt ZeroValue(Ty->getBitWidth(), 0);
1745 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
1746 return true;
1747 }
1748 }
1749 }
1750
Duncan Sandsd3951082011-01-25 09:38:29 +00001751 // The remaining tests are all recursive, so bail out if we hit the limit.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001752 if (Depth++ >= MaxDepth)
Duncan Sandsd3951082011-01-25 09:38:29 +00001753 return false;
1754
Chandler Carruth80d3e562012-12-07 02:08:58 +00001755 // Check for pointer simplifications.
1756 if (V->getType()->isPointerTy()) {
Manman Ren12171122013-03-18 21:23:25 +00001757 if (isKnownNonNull(V))
1758 return true;
Chandler Carruth80d3e562012-12-07 02:08:58 +00001759 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001760 if (isGEPKnownNonNull(GEP, DL, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001761 return true;
1762 }
1763
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001764 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001765
1766 // X | Y != 0 if X != 0 or Y != 0.
Craig Topper9f008862014-04-15 04:59:12 +00001767 Value *X = nullptr, *Y = nullptr;
Duncan Sandsd3951082011-01-25 09:38:29 +00001768 if (match(V, m_Or(m_Value(X), m_Value(Y))))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001769 return isKnownNonZero(X, DL, Depth, Q) || isKnownNonZero(Y, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001770
1771 // ext X != 0 if X != 0.
1772 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001773 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001774
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001775 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd3951082011-01-25 09:38:29 +00001776 // if the lowest bit is shifted off the end.
1777 if (BitWidth && match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001778 // shl nuw can't remove any non-zero bits.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001779 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001780 if (BO->hasNoUnsignedWrap())
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001781 return isKnownNonZero(X, DL, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001782
Duncan Sandsd3951082011-01-25 09:38:29 +00001783 APInt KnownZero(BitWidth, 0);
1784 APInt KnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001785 computeKnownBits(X, KnownZero, KnownOne, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001786 if (KnownOne[0])
1787 return true;
1788 }
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001789 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd3951082011-01-25 09:38:29 +00001790 // defined if the sign bit is shifted off the end.
1791 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001792 // shr exact can only shift out zero bits.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001793 PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001794 if (BO->isExact())
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001795 return isKnownNonZero(X, DL, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001796
Duncan Sandsd3951082011-01-25 09:38:29 +00001797 bool XKnownNonNegative, XKnownNegative;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001798 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001799 if (XKnownNegative)
1800 return true;
1801 }
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001802 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001803 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001804 return isKnownNonZero(X, DL, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001805 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001806 // X + Y.
1807 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
1808 bool XKnownNonNegative, XKnownNegative;
1809 bool YKnownNonNegative, YKnownNegative;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001810 ComputeSignBit(X, XKnownNonNegative, XKnownNegative, DL, Depth, Q);
1811 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001812
1813 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001814 // zero unless both X and Y are zero.
Duncan Sandsd3951082011-01-25 09:38:29 +00001815 if (XKnownNonNegative && YKnownNonNegative)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001816 if (isKnownNonZero(X, DL, Depth, Q) || isKnownNonZero(Y, DL, Depth, Q))
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001817 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00001818
1819 // If X and Y are both negative (as signed values) then their sum is not
1820 // zero unless both X and Y equal INT_MIN.
1821 if (BitWidth && XKnownNegative && YKnownNegative) {
1822 APInt KnownZero(BitWidth, 0);
1823 APInt KnownOne(BitWidth, 0);
1824 APInt Mask = APInt::getSignedMaxValue(BitWidth);
1825 // The sign bit of X is set. If some other bit is set then X is not equal
1826 // to INT_MIN.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001827 computeKnownBits(X, KnownZero, KnownOne, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001828 if ((KnownOne & Mask) != 0)
1829 return true;
1830 // The sign bit of Y is set. If some other bit is set then Y is not equal
1831 // to INT_MIN.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001832 computeKnownBits(Y, KnownZero, KnownOne, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001833 if ((KnownOne & Mask) != 0)
1834 return true;
1835 }
1836
1837 // The sum of a non-negative number and a power of two is not zero.
Hal Finkel60db0582014-09-07 18:57:58 +00001838 if (XKnownNonNegative &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001839 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q, DL))
Duncan Sandsd3951082011-01-25 09:38:29 +00001840 return true;
Hal Finkel60db0582014-09-07 18:57:58 +00001841 if (YKnownNonNegative &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001842 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q, DL))
Duncan Sandsd3951082011-01-25 09:38:29 +00001843 return true;
1844 }
Duncan Sands7cb61e52011-10-27 19:16:21 +00001845 // X * Y.
1846 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
1847 OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
1848 // If X and Y are non-zero then so is X * Y as long as the multiplication
1849 // does not overflow.
1850 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001851 isKnownNonZero(X, DL, Depth, Q) && isKnownNonZero(Y, DL, Depth, Q))
Duncan Sands7cb61e52011-10-27 19:16:21 +00001852 return true;
1853 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001854 // (C ? X : Y) != 0 if X != 0 and Y != 0.
1855 else if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001856 if (isKnownNonZero(SI->getTrueValue(), DL, Depth, Q) &&
1857 isKnownNonZero(SI->getFalseValue(), DL, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001858 return true;
1859 }
1860
1861 if (!BitWidth) return false;
1862 APInt KnownZero(BitWidth, 0);
1863 APInt KnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001864 computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001865 return KnownOne != 0;
1866}
1867
Sanjay Patelaee84212014-11-04 16:27:42 +00001868/// Return true if 'V & Mask' is known to be zero. We use this predicate to
1869/// simplify operations downstream. Mask is known to be zero for bits that V
1870/// cannot have.
Chris Lattner4bc28252009-09-08 00:06:16 +00001871///
1872/// This function is defined on values with integer type, values with pointer
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001873/// type, and vectors of integers. In the case
Chris Lattner4bc28252009-09-08 00:06:16 +00001874/// where V is a vector, the mask, known zero, and known one values are the
1875/// same width as the vector element, and the bit is set only if it is true
1876/// for all of the elements in the vector.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001877bool MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
1878 unsigned Depth, const Query &Q) {
Chris Lattner965c7692008-06-02 01:18:21 +00001879 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001880 computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001881 return (KnownZero & Mask) == Mask;
1882}
1883
1884
1885
Sanjay Patelaee84212014-11-04 16:27:42 +00001886/// Return the number of times the sign bit of the register is replicated into
1887/// the other bits. We know that at least 1 bit is always equal to the sign bit
1888/// (itself), but other cases can give us information. For example, immediately
1889/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
1890/// other, so we return 3.
Chris Lattner965c7692008-06-02 01:18:21 +00001891///
1892/// 'Op' must have a scalar integer type.
1893///
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001894unsigned ComputeNumSignBits(Value *V, const DataLayout &DL, unsigned Depth,
1895 const Query &Q) {
1896 unsigned TyBits = DL.getTypeSizeInBits(V->getType()->getScalarType());
Chris Lattner965c7692008-06-02 01:18:21 +00001897 unsigned Tmp, Tmp2;
1898 unsigned FirstAnswer = 1;
1899
Jay Foada0653a32014-05-14 21:14:37 +00001900 // Note that ConstantInt is handled by the general computeKnownBits case
Chris Lattner2e01a692008-06-02 18:39:07 +00001901 // below.
1902
Chris Lattner965c7692008-06-02 01:18:21 +00001903 if (Depth == 6)
1904 return 1; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00001905
Dan Gohman80ca01c2009-07-17 20:47:02 +00001906 Operator *U = dyn_cast<Operator>(V);
1907 switch (Operator::getOpcode(V)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001908 default: break;
1909 case Instruction::SExt:
Mon P Wangbb3eac92009-12-02 04:59:58 +00001910 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001911 return ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q) + Tmp;
Craig Topper1bef2c82012-12-22 19:15:35 +00001912
Nadav Rotemc99a3872015-03-06 00:23:58 +00001913 case Instruction::SDiv: {
Nadav Rotem029c5c72015-03-03 21:39:02 +00001914 const APInt *Denominator;
1915 // sdiv X, C -> adds log(C) sign bits.
1916 if (match(U->getOperand(1), m_APInt(Denominator))) {
1917
1918 // Ignore non-positive denominator.
1919 if (!Denominator->isStrictlyPositive())
1920 break;
1921
1922 // Calculate the incoming numerator bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001923 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
Nadav Rotem029c5c72015-03-03 21:39:02 +00001924
1925 // Add floor(log(C)) bits to the numerator bits.
1926 return std::min(TyBits, NumBits + Denominator->logBase2());
1927 }
1928 break;
Nadav Rotemc99a3872015-03-06 00:23:58 +00001929 }
1930
1931 case Instruction::SRem: {
1932 const APInt *Denominator;
Sanjoy Dase561fee2015-03-25 22:33:53 +00001933 // srem X, C -> we know that the result is within [-C+1,C) when C is a
1934 // positive constant. This let us put a lower bound on the number of sign
1935 // bits.
Nadav Rotemc99a3872015-03-06 00:23:58 +00001936 if (match(U->getOperand(1), m_APInt(Denominator))) {
1937
1938 // Ignore non-positive denominator.
1939 if (!Denominator->isStrictlyPositive())
1940 break;
1941
1942 // Calculate the incoming numerator bits. SRem by a positive constant
1943 // can't lower the number of sign bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001944 unsigned NumrBits =
1945 ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
Nadav Rotemc99a3872015-03-06 00:23:58 +00001946
1947 // Calculate the leading sign bit constraints by examining the
Sanjoy Dase561fee2015-03-25 22:33:53 +00001948 // denominator. Given that the denominator is positive, there are two
1949 // cases:
1950 //
1951 // 1. the numerator is positive. The result range is [0,C) and [0,C) u<
1952 // (1 << ceilLogBase2(C)).
1953 //
1954 // 2. the numerator is negative. Then the result range is (-C,0] and
1955 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
1956 //
1957 // Thus a lower bound on the number of sign bits is `TyBits -
1958 // ceilLogBase2(C)`.
Nadav Rotemc99a3872015-03-06 00:23:58 +00001959
Sanjoy Dase561fee2015-03-25 22:33:53 +00001960 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
Nadav Rotemc99a3872015-03-06 00:23:58 +00001961 return std::max(NumrBits, ResBits);
1962 }
1963 break;
1964 }
Nadav Rotem029c5c72015-03-03 21:39:02 +00001965
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001966 case Instruction::AShr: {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001967 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001968 // ashr X, C -> adds C sign bits. Vectors too.
1969 const APInt *ShAmt;
1970 if (match(U->getOperand(1), m_APInt(ShAmt))) {
1971 Tmp += ShAmt->getZExtValue();
Chris Lattner965c7692008-06-02 01:18:21 +00001972 if (Tmp > TyBits) Tmp = TyBits;
1973 }
1974 return Tmp;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001975 }
1976 case Instruction::Shl: {
1977 const APInt *ShAmt;
1978 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner965c7692008-06-02 01:18:21 +00001979 // shl destroys sign bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001980 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001981 Tmp2 = ShAmt->getZExtValue();
1982 if (Tmp2 >= TyBits || // Bad shift.
1983 Tmp2 >= Tmp) break; // Shifted all sign bits out.
1984 return Tmp - Tmp2;
Chris Lattner965c7692008-06-02 01:18:21 +00001985 }
1986 break;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001987 }
Chris Lattner965c7692008-06-02 01:18:21 +00001988 case Instruction::And:
1989 case Instruction::Or:
1990 case Instruction::Xor: // NOT is handled here.
1991 // Logical binary ops preserve the number of sign bits at the worst.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001992 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001993 if (Tmp != 1) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001994 Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001995 FirstAnswer = std::min(Tmp, Tmp2);
1996 // We computed what we know about the sign bits as our first
1997 // answer. Now proceed to the generic code that uses
Jay Foada0653a32014-05-14 21:14:37 +00001998 // computeKnownBits, and pick whichever answer is better.
Chris Lattner965c7692008-06-02 01:18:21 +00001999 }
2000 break;
2001
2002 case Instruction::Select:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002003 Tmp = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002004 if (Tmp == 1) return 1; // Early out.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002005 Tmp2 = ComputeNumSignBits(U->getOperand(2), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002006 return std::min(Tmp, Tmp2);
Craig Topper1bef2c82012-12-22 19:15:35 +00002007
Chris Lattner965c7692008-06-02 01:18:21 +00002008 case Instruction::Add:
2009 // Add can have at most one carry bit. Thus we know that the output
2010 // is, at worst, one more bit than the inputs.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002011 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002012 if (Tmp == 1) return 1; // Early out.
Craig Topper1bef2c82012-12-22 19:15:35 +00002013
Chris Lattner965c7692008-06-02 01:18:21 +00002014 // Special case decrementing a value (ADD X, -1):
David Majnemera55027f2014-12-26 09:20:17 +00002015 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
Chris Lattner965c7692008-06-02 01:18:21 +00002016 if (CRHS->isAllOnesValue()) {
2017 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002018 computeKnownBits(U->getOperand(0), KnownZero, KnownOne, DL, Depth + 1,
2019 Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002020
Chris Lattner965c7692008-06-02 01:18:21 +00002021 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2022 // sign bits set.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00002023 if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002024 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002025
Chris Lattner965c7692008-06-02 01:18:21 +00002026 // If we are subtracting one from a positive number, there is no carry
2027 // out of the result.
2028 if (KnownZero.isNegative())
2029 return Tmp;
2030 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002031
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002032 Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002033 if (Tmp2 == 1) return 1;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002034 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002035
Chris Lattner965c7692008-06-02 01:18:21 +00002036 case Instruction::Sub:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002037 Tmp2 = ComputeNumSignBits(U->getOperand(1), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002038 if (Tmp2 == 1) return 1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002039
Chris Lattner965c7692008-06-02 01:18:21 +00002040 // Handle NEG.
David Majnemera55027f2014-12-26 09:20:17 +00002041 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
Chris Lattner965c7692008-06-02 01:18:21 +00002042 if (CLHS->isNullValue()) {
2043 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002044 computeKnownBits(U->getOperand(1), KnownZero, KnownOne, DL, Depth + 1,
2045 Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002046 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2047 // sign bits set.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00002048 if ((KnownZero | APInt(TyBits, 1)).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002049 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002050
Chris Lattner965c7692008-06-02 01:18:21 +00002051 // If the input is known to be positive (the sign bit is known clear),
2052 // the output of the NEG has the same number of sign bits as the input.
2053 if (KnownZero.isNegative())
2054 return Tmp2;
Craig Topper1bef2c82012-12-22 19:15:35 +00002055
Chris Lattner965c7692008-06-02 01:18:21 +00002056 // Otherwise, we treat this like a SUB.
2057 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002058
Chris Lattner965c7692008-06-02 01:18:21 +00002059 // Sub can have at most one carry bit. Thus we know that the output
2060 // is, at worst, one more bit than the inputs.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002061 Tmp = ComputeNumSignBits(U->getOperand(0), DL, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002062 if (Tmp == 1) return 1; // Early out.
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002063 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002064
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002065 case Instruction::PHI: {
2066 PHINode *PN = cast<PHINode>(U);
David Majnemer6ee8d172015-01-04 07:06:53 +00002067 unsigned NumIncomingValues = PN->getNumIncomingValues();
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002068 // Don't analyze large in-degree PHIs.
David Majnemer6ee8d172015-01-04 07:06:53 +00002069 if (NumIncomingValues > 4) break;
2070 // Unreachable blocks may have zero-operand PHI nodes.
2071 if (NumIncomingValues == 0) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002072
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002073 // Take the minimum of all incoming values. This can't infinitely loop
2074 // because of our depth threshold.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002075 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), DL, Depth + 1, Q);
David Majnemer6ee8d172015-01-04 07:06:53 +00002076 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002077 if (Tmp == 1) return Tmp;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002078 Tmp = std::min(
2079 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), DL, Depth + 1, Q));
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002080 }
2081 return Tmp;
2082 }
2083
Chris Lattner965c7692008-06-02 01:18:21 +00002084 case Instruction::Trunc:
2085 // FIXME: it's tricky to do anything useful for this, but it is an important
2086 // case for targets like X86.
2087 break;
2088 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002089
Chris Lattner965c7692008-06-02 01:18:21 +00002090 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2091 // use this information.
2092 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00002093 APInt Mask;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002094 computeKnownBits(V, KnownZero, KnownOne, DL, Depth, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002095
Chris Lattner965c7692008-06-02 01:18:21 +00002096 if (KnownZero.isNegative()) { // sign bit is 0
2097 Mask = KnownZero;
2098 } else if (KnownOne.isNegative()) { // sign bit is 1;
2099 Mask = KnownOne;
2100 } else {
2101 // Nothing known.
2102 return FirstAnswer;
2103 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002104
Chris Lattner965c7692008-06-02 01:18:21 +00002105 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2106 // the number of identical bits in the top of the input value.
2107 Mask = ~Mask;
2108 Mask <<= Mask.getBitWidth()-TyBits;
2109 // Return # leading zeros. We use 'min' here in case Val was zero before
2110 // shifting. We don't want to return '64' as for an i32 "0".
2111 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
2112}
Chris Lattnera12a6de2008-06-02 01:29:46 +00002113
Sanjay Patelaee84212014-11-04 16:27:42 +00002114/// This function computes the integer multiple of Base that equals V.
2115/// If successful, it returns true and returns the multiple in
2116/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez47444882009-11-10 08:28:35 +00002117/// through SExt instructions only if LookThroughSExt is true.
2118bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman6a976bb2009-11-18 00:58:27 +00002119 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez47444882009-11-10 08:28:35 +00002120 const unsigned MaxDepth = 6;
2121
Dan Gohman6a976bb2009-11-18 00:58:27 +00002122 assert(V && "No Value?");
Victor Hernandez47444882009-11-10 08:28:35 +00002123 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002124 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez47444882009-11-10 08:28:35 +00002125
Chris Lattner229907c2011-07-18 04:54:35 +00002126 Type *T = V->getType();
Victor Hernandez47444882009-11-10 08:28:35 +00002127
Dan Gohman6a976bb2009-11-18 00:58:27 +00002128 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez47444882009-11-10 08:28:35 +00002129
2130 if (Base == 0)
2131 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002132
Victor Hernandez47444882009-11-10 08:28:35 +00002133 if (Base == 1) {
2134 Multiple = V;
2135 return true;
2136 }
2137
2138 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2139 Constant *BaseVal = ConstantInt::get(T, Base);
2140 if (CO && CO == BaseVal) {
2141 // Multiple is 1.
2142 Multiple = ConstantInt::get(T, 1);
2143 return true;
2144 }
2145
2146 if (CI && CI->getZExtValue() % Base == 0) {
2147 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
Craig Topper1bef2c82012-12-22 19:15:35 +00002148 return true;
Victor Hernandez47444882009-11-10 08:28:35 +00002149 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002150
Victor Hernandez47444882009-11-10 08:28:35 +00002151 if (Depth == MaxDepth) return false; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002152
Victor Hernandez47444882009-11-10 08:28:35 +00002153 Operator *I = dyn_cast<Operator>(V);
2154 if (!I) return false;
2155
2156 switch (I->getOpcode()) {
2157 default: break;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002158 case Instruction::SExt:
Victor Hernandez47444882009-11-10 08:28:35 +00002159 if (!LookThroughSExt) return false;
2160 // otherwise fall through to ZExt
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002161 case Instruction::ZExt:
Dan Gohman6a976bb2009-11-18 00:58:27 +00002162 return ComputeMultiple(I->getOperand(0), Base, Multiple,
2163 LookThroughSExt, Depth+1);
Victor Hernandez47444882009-11-10 08:28:35 +00002164 case Instruction::Shl:
2165 case Instruction::Mul: {
2166 Value *Op0 = I->getOperand(0);
2167 Value *Op1 = I->getOperand(1);
2168
2169 if (I->getOpcode() == Instruction::Shl) {
2170 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2171 if (!Op1CI) return false;
2172 // Turn Op0 << Op1 into Op0 * 2^Op1
2173 APInt Op1Int = Op1CI->getValue();
2174 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foad15084f02010-11-30 09:02:01 +00002175 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002176 API.setBit(BitToSet);
Jay Foad15084f02010-11-30 09:02:01 +00002177 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez47444882009-11-10 08:28:35 +00002178 }
2179
Craig Topper9f008862014-04-15 04:59:12 +00002180 Value *Mul0 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002181 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2182 if (Constant *Op1C = dyn_cast<Constant>(Op1))
2183 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002184 if (Op1C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002185 MulC->getType()->getPrimitiveSizeInBits())
2186 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002187 if (Op1C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002188 MulC->getType()->getPrimitiveSizeInBits())
2189 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002190
Chris Lattner72d283c2010-09-05 17:20:46 +00002191 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2192 Multiple = ConstantExpr::getMul(MulC, Op1C);
2193 return true;
2194 }
Victor Hernandez47444882009-11-10 08:28:35 +00002195
2196 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2197 if (Mul0CI->getValue() == 1) {
2198 // V == Base * Op1, so return Op1
2199 Multiple = Op1;
2200 return true;
2201 }
2202 }
2203
Craig Topper9f008862014-04-15 04:59:12 +00002204 Value *Mul1 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002205 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2206 if (Constant *Op0C = dyn_cast<Constant>(Op0))
2207 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002208 if (Op0C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002209 MulC->getType()->getPrimitiveSizeInBits())
2210 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002211 if (Op0C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002212 MulC->getType()->getPrimitiveSizeInBits())
2213 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002214
Chris Lattner72d283c2010-09-05 17:20:46 +00002215 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2216 Multiple = ConstantExpr::getMul(MulC, Op0C);
2217 return true;
2218 }
Victor Hernandez47444882009-11-10 08:28:35 +00002219
2220 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2221 if (Mul1CI->getValue() == 1) {
2222 // V == Base * Op0, so return Op0
2223 Multiple = Op0;
2224 return true;
2225 }
2226 }
Victor Hernandez47444882009-11-10 08:28:35 +00002227 }
2228 }
2229
2230 // We could not determine if V is a multiple of Base.
2231 return false;
2232}
2233
Sanjay Patelaee84212014-11-04 16:27:42 +00002234/// Return true if we can prove that the specified FP value is never equal to
2235/// -0.0.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002236///
2237/// NOTE: this function will need to be revisited when we support non-default
2238/// rounding modes!
2239///
2240bool llvm::CannotBeNegativeZero(const Value *V, unsigned Depth) {
2241 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2242 return !CFP->getValueAPF().isNegZero();
Craig Topper1bef2c82012-12-22 19:15:35 +00002243
Sanjay Patel40eaa8d2015-02-25 18:00:15 +00002244 // FIXME: Magic number! At the least, this should be given a name because it's
2245 // used similarly in CannotBeOrderedLessThanZero(). A better fix may be to
2246 // expose it as a parameter, so it can be used for testing / experimenting.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002247 if (Depth == 6)
Sanjay Patel40eaa8d2015-02-25 18:00:15 +00002248 return false; // Limit search depth.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002249
Dan Gohman80ca01c2009-07-17 20:47:02 +00002250 const Operator *I = dyn_cast<Operator>(V);
Craig Topper9f008862014-04-15 04:59:12 +00002251 if (!I) return false;
Michael Ilseman0f128372012-12-06 00:07:09 +00002252
2253 // Check if the nsz fast-math flag is set
2254 if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
2255 if (FPO->hasNoSignedZeros())
2256 return true;
2257
Chris Lattnera12a6de2008-06-02 01:29:46 +00002258 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Jakub Staszakb7129f22013-03-06 00:16:16 +00002259 if (I->getOpcode() == Instruction::FAdd)
2260 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
2261 if (CFP->isNullValue())
2262 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002263
Chris Lattnera12a6de2008-06-02 01:29:46 +00002264 // sitofp and uitofp turn into +0.0 for zero.
2265 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2266 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002267
Chris Lattnera12a6de2008-06-02 01:29:46 +00002268 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2269 // sqrt(-0.0) = -0.0, no other negative results are possible.
2270 if (II->getIntrinsicID() == Intrinsic::sqrt)
Gabor Greif1abbde32010-06-23 23:38:07 +00002271 return CannotBeNegativeZero(II->getArgOperand(0), Depth+1);
Craig Topper1bef2c82012-12-22 19:15:35 +00002272
Chris Lattnera12a6de2008-06-02 01:29:46 +00002273 if (const CallInst *CI = dyn_cast<CallInst>(I))
2274 if (const Function *F = CI->getCalledFunction()) {
2275 if (F->isDeclaration()) {
Daniel Dunbarca414c72009-07-26 08:34:35 +00002276 // abs(x) != -0.0
2277 if (F->getName() == "abs") return true;
Dale Johannesenf6a987b2009-09-25 20:54:50 +00002278 // fabs[lf](x) != -0.0
2279 if (F->getName() == "fabs") return true;
2280 if (F->getName() == "fabsf") return true;
2281 if (F->getName() == "fabsl") return true;
2282 if (F->getName() == "sqrt" || F->getName() == "sqrtf" ||
2283 F->getName() == "sqrtl")
Gabor Greif1abbde32010-06-23 23:38:07 +00002284 return CannotBeNegativeZero(CI->getArgOperand(0), Depth+1);
Chris Lattnera12a6de2008-06-02 01:29:46 +00002285 }
2286 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002287
Chris Lattnera12a6de2008-06-02 01:29:46 +00002288 return false;
2289}
2290
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002291bool llvm::CannotBeOrderedLessThanZero(const Value *V, unsigned Depth) {
2292 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2293 return !CFP->getValueAPF().isNegative() || CFP->getValueAPF().isZero();
2294
Sanjay Patel40eaa8d2015-02-25 18:00:15 +00002295 // FIXME: Magic number! At the least, this should be given a name because it's
2296 // used similarly in CannotBeNegativeZero(). A better fix may be to
2297 // expose it as a parameter, so it can be used for testing / experimenting.
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002298 if (Depth == 6)
2299 return false; // Limit search depth.
2300
2301 const Operator *I = dyn_cast<Operator>(V);
2302 if (!I) return false;
2303
2304 switch (I->getOpcode()) {
2305 default: break;
2306 case Instruction::FMul:
2307 // x*x is always non-negative or a NaN.
2308 if (I->getOperand(0) == I->getOperand(1))
2309 return true;
2310 // Fall through
2311 case Instruction::FAdd:
2312 case Instruction::FDiv:
2313 case Instruction::FRem:
2314 return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1) &&
2315 CannotBeOrderedLessThanZero(I->getOperand(1), Depth+1);
2316 case Instruction::FPExt:
2317 case Instruction::FPTrunc:
2318 // Widening/narrowing never change sign.
2319 return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
2320 case Instruction::Call:
2321 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2322 switch (II->getIntrinsicID()) {
2323 default: break;
2324 case Intrinsic::exp:
2325 case Intrinsic::exp2:
2326 case Intrinsic::fabs:
2327 case Intrinsic::sqrt:
2328 return true;
2329 case Intrinsic::powi:
2330 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
2331 // powi(x,n) is non-negative if n is even.
2332 if (CI->getBitWidth() <= 64 && CI->getSExtValue() % 2u == 0)
2333 return true;
2334 }
2335 return CannotBeOrderedLessThanZero(I->getOperand(0), Depth+1);
2336 case Intrinsic::fma:
2337 case Intrinsic::fmuladd:
2338 // x*x+y is non-negative if y is non-negative.
2339 return I->getOperand(0) == I->getOperand(1) &&
2340 CannotBeOrderedLessThanZero(I->getOperand(2), Depth+1);
2341 }
2342 break;
2343 }
2344 return false;
2345}
2346
Sanjay Patelaee84212014-11-04 16:27:42 +00002347/// If the specified value can be set by repeating the same byte in memory,
2348/// return the i8 value that it is represented with. This is
Chris Lattner9cb10352010-12-26 20:15:01 +00002349/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2350/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
2351/// byte store (e.g. i16 0x1234), return null.
2352Value *llvm::isBytewiseValue(Value *V) {
2353 // All byte-wide stores are splatable, even of arbitrary variables.
2354 if (V->getType()->isIntegerTy(8)) return V;
Chris Lattneracf6b072011-02-19 19:35:49 +00002355
2356 // Handle 'null' ConstantArrayZero etc.
2357 if (Constant *C = dyn_cast<Constant>(V))
2358 if (C->isNullValue())
2359 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
Craig Topper1bef2c82012-12-22 19:15:35 +00002360
Chris Lattner9cb10352010-12-26 20:15:01 +00002361 // Constant float and double values can be handled as integer values if the
Craig Topper1bef2c82012-12-22 19:15:35 +00002362 // corresponding integer value is "byteable". An important case is 0.0.
Chris Lattner9cb10352010-12-26 20:15:01 +00002363 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2364 if (CFP->getType()->isFloatTy())
2365 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2366 if (CFP->getType()->isDoubleTy())
2367 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2368 // Don't handle long double formats, which have strange constraints.
2369 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002370
Benjamin Kramer17d90152015-02-07 19:29:02 +00002371 // We can handle constant integers that are multiple of 8 bits.
Chris Lattner9cb10352010-12-26 20:15:01 +00002372 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Benjamin Kramer17d90152015-02-07 19:29:02 +00002373 if (CI->getBitWidth() % 8 == 0) {
2374 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
Craig Topper1bef2c82012-12-22 19:15:35 +00002375
Benjamin Kramerb4b51502015-03-25 16:49:59 +00002376 if (!CI->getValue().isSplat(8))
Benjamin Kramer17d90152015-02-07 19:29:02 +00002377 return nullptr;
2378 return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
Chris Lattner9cb10352010-12-26 20:15:01 +00002379 }
2380 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002381
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002382 // A ConstantDataArray/Vector is splatable if all its members are equal and
2383 // also splatable.
2384 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2385 Value *Elt = CA->getElementAsConstant(0);
2386 Value *Val = isBytewiseValue(Elt);
Chris Lattner9cb10352010-12-26 20:15:01 +00002387 if (!Val)
Craig Topper9f008862014-04-15 04:59:12 +00002388 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002389
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002390 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2391 if (CA->getElementAsConstant(I) != Elt)
Craig Topper9f008862014-04-15 04:59:12 +00002392 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002393
Chris Lattner9cb10352010-12-26 20:15:01 +00002394 return Val;
2395 }
Chad Rosier8abf65a2011-12-06 00:19:08 +00002396
Chris Lattner9cb10352010-12-26 20:15:01 +00002397 // Conceptually, we could handle things like:
2398 // %a = zext i8 %X to i16
2399 // %b = shl i16 %a, 8
2400 // %c = or i16 %a, %b
2401 // but until there is an example that actually needs this, it doesn't seem
2402 // worth worrying about.
Craig Topper9f008862014-04-15 04:59:12 +00002403 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00002404}
2405
2406
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002407// This is the recursive version of BuildSubAggregate. It takes a few different
2408// arguments. Idxs is the index within the nested struct From that we are
2409// looking at now (which is of type IndexedType). IdxSkip is the number of
2410// indices from Idxs that should be left out when inserting into the resulting
2411// struct. To is the result struct built so far, new insertvalue instructions
2412// build on that.
Chris Lattner229907c2011-07-18 04:54:35 +00002413static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Craig Topper2cd5ff82013-07-11 16:22:38 +00002414 SmallVectorImpl<unsigned> &Idxs,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002415 unsigned IdxSkip,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002416 Instruction *InsertBefore) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +00002417 llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002418 if (STy) {
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002419 // Save the original To argument so we can modify it
2420 Value *OrigTo = To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002421 // General case, the type indexed by Idxs is a struct
2422 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2423 // Process each struct element recursively
2424 Idxs.push_back(i);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002425 Value *PrevTo = To;
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002426 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002427 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002428 Idxs.pop_back();
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002429 if (!To) {
2430 // Couldn't find any inserted value for this index? Cleanup
2431 while (PrevTo != OrigTo) {
2432 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
2433 PrevTo = Del->getAggregateOperand();
2434 Del->eraseFromParent();
2435 }
2436 // Stop processing elements
2437 break;
2438 }
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002439 }
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002440 // If we successfully found a value for each of our subaggregates
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002441 if (To)
2442 return To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002443 }
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002444 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
2445 // the struct's elements had a value that was inserted directly. In the latter
2446 // case, perhaps we can't determine each of the subelements individually, but
2447 // we might be able to find the complete struct somewhere.
Craig Topper1bef2c82012-12-22 19:15:35 +00002448
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002449 // Find the value that is at that particular spot
Jay Foad57aa6362011-07-13 10:26:04 +00002450 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002451
2452 if (!V)
Craig Topper9f008862014-04-15 04:59:12 +00002453 return nullptr;
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002454
2455 // Insert the value in the new (sub) aggregrate
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002456 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
Jay Foad57aa6362011-07-13 10:26:04 +00002457 "tmp", InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002458}
2459
2460// This helper takes a nested struct and extracts a part of it (which is again a
2461// struct) into a new value. For example, given the struct:
2462// { a, { b, { c, d }, e } }
2463// and the indices "1, 1" this returns
2464// { c, d }.
2465//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002466// It does this by inserting an insertvalue for each element in the resulting
2467// struct, as opposed to just inserting a single struct. This will only work if
2468// each of the elements of the substruct are known (ie, inserted into From by an
2469// insertvalue instruction somewhere).
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002470//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002471// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foad57aa6362011-07-13 10:26:04 +00002472static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002473 Instruction *InsertBefore) {
Matthijs Kooijman69801d42008-06-16 13:28:31 +00002474 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattner229907c2011-07-18 04:54:35 +00002475 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foad57aa6362011-07-13 10:26:04 +00002476 idx_range);
Owen Andersonb292b8c2009-07-30 23:03:37 +00002477 Value *To = UndefValue::get(IndexedType);
Jay Foad57aa6362011-07-13 10:26:04 +00002478 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002479 unsigned IdxSkip = Idxs.size();
2480
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002481 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002482}
2483
Sanjay Patelaee84212014-11-04 16:27:42 +00002484/// Given an aggregrate and an sequence of indices, see if
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002485/// the scalar value indexed is already around as a register, for example if it
2486/// were inserted directly into the aggregrate.
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002487///
2488/// If InsertBefore is not null, this function will duplicate (modified)
2489/// insertvalues when a part of a nested struct is extracted.
Jay Foad57aa6362011-07-13 10:26:04 +00002490Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
2491 Instruction *InsertBefore) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002492 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002493 // recursion).
Jay Foad57aa6362011-07-13 10:26:04 +00002494 if (idx_range.empty())
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002495 return V;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002496 // We have indices, so V should have an indexable type.
2497 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
2498 "Not looking at a struct or array?");
2499 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
2500 "Invalid indices for type?");
Owen Andersonf1f17432009-07-06 22:37:39 +00002501
Chris Lattner67058832012-01-25 06:48:06 +00002502 if (Constant *C = dyn_cast<Constant>(V)) {
2503 C = C->getAggregateElement(idx_range[0]);
Craig Topper9f008862014-04-15 04:59:12 +00002504 if (!C) return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00002505 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
2506 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002507
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002508 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002509 // Loop the indices for the insertvalue instruction in parallel with the
2510 // requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00002511 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002512 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
2513 i != e; ++i, ++req_idx) {
Jay Foad57aa6362011-07-13 10:26:04 +00002514 if (req_idx == idx_range.end()) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002515 // We can't handle this without inserting insertvalues
2516 if (!InsertBefore)
Craig Topper9f008862014-04-15 04:59:12 +00002517 return nullptr;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002518
2519 // The requested index identifies a part of a nested aggregate. Handle
2520 // this specially. For example,
2521 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
2522 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
2523 // %C = extractvalue {i32, { i32, i32 } } %B, 1
2524 // This can be changed into
2525 // %A = insertvalue {i32, i32 } undef, i32 10, 0
2526 // %C = insertvalue {i32, i32 } %A, i32 11, 1
2527 // which allows the unused 0,0 element from the nested struct to be
2528 // removed.
2529 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
2530 InsertBefore);
Duncan Sandsdb356ee2008-06-19 08:47:31 +00002531 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002532
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002533 // This insert value inserts something else than what we are looking for.
2534 // See if the (aggregrate) value inserted into has the value we are
2535 // looking for, then.
2536 if (*req_idx != *i)
Jay Foad57aa6362011-07-13 10:26:04 +00002537 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002538 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002539 }
2540 // If we end up here, the indices of the insertvalue match with those
2541 // requested (though possibly only partially). Now we recursively look at
2542 // the inserted value, passing any remaining indices.
Jay Foad57aa6362011-07-13 10:26:04 +00002543 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002544 makeArrayRef(req_idx, idx_range.end()),
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002545 InsertBefore);
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002546 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002547
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002548 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002549 // If we're extracting a value from an aggregrate that was extracted from
2550 // something else, we can extract from that something else directly instead.
2551 // However, we will need to chain I's indices with the requested indices.
Craig Topper1bef2c82012-12-22 19:15:35 +00002552
2553 // Calculate the number of indices required
Jay Foad57aa6362011-07-13 10:26:04 +00002554 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002555 // Allocate some space to put the new indices in
Matthijs Kooijman8369c672008-06-17 08:24:37 +00002556 SmallVector<unsigned, 5> Idxs;
2557 Idxs.reserve(size);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002558 // Add indices from the extract value instruction
Jay Foad57aa6362011-07-13 10:26:04 +00002559 Idxs.append(I->idx_begin(), I->idx_end());
Craig Topper1bef2c82012-12-22 19:15:35 +00002560
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002561 // Add requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00002562 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002563
Craig Topper1bef2c82012-12-22 19:15:35 +00002564 assert(Idxs.size() == size
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002565 && "Number of indices added not correct?");
Craig Topper1bef2c82012-12-22 19:15:35 +00002566
Jay Foad57aa6362011-07-13 10:26:04 +00002567 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002568 }
2569 // Otherwise, we don't know (such as, extracting from a function return value
2570 // or load instruction)
Craig Topper9f008862014-04-15 04:59:12 +00002571 return nullptr;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002572}
Evan Chengda3db112008-06-30 07:31:25 +00002573
Sanjay Patelaee84212014-11-04 16:27:42 +00002574/// Analyze the specified pointer to see if it can be expressed as a base
2575/// pointer plus a constant offset. Return the base and offset to the caller.
Chris Lattnere28618d2010-11-30 22:25:26 +00002576Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002577 const DataLayout &DL) {
2578 unsigned BitWidth = DL.getPointerTypeSizeInBits(Ptr->getType());
Nuno Lopes368c4d02012-12-31 20:48:35 +00002579 APInt ByteOffset(BitWidth, 0);
2580 while (1) {
2581 if (Ptr->getType()->isVectorTy())
2582 break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002583
Nuno Lopes368c4d02012-12-31 20:48:35 +00002584 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002585 APInt GEPOffset(BitWidth, 0);
2586 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
2587 break;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00002588
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002589 ByteOffset += GEPOffset;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00002590
Nuno Lopes368c4d02012-12-31 20:48:35 +00002591 Ptr = GEP->getPointerOperand();
Matt Arsenaultfd78d0c2014-07-14 22:39:22 +00002592 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
2593 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002594 Ptr = cast<Operator>(Ptr)->getOperand(0);
2595 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
2596 if (GA->mayBeOverridden())
2597 break;
2598 Ptr = GA->getAliasee();
Chris Lattnere28618d2010-11-30 22:25:26 +00002599 } else {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002600 break;
Chris Lattnere28618d2010-11-30 22:25:26 +00002601 }
2602 }
Nuno Lopes368c4d02012-12-31 20:48:35 +00002603 Offset = ByteOffset.getSExtValue();
2604 return Ptr;
Chris Lattnere28618d2010-11-30 22:25:26 +00002605}
2606
2607
Sanjay Patelaee84212014-11-04 16:27:42 +00002608/// This function computes the length of a null-terminated C string pointed to
2609/// by V. If successful, it returns true and returns the string in Str.
2610/// If unsuccessful, it returns false.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002611bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
2612 uint64_t Offset, bool TrimAtNul) {
2613 assert(V);
Evan Chengda3db112008-06-30 07:31:25 +00002614
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002615 // Look through bitcast instructions and geps.
2616 V = V->stripPointerCasts();
Craig Topper1bef2c82012-12-22 19:15:35 +00002617
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00002618 // If the value is a GEP instruction or constant expression, treat it as an
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002619 // offset.
2620 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Evan Chengda3db112008-06-30 07:31:25 +00002621 // Make sure the GEP has exactly three arguments.
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002622 if (GEP->getNumOperands() != 3)
2623 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002624
Evan Chengda3db112008-06-30 07:31:25 +00002625 // Make sure the index-ee is a pointer to array of i8.
Chris Lattner229907c2011-07-18 04:54:35 +00002626 PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
2627 ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
Craig Topper9f008862014-04-15 04:59:12 +00002628 if (!AT || !AT->getElementType()->isIntegerTy(8))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002629 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002630
Evan Chengda3db112008-06-30 07:31:25 +00002631 // Check to make sure that the first operand of the GEP is an integer and
2632 // has value 0 so that we are sure we're indexing into the initializer.
Dan Gohman0b4df042010-04-14 22:20:45 +00002633 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
Craig Topper9f008862014-04-15 04:59:12 +00002634 if (!FirstIdx || !FirstIdx->isZero())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002635 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002636
Evan Chengda3db112008-06-30 07:31:25 +00002637 // If the second index isn't a ConstantInt, then this is a variable index
2638 // into the array. If this occurs, we can't say anything meaningful about
2639 // the string.
2640 uint64_t StartIdx = 0;
Dan Gohman0b4df042010-04-14 22:20:45 +00002641 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Chengda3db112008-06-30 07:31:25 +00002642 StartIdx = CI->getZExtValue();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002643 else
2644 return false;
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00002645 return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx + Offset,
2646 TrimAtNul);
Evan Chengda3db112008-06-30 07:31:25 +00002647 }
Nick Lewycky46209882011-10-20 00:34:35 +00002648
Evan Chengda3db112008-06-30 07:31:25 +00002649 // The GEP instruction, constant or instruction, must reference a global
2650 // variable that is a constant and is initialized. The referenced constant
2651 // initializer is the array that we'll use for optimization.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002652 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00002653 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002654 return false;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002655
Nick Lewycky46209882011-10-20 00:34:35 +00002656 // Handle the all-zeros case
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002657 if (GV->getInitializer()->isNullValue()) {
Evan Chengda3db112008-06-30 07:31:25 +00002658 // This is a degenerate case. The initializer is constant zero so the
2659 // length of the string must be zero.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002660 Str = "";
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002661 return true;
2662 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002663
Evan Chengda3db112008-06-30 07:31:25 +00002664 // Must be a Constant Array
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002665 const ConstantDataArray *Array =
2666 dyn_cast<ConstantDataArray>(GV->getInitializer());
Craig Topper9f008862014-04-15 04:59:12 +00002667 if (!Array || !Array->isString())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002668 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002669
Evan Chengda3db112008-06-30 07:31:25 +00002670 // Get the number of elements in the array
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002671 uint64_t NumElts = Array->getType()->getArrayNumElements();
2672
2673 // Start out with the entire array in the StringRef.
2674 Str = Array->getAsString();
2675
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002676 if (Offset > NumElts)
2677 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002678
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002679 // Skip over 'offset' bytes.
2680 Str = Str.substr(Offset);
Craig Topper1bef2c82012-12-22 19:15:35 +00002681
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002682 if (TrimAtNul) {
2683 // Trim off the \0 and anything after it. If the array is not nul
2684 // terminated, we just return the whole end of string. The client may know
2685 // some other way that the string is length-bound.
2686 Str = Str.substr(0, Str.find('\0'));
2687 }
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002688 return true;
Evan Chengda3db112008-06-30 07:31:25 +00002689}
Eric Christopher4899cbc2010-03-05 06:58:57 +00002690
2691// These next two are very similar to the above, but also look through PHI
2692// nodes.
2693// TODO: See if we can integrate these two together.
2694
Sanjay Patelaee84212014-11-04 16:27:42 +00002695/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00002696/// the specified pointer, return 'len+1'. If we can't, return 0.
Craig Topper71b7b682014-08-21 05:55:13 +00002697static uint64_t GetStringLengthH(Value *V, SmallPtrSetImpl<PHINode*> &PHIs) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00002698 // Look through noop bitcast instructions.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002699 V = V->stripPointerCasts();
Eric Christopher4899cbc2010-03-05 06:58:57 +00002700
2701 // If this is a PHI node, there are two cases: either we have already seen it
2702 // or we haven't.
2703 if (PHINode *PN = dyn_cast<PHINode>(V)) {
David Blaikie70573dc2014-11-19 07:49:26 +00002704 if (!PHIs.insert(PN).second)
Eric Christopher4899cbc2010-03-05 06:58:57 +00002705 return ~0ULL; // already in the set.
2706
2707 // If it was new, see if all the input strings are the same length.
2708 uint64_t LenSoFar = ~0ULL;
Pete Cooper833f34d2015-05-12 20:05:31 +00002709 for (Value *IncValue : PN->incoming_values()) {
2710 uint64_t Len = GetStringLengthH(IncValue, PHIs);
Eric Christopher4899cbc2010-03-05 06:58:57 +00002711 if (Len == 0) return 0; // Unknown length -> unknown.
2712
2713 if (Len == ~0ULL) continue;
2714
2715 if (Len != LenSoFar && LenSoFar != ~0ULL)
2716 return 0; // Disagree -> unknown.
2717 LenSoFar = Len;
2718 }
2719
2720 // Success, all agree.
2721 return LenSoFar;
2722 }
2723
2724 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
2725 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
2726 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
2727 if (Len1 == 0) return 0;
2728 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
2729 if (Len2 == 0) return 0;
2730 if (Len1 == ~0ULL) return Len2;
2731 if (Len2 == ~0ULL) return Len1;
2732 if (Len1 != Len2) return 0;
2733 return Len1;
2734 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002735
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002736 // Otherwise, see if we can read the string.
2737 StringRef StrData;
2738 if (!getConstantStringInfo(V, StrData))
Eric Christopher4899cbc2010-03-05 06:58:57 +00002739 return 0;
2740
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002741 return StrData.size()+1;
Eric Christopher4899cbc2010-03-05 06:58:57 +00002742}
2743
Sanjay Patelaee84212014-11-04 16:27:42 +00002744/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00002745/// the specified pointer, return 'len+1'. If we can't, return 0.
2746uint64_t llvm::GetStringLength(Value *V) {
2747 if (!V->getType()->isPointerTy()) return 0;
2748
2749 SmallPtrSet<PHINode*, 32> PHIs;
2750 uint64_t Len = GetStringLengthH(V, PHIs);
2751 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
2752 // an empty string as a length.
2753 return Len == ~0ULL ? 1 : Len;
2754}
Dan Gohmana4fcd242010-12-15 20:02:24 +00002755
Adam Nemete2b885c2015-04-23 20:09:20 +00002756/// \brief \p PN defines a loop-variant pointer to an object. Check if the
2757/// previous iteration of the loop was referring to the same object as \p PN.
2758static bool isSameUnderlyingObjectInLoop(PHINode *PN, LoopInfo *LI) {
2759 // Find the loop-defined value.
2760 Loop *L = LI->getLoopFor(PN->getParent());
2761 if (PN->getNumIncomingValues() != 2)
2762 return true;
2763
2764 // Find the value from previous iteration.
2765 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
2766 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
2767 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
2768 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
2769 return true;
2770
2771 // If a new pointer is loaded in the loop, the pointer references a different
2772 // object in every iteration. E.g.:
2773 // for (i)
2774 // int *p = a[i];
2775 // ...
2776 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
2777 if (!L->isLoopInvariant(Load->getPointerOperand()))
2778 return false;
2779 return true;
2780}
2781
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002782Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
2783 unsigned MaxLookup) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00002784 if (!V->getType()->isPointerTy())
2785 return V;
2786 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
2787 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2788 V = GEP->getPointerOperand();
Matt Arsenault70f4db882014-07-15 00:56:40 +00002789 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
2790 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00002791 V = cast<Operator>(V)->getOperand(0);
2792 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2793 if (GA->mayBeOverridden())
2794 return V;
2795 V = GA->getAliasee();
2796 } else {
Dan Gohman05b18f12010-12-15 20:49:55 +00002797 // See if InstructionSimplify knows any relevant tricks.
2798 if (Instruction *I = dyn_cast<Instruction>(V))
Chandler Carruth66b31302015-01-04 12:03:27 +00002799 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002800 if (Value *Simplified = SimplifyInstruction(I, DL, nullptr)) {
Dan Gohman05b18f12010-12-15 20:49:55 +00002801 V = Simplified;
2802 continue;
2803 }
2804
Dan Gohmana4fcd242010-12-15 20:02:24 +00002805 return V;
2806 }
2807 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
2808 }
2809 return V;
2810}
Nick Lewycky3e334a42011-06-27 04:20:45 +00002811
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002812void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
Adam Nemete2b885c2015-04-23 20:09:20 +00002813 const DataLayout &DL, LoopInfo *LI,
2814 unsigned MaxLookup) {
Dan Gohmaned7c24e22012-05-10 18:57:38 +00002815 SmallPtrSet<Value *, 4> Visited;
2816 SmallVector<Value *, 4> Worklist;
2817 Worklist.push_back(V);
2818 do {
2819 Value *P = Worklist.pop_back_val();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002820 P = GetUnderlyingObject(P, DL, MaxLookup);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00002821
David Blaikie70573dc2014-11-19 07:49:26 +00002822 if (!Visited.insert(P).second)
Dan Gohmaned7c24e22012-05-10 18:57:38 +00002823 continue;
2824
2825 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
2826 Worklist.push_back(SI->getTrueValue());
2827 Worklist.push_back(SI->getFalseValue());
2828 continue;
2829 }
2830
2831 if (PHINode *PN = dyn_cast<PHINode>(P)) {
Adam Nemete2b885c2015-04-23 20:09:20 +00002832 // If this PHI changes the underlying object in every iteration of the
2833 // loop, don't look through it. Consider:
2834 // int **A;
2835 // for (i) {
2836 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
2837 // Curr = A[i];
2838 // *Prev, *Curr;
2839 //
2840 // Prev is tracking Curr one iteration behind so they refer to different
2841 // underlying objects.
2842 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
2843 isSameUnderlyingObjectInLoop(PN, LI))
Pete Cooper833f34d2015-05-12 20:05:31 +00002844 for (Value *IncValue : PN->incoming_values())
2845 Worklist.push_back(IncValue);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00002846 continue;
2847 }
2848
2849 Objects.push_back(P);
2850 } while (!Worklist.empty());
2851}
2852
Sanjay Patelaee84212014-11-04 16:27:42 +00002853/// Return true if the only users of this pointer are lifetime markers.
Nick Lewycky3e334a42011-06-27 04:20:45 +00002854bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00002855 for (const User *U : V->users()) {
2856 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Nick Lewycky3e334a42011-06-27 04:20:45 +00002857 if (!II) return false;
2858
2859 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
2860 II->getIntrinsicID() != Intrinsic::lifetime_end)
2861 return false;
2862 }
2863 return true;
2864}
Dan Gohman75d7d5e2011-12-14 23:49:11 +00002865
Philip Reames5461d452015-04-23 17:36:48 +00002866static bool isDereferenceableFromAttribute(const Value *BV, APInt Offset,
2867 Type *Ty, const DataLayout &DL) {
2868 assert(Offset.isNonNegative() && "offset can't be negative");
2869 assert(Ty->isSized() && "must be sized");
2870
2871 APInt DerefBytes(Offset.getBitWidth(), 0);
2872 if (const Argument *A = dyn_cast<Argument>(BV)) {
2873 DerefBytes = A->getDereferenceableBytes();
2874 } else if (auto CS = ImmutableCallSite(BV)) {
2875 DerefBytes = CS.getDereferenceableBytes(0);
2876 }
2877
2878 if (DerefBytes.getBoolValue())
2879 if (DerefBytes.uge(Offset + DL.getTypeStoreSize(Ty)))
2880 return true;
2881
2882 return false;
2883}
2884
2885static bool isDereferenceableFromAttribute(const Value *V,
2886 const DataLayout &DL) {
2887 Type *VTy = V->getType();
2888 Type *Ty = VTy->getPointerElementType();
2889 if (!Ty->isSized())
2890 return false;
2891
2892 APInt Offset(DL.getTypeStoreSizeInBits(VTy), 0);
2893 return isDereferenceableFromAttribute(V, Offset, Ty, DL);
2894}
2895
2896/// Return true if Value is always a dereferenceable pointer.
2897///
2898/// Test if V is always a pointer to allocated and suitably aligned memory for
2899/// a simple load or store.
2900static bool isDereferenceablePointer(const Value *V, const DataLayout &DL,
2901 SmallPtrSetImpl<const Value *> &Visited) {
2902 // Note that it is not safe to speculate into a malloc'd region because
2903 // malloc may return null.
2904
2905 // These are obviously ok.
2906 if (isa<AllocaInst>(V)) return true;
2907
2908 // It's not always safe to follow a bitcast, for example:
2909 // bitcast i8* (alloca i8) to i32*
2910 // would result in a 4-byte load from a 1-byte alloca. However,
2911 // if we're casting from a pointer from a type of larger size
2912 // to a type of smaller size (or the same size), and the alignment
2913 // is at least as large as for the resulting pointer type, then
2914 // we can look through the bitcast.
2915 if (const BitCastOperator *BC = dyn_cast<BitCastOperator>(V)) {
2916 Type *STy = BC->getSrcTy()->getPointerElementType(),
2917 *DTy = BC->getDestTy()->getPointerElementType();
2918 if (STy->isSized() && DTy->isSized() &&
2919 (DL.getTypeStoreSize(STy) >= DL.getTypeStoreSize(DTy)) &&
2920 (DL.getABITypeAlignment(STy) >= DL.getABITypeAlignment(DTy)))
2921 return isDereferenceablePointer(BC->getOperand(0), DL, Visited);
2922 }
2923
2924 // Global variables which can't collapse to null are ok.
2925 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
2926 return !GV->hasExternalWeakLinkage();
2927
2928 // byval arguments are okay.
2929 if (const Argument *A = dyn_cast<Argument>(V))
2930 if (A->hasByValAttr())
2931 return true;
2932
2933 if (isDereferenceableFromAttribute(V, DL))
2934 return true;
2935
2936 // For GEPs, determine if the indexing lands within the allocated object.
2937 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2938 // Conservatively require that the base pointer be fully dereferenceable.
2939 if (!Visited.insert(GEP->getOperand(0)).second)
2940 return false;
2941 if (!isDereferenceablePointer(GEP->getOperand(0), DL, Visited))
2942 return false;
2943 // Check the indices.
2944 gep_type_iterator GTI = gep_type_begin(GEP);
2945 for (User::const_op_iterator I = GEP->op_begin()+1,
2946 E = GEP->op_end(); I != E; ++I) {
2947 Value *Index = *I;
2948 Type *Ty = *GTI++;
2949 // Struct indices can't be out of bounds.
2950 if (isa<StructType>(Ty))
2951 continue;
2952 ConstantInt *CI = dyn_cast<ConstantInt>(Index);
2953 if (!CI)
2954 return false;
2955 // Zero is always ok.
2956 if (CI->isZero())
2957 continue;
2958 // Check to see that it's within the bounds of an array.
2959 ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2960 if (!ATy)
2961 return false;
2962 if (CI->getValue().getActiveBits() > 64)
2963 return false;
2964 if (CI->getZExtValue() >= ATy->getNumElements())
2965 return false;
2966 }
2967 // Indices check out; this is dereferenceable.
2968 return true;
2969 }
2970
2971 // For gc.relocate, look through relocations
2972 if (const IntrinsicInst *I = dyn_cast<IntrinsicInst>(V))
2973 if (I->getIntrinsicID() == Intrinsic::experimental_gc_relocate) {
2974 GCRelocateOperands RelocateInst(I);
Sanjoy Das499d7032015-05-06 02:36:26 +00002975 return isDereferenceablePointer(RelocateInst.getDerivedPtr(), DL,
2976 Visited);
Philip Reames5461d452015-04-23 17:36:48 +00002977 }
2978
2979 if (const AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(V))
2980 return isDereferenceablePointer(ASC->getOperand(0), DL, Visited);
2981
2982 // If we don't know, assume the worst.
2983 return false;
2984}
2985
2986bool llvm::isDereferenceablePointer(const Value *V, const DataLayout &DL) {
2987 // When dereferenceability information is provided by a dereferenceable
2988 // attribute, we know exactly how many bytes are dereferenceable. If we can
2989 // determine the exact offset to the attributed variable, we can use that
2990 // information here.
2991 Type *VTy = V->getType();
2992 Type *Ty = VTy->getPointerElementType();
2993 if (Ty->isSized()) {
2994 APInt Offset(DL.getTypeStoreSizeInBits(VTy), 0);
2995 const Value *BV = V->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
2996
2997 if (Offset.isNonNegative())
2998 if (isDereferenceableFromAttribute(BV, Offset, Ty, DL))
2999 return true;
3000 }
3001
3002 SmallPtrSet<const Value *, 32> Visited;
3003 return ::isDereferenceablePointer(V, DL, Visited);
3004}
3005
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003006bool llvm::isSafeToSpeculativelyExecute(const Value *V) {
Dan Gohman7ac046a2012-01-04 23:01:09 +00003007 const Operator *Inst = dyn_cast<Operator>(V);
3008 if (!Inst)
3009 return false;
3010
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003011 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3012 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3013 if (C->canTrap())
3014 return false;
3015
3016 switch (Inst->getOpcode()) {
3017 default:
3018 return true;
3019 case Instruction::UDiv:
David Majnemerf20d7c42014-11-04 23:49:08 +00003020 case Instruction::URem: {
3021 // x / y is undefined if y == 0.
3022 const APInt *V;
3023 if (match(Inst->getOperand(1), m_APInt(V)))
3024 return *V != 0;
3025 return false;
3026 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003027 case Instruction::SDiv:
3028 case Instruction::SRem: {
David Majnemerf20d7c42014-11-04 23:49:08 +00003029 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
David Majnemer8a6578a2015-02-01 19:10:19 +00003030 const APInt *Numerator, *Denominator;
3031 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3032 return false;
3033 // We cannot hoist this division if the denominator is 0.
3034 if (*Denominator == 0)
3035 return false;
3036 // It's safe to hoist if the denominator is not 0 or -1.
3037 if (*Denominator != -1)
3038 return true;
3039 // At this point we know that the denominator is -1. It is safe to hoist as
3040 // long we know that the numerator is not INT_MIN.
3041 if (match(Inst->getOperand(0), m_APInt(Numerator)))
3042 return !Numerator->isMinSignedValue();
3043 // The numerator *might* be MinSignedValue.
David Majnemerf20d7c42014-11-04 23:49:08 +00003044 return false;
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003045 }
3046 case Instruction::Load: {
3047 const LoadInst *LI = cast<LoadInst>(Inst);
Kostya Serebryany0b458282013-11-21 07:29:28 +00003048 if (!LI->isUnordered() ||
3049 // Speculative load may create a race that did not exist in the source.
3050 LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003051 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003052 const DataLayout &DL = LI->getModule()->getDataLayout();
Philip Reames5461d452015-04-23 17:36:48 +00003053 return isDereferenceablePointer(LI->getPointerOperand(), DL);
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003054 }
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003055 case Instruction::Call: {
Michael Liao736bac62014-11-06 19:05:57 +00003056 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
3057 switch (II->getIntrinsicID()) {
3058 // These synthetic intrinsics have no side-effects and just mark
3059 // information about their operands.
3060 // FIXME: There are other no-op synthetic instructions that potentially
3061 // should be considered at least *safe* to speculate...
3062 case Intrinsic::dbg_declare:
3063 case Intrinsic::dbg_value:
3064 return true;
Chandler Carruth28192c92012-04-07 19:22:18 +00003065
Michael Liao736bac62014-11-06 19:05:57 +00003066 case Intrinsic::bswap:
3067 case Intrinsic::ctlz:
3068 case Intrinsic::ctpop:
3069 case Intrinsic::cttz:
3070 case Intrinsic::objectsize:
3071 case Intrinsic::sadd_with_overflow:
3072 case Intrinsic::smul_with_overflow:
3073 case Intrinsic::ssub_with_overflow:
3074 case Intrinsic::uadd_with_overflow:
3075 case Intrinsic::umul_with_overflow:
3076 case Intrinsic::usub_with_overflow:
3077 return true;
3078 // Sqrt should be OK, since the llvm sqrt intrinsic isn't defined to set
3079 // errno like libm sqrt would.
3080 case Intrinsic::sqrt:
3081 case Intrinsic::fma:
3082 case Intrinsic::fmuladd:
3083 case Intrinsic::fabs:
3084 case Intrinsic::minnum:
3085 case Intrinsic::maxnum:
3086 return true;
3087 // TODO: some fp intrinsics are marked as having the same error handling
3088 // as libm. They're safe to speculate when they won't error.
3089 // TODO: are convert_{from,to}_fp16 safe?
3090 // TODO: can we list target-specific intrinsics here?
3091 default: break;
3092 }
3093 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003094 return false; // The called function could have undefined behavior or
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003095 // side-effects, even if marked readnone nounwind.
3096 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003097 case Instruction::VAArg:
3098 case Instruction::Alloca:
3099 case Instruction::Invoke:
3100 case Instruction::PHI:
3101 case Instruction::Store:
3102 case Instruction::Ret:
3103 case Instruction::Br:
3104 case Instruction::IndirectBr:
3105 case Instruction::Switch:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003106 case Instruction::Unreachable:
3107 case Instruction::Fence:
3108 case Instruction::LandingPad:
3109 case Instruction::AtomicRMW:
3110 case Instruction::AtomicCmpXchg:
3111 case Instruction::Resume:
3112 return false; // Misc instructions which have effects
3113 }
3114}
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003115
Sanjay Patelaee84212014-11-04 16:27:42 +00003116/// Return true if we know that the specified value is never null.
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00003117bool llvm::isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI) {
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003118 // Alloca never returns null, malloc might.
3119 if (isa<AllocaInst>(V)) return true;
3120
Nick Lewyckyd52b1522014-05-20 01:23:40 +00003121 // A byval, inalloca, or nonnull argument is never null.
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003122 if (const Argument *A = dyn_cast<Argument>(V))
Nick Lewyckyd52b1522014-05-20 01:23:40 +00003123 return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003124
3125 // Global values are not null unless extern weak.
3126 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
3127 return !GV->hasExternalWeakLinkage();
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00003128
Philip Reamescdb72f32014-10-20 22:40:55 +00003129 // A Load tagged w/nonnull metadata is never null.
3130 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
Philip Reames5a3f5f72014-10-21 00:13:20 +00003131 return LI->getMetadata(LLVMContext::MD_nonnull);
Philip Reamescdb72f32014-10-20 22:40:55 +00003132
Benjamin Kramer3a09ef62015-04-10 14:50:08 +00003133 if (auto CS = ImmutableCallSite(V))
Hal Finkelb0407ba2014-07-18 15:51:28 +00003134 if (CS.isReturnNonNull())
Nick Lewyckyec373542014-05-20 05:13:21 +00003135 return true;
3136
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00003137 // operator new never returns null.
3138 if (isOperatorNewLikeFn(V, TLI, /*LookThroughBitCast=*/true))
3139 return true;
3140
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003141 return false;
3142}
David Majnemer491331a2015-01-02 07:29:43 +00003143
3144OverflowResult llvm::computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003145 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00003146 AssumptionCache *AC,
David Majnemer491331a2015-01-02 07:29:43 +00003147 const Instruction *CxtI,
3148 const DominatorTree *DT) {
3149 // Multiplying n * m significant bits yields a result of n + m significant
3150 // bits. If the total number of significant bits does not exceed the
3151 // result bit width (minus 1), there is no overflow.
3152 // This means if we have enough leading zero bits in the operands
3153 // we can guarantee that the result does not overflow.
3154 // Ref: "Hacker's Delight" by Henry Warren
3155 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
3156 APInt LHSKnownZero(BitWidth, 0);
David Majnemerc8a576b2015-01-02 07:29:47 +00003157 APInt LHSKnownOne(BitWidth, 0);
David Majnemer491331a2015-01-02 07:29:43 +00003158 APInt RHSKnownZero(BitWidth, 0);
David Majnemerc8a576b2015-01-02 07:29:47 +00003159 APInt RHSKnownOne(BitWidth, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00003160 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
3161 DT);
3162 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, DL, /*Depth=*/0, AC, CxtI,
3163 DT);
David Majnemer491331a2015-01-02 07:29:43 +00003164 // Note that underestimating the number of zero bits gives a more
3165 // conservative answer.
3166 unsigned ZeroBits = LHSKnownZero.countLeadingOnes() +
3167 RHSKnownZero.countLeadingOnes();
3168 // First handle the easy case: if we have enough zero bits there's
3169 // definitely no overflow.
3170 if (ZeroBits >= BitWidth)
3171 return OverflowResult::NeverOverflows;
3172
3173 // Get the largest possible values for each operand.
3174 APInt LHSMax = ~LHSKnownZero;
3175 APInt RHSMax = ~RHSKnownZero;
3176
3177 // We know the multiply operation doesn't overflow if the maximum values for
3178 // each operand will not overflow after we multiply them together.
David Majnemerc8a576b2015-01-02 07:29:47 +00003179 bool MaxOverflow;
3180 LHSMax.umul_ov(RHSMax, MaxOverflow);
3181 if (!MaxOverflow)
3182 return OverflowResult::NeverOverflows;
David Majnemer491331a2015-01-02 07:29:43 +00003183
David Majnemerc8a576b2015-01-02 07:29:47 +00003184 // We know it always overflows if multiplying the smallest possible values for
3185 // the operands also results in overflow.
3186 bool MinOverflow;
3187 LHSKnownOne.umul_ov(RHSKnownOne, MinOverflow);
3188 if (MinOverflow)
3189 return OverflowResult::AlwaysOverflows;
3190
3191 return OverflowResult::MayOverflow;
David Majnemer491331a2015-01-02 07:29:43 +00003192}
David Majnemer5310c1e2015-01-07 00:39:50 +00003193
3194OverflowResult llvm::computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003195 const DataLayout &DL,
David Majnemer5310c1e2015-01-07 00:39:50 +00003196 AssumptionCache *AC,
3197 const Instruction *CxtI,
3198 const DominatorTree *DT) {
3199 bool LHSKnownNonNegative, LHSKnownNegative;
3200 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, /*Depth=*/0,
3201 AC, CxtI, DT);
3202 if (LHSKnownNonNegative || LHSKnownNegative) {
3203 bool RHSKnownNonNegative, RHSKnownNegative;
3204 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, /*Depth=*/0,
3205 AC, CxtI, DT);
3206
3207 if (LHSKnownNegative && RHSKnownNegative) {
3208 // The sign bit is set in both cases: this MUST overflow.
3209 // Create a simple add instruction, and insert it into the struct.
3210 return OverflowResult::AlwaysOverflows;
3211 }
3212
3213 if (LHSKnownNonNegative && RHSKnownNonNegative) {
3214 // The sign bit is clear in both cases: this CANNOT overflow.
3215 // Create a simple add instruction, and insert it into the struct.
3216 return OverflowResult::NeverOverflows;
3217 }
3218 }
3219
3220 return OverflowResult::MayOverflow;
3221}
James Molloy71b91c22015-05-11 14:42:20 +00003222
James Molloy270ef8c2015-05-15 16:04:50 +00003223static SelectPatternFlavor matchSelectPattern(ICmpInst::Predicate Pred,
3224 Value *CmpLHS, Value *CmpRHS,
3225 Value *TrueVal, Value *FalseVal,
3226 Value *&LHS, Value *&RHS) {
James Molloy71b91c22015-05-11 14:42:20 +00003227 LHS = CmpLHS;
3228 RHS = CmpRHS;
3229
3230 // (icmp X, Y) ? X : Y
3231 if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
3232 switch (Pred) {
3233 default: return SPF_UNKNOWN; // Equality.
3234 case ICmpInst::ICMP_UGT:
3235 case ICmpInst::ICMP_UGE: return SPF_UMAX;
3236 case ICmpInst::ICMP_SGT:
3237 case ICmpInst::ICMP_SGE: return SPF_SMAX;
3238 case ICmpInst::ICMP_ULT:
3239 case ICmpInst::ICMP_ULE: return SPF_UMIN;
3240 case ICmpInst::ICMP_SLT:
3241 case ICmpInst::ICMP_SLE: return SPF_SMIN;
3242 }
3243 }
3244
3245 // (icmp X, Y) ? Y : X
3246 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
3247 switch (Pred) {
3248 default: return SPF_UNKNOWN; // Equality.
3249 case ICmpInst::ICMP_UGT:
3250 case ICmpInst::ICMP_UGE: return SPF_UMIN;
3251 case ICmpInst::ICMP_SGT:
3252 case ICmpInst::ICMP_SGE: return SPF_SMIN;
3253 case ICmpInst::ICMP_ULT:
3254 case ICmpInst::ICMP_ULE: return SPF_UMAX;
3255 case ICmpInst::ICMP_SLT:
3256 case ICmpInst::ICMP_SLE: return SPF_SMAX;
3257 }
3258 }
3259
3260 if (ConstantInt *C1 = dyn_cast<ConstantInt>(CmpRHS)) {
3261 if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) ||
3262 (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) {
3263
3264 // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X
3265 // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X
3266 if (Pred == ICmpInst::ICMP_SGT && (C1->isZero() || C1->isMinusOne())) {
3267 return (CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS;
3268 }
3269
3270 // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X
3271 // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X
3272 if (Pred == ICmpInst::ICMP_SLT && (C1->isZero() || C1->isOne())) {
3273 return (CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS;
3274 }
3275 }
3276
3277 // Y >s C ? ~Y : ~C == ~Y <s ~C ? ~Y : ~C = SMIN(~Y, ~C)
3278 if (const auto *C2 = dyn_cast<ConstantInt>(FalseVal)) {
3279 if (C1->getType() == C2->getType() && ~C1->getValue() == C2->getValue() &&
3280 (match(TrueVal, m_Not(m_Specific(CmpLHS))) ||
3281 match(CmpLHS, m_Not(m_Specific(TrueVal))))) {
3282 LHS = TrueVal;
3283 RHS = FalseVal;
3284 return SPF_SMIN;
3285 }
3286 }
3287 }
3288
3289 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
3290
3291 return SPF_UNKNOWN;
3292}
James Molloy270ef8c2015-05-15 16:04:50 +00003293
3294static Constant *lookThroughCast(ICmpInst *CmpI, Value *V1, Value *V2,
3295 Instruction::CastOps *CastOp) {
3296 CastInst *CI = dyn_cast<CastInst>(V1);
3297 Constant *C = dyn_cast<Constant>(V2);
3298 if (!CI || !C)
3299 return nullptr;
3300 *CastOp = CI->getOpcode();
3301
3302 if ((isa<SExtInst>(CI) && CmpI->isSigned()) ||
3303 (isa<ZExtInst>(CI) && CmpI->isUnsigned()))
3304 return ConstantExpr::getTrunc(C, CI->getSrcTy());
3305
3306 if (isa<TruncInst>(CI))
3307 return ConstantExpr::getIntegerCast(C, CI->getSrcTy(), CmpI->isSigned());
3308
3309 return nullptr;
3310}
3311
3312SelectPatternFlavor llvm::matchSelectPattern(Value *V,
3313 Value *&LHS, Value *&RHS,
3314 Instruction::CastOps *CastOp) {
3315 SelectInst *SI = dyn_cast<SelectInst>(V);
3316 if (!SI) return SPF_UNKNOWN;
3317
3318 ICmpInst *CmpI = dyn_cast<ICmpInst>(SI->getCondition());
3319 if (!CmpI) return SPF_UNKNOWN;
3320
3321 ICmpInst::Predicate Pred = CmpI->getPredicate();
3322 Value *CmpLHS = CmpI->getOperand(0);
3323 Value *CmpRHS = CmpI->getOperand(1);
3324 Value *TrueVal = SI->getTrueValue();
3325 Value *FalseVal = SI->getFalseValue();
3326
3327 // Bail out early.
3328 if (CmpI->isEquality())
3329 return SPF_UNKNOWN;
3330
3331 // Deal with type mismatches.
3332 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
3333 if (Constant *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp))
3334 return ::matchSelectPattern(Pred, CmpLHS, CmpRHS,
3335 cast<CastInst>(TrueVal)->getOperand(0), C,
3336 LHS, RHS);
3337 if (Constant *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp))
3338 return ::matchSelectPattern(Pred, CmpLHS, CmpRHS,
3339 C, cast<CastInst>(FalseVal)->getOperand(0),
3340 LHS, RHS);
3341 }
3342 return ::matchSelectPattern(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal,
3343 LHS, RHS);
3344}