blob: cba7363a0afabea57cf82656018ad6c1d09da01d [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"
James Molloy493e57d2015-10-26 14:10:46 +000016#include "llvm/ADT/Optional.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/SmallPtrSet.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000018#include "llvm/Analysis/AssumptionCache.h"
Dan Gohman949ab782010-12-15 20:10:26 +000019#include "llvm/Analysis/InstructionSimplify.h"
Benjamin Kramerfd4777c2013-09-24 16:37:51 +000020#include "llvm/Analysis/MemoryBuiltins.h"
Artur Pilipenko31bcca42016-02-24 12:49:04 +000021#include "llvm/Analysis/Loads.h"
Adam Nemete2b885c2015-04-23 20:09:20 +000022#include "llvm/Analysis/LoopInfo.h"
Sanjay Patel54656ca2017-02-06 18:26:06 +000023#include "llvm/Analysis/OptimizationDiagnosticInfo.h"
David Majnemer3ee5f342016-04-13 06:55:52 +000024#include "llvm/Analysis/VectorUtils.h"
Nick Lewyckyec373542014-05-20 05:13:21 +000025#include "llvm/IR/CallSite.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000026#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
Hal Finkel60db0582014-09-07 18:57:58 +000029#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000030#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/GlobalAlias.h"
32#include "llvm/IR/GlobalVariable.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/LLVMContext.h"
36#include "llvm/IR/Metadata.h"
37#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000038#include "llvm/IR/PatternMatch.h"
Philip Reames5461d452015-04-23 17:36:48 +000039#include "llvm/IR/Statepoint.h"
Matt Arsenaultf1a7e622014-07-15 01:55:03 +000040#include "llvm/Support/Debug.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000041#include "llvm/Support/KnownBits.h"
Chris Lattner965c7692008-06-02 01:18:21 +000042#include "llvm/Support/MathExtras.h"
Matthias Braun37e5d792016-01-28 06:29:33 +000043#include <algorithm>
44#include <array>
Chris Lattner64496902008-06-04 04:46:14 +000045#include <cstring>
Chris Lattner965c7692008-06-02 01:18:21 +000046using namespace llvm;
Duncan Sandsd3951082011-01-25 09:38:29 +000047using namespace llvm::PatternMatch;
48
49const unsigned MaxDepth = 6;
50
Philip Reames1c292272015-03-10 22:43:20 +000051// Controls the number of uses of the value searched for possible
52// dominating comparisons.
53static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
Igor Laevskycea9ede2015-09-29 14:57:52 +000054 cl::Hidden, cl::init(20));
Philip Reames1c292272015-03-10 22:43:20 +000055
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +000056// This optimization is known to cause performance regressions is some cases,
57// keep it under a temporary flag for now.
58static cl::opt<bool>
59DontImproveNonNegativePhiBits("dont-improve-non-negative-phi-bits",
60 cl::Hidden, cl::init(true));
61
Craig Topper6b3940a2017-05-03 22:25:19 +000062/// Returns the bitwidth of the given scalar or pointer type. For vector types,
63/// returns the element type's bitwidth.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000064static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
Duncan Sandsd3951082011-01-25 09:38:29 +000065 if (unsigned BitWidth = Ty->getScalarSizeInBits())
66 return BitWidth;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +000067
Mehdi Aminia28d91d2015-03-10 02:37:25 +000068 return DL.getPointerTypeSizeInBits(Ty);
Duncan Sandsd3951082011-01-25 09:38:29 +000069}
Chris Lattner965c7692008-06-02 01:18:21 +000070
Benjamin Kramercfd8d902014-09-12 08:56:53 +000071namespace {
Hal Finkel60db0582014-09-07 18:57:58 +000072// Simplifying using an assume can only be done in a particular control-flow
73// context (the context instruction provides that context). If an assume and
74// the context instruction are not in the same block then the DT helps in
75// figuring out if we can use it.
76struct Query {
Matthias Braunfeb81bc2016-01-15 22:22:04 +000077 const DataLayout &DL;
Daniel Jasperaec2fa32016-12-19 08:22:17 +000078 AssumptionCache *AC;
Hal Finkel60db0582014-09-07 18:57:58 +000079 const Instruction *CxtI;
80 const DominatorTree *DT;
Sanjay Patel54656ca2017-02-06 18:26:06 +000081 // Unlike the other analyses, this may be a nullptr because not all clients
82 // provide it currently.
83 OptimizationRemarkEmitter *ORE;
Hal Finkel60db0582014-09-07 18:57:58 +000084
Matthias Braun37e5d792016-01-28 06:29:33 +000085 /// Set of assumptions that should be excluded from further queries.
86 /// This is because of the potential for mutual recursion to cause
87 /// computeKnownBits to repeatedly visit the same assume intrinsic. The
88 /// classic case of this is assume(x = y), which will attempt to determine
89 /// bits in x from bits in y, which will attempt to determine bits in y from
90 /// bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
Craig Topper6e11a052017-05-08 16:22:48 +000091 /// isKnownNonZero, which calls computeKnownBits and isKnownToBeAPowerOfTwo
92 /// (all of which can call computeKnownBits), and so on.
Li Huang755f75f2016-10-15 19:00:04 +000093 std::array<const Value *, MaxDepth> Excluded;
Matthias Braun37e5d792016-01-28 06:29:33 +000094 unsigned NumExcluded;
95
Daniel Jasperaec2fa32016-12-19 08:22:17 +000096 Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI,
Sanjay Patel54656ca2017-02-06 18:26:06 +000097 const DominatorTree *DT, OptimizationRemarkEmitter *ORE = nullptr)
98 : DL(DL), AC(AC), CxtI(CxtI), DT(DT), ORE(ORE), NumExcluded(0) {}
Hal Finkel60db0582014-09-07 18:57:58 +000099
100 Query(const Query &Q, const Value *NewExcl)
Sanjay Patel54656ca2017-02-06 18:26:06 +0000101 : DL(Q.DL), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT), ORE(Q.ORE),
102 NumExcluded(Q.NumExcluded) {
Matthias Braun37e5d792016-01-28 06:29:33 +0000103 Excluded = Q.Excluded;
104 Excluded[NumExcluded++] = NewExcl;
105 assert(NumExcluded <= Excluded.size());
106 }
107
108 bool isExcluded(const Value *Value) const {
109 if (NumExcluded == 0)
110 return false;
111 auto End = Excluded.begin() + NumExcluded;
112 return std::find(Excluded.begin(), End, Value) != End;
Hal Finkel60db0582014-09-07 18:57:58 +0000113 }
114};
Benjamin Kramercfd8d902014-09-12 08:56:53 +0000115} // end anonymous namespace
Hal Finkel60db0582014-09-07 18:57:58 +0000116
Sanjay Patel547e9752014-11-04 16:09:50 +0000117// Given the provided Value and, potentially, a context instruction, return
Hal Finkel60db0582014-09-07 18:57:58 +0000118// the preferred context instruction (if any).
119static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
120 // If we've been provided with a context instruction, then use that (provided
121 // it has been inserted).
122 if (CxtI && CxtI->getParent())
123 return CxtI;
124
125 // If the value is really an already-inserted instruction, then use that.
126 CxtI = dyn_cast<Instruction>(V);
127 if (CxtI && CxtI->getParent())
128 return CxtI;
129
130 return nullptr;
131}
132
Craig Topperb45eabc2017-04-26 16:39:58 +0000133static void computeKnownBits(const Value *V, KnownBits &Known,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000134 unsigned Depth, const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000135
Craig Topperb45eabc2017-04-26 16:39:58 +0000136void llvm::computeKnownBits(const Value *V, KnownBits &Known,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000137 const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000138 AssumptionCache *AC, const Instruction *CxtI,
Sanjay Patel54656ca2017-02-06 18:26:06 +0000139 const DominatorTree *DT,
140 OptimizationRemarkEmitter *ORE) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000141 ::computeKnownBits(V, Known, Depth,
Sanjay Patel54656ca2017-02-06 18:26:06 +0000142 Query(DL, AC, safeCxtI(V, CxtI), DT, ORE));
Hal Finkel60db0582014-09-07 18:57:58 +0000143}
144
Craig Topper6e11a052017-05-08 16:22:48 +0000145static KnownBits computeKnownBits(const Value *V, unsigned Depth,
146 const Query &Q);
147
148KnownBits llvm::computeKnownBits(const Value *V, const DataLayout &DL,
149 unsigned Depth, AssumptionCache *AC,
150 const Instruction *CxtI,
151 const DominatorTree *DT) {
152 return ::computeKnownBits(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
153}
154
Pete Cooper35b00d52016-08-13 01:05:32 +0000155bool llvm::haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
156 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000157 AssumptionCache *AC, const Instruction *CxtI,
Jingyue Wuca321902015-05-14 23:53:19 +0000158 const DominatorTree *DT) {
159 assert(LHS->getType() == RHS->getType() &&
160 "LHS and RHS should have the same type");
161 assert(LHS->getType()->isIntOrIntVectorTy() &&
162 "LHS and RHS should be integers");
163 IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
Craig Topperb45eabc2017-04-26 16:39:58 +0000164 KnownBits LHSKnown(IT->getBitWidth());
165 KnownBits RHSKnown(IT->getBitWidth());
166 computeKnownBits(LHS, LHSKnown, DL, 0, AC, CxtI, DT);
167 computeKnownBits(RHS, RHSKnown, DL, 0, AC, CxtI, DT);
168 return (LHSKnown.Zero | RHSKnown.Zero).isAllOnesValue();
Jingyue Wuca321902015-05-14 23:53:19 +0000169}
170
Hal Finkel60db0582014-09-07 18:57:58 +0000171
Pete Cooper35b00d52016-08-13 01:05:32 +0000172static bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000173 const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000174
Pete Cooper35b00d52016-08-13 01:05:32 +0000175bool llvm::isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
176 bool OrZero,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000177 unsigned Depth, AssumptionCache *AC,
178 const Instruction *CxtI,
Hal Finkel60db0582014-09-07 18:57:58 +0000179 const DominatorTree *DT) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000180 return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000181 Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000182}
183
Pete Cooper35b00d52016-08-13 01:05:32 +0000184static bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000185
Pete Cooper35b00d52016-08-13 01:05:32 +0000186bool llvm::isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000187 AssumptionCache *AC, const Instruction *CxtI,
188 const DominatorTree *DT) {
189 return ::isKnownNonZero(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000190}
191
Pete Cooper35b00d52016-08-13 01:05:32 +0000192bool llvm::isKnownNonNegative(const Value *V, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000193 unsigned Depth,
194 AssumptionCache *AC, const Instruction *CxtI,
Jingyue Wu10fcea52015-08-20 18:27:04 +0000195 const DominatorTree *DT) {
Craig Topper6e11a052017-05-08 16:22:48 +0000196 KnownBits Known = computeKnownBits(V, DL, Depth, AC, CxtI, DT);
197 return Known.isNonNegative();
Jingyue Wu10fcea52015-08-20 18:27:04 +0000198}
199
Pete Cooper35b00d52016-08-13 01:05:32 +0000200bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000201 AssumptionCache *AC, const Instruction *CxtI,
202 const DominatorTree *DT) {
Philip Reames8f12eba2016-03-09 21:31:47 +0000203 if (auto *CI = dyn_cast<ConstantInt>(V))
204 return CI->getValue().isStrictlyPositive();
Sanjoy Das6082c1a2016-05-07 02:08:15 +0000205
Philip Reames8f12eba2016-03-09 21:31:47 +0000206 // TODO: We'd doing two recursive queries here. We should factor this such
207 // that only a single query is needed.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000208 return isKnownNonNegative(V, DL, Depth, AC, CxtI, DT) &&
209 isKnownNonZero(V, DL, Depth, AC, CxtI, DT);
Philip Reames8f12eba2016-03-09 21:31:47 +0000210}
211
Pete Cooper35b00d52016-08-13 01:05:32 +0000212bool llvm::isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000213 AssumptionCache *AC, const Instruction *CxtI,
214 const DominatorTree *DT) {
Craig Topper6e11a052017-05-08 16:22:48 +0000215 KnownBits Known = computeKnownBits(V, DL, Depth, AC, CxtI, DT);
216 return Known.isNegative();
Nick Lewycky762f8a82016-04-21 00:53:14 +0000217}
218
Pete Cooper35b00d52016-08-13 01:05:32 +0000219static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q);
James Molloy1d88d6f2015-10-22 13:18:42 +0000220
Pete Cooper35b00d52016-08-13 01:05:32 +0000221bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000222 const DataLayout &DL,
223 AssumptionCache *AC, const Instruction *CxtI,
Pete Cooper35b00d52016-08-13 01:05:32 +0000224 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000225 return ::isKnownNonEqual(V1, V2, Query(DL, AC,
226 safeCxtI(V1, safeCxtI(V2, CxtI)),
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000227 DT));
James Molloy1d88d6f2015-10-22 13:18:42 +0000228}
229
Pete Cooper35b00d52016-08-13 01:05:32 +0000230static bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000231 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000232
Pete Cooper35b00d52016-08-13 01:05:32 +0000233bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
234 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000235 unsigned Depth, AssumptionCache *AC,
236 const Instruction *CxtI, const DominatorTree *DT) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000237 return ::MaskedValueIsZero(V, Mask, Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000238 Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000239}
240
Pete Cooper35b00d52016-08-13 01:05:32 +0000241static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
242 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000243
Pete Cooper35b00d52016-08-13 01:05:32 +0000244unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000245 unsigned Depth, AssumptionCache *AC,
246 const Instruction *CxtI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000247 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000248 return ::ComputeNumSignBits(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
Hal Finkel60db0582014-09-07 18:57:58 +0000249}
250
Craig Topper8fbb74b2017-03-24 22:12:10 +0000251static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
252 bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000253 KnownBits &KnownOut, KnownBits &Known2,
Craig Topper8fbb74b2017-03-24 22:12:10 +0000254 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000255 unsigned BitWidth = KnownOut.getBitWidth();
Craig Topper8fbb74b2017-03-24 22:12:10 +0000256
257 // If an initial sequence of bits in the result is not needed, the
258 // corresponding bits in the operands are not needed.
Craig Topperb45eabc2017-04-26 16:39:58 +0000259 KnownBits LHSKnown(BitWidth);
260 computeKnownBits(Op0, LHSKnown, Depth + 1, Q);
261 computeKnownBits(Op1, Known2, Depth + 1, Q);
Craig Topper8fbb74b2017-03-24 22:12:10 +0000262
David Majnemer97ddca32014-08-22 00:40:43 +0000263 // Carry in a 1 for a subtract, rather than a 0.
Craig Topper059b98e2017-03-24 05:38:09 +0000264 uint64_t CarryIn = 0;
David Majnemer97ddca32014-08-22 00:40:43 +0000265 if (!Add) {
266 // Sum = LHS + ~RHS + 1
Craig Topperb45eabc2017-04-26 16:39:58 +0000267 std::swap(Known2.Zero, Known2.One);
Craig Topper059b98e2017-03-24 05:38:09 +0000268 CarryIn = 1;
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000269 }
270
Craig Topperb45eabc2017-04-26 16:39:58 +0000271 APInt PossibleSumZero = ~LHSKnown.Zero + ~Known2.Zero + CarryIn;
272 APInt PossibleSumOne = LHSKnown.One + Known2.One + CarryIn;
David Majnemer97ddca32014-08-22 00:40:43 +0000273
274 // Compute known bits of the carry.
Craig Topperb45eabc2017-04-26 16:39:58 +0000275 APInt CarryKnownZero = ~(PossibleSumZero ^ LHSKnown.Zero ^ Known2.Zero);
276 APInt CarryKnownOne = PossibleSumOne ^ LHSKnown.One ^ Known2.One;
David Majnemer97ddca32014-08-22 00:40:43 +0000277
278 // Compute set of known bits (where all three relevant bits are known).
Craig Topperb45eabc2017-04-26 16:39:58 +0000279 APInt LHSKnownUnion = LHSKnown.Zero | LHSKnown.One;
280 APInt RHSKnownUnion = Known2.Zero | Known2.One;
281 APInt CarryKnownUnion = CarryKnownZero | CarryKnownOne;
282 APInt Known = LHSKnownUnion & RHSKnownUnion & CarryKnownUnion;
David Majnemer97ddca32014-08-22 00:40:43 +0000283
284 assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
285 "known bits of sum differ");
286
287 // Compute known bits of the result.
Craig Topperb45eabc2017-04-26 16:39:58 +0000288 KnownOut.Zero = ~PossibleSumOne & Known;
289 KnownOut.One = PossibleSumOne & Known;
David Majnemer97ddca32014-08-22 00:40:43 +0000290
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000291 // Are we still trying to solve for the sign bit?
Craig Topperd23004c2017-04-17 16:38:20 +0000292 if (!Known.isSignBitSet()) {
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000293 if (NSW) {
David Majnemer97ddca32014-08-22 00:40:43 +0000294 // Adding two non-negative numbers, or subtracting a negative number from
295 // a non-negative one, can't wrap into negative.
Craig Topperca48af32017-04-29 16:43:11 +0000296 if (LHSKnown.isNonNegative() && Known2.isNonNegative())
297 KnownOut.makeNonNegative();
David Majnemer97ddca32014-08-22 00:40:43 +0000298 // Adding two negative numbers, or subtracting a non-negative number from
299 // a negative one, can't wrap into non-negative.
Craig Topperca48af32017-04-29 16:43:11 +0000300 else if (LHSKnown.isNegative() && Known2.isNegative())
301 KnownOut.makeNegative();
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000302 }
303 }
304}
305
Pete Cooper35b00d52016-08-13 01:05:32 +0000306static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000307 KnownBits &Known, KnownBits &Known2,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000308 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000309 unsigned BitWidth = Known.getBitWidth();
310 computeKnownBits(Op1, Known, Depth + 1, Q);
311 computeKnownBits(Op0, Known2, Depth + 1, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000312
313 bool isKnownNegative = false;
314 bool isKnownNonNegative = false;
315 // If the multiplication is known not to overflow, compute the sign bit.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000316 if (NSW) {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000317 if (Op0 == Op1) {
318 // The product of a number with itself is non-negative.
319 isKnownNonNegative = true;
320 } else {
Craig Topperca48af32017-04-29 16:43:11 +0000321 bool isKnownNonNegativeOp1 = Known.isNonNegative();
322 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
323 bool isKnownNegativeOp1 = Known.isNegative();
324 bool isKnownNegativeOp0 = Known2.isNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000325 // The product of two numbers with the same sign is non-negative.
326 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
327 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
328 // The product of a negative number and a non-negative number is either
329 // negative or zero.
330 if (!isKnownNonNegative)
331 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000332 isKnownNonZero(Op0, Depth, Q)) ||
Nick Lewyckyfa306072012-03-18 23:28:48 +0000333 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000334 isKnownNonZero(Op1, Depth, Q));
Nick Lewyckyfa306072012-03-18 23:28:48 +0000335 }
336 }
337
338 // If low bits are zero in either operand, output low known-0 bits.
Sanjay Patel5dd66c32015-09-17 20:51:50 +0000339 // Also compute a conservative estimate for high known-0 bits.
Nick Lewyckyfa306072012-03-18 23:28:48 +0000340 // More trickiness is possible, but this is sufficient for the
341 // interesting case of alignment computation.
Craig Topper8df66c62017-05-12 17:20:30 +0000342 unsigned TrailZ = Known.countMinTrailingZeros() +
343 Known2.countMinTrailingZeros();
344 unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
345 Known2.countMinLeadingZeros(),
Nick Lewyckyfa306072012-03-18 23:28:48 +0000346 BitWidth) - BitWidth;
347
348 TrailZ = std::min(TrailZ, BitWidth);
349 LeadZ = std::min(LeadZ, BitWidth);
Craig Topperf0aeee02017-05-05 17:36:09 +0000350 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000351 Known.Zero.setLowBits(TrailZ);
352 Known.Zero.setHighBits(LeadZ);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000353
354 // Only make use of no-wrap flags if we failed to compute the sign bit
355 // directly. This matters if the multiplication always overflows, in
356 // which case we prefer to follow the result of the direct computation,
357 // though as the program is invoking undefined behaviour we can choose
358 // whatever we like here.
Craig Topperca48af32017-04-29 16:43:11 +0000359 if (isKnownNonNegative && !Known.isNegative())
360 Known.makeNonNegative();
361 else if (isKnownNegative && !Known.isNonNegative())
362 Known.makeNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000363}
364
Jingyue Wu37fcb592014-06-19 16:50:16 +0000365void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
Craig Topperf42b23f2017-04-28 06:28:56 +0000366 KnownBits &Known) {
367 unsigned BitWidth = Known.getBitWidth();
Rafael Espindola53190532012-03-30 15:52:11 +0000368 unsigned NumRanges = Ranges.getNumOperands() / 2;
369 assert(NumRanges >= 1);
370
Craig Topperf42b23f2017-04-28 06:28:56 +0000371 Known.Zero.setAllBits();
372 Known.One.setAllBits();
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000373
Rafael Espindola53190532012-03-30 15:52:11 +0000374 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000375 ConstantInt *Lower =
376 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
377 ConstantInt *Upper =
378 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
Rafael Espindola53190532012-03-30 15:52:11 +0000379 ConstantRange Range(Lower->getValue(), Upper->getValue());
Rafael Espindola53190532012-03-30 15:52:11 +0000380
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000381 // The first CommonPrefixBits of all values in Range are equal.
382 unsigned CommonPrefixBits =
383 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
384
385 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
Craig Topperf42b23f2017-04-28 06:28:56 +0000386 Known.One &= Range.getUnsignedMax() & Mask;
387 Known.Zero &= ~Range.getUnsignedMax() & Mask;
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000388 }
Rafael Espindola53190532012-03-30 15:52:11 +0000389}
Jay Foad5a29c362014-05-15 12:12:55 +0000390
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000391static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
Hal Finkel60db0582014-09-07 18:57:58 +0000392 SmallVector<const Value *, 16> WorkSet(1, I);
393 SmallPtrSet<const Value *, 32> Visited;
394 SmallPtrSet<const Value *, 16> EphValues;
395
Hal Finkelf2199b22015-10-23 20:37:08 +0000396 // The instruction defining an assumption's condition itself is always
397 // considered ephemeral to that assumption (even if it has other
398 // non-ephemeral users). See r246696's test case for an example.
David Majnemer0a16c222016-08-11 21:15:00 +0000399 if (is_contained(I->operands(), E))
Hal Finkelf2199b22015-10-23 20:37:08 +0000400 return true;
401
Hal Finkel60db0582014-09-07 18:57:58 +0000402 while (!WorkSet.empty()) {
403 const Value *V = WorkSet.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +0000404 if (!Visited.insert(V).second)
Hal Finkel60db0582014-09-07 18:57:58 +0000405 continue;
406
407 // If all uses of this value are ephemeral, then so is this value.
David Majnemer0a16c222016-08-11 21:15:00 +0000408 if (all_of(V->users(), [&](const User *U) { return EphValues.count(U); })) {
Hal Finkel60db0582014-09-07 18:57:58 +0000409 if (V == E)
410 return true;
411
412 EphValues.insert(V);
413 if (const User *U = dyn_cast<User>(V))
414 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
415 J != JE; ++J) {
416 if (isSafeToSpeculativelyExecute(*J))
417 WorkSet.push_back(*J);
418 }
419 }
420 }
421
422 return false;
423}
424
425// Is this an intrinsic that cannot be speculated but also cannot trap?
426static bool isAssumeLikeIntrinsic(const Instruction *I) {
427 if (const CallInst *CI = dyn_cast<CallInst>(I))
428 if (Function *F = CI->getCalledFunction())
429 switch (F->getIntrinsicID()) {
430 default: break;
431 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
432 case Intrinsic::assume:
433 case Intrinsic::dbg_declare:
434 case Intrinsic::dbg_value:
435 case Intrinsic::invariant_start:
436 case Intrinsic::invariant_end:
437 case Intrinsic::lifetime_start:
438 case Intrinsic::lifetime_end:
439 case Intrinsic::objectsize:
440 case Intrinsic::ptr_annotation:
441 case Intrinsic::var_annotation:
442 return true;
443 }
444
445 return false;
446}
447
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000448bool llvm::isValidAssumeForContext(const Instruction *Inv,
449 const Instruction *CxtI,
450 const DominatorTree *DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000451
452 // There are two restrictions on the use of an assume:
453 // 1. The assume must dominate the context (or the control flow must
454 // reach the assume whenever it reaches the context).
455 // 2. The context must not be in the assume's set of ephemeral values
456 // (otherwise we will use the assume to prove that the condition
457 // feeding the assume is trivially true, thus causing the removal of
458 // the assume).
459
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000460 if (DT) {
Pete Cooper54a02552016-08-12 01:00:15 +0000461 if (DT->dominates(Inv, CxtI))
Hal Finkel60db0582014-09-07 18:57:58 +0000462 return true;
Pete Cooper54a02552016-08-12 01:00:15 +0000463 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
464 // We don't have a DT, but this trivially dominates.
465 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000466 }
467
Pete Cooper54a02552016-08-12 01:00:15 +0000468 // With or without a DT, the only remaining case we will check is if the
469 // instructions are in the same BB. Give up if that is not the case.
470 if (Inv->getParent() != CxtI->getParent())
471 return false;
472
473 // If we have a dom tree, then we now know that the assume doens't dominate
474 // the other instruction. If we don't have a dom tree then we can check if
475 // the assume is first in the BB.
476 if (!DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000477 // Search forward from the assume until we reach the context (or the end
478 // of the block); the common case is that the assume will come first.
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000479 for (auto I = std::next(BasicBlock::const_iterator(Inv)),
Hal Finkel60db0582014-09-07 18:57:58 +0000480 IE = Inv->getParent()->end(); I != IE; ++I)
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000481 if (&*I == CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000482 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000483 }
484
Pete Cooper54a02552016-08-12 01:00:15 +0000485 // The context comes first, but they're both in the same block. Make sure
486 // there is nothing in between that might interrupt the control flow.
487 for (BasicBlock::const_iterator I =
488 std::next(BasicBlock::const_iterator(CxtI)), IE(Inv);
489 I != IE; ++I)
490 if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
491 return false;
492
493 return !isEphemeralValueOf(Inv, CxtI);
Hal Finkel60db0582014-09-07 18:57:58 +0000494}
495
Craig Topperb45eabc2017-04-26 16:39:58 +0000496static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known,
497 unsigned Depth, const Query &Q) {
Hal Finkel60db0582014-09-07 18:57:58 +0000498 // Use of assumptions is context-sensitive. If we don't have a context, we
499 // cannot use them!
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000500 if (!Q.AC || !Q.CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000501 return;
502
Craig Topperb45eabc2017-04-26 16:39:58 +0000503 unsigned BitWidth = Known.getBitWidth();
Hal Finkel60db0582014-09-07 18:57:58 +0000504
Hal Finkel8a9a7832017-01-11 13:24:24 +0000505 // Note that the patterns below need to be kept in sync with the code
506 // in AssumptionCache::updateAffectedValues.
507
508 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000509 if (!AssumeVH)
Chandler Carruth66b31302015-01-04 12:03:27 +0000510 continue;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000511 CallInst *I = cast<CallInst>(AssumeVH);
512 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
513 "Got assumption for the wrong function!");
514 if (Q.isExcluded(I))
Hal Finkel60db0582014-09-07 18:57:58 +0000515 continue;
516
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000517 // Warning: This loop can end up being somewhat performance sensetive.
518 // We're running this loop for once for each value queried resulting in a
519 // runtime of ~O(#assumes * #values).
Philip Reames00d3b272014-11-24 23:44:28 +0000520
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000521 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
522 "must be an assume intrinsic");
523
524 Value *Arg = I->getArgOperand(0);
525
526 if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000527 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000528 Known.setAllOnes();
Hal Finkel60db0582014-09-07 18:57:58 +0000529 return;
530 }
Sanjay Patel96669962017-01-17 18:15:49 +0000531 if (match(Arg, m_Not(m_Specific(V))) &&
532 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
533 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000534 Known.setAllZero();
Sanjay Patel96669962017-01-17 18:15:49 +0000535 return;
536 }
Hal Finkel60db0582014-09-07 18:57:58 +0000537
David Majnemer9b609752014-12-12 23:59:29 +0000538 // The remaining tests are all recursive, so bail out if we hit the limit.
539 if (Depth == MaxDepth)
540 continue;
541
Hal Finkel60db0582014-09-07 18:57:58 +0000542 Value *A, *B;
543 auto m_V = m_CombineOr(m_Specific(V),
544 m_CombineOr(m_PtrToInt(m_Specific(V)),
545 m_BitCast(m_Specific(V))));
546
547 CmpInst::Predicate Pred;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000548 ConstantInt *C;
Hal Finkel60db0582014-09-07 18:57:58 +0000549 // assume(v = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000550 if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000551 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000552 KnownBits RHSKnown(BitWidth);
553 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
554 Known.Zero |= RHSKnown.Zero;
555 Known.One |= RHSKnown.One;
Hal Finkel60db0582014-09-07 18:57:58 +0000556 // assume(v & b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000557 } else if (match(Arg,
558 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000559 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000560 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000561 KnownBits RHSKnown(BitWidth);
562 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
563 KnownBits MaskKnown(BitWidth);
564 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel60db0582014-09-07 18:57:58 +0000565
566 // For those bits in the mask that are known to be one, we can propagate
567 // known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000568 Known.Zero |= RHSKnown.Zero & MaskKnown.One;
569 Known.One |= RHSKnown.One & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000570 // assume(~(v & b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000571 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
572 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000573 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000574 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000575 KnownBits RHSKnown(BitWidth);
576 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
577 KnownBits MaskKnown(BitWidth);
578 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000579
580 // For those bits in the mask that are known to be one, we can propagate
581 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000582 Known.Zero |= RHSKnown.One & MaskKnown.One;
583 Known.One |= RHSKnown.Zero & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000584 // assume(v | b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000585 } else if (match(Arg,
586 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000587 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000588 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000589 KnownBits RHSKnown(BitWidth);
590 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
591 KnownBits BKnown(BitWidth);
592 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000593
594 // For those bits in B that are known to be zero, we can propagate known
595 // bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000596 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
597 Known.One |= RHSKnown.One & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000598 // assume(~(v | b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000599 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
600 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000601 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000602 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000603 KnownBits RHSKnown(BitWidth);
604 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
605 KnownBits BKnown(BitWidth);
606 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000607
608 // For those bits in B that are known to be zero, we can propagate
609 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000610 Known.Zero |= RHSKnown.One & BKnown.Zero;
611 Known.One |= RHSKnown.Zero & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000612 // assume(v ^ b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000613 } else if (match(Arg,
614 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000615 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000616 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000617 KnownBits RHSKnown(BitWidth);
618 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
619 KnownBits BKnown(BitWidth);
620 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000621
622 // For those bits in B that are known to be zero, we can propagate known
623 // bits from the RHS to V. For those bits in B that are known to be one,
624 // we can propagate inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000625 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
626 Known.One |= RHSKnown.One & BKnown.Zero;
627 Known.Zero |= RHSKnown.One & BKnown.One;
628 Known.One |= RHSKnown.Zero & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000629 // assume(~(v ^ b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000630 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
631 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000632 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000633 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000634 KnownBits RHSKnown(BitWidth);
635 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
636 KnownBits BKnown(BitWidth);
637 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000638
639 // For those bits in B that are known to be zero, we can propagate
640 // inverted known bits from the RHS to V. For those bits in B that are
641 // known to be one, we can propagate known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000642 Known.Zero |= RHSKnown.One & BKnown.Zero;
643 Known.One |= RHSKnown.Zero & BKnown.Zero;
644 Known.Zero |= RHSKnown.Zero & BKnown.One;
645 Known.One |= RHSKnown.One & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000646 // assume(v << c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000647 } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
648 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000649 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000650 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000651 KnownBits RHSKnown(BitWidth);
652 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000653 // For those bits in RHS that are known, we can propagate them to known
654 // bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000655 RHSKnown.Zero.lshrInPlace(C->getZExtValue());
656 Known.Zero |= RHSKnown.Zero;
657 RHSKnown.One.lshrInPlace(C->getZExtValue());
658 Known.One |= RHSKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000659 // assume(~(v << c) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000660 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
661 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000662 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000663 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000664 KnownBits RHSKnown(BitWidth);
665 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000666 // For those bits in RHS that are known, we can propagate them inverted
667 // to known bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000668 RHSKnown.One.lshrInPlace(C->getZExtValue());
669 Known.Zero |= RHSKnown.One;
670 RHSKnown.Zero.lshrInPlace(C->getZExtValue());
671 Known.One |= RHSKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000672 // assume(v >> c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000673 } else if (match(Arg,
674 m_c_ICmp(Pred, m_CombineOr(m_LShr(m_V, m_ConstantInt(C)),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000675 m_AShr(m_V, m_ConstantInt(C))),
676 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000677 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000678 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000679 KnownBits RHSKnown(BitWidth);
680 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000681 // For those bits in RHS that are known, we can propagate them to known
682 // bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000683 Known.Zero |= RHSKnown.Zero << C->getZExtValue();
684 Known.One |= RHSKnown.One << C->getZExtValue();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000685 // assume(~(v >> c) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000686 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_CombineOr(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000687 m_LShr(m_V, m_ConstantInt(C)),
688 m_AShr(m_V, m_ConstantInt(C)))),
Philip Reames00d3b272014-11-24 23:44:28 +0000689 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000690 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000691 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000692 KnownBits RHSKnown(BitWidth);
693 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000694 // For those bits in RHS that are known, we can propagate them inverted
695 // to known bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000696 Known.Zero |= RHSKnown.One << C->getZExtValue();
697 Known.One |= RHSKnown.Zero << C->getZExtValue();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000698 // assume(v >=_s c) where c is non-negative
Philip Reames00d3b272014-11-24 23:44:28 +0000699 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000700 Pred == ICmpInst::ICMP_SGE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000701 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000702 KnownBits RHSKnown(BitWidth);
703 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000704
Craig Topperca48af32017-04-29 16:43:11 +0000705 if (RHSKnown.isNonNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000706 // We know that the sign bit is zero.
Craig Topperca48af32017-04-29 16:43:11 +0000707 Known.makeNonNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000708 }
709 // assume(v >_s c) where c is at least -1.
Philip Reames00d3b272014-11-24 23:44:28 +0000710 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000711 Pred == ICmpInst::ICMP_SGT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000712 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000713 KnownBits RHSKnown(BitWidth);
714 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000715
Craig Topperf0aeee02017-05-05 17:36:09 +0000716 if (RHSKnown.isAllOnes() || RHSKnown.isNonNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000717 // We know that the sign bit is zero.
Craig Topperca48af32017-04-29 16:43:11 +0000718 Known.makeNonNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000719 }
720 // assume(v <=_s c) where c is negative
Philip Reames00d3b272014-11-24 23:44:28 +0000721 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000722 Pred == ICmpInst::ICMP_SLE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000723 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000724 KnownBits RHSKnown(BitWidth);
725 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000726
Craig Topperca48af32017-04-29 16:43:11 +0000727 if (RHSKnown.isNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000728 // We know that the sign bit is one.
Craig Topperca48af32017-04-29 16:43:11 +0000729 Known.makeNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000730 }
731 // assume(v <_s c) where c is non-positive
Philip Reames00d3b272014-11-24 23:44:28 +0000732 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000733 Pred == ICmpInst::ICMP_SLT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000734 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000735 KnownBits RHSKnown(BitWidth);
736 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000737
Craig Topperf0aeee02017-05-05 17:36:09 +0000738 if (RHSKnown.isZero() || RHSKnown.isNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000739 // We know that the sign bit is one.
Craig Topperca48af32017-04-29 16:43:11 +0000740 Known.makeNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000741 }
742 // assume(v <=_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000743 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000744 Pred == ICmpInst::ICMP_ULE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000745 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000746 KnownBits RHSKnown(BitWidth);
747 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000748
749 // Whatever high bits in c are zero are known to be zero.
Craig Topper8df66c62017-05-12 17:20:30 +0000750 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
751 // assume(v <_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000752 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000753 Pred == ICmpInst::ICMP_ULT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000754 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000755 KnownBits RHSKnown(BitWidth);
756 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000757
758 // Whatever high bits in c are zero are known to be zero (if c is a power
759 // of 2, then one more).
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000760 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I)))
Craig Topper8df66c62017-05-12 17:20:30 +0000761 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros() + 1);
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000762 else
Craig Topper8df66c62017-05-12 17:20:30 +0000763 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
Hal Finkel60db0582014-09-07 18:57:58 +0000764 }
765 }
Sanjay Patel25f6d712017-02-01 15:41:32 +0000766
767 // If assumptions conflict with each other or previous known bits, then we
Sanjay Patel54656ca2017-02-06 18:26:06 +0000768 // have a logical fallacy. It's possible that the assumption is not reachable,
769 // so this isn't a real bug. On the other hand, the program may have undefined
770 // behavior, or we might have a bug in the compiler. We can't assert/crash, so
771 // clear out the known bits, try to warn the user, and hope for the best.
Craig Topperb45eabc2017-04-26 16:39:58 +0000772 if (Known.Zero.intersects(Known.One)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000773 Known.resetAll();
Sanjay Patel54656ca2017-02-06 18:26:06 +0000774
775 if (Q.ORE) {
776 auto *CxtI = const_cast<Instruction *>(Q.CxtI);
777 OptimizationRemarkAnalysis ORA("value-tracking", "BadAssumption", CxtI);
778 Q.ORE->emit(ORA << "Detected conflicting code assumptions. Program may "
779 "have undefined behavior, or compiler may have "
780 "internal error.");
781 }
Sanjay Patel25f6d712017-02-01 15:41:32 +0000782 }
Hal Finkel60db0582014-09-07 18:57:58 +0000783}
784
Hal Finkelf2199b22015-10-23 20:37:08 +0000785// Compute known bits from a shift operator, including those with a
Craig Topperb45eabc2017-04-26 16:39:58 +0000786// non-constant shift amount. Known is the outputs of this function. Known2 is a
787// pre-allocated temporary with the/ same bit width as Known. KZF and KOF are
788// operator-specific functors that, given the known-zero or known-one bits
789// respectively, and a shift amount, compute the implied known-zero or known-one
790// bits of the shift operator's result respectively for that shift amount. The
791// results from calling KZF and KOF are conservatively combined for all
792// permitted shift amounts.
David Majnemer54690dc2016-08-23 20:52:00 +0000793static void computeKnownBitsFromShiftOperator(
Craig Topperb45eabc2017-04-26 16:39:58 +0000794 const Operator *I, KnownBits &Known, KnownBits &Known2,
795 unsigned Depth, const Query &Q,
David Majnemer54690dc2016-08-23 20:52:00 +0000796 function_ref<APInt(const APInt &, unsigned)> KZF,
797 function_ref<APInt(const APInt &, unsigned)> KOF) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000798 unsigned BitWidth = Known.getBitWidth();
Hal Finkelf2199b22015-10-23 20:37:08 +0000799
800 if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
801 unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1);
802
Craig Topperb45eabc2017-04-26 16:39:58 +0000803 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
804 Known.Zero = KZF(Known.Zero, ShiftAmt);
805 Known.One = KOF(Known.One, ShiftAmt);
806 // If there is conflict between Known.Zero and Known.One, this must be an
807 // overflowing left shift, so the shift result is undefined. Clear Known
808 // bits so that other code could propagate this undef.
Craig Topperf0aeee02017-05-05 17:36:09 +0000809 if ((Known.Zero & Known.One) != 0)
810 Known.resetAll();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +0000811
Hal Finkelf2199b22015-10-23 20:37:08 +0000812 return;
813 }
814
Craig Topperb45eabc2017-04-26 16:39:58 +0000815 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000816
Oliver Stannard06204112017-03-14 10:13:17 +0000817 // If the shift amount could be greater than or equal to the bit-width of the LHS, the
818 // value could be undef, so we don't know anything about it.
Craig Topperb45eabc2017-04-26 16:39:58 +0000819 if ((~Known.Zero).uge(BitWidth)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000820 Known.resetAll();
Oliver Stannard06204112017-03-14 10:13:17 +0000821 return;
822 }
823
Craig Topperb45eabc2017-04-26 16:39:58 +0000824 // Note: We cannot use Known.Zero.getLimitedValue() here, because if
Hal Finkelf2199b22015-10-23 20:37:08 +0000825 // BitWidth > 64 and any upper bits are known, we'll end up returning the
826 // limit value (which implies all bits are known).
Craig Topperb45eabc2017-04-26 16:39:58 +0000827 uint64_t ShiftAmtKZ = Known.Zero.zextOrTrunc(64).getZExtValue();
828 uint64_t ShiftAmtKO = Known.One.zextOrTrunc(64).getZExtValue();
Hal Finkelf2199b22015-10-23 20:37:08 +0000829
830 // It would be more-clearly correct to use the two temporaries for this
831 // calculation. Reusing the APInts here to prevent unnecessary allocations.
Craig Topperf0aeee02017-05-05 17:36:09 +0000832 Known.resetAll();
Hal Finkelf2199b22015-10-23 20:37:08 +0000833
James Molloy493e57d2015-10-26 14:10:46 +0000834 // If we know the shifter operand is nonzero, we can sometimes infer more
835 // known bits. However this is expensive to compute, so be lazy about it and
836 // only compute it when absolutely necessary.
837 Optional<bool> ShifterOperandIsNonZero;
838
Hal Finkelf2199b22015-10-23 20:37:08 +0000839 // Early exit if we can't constrain any well-defined shift amount.
James Molloy493e57d2015-10-26 14:10:46 +0000840 if (!(ShiftAmtKZ & (BitWidth - 1)) && !(ShiftAmtKO & (BitWidth - 1))) {
841 ShifterOperandIsNonZero =
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000842 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000843 if (!*ShifterOperandIsNonZero)
844 return;
845 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000846
Craig Topperb45eabc2017-04-26 16:39:58 +0000847 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000848
Craig Topperb45eabc2017-04-26 16:39:58 +0000849 Known.Zero.setAllBits();
850 Known.One.setAllBits();
Hal Finkelf2199b22015-10-23 20:37:08 +0000851 for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
852 // Combine the shifted known input bits only for those shift amounts
853 // compatible with its known constraints.
854 if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
855 continue;
856 if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
857 continue;
James Molloy493e57d2015-10-26 14:10:46 +0000858 // If we know the shifter is nonzero, we may be able to infer more known
859 // bits. This check is sunk down as far as possible to avoid the expensive
860 // call to isKnownNonZero if the cheaper checks above fail.
861 if (ShiftAmt == 0) {
862 if (!ShifterOperandIsNonZero.hasValue())
863 ShifterOperandIsNonZero =
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000864 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000865 if (*ShifterOperandIsNonZero)
866 continue;
867 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000868
Craig Topperb45eabc2017-04-26 16:39:58 +0000869 Known.Zero &= KZF(Known2.Zero, ShiftAmt);
870 Known.One &= KOF(Known2.One, ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +0000871 }
872
873 // If there are no compatible shift amounts, then we've proven that the shift
874 // amount must be >= the BitWidth, and the result is undefined. We could
875 // return anything we'd like, but we need to make sure the sets of known bits
876 // stay disjoint (it should be better for some other code to actually
877 // propagate the undef than to pick a value here using known bits).
Craig Topperf0aeee02017-05-05 17:36:09 +0000878 if (Known.Zero.intersects(Known.One))
879 Known.resetAll();
Hal Finkelf2199b22015-10-23 20:37:08 +0000880}
881
Craig Topperb45eabc2017-04-26 16:39:58 +0000882static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known,
883 unsigned Depth, const Query &Q) {
884 unsigned BitWidth = Known.getBitWidth();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000885
Craig Topperb45eabc2017-04-26 16:39:58 +0000886 KnownBits Known2(Known);
Dan Gohman80ca01c2009-07-17 20:47:02 +0000887 switch (I->getOpcode()) {
Chris Lattner965c7692008-06-02 01:18:21 +0000888 default: break;
Rafael Espindola53190532012-03-30 15:52:11 +0000889 case Instruction::Load:
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000890 if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +0000891 computeKnownBitsFromRangeMetadata(*MD, Known);
Jay Foad5a29c362014-05-15 12:12:55 +0000892 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000893 case Instruction::And: {
894 // If either the LHS or the RHS are Zero, the result is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +0000895 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
896 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000897
Chris Lattner965c7692008-06-02 01:18:21 +0000898 // Output known-1 bits are only known if set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000899 Known.One &= Known2.One;
Chris Lattner965c7692008-06-02 01:18:21 +0000900 // Output known-0 are known to be clear if zero in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000901 Known.Zero |= Known2.Zero;
Philip Reames2d858742015-11-10 18:46:14 +0000902
903 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
904 // here we handle the more general case of adding any odd number by
905 // matching the form add(x, add(x, y)) where y is odd.
906 // TODO: This could be generalized to clearing any bit set in y where the
907 // following bit is known to be unset in y.
908 Value *Y = nullptr;
Craig Topperb45eabc2017-04-26 16:39:58 +0000909 if (!Known.Zero[0] && !Known.One[0] &&
Craig Toppera80f2042017-04-13 19:04:45 +0000910 (match(I->getOperand(0), m_Add(m_Specific(I->getOperand(1)),
911 m_Value(Y))) ||
912 match(I->getOperand(1), m_Add(m_Specific(I->getOperand(0)),
913 m_Value(Y))))) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000914 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000915 computeKnownBits(Y, Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +0000916 if (Known2.countMinTrailingOnes() > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +0000917 Known.Zero.setBit(0);
Philip Reames2d858742015-11-10 18:46:14 +0000918 }
Jay Foad5a29c362014-05-15 12:12:55 +0000919 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000920 }
921 case Instruction::Or: {
Craig Topperb45eabc2017-04-26 16:39:58 +0000922 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
923 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000924
Chris Lattner965c7692008-06-02 01:18:21 +0000925 // Output known-0 bits are only known if clear in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000926 Known.Zero &= Known2.Zero;
Chris Lattner965c7692008-06-02 01:18:21 +0000927 // Output known-1 are known to be set if set in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000928 Known.One |= Known2.One;
Jay Foad5a29c362014-05-15 12:12:55 +0000929 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000930 }
931 case Instruction::Xor: {
Craig Topperb45eabc2017-04-26 16:39:58 +0000932 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
933 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000934
Chris Lattner965c7692008-06-02 01:18:21 +0000935 // Output known-0 bits are known if clear or set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000936 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
Chris Lattner965c7692008-06-02 01:18:21 +0000937 // Output known-1 are known to be set if set in only one of the LHS, RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000938 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
939 Known.Zero = std::move(KnownZeroOut);
Jay Foad5a29c362014-05-15 12:12:55 +0000940 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000941 }
942 case Instruction::Mul: {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000943 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Craig Topperb45eabc2017-04-26 16:39:58 +0000944 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, Known,
945 Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000946 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000947 }
948 case Instruction::UDiv: {
949 // For the purposes of computing leading zeros we can conservatively
950 // treat a udiv as a logical right shift by the power of 2 known to
951 // be less than the denominator.
Craig Topperb45eabc2017-04-26 16:39:58 +0000952 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +0000953 unsigned LeadZ = Known2.countMinLeadingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +0000954
Craig Topperf0aeee02017-05-05 17:36:09 +0000955 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000956 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +0000957 unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
958 if (RHSMaxLeadingZeros != BitWidth)
959 LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
Chris Lattner965c7692008-06-02 01:18:21 +0000960
Craig Topperb45eabc2017-04-26 16:39:58 +0000961 Known.Zero.setHighBits(LeadZ);
Jay Foad5a29c362014-05-15 12:12:55 +0000962 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000963 }
David Majnemera19d0f22016-08-06 08:16:00 +0000964 case Instruction::Select: {
Craig Toppere953dec2017-04-13 20:39:37 +0000965 const Value *LHS, *RHS;
David Majnemera19d0f22016-08-06 08:16:00 +0000966 SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
967 if (SelectPatternResult::isMinOrMax(SPF)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000968 computeKnownBits(RHS, Known, Depth + 1, Q);
969 computeKnownBits(LHS, Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +0000970 } else {
Craig Topperb45eabc2017-04-26 16:39:58 +0000971 computeKnownBits(I->getOperand(2), Known, Depth + 1, Q);
972 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +0000973 }
974
975 unsigned MaxHighOnes = 0;
976 unsigned MaxHighZeros = 0;
977 if (SPF == SPF_SMAX) {
978 // If both sides are negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +0000979 if (Known.isNegative() && Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +0000980 // We can derive a lower bound on the result by taking the max of the
981 // leading one bits.
Craig Topper8df66c62017-05-12 17:20:30 +0000982 MaxHighOnes =
983 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +0000984 // If either side is non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +0000985 else if (Known.isNonNegative() || Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +0000986 MaxHighZeros = 1;
987 } else if (SPF == SPF_SMIN) {
988 // If both sides are non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +0000989 if (Known.isNonNegative() && Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +0000990 // We can derive an upper bound on the result by taking the max of the
991 // leading zero bits.
Craig Topper8df66c62017-05-12 17:20:30 +0000992 MaxHighZeros = std::max(Known.countMinLeadingZeros(),
993 Known2.countMinLeadingZeros());
David Majnemera19d0f22016-08-06 08:16:00 +0000994 // If either side is negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +0000995 else if (Known.isNegative() || Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +0000996 MaxHighOnes = 1;
997 } else if (SPF == SPF_UMAX) {
998 // We can derive a lower bound on the result by taking the max of the
999 // leading one bits.
1000 MaxHighOnes =
Craig Topper8df66c62017-05-12 17:20:30 +00001001 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001002 } else if (SPF == SPF_UMIN) {
1003 // We can derive an upper bound on the result by taking the max of the
1004 // leading zero bits.
1005 MaxHighZeros =
Craig Topper8df66c62017-05-12 17:20:30 +00001006 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
David Majnemera19d0f22016-08-06 08:16:00 +00001007 }
1008
Chris Lattner965c7692008-06-02 01:18:21 +00001009 // Only known if known in both the LHS and RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001010 Known.One &= Known2.One;
1011 Known.Zero &= Known2.Zero;
David Majnemera19d0f22016-08-06 08:16:00 +00001012 if (MaxHighOnes > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001013 Known.One.setHighBits(MaxHighOnes);
David Majnemera19d0f22016-08-06 08:16:00 +00001014 if (MaxHighZeros > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001015 Known.Zero.setHighBits(MaxHighZeros);
Jay Foad5a29c362014-05-15 12:12:55 +00001016 break;
David Majnemera19d0f22016-08-06 08:16:00 +00001017 }
Chris Lattner965c7692008-06-02 01:18:21 +00001018 case Instruction::FPTrunc:
1019 case Instruction::FPExt:
1020 case Instruction::FPToUI:
1021 case Instruction::FPToSI:
1022 case Instruction::SIToFP:
1023 case Instruction::UIToFP:
Jay Foad5a29c362014-05-15 12:12:55 +00001024 break; // Can't work with floating point.
Chris Lattner965c7692008-06-02 01:18:21 +00001025 case Instruction::PtrToInt:
1026 case Instruction::IntToPtr:
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001027 // Fall through and handle them the same as zext/trunc.
1028 LLVM_FALLTHROUGH;
Chris Lattner965c7692008-06-02 01:18:21 +00001029 case Instruction::ZExt:
1030 case Instruction::Trunc: {
Chris Lattner229907c2011-07-18 04:54:35 +00001031 Type *SrcTy = I->getOperand(0)->getType();
Nadav Rotem15198e92012-10-26 17:17:05 +00001032
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001033 unsigned SrcBitWidth;
Chris Lattner965c7692008-06-02 01:18:21 +00001034 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1035 // which fall through here.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001036 SrcBitWidth = Q.DL.getTypeSizeInBits(SrcTy->getScalarType());
Nadav Rotem15198e92012-10-26 17:17:05 +00001037
1038 assert(SrcBitWidth && "SrcBitWidth can't be zero");
Craig Topperd938fd12017-05-03 22:07:25 +00001039 Known = Known.zextOrTrunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001040 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Craig Topperd938fd12017-05-03 22:07:25 +00001041 Known = Known.zextOrTrunc(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +00001042 // Any top bits are known to be zero.
1043 if (BitWidth > SrcBitWidth)
Craig Topperb45eabc2017-04-26 16:39:58 +00001044 Known.Zero.setBitsFrom(SrcBitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001045 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001046 }
1047 case Instruction::BitCast: {
Chris Lattner229907c2011-07-18 04:54:35 +00001048 Type *SrcTy = I->getOperand(0)->getType();
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001049 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattneredb84072009-07-02 16:04:08 +00001050 // TODO: For now, not handling conversions like:
1051 // (bitcast i64 %x to <2 x i32>)
Duncan Sands19d0b472010-02-16 11:11:14 +00001052 !I->getType()->isVectorTy()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001053 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Jay Foad5a29c362014-05-15 12:12:55 +00001054 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001055 }
1056 break;
1057 }
1058 case Instruction::SExt: {
1059 // Compute the bits in the result that are not present in the input.
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001060 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Craig Topper1bef2c82012-12-22 19:15:35 +00001061
Craig Topperd938fd12017-05-03 22:07:25 +00001062 Known = Known.trunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001063 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001064 // If the sign bit of the input is known set or clear, then we know the
1065 // top bits of the result.
Craig Topperd938fd12017-05-03 22:07:25 +00001066 Known = Known.sext(BitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001067 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001068 }
Hal Finkelf2199b22015-10-23 20:37:08 +00001069 case Instruction::Shl: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001070 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001071 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Craig Topperd73c6b42017-03-23 07:06:39 +00001072 auto KZF = [NSW](const APInt &KnownZero, unsigned ShiftAmt) {
1073 APInt KZResult = KnownZero << ShiftAmt;
1074 KZResult.setLowBits(ShiftAmt); // Low bits known 0.
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001075 // If this shift has "nsw" keyword, then the result is either a poison
1076 // value or has the same sign bit as the first operand.
Craig Topperd23004c2017-04-17 16:38:20 +00001077 if (NSW && KnownZero.isSignBitSet())
Craig Topperd73c6b42017-03-23 07:06:39 +00001078 KZResult.setSignBit();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001079 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001080 };
1081
Craig Topperd73c6b42017-03-23 07:06:39 +00001082 auto KOF = [NSW](const APInt &KnownOne, unsigned ShiftAmt) {
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001083 APInt KOResult = KnownOne << ShiftAmt;
Craig Topperd23004c2017-04-17 16:38:20 +00001084 if (NSW && KnownOne.isSignBitSet())
Craig Topperd73c6b42017-03-23 07:06:39 +00001085 KOResult.setSignBit();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001086 return KOResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001087 };
1088
Craig Topperb45eabc2017-04-26 16:39:58 +00001089 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001090 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001091 }
1092 case Instruction::LShr: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001093 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Craig Topperfc947bc2017-04-18 17:14:21 +00001094 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1095 APInt KZResult = KnownZero.lshr(ShiftAmt);
1096 // High bits known zero.
1097 KZResult.setHighBits(ShiftAmt);
1098 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001099 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001100
Malcolm Parsons17d266b2017-01-13 17:12:16 +00001101 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
Craig Topper885fa122017-03-31 20:01:16 +00001102 return KnownOne.lshr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001103 };
1104
Craig Topperb45eabc2017-04-26 16:39:58 +00001105 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001106 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001107 }
1108 case Instruction::AShr: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001109 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Malcolm Parsons17d266b2017-01-13 17:12:16 +00001110 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
Craig Topper885fa122017-03-31 20:01:16 +00001111 return KnownZero.ashr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001112 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001113
Malcolm Parsons17d266b2017-01-13 17:12:16 +00001114 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
Craig Topper885fa122017-03-31 20:01:16 +00001115 return KnownOne.ashr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001116 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001117
Craig Topperb45eabc2017-04-26 16:39:58 +00001118 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001119 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001120 }
Chris Lattner965c7692008-06-02 01:18:21 +00001121 case Instruction::Sub: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001122 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001123 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001124 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001125 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001126 }
Chris Lattner965c7692008-06-02 01:18:21 +00001127 case Instruction::Add: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001128 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001129 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001130 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001131 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001132 }
1133 case Instruction::SRem:
1134 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001135 APInt RA = Rem->getValue().abs();
1136 if (RA.isPowerOf2()) {
1137 APInt LowBits = RA - 1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001138 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001139
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001140 // The low bits of the first operand are unchanged by the srem.
Craig Topperb45eabc2017-04-26 16:39:58 +00001141 Known.Zero = Known2.Zero & LowBits;
1142 Known.One = Known2.One & LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001143
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001144 // If the first operand is non-negative or has all low bits zero, then
1145 // the upper bits are all zero.
Craig Topperca48af32017-04-29 16:43:11 +00001146 if (Known2.isNonNegative() || LowBits.isSubsetOf(Known2.Zero))
Craig Topperb45eabc2017-04-26 16:39:58 +00001147 Known.Zero |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001148
1149 // If the first operand is negative and not all low bits are zero, then
1150 // the upper bits are all one.
Craig Topperca48af32017-04-29 16:43:11 +00001151 if (Known2.isNegative() && LowBits.intersects(Known2.One))
Craig Topperb45eabc2017-04-26 16:39:58 +00001152 Known.One |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001153
Craig Topperb45eabc2017-04-26 16:39:58 +00001154 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Craig Topperda886c62017-04-16 21:46:12 +00001155 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001156 }
1157 }
Nick Lewyckye4679792011-03-07 01:50:10 +00001158
1159 // The sign bit is the LHS's sign bit, except when the result of the
1160 // remainder is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +00001161 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topperda886c62017-04-16 21:46:12 +00001162 // If it's known zero, our sign bit is also zero.
Craig Topperca48af32017-04-29 16:43:11 +00001163 if (Known2.isNonNegative())
1164 Known.makeNonNegative();
Nick Lewyckye4679792011-03-07 01:50:10 +00001165
Chris Lattner965c7692008-06-02 01:18:21 +00001166 break;
1167 case Instruction::URem: {
1168 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001169 const APInt &RA = Rem->getValue();
Chris Lattner965c7692008-06-02 01:18:21 +00001170 if (RA.isPowerOf2()) {
1171 APInt LowBits = (RA - 1);
Craig Topperb45eabc2017-04-26 16:39:58 +00001172 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1173 Known.Zero |= ~LowBits;
1174 Known.One &= LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001175 break;
1176 }
1177 }
1178
1179 // Since the result is less than or equal to either operand, any leading
1180 // zero bits in either operand must also exist in the result.
Craig Topperb45eabc2017-04-26 16:39:58 +00001181 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1182 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001183
Craig Topper8df66c62017-05-12 17:20:30 +00001184 unsigned Leaders =
1185 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
Craig Topperf0aeee02017-05-05 17:36:09 +00001186 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001187 Known.Zero.setHighBits(Leaders);
Chris Lattner965c7692008-06-02 01:18:21 +00001188 break;
1189 }
1190
Victor Hernandeza3aaf852009-10-17 01:18:07 +00001191 case Instruction::Alloca: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001192 const AllocaInst *AI = cast<AllocaInst>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001193 unsigned Align = AI->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001194 if (Align == 0)
Eduard Burtescu90c44492016-01-18 00:10:01 +00001195 Align = Q.DL.getABITypeAlignment(AI->getAllocatedType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001196
Chris Lattner965c7692008-06-02 01:18:21 +00001197 if (Align > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001198 Known.Zero.setLowBits(countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +00001199 break;
1200 }
1201 case Instruction::GetElementPtr: {
1202 // Analyze all of the subscripts of this getelementptr instruction
1203 // to determine if we can prove known low zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001204 KnownBits LocalKnown(BitWidth);
1205 computeKnownBits(I->getOperand(0), LocalKnown, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001206 unsigned TrailZ = LocalKnown.countMinTrailingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +00001207
1208 gep_type_iterator GTI = gep_type_begin(I);
1209 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1210 Value *Index = I->getOperand(i);
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001211 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chris Lattner965c7692008-06-02 01:18:21 +00001212 // Handle struct member offset arithmetic.
Matt Arsenault74742a12013-08-19 21:43:16 +00001213
1214 // Handle case when index is vector zeroinitializer
1215 Constant *CIndex = cast<Constant>(Index);
1216 if (CIndex->isZeroValue())
1217 continue;
1218
1219 if (CIndex->getType()->isVectorTy())
1220 Index = CIndex->getSplatValue();
1221
Chris Lattner965c7692008-06-02 01:18:21 +00001222 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001223 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chris Lattner965c7692008-06-02 01:18:21 +00001224 uint64_t Offset = SL->getElementOffset(Idx);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001225 TrailZ = std::min<unsigned>(TrailZ,
1226 countTrailingZeros(Offset));
Chris Lattner965c7692008-06-02 01:18:21 +00001227 } else {
1228 // Handle array index arithmetic.
Chris Lattner229907c2011-07-18 04:54:35 +00001229 Type *IndexedTy = GTI.getIndexedType();
Jay Foad5a29c362014-05-15 12:12:55 +00001230 if (!IndexedTy->isSized()) {
1231 TrailZ = 0;
1232 break;
1233 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001234 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001235 uint64_t TypeSize = Q.DL.getTypeAllocSize(IndexedTy);
Craig Topperb45eabc2017-04-26 16:39:58 +00001236 LocalKnown.Zero = LocalKnown.One = APInt(GEPOpiBits, 0);
1237 computeKnownBits(Index, LocalKnown, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001238 TrailZ = std::min(TrailZ,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001239 unsigned(countTrailingZeros(TypeSize) +
Craig Topper8df66c62017-05-12 17:20:30 +00001240 LocalKnown.countMinTrailingZeros()));
Chris Lattner965c7692008-06-02 01:18:21 +00001241 }
1242 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001243
Craig Topperb45eabc2017-04-26 16:39:58 +00001244 Known.Zero.setLowBits(TrailZ);
Chris Lattner965c7692008-06-02 01:18:21 +00001245 break;
1246 }
1247 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001248 const PHINode *P = cast<PHINode>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001249 // Handle the case of a simple two-predecessor recurrence PHI.
1250 // There's a lot more that could theoretically be done here, but
1251 // this is sufficient to catch some interesting cases.
1252 if (P->getNumIncomingValues() == 2) {
1253 for (unsigned i = 0; i != 2; ++i) {
1254 Value *L = P->getIncomingValue(i);
1255 Value *R = P->getIncomingValue(!i);
Dan Gohman80ca01c2009-07-17 20:47:02 +00001256 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner965c7692008-06-02 01:18:21 +00001257 if (!LU)
1258 continue;
Dan Gohman80ca01c2009-07-17 20:47:02 +00001259 unsigned Opcode = LU->getOpcode();
Chris Lattner965c7692008-06-02 01:18:21 +00001260 // Check for operations that have the property that if
1261 // both their operands have low zero bits, the result
Artur Pilipenkobc76eca2016-08-22 13:14:07 +00001262 // will have low zero bits.
Chris Lattner965c7692008-06-02 01:18:21 +00001263 if (Opcode == Instruction::Add ||
1264 Opcode == Instruction::Sub ||
1265 Opcode == Instruction::And ||
1266 Opcode == Instruction::Or ||
1267 Opcode == Instruction::Mul) {
1268 Value *LL = LU->getOperand(0);
1269 Value *LR = LU->getOperand(1);
1270 // Find a recurrence.
1271 if (LL == I)
1272 L = LR;
1273 else if (LR == I)
1274 L = LL;
1275 else
1276 break;
1277 // Ok, we have a PHI of the form L op= R. Check for low
1278 // zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001279 computeKnownBits(R, Known2, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001280
1281 // We need to take the minimum number of known bits
Craig Topperb45eabc2017-04-26 16:39:58 +00001282 KnownBits Known3(Known);
1283 computeKnownBits(L, Known3, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001284
Craig Topper8df66c62017-05-12 17:20:30 +00001285 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1286 Known3.countMinTrailingZeros()));
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001287
1288 if (DontImproveNonNegativePhiBits)
1289 break;
1290
1291 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(LU);
1292 if (OverflowOp && OverflowOp->hasNoSignedWrap()) {
1293 // If initial value of recurrence is nonnegative, and we are adding
1294 // a nonnegative number with nsw, the result can only be nonnegative
1295 // or poison value regardless of the number of times we execute the
1296 // add in phi recurrence. If initial value is negative and we are
1297 // adding a negative number with nsw, the result can only be
1298 // negative or poison value. Similar arguments apply to sub and mul.
1299 //
1300 // (add non-negative, non-negative) --> non-negative
1301 // (add negative, negative) --> negative
1302 if (Opcode == Instruction::Add) {
Craig Topperca48af32017-04-29 16:43:11 +00001303 if (Known2.isNonNegative() && Known3.isNonNegative())
1304 Known.makeNonNegative();
1305 else if (Known2.isNegative() && Known3.isNegative())
1306 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001307 }
1308
1309 // (sub nsw non-negative, negative) --> non-negative
1310 // (sub nsw negative, non-negative) --> negative
1311 else if (Opcode == Instruction::Sub && LL == I) {
Craig Topperca48af32017-04-29 16:43:11 +00001312 if (Known2.isNonNegative() && Known3.isNegative())
1313 Known.makeNonNegative();
1314 else if (Known2.isNegative() && Known3.isNonNegative())
1315 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001316 }
1317
1318 // (mul nsw non-negative, non-negative) --> non-negative
Craig Topperca48af32017-04-29 16:43:11 +00001319 else if (Opcode == Instruction::Mul && Known2.isNonNegative() &&
1320 Known3.isNonNegative())
1321 Known.makeNonNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001322 }
1323
Chris Lattner965c7692008-06-02 01:18:21 +00001324 break;
1325 }
1326 }
1327 }
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001328
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001329 // Unreachable blocks may have zero-operand PHI nodes.
1330 if (P->getNumIncomingValues() == 0)
Jay Foad5a29c362014-05-15 12:12:55 +00001331 break;
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001332
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001333 // Otherwise take the unions of the known bit sets of the operands,
1334 // taking conservative care to avoid excessive recursion.
Craig Topperb45eabc2017-04-26 16:39:58 +00001335 if (Depth < MaxDepth - 1 && !Known.Zero && !Known.One) {
Duncan Sands7dc3d472011-03-08 12:39:03 +00001336 // Skip if every incoming value references to ourself.
Nuno Lopes0d44a502012-07-03 21:15:40 +00001337 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
Duncan Sands7dc3d472011-03-08 12:39:03 +00001338 break;
1339
Craig Topperb45eabc2017-04-26 16:39:58 +00001340 Known.Zero.setAllBits();
1341 Known.One.setAllBits();
Pete Cooper833f34d2015-05-12 20:05:31 +00001342 for (Value *IncValue : P->incoming_values()) {
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001343 // Skip direct self references.
Pete Cooper833f34d2015-05-12 20:05:31 +00001344 if (IncValue == P) continue;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001345
Craig Topperb45eabc2017-04-26 16:39:58 +00001346 Known2 = KnownBits(BitWidth);
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001347 // Recurse, but cap the recursion to one level, because we don't
1348 // want to waste time spinning around in loops.
Craig Topperb45eabc2017-04-26 16:39:58 +00001349 computeKnownBits(IncValue, Known2, MaxDepth - 1, Q);
1350 Known.Zero &= Known2.Zero;
1351 Known.One &= Known2.One;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001352 // If all bits have been ruled out, there's no need to check
1353 // more operands.
Craig Topperb45eabc2017-04-26 16:39:58 +00001354 if (!Known.Zero && !Known.One)
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001355 break;
1356 }
1357 }
Chris Lattner965c7692008-06-02 01:18:21 +00001358 break;
1359 }
1360 case Instruction::Call:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001361 case Instruction::Invoke:
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001362 // If range metadata is attached to this call, set known bits from that,
1363 // and then intersect with known bits based on other properties of the
1364 // function.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001365 if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +00001366 computeKnownBitsFromRangeMetadata(*MD, Known);
Pete Cooper35b00d52016-08-13 01:05:32 +00001367 if (const Value *RV = ImmutableCallSite(I).getReturnedArgOperand()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001368 computeKnownBits(RV, Known2, Depth + 1, Q);
1369 Known.Zero |= Known2.Zero;
1370 Known.One |= Known2.One;
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001371 }
Pete Cooper35b00d52016-08-13 01:05:32 +00001372 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001373 switch (II->getIntrinsicID()) {
1374 default: break;
Chad Rosier85204292017-01-17 17:23:51 +00001375 case Intrinsic::bitreverse:
Craig Topperb45eabc2017-04-26 16:39:58 +00001376 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1377 Known.Zero |= Known2.Zero.reverseBits();
1378 Known.One |= Known2.One.reverseBits();
Chad Rosier85204292017-01-17 17:23:51 +00001379 break;
Philip Reames675418e2015-10-06 20:20:45 +00001380 case Intrinsic::bswap:
Craig Topperb45eabc2017-04-26 16:39:58 +00001381 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1382 Known.Zero |= Known2.Zero.byteSwap();
1383 Known.One |= Known2.One.byteSwap();
Philip Reames675418e2015-10-06 20:20:45 +00001384 break;
Craig Topper868813f2017-05-08 17:22:34 +00001385 case Intrinsic::ctlz: {
1386 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1387 // If we have a known 1, its position is our upper bound.
1388 unsigned PossibleLZ = Known2.One.countLeadingZeros();
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001389 // If this call is undefined for 0, the result will be less than 2^n.
1390 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
Craig Topper868813f2017-05-08 17:22:34 +00001391 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
1392 unsigned LowBits = Log2_32(PossibleLZ)+1;
1393 Known.Zero.setBitsFrom(LowBits);
1394 break;
1395 }
1396 case Intrinsic::cttz: {
1397 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1398 // If we have a known 1, its position is our upper bound.
1399 unsigned PossibleTZ = Known2.One.countTrailingZeros();
1400 // If this call is undefined for 0, the result will be less than 2^n.
1401 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1402 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
1403 unsigned LowBits = Log2_32(PossibleTZ)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001404 Known.Zero.setBitsFrom(LowBits);
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001405 break;
1406 }
1407 case Intrinsic::ctpop: {
Craig Topperb45eabc2017-04-26 16:39:58 +00001408 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001409 // We can bound the space the count needs. Also, bits known to be zero
1410 // can't contribute to the population.
Craig Topper8df66c62017-05-12 17:20:30 +00001411 unsigned BitsPossiblySet = Known2.countMaxPopulation();
Craig Topper66df10f2017-04-14 06:43:34 +00001412 unsigned LowBits = Log2_32(BitsPossiblySet)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001413 Known.Zero.setBitsFrom(LowBits);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001414 // TODO: we could bound KnownOne using the lower bound on the number
1415 // of bits which might be set provided by popcnt KnownOne2.
Chris Lattner965c7692008-06-02 01:18:21 +00001416 break;
1417 }
Chad Rosierb3628842011-05-26 23:13:19 +00001418 case Intrinsic::x86_sse42_crc32_64_64:
Craig Topperb45eabc2017-04-26 16:39:58 +00001419 Known.Zero.setBitsFrom(32);
Evan Cheng2a746bf2011-05-22 18:25:30 +00001420 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001421 }
1422 }
1423 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00001424 case Instruction::ExtractElement:
1425 // Look through extract element. At the moment we keep this simple and skip
1426 // tracking the specific element. But at least we might find information
1427 // valid for all elements of the vector (for example if vector is sign
1428 // extended, shifted, etc).
Craig Topperb45eabc2017-04-26 16:39:58 +00001429 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Bjorn Pettersson39616032016-10-06 09:56:21 +00001430 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001431 case Instruction::ExtractValue:
1432 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001433 const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001434 if (EVI->getNumIndices() != 1) break;
1435 if (EVI->getIndices()[0] == 0) {
1436 switch (II->getIntrinsicID()) {
1437 default: break;
1438 case Intrinsic::uadd_with_overflow:
1439 case Intrinsic::sadd_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001440 computeKnownBitsAddSub(true, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001441 II->getArgOperand(1), false, Known, Known2,
1442 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001443 break;
1444 case Intrinsic::usub_with_overflow:
1445 case Intrinsic::ssub_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001446 computeKnownBitsAddSub(false, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001447 II->getArgOperand(1), false, Known, Known2,
1448 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001449 break;
Nick Lewyckyfa306072012-03-18 23:28:48 +00001450 case Intrinsic::umul_with_overflow:
1451 case Intrinsic::smul_with_overflow:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001452 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
Craig Topperb45eabc2017-04-26 16:39:58 +00001453 Known, Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001454 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001455 }
1456 }
1457 }
Chris Lattner965c7692008-06-02 01:18:21 +00001458 }
Jingyue Wu12b0c282015-06-15 05:46:29 +00001459}
1460
1461/// Determine which bits of V are known to be either zero or one and return
Craig Topper6e11a052017-05-08 16:22:48 +00001462/// them.
1463KnownBits computeKnownBits(const Value *V, unsigned Depth, const Query &Q) {
1464 KnownBits Known(getBitWidth(V->getType(), Q.DL));
1465 computeKnownBits(V, Known, Depth, Q);
1466 return Known;
1467}
1468
1469/// Determine which bits of V are known to be either zero or one and return
Craig Topperb45eabc2017-04-26 16:39:58 +00001470/// them in the Known bit set.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001471///
1472/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
1473/// we cannot optimize based on the assumption that it is zero without changing
1474/// it to be an explicit zero. If we don't change it to zero, other code could
1475/// optimized based on the contradictory assumption that it is non-zero.
1476/// Because instcombine aggressively folds operations with undef args anyway,
1477/// this won't lose us code quality.
1478///
1479/// This function is defined on values with integer type, values with pointer
1480/// type, and vectors of integers. In the case
1481/// where V is a vector, known zero, and known one values are the
1482/// same width as the vector element, and the bit is set only if it is true
1483/// for all of the elements in the vector.
Craig Topperb45eabc2017-04-26 16:39:58 +00001484void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
1485 const Query &Q) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001486 assert(V && "No Value?");
1487 assert(Depth <= MaxDepth && "Limit Search Depth");
Craig Topperb45eabc2017-04-26 16:39:58 +00001488 unsigned BitWidth = Known.getBitWidth();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001489
1490 assert((V->getType()->isIntOrIntVectorTy() ||
1491 V->getType()->getScalarType()->isPointerTy()) &&
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001492 "Not integer or pointer type!");
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001493 assert((Q.DL.getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
Jingyue Wu12b0c282015-06-15 05:46:29 +00001494 (!V->getType()->isIntOrIntVectorTy() ||
1495 V->getType()->getScalarSizeInBits() == BitWidth) &&
Craig Topperb45eabc2017-04-26 16:39:58 +00001496 "V and Known should have same BitWidth");
Craig Topperd73c6b42017-03-23 07:06:39 +00001497 (void)BitWidth;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001498
Sanjay Patelc96f6db2016-09-16 21:20:36 +00001499 const APInt *C;
1500 if (match(V, m_APInt(C))) {
1501 // We know all of the bits for a scalar constant or a splat vector constant!
Craig Topperb45eabc2017-04-26 16:39:58 +00001502 Known.One = *C;
1503 Known.Zero = ~Known.One;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001504 return;
1505 }
1506 // Null and aggregate-zero are all-zeros.
Sanjay Patele8dc0902016-05-23 17:57:54 +00001507 if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001508 Known.setAllZero();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001509 return;
1510 }
1511 // Handle a constant vector by taking the intersection of the known bits of
David Majnemer3918cdd2016-05-04 06:13:33 +00001512 // each element.
Pete Cooper35b00d52016-08-13 01:05:32 +00001513 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001514 // We know that CDS must be a vector of integers. Take the intersection of
1515 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001516 Known.Zero.setAllBits(); Known.One.setAllBits();
Craig Topper9c932d32017-04-25 16:48:03 +00001517 APInt Elt(BitWidth, 0);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001518 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1519 Elt = CDS->getElementAsInteger(i);
Craig Topperb45eabc2017-04-26 16:39:58 +00001520 Known.Zero &= ~Elt;
1521 Known.One &= Elt;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001522 }
1523 return;
1524 }
1525
Pete Cooper35b00d52016-08-13 01:05:32 +00001526 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
David Majnemer3918cdd2016-05-04 06:13:33 +00001527 // We know that CV must be a vector of integers. Take the intersection of
1528 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001529 Known.Zero.setAllBits(); Known.One.setAllBits();
1530 APInt Elt(BitWidth, 0);
David Majnemer3918cdd2016-05-04 06:13:33 +00001531 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1532 Constant *Element = CV->getAggregateElement(i);
1533 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
1534 if (!ElementCI) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001535 Known.resetAll();
David Majnemer3918cdd2016-05-04 06:13:33 +00001536 return;
1537 }
1538 Elt = ElementCI->getValue();
Craig Topperb45eabc2017-04-26 16:39:58 +00001539 Known.Zero &= ~Elt;
1540 Known.One &= Elt;
David Majnemer3918cdd2016-05-04 06:13:33 +00001541 }
1542 return;
1543 }
1544
Jingyue Wu12b0c282015-06-15 05:46:29 +00001545 // Start out not knowing anything.
Craig Topperf0aeee02017-05-05 17:36:09 +00001546 Known.resetAll();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001547
Duncan P. N. Exon Smithb1b208a2016-09-24 20:42:02 +00001548 // We can't imply anything about undefs.
1549 if (isa<UndefValue>(V))
1550 return;
1551
1552 // There's no point in looking through other users of ConstantData for
1553 // assumptions. Confirm that we've handled them all.
1554 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
1555
Jingyue Wu12b0c282015-06-15 05:46:29 +00001556 // Limit search depth.
1557 // All recursive calls that increase depth must come after this.
1558 if (Depth == MaxDepth)
1559 return;
1560
1561 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1562 // the bits of its aliasee.
Pete Cooper35b00d52016-08-13 01:05:32 +00001563 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001564 if (!GA->isInterposable())
Craig Topperb45eabc2017-04-26 16:39:58 +00001565 computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001566 return;
1567 }
1568
Pete Cooper35b00d52016-08-13 01:05:32 +00001569 if (const Operator *I = dyn_cast<Operator>(V))
Craig Topperb45eabc2017-04-26 16:39:58 +00001570 computeKnownBitsFromOperator(I, Known, Depth, Q);
Sanjay Patela67559c2015-09-25 20:12:43 +00001571
Craig Topperb45eabc2017-04-26 16:39:58 +00001572 // Aligned pointers have trailing zeros - refine Known.Zero set
Artur Pilipenko029d8532015-09-30 11:55:45 +00001573 if (V->getType()->isPointerTy()) {
Artur Pilipenkoae51afc2016-02-24 12:25:10 +00001574 unsigned Align = V->getPointerAlignment(Q.DL);
Artur Pilipenko029d8532015-09-30 11:55:45 +00001575 if (Align)
Craig Topperb45eabc2017-04-26 16:39:58 +00001576 Known.Zero.setLowBits(countTrailingZeros(Align));
Artur Pilipenko029d8532015-09-30 11:55:45 +00001577 }
1578
Craig Topperb45eabc2017-04-26 16:39:58 +00001579 // computeKnownBitsFromAssume strictly refines Known.
1580 // Therefore, we run them after computeKnownBitsFromOperator.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001581
1582 // Check whether a nearby assume intrinsic can determine some known bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001583 computeKnownBitsFromAssume(V, Known, Depth, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001584
Craig Topperb45eabc2017-04-26 16:39:58 +00001585 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001586}
1587
Sanjay Patelaee84212014-11-04 16:27:42 +00001588/// Return true if the given value is known to have exactly one
Duncan Sandsd3951082011-01-25 09:38:29 +00001589/// bit set when defined. For vectors return true if every element is known to
Sanjay Patelaee84212014-11-04 16:27:42 +00001590/// be a power of two when defined. Supports values with integer or pointer
Duncan Sandsd3951082011-01-25 09:38:29 +00001591/// types and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001592bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001593 const Query &Q) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001594 if (const Constant *C = dyn_cast<Constant>(V)) {
Duncan Sandsba286d72011-10-26 20:55:21 +00001595 if (C->isNullValue())
1596 return OrZero;
Sanjay Patele2e89ef2016-05-22 15:41:53 +00001597
1598 const APInt *ConstIntOrConstSplatInt;
1599 if (match(C, m_APInt(ConstIntOrConstSplatInt)))
1600 return ConstIntOrConstSplatInt->isPowerOf2();
Duncan Sandsba286d72011-10-26 20:55:21 +00001601 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001602
1603 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1604 // it is shifted off the end then the result is undefined.
1605 if (match(V, m_Shl(m_One(), m_Value())))
1606 return true;
1607
Craig Topperbcfd2d12017-04-20 16:56:25 +00001608 // (signmask) >>l X is clearly a power of two if the one is not shifted off
1609 // the bottom. If it is shifted off the bottom then the result is undefined.
1610 if (match(V, m_LShr(m_SignMask(), m_Value())))
Duncan Sandsd3951082011-01-25 09:38:29 +00001611 return true;
1612
1613 // The remaining tests are all recursive, so bail out if we hit the limit.
1614 if (Depth++ == MaxDepth)
1615 return false;
1616
Craig Topper9f008862014-04-15 04:59:12 +00001617 Value *X = nullptr, *Y = nullptr;
Sanjay Patel41160c22015-12-30 22:40:52 +00001618 // A shift left or a logical shift right of a power of two is a power of two
1619 // or zero.
Duncan Sands985ba632011-10-28 18:30:05 +00001620 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
Sanjay Patel41160c22015-12-30 22:40:52 +00001621 match(V, m_LShr(m_Value(X), m_Value()))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001622 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
Duncan Sands985ba632011-10-28 18:30:05 +00001623
Pete Cooper35b00d52016-08-13 01:05:32 +00001624 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001625 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001626
Pete Cooper35b00d52016-08-13 01:05:32 +00001627 if (const SelectInst *SI = dyn_cast<SelectInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001628 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1629 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
Duncan Sandsba286d72011-10-26 20:55:21 +00001630
Duncan Sandsba286d72011-10-26 20:55:21 +00001631 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1632 // A power of two and'd with anything is a power of two or zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001633 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
1634 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
Duncan Sandsba286d72011-10-26 20:55:21 +00001635 return true;
1636 // X & (-X) is always a power of two or zero.
1637 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1638 return true;
1639 return false;
1640 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001641
David Majnemerb7d54092013-07-30 21:01:36 +00001642 // Adding a power-of-two or zero to the same power-of-two or zero yields
1643 // either the original power-of-two, a larger power-of-two or zero.
1644 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001645 const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
David Majnemerb7d54092013-07-30 21:01:36 +00001646 if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1647 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1648 match(X, m_And(m_Value(), m_Specific(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001649 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001650 return true;
1651 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1652 match(Y, m_And(m_Value(), m_Specific(X))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001653 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001654 return true;
1655
1656 unsigned BitWidth = V->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00001657 KnownBits LHSBits(BitWidth);
1658 computeKnownBits(X, LHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001659
Craig Topperb45eabc2017-04-26 16:39:58 +00001660 KnownBits RHSBits(BitWidth);
1661 computeKnownBits(Y, RHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001662 // If i8 V is a power of two or zero:
1663 // ZeroBits: 1 1 1 0 1 1 1 1
1664 // ~ZeroBits: 0 0 0 1 0 0 0 0
Craig Topperb45eabc2017-04-26 16:39:58 +00001665 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
David Majnemerb7d54092013-07-30 21:01:36 +00001666 // If OrZero isn't set, we cannot give back a zero result.
1667 // Make sure either the LHS or RHS has a bit set.
Craig Topperb45eabc2017-04-26 16:39:58 +00001668 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
David Majnemerb7d54092013-07-30 21:01:36 +00001669 return true;
1670 }
1671 }
David Majnemerbeab5672013-05-18 19:30:37 +00001672
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001673 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewyckyf0469af2011-03-21 21:40:32 +00001674 // is a power of two only if the first operand is a power of two and not
1675 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001676 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1677 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
Hal Finkel60db0582014-09-07 18:57:58 +00001678 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001679 Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001680 }
1681
Duncan Sandsd3951082011-01-25 09:38:29 +00001682 return false;
1683}
1684
Chandler Carruth80d3e562012-12-07 02:08:58 +00001685/// \brief Test whether a GEP's result is known to be non-null.
1686///
1687/// Uses properties inherent in a GEP to try to determine whether it is known
1688/// to be non-null.
1689///
1690/// Currently this routine does not support vector GEPs.
Pete Cooper35b00d52016-08-13 01:05:32 +00001691static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001692 const Query &Q) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001693 if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1694 return false;
1695
1696 // FIXME: Support vector-GEPs.
1697 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1698
1699 // If the base pointer is non-null, we cannot walk to a null address with an
1700 // inbounds GEP in address space zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001701 if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001702 return true;
1703
Chandler Carruth80d3e562012-12-07 02:08:58 +00001704 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1705 // If so, then the GEP cannot produce a null pointer, as doing so would
1706 // inherently violate the inbounds contract within address space zero.
1707 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1708 GTI != GTE; ++GTI) {
1709 // Struct types are easy -- they must always be indexed by a constant.
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001710 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001711 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1712 unsigned ElementIdx = OpC->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001713 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chandler Carruth80d3e562012-12-07 02:08:58 +00001714 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1715 if (ElementOffset > 0)
1716 return true;
1717 continue;
1718 }
1719
1720 // If we have a zero-sized type, the index doesn't matter. Keep looping.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001721 if (Q.DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
Chandler Carruth80d3e562012-12-07 02:08:58 +00001722 continue;
1723
1724 // Fast path the constant operand case both for efficiency and so we don't
1725 // increment Depth when just zipping down an all-constant GEP.
1726 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1727 if (!OpC->isZero())
1728 return true;
1729 continue;
1730 }
1731
1732 // We post-increment Depth here because while isKnownNonZero increments it
1733 // as well, when we pop back up that increment won't persist. We don't want
1734 // to recurse 10k times just because we have 10k GEP operands. We don't
1735 // bail completely out because we want to handle constant GEPs regardless
1736 // of depth.
1737 if (Depth++ >= MaxDepth)
1738 continue;
1739
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001740 if (isKnownNonZero(GTI.getOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001741 return true;
1742 }
1743
1744 return false;
1745}
1746
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001747/// Does the 'Range' metadata (which must be a valid MD_range operand list)
1748/// ensure that the value it's attached to is never Value? 'RangeType' is
1749/// is the type of the value described by the range.
Pete Cooper35b00d52016-08-13 01:05:32 +00001750static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001751 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1752 assert(NumRanges >= 1);
1753 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001754 ConstantInt *Lower =
1755 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1756 ConstantInt *Upper =
1757 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001758 ConstantRange Range(Lower->getValue(), Upper->getValue());
1759 if (Range.contains(Value))
1760 return false;
1761 }
1762 return true;
1763}
1764
Sanjay Patel97e4b9872017-02-12 15:35:34 +00001765/// Return true if the given value is known to be non-zero when defined. For
1766/// vectors, return true if every element is known to be non-zero when
1767/// defined. For pointers, if the context instruction and dominator tree are
1768/// specified, perform context-sensitive analysis and return true if the
1769/// pointer couldn't possibly be null at the specified instruction.
1770/// Supports values with integer or pointer type and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001771bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q) {
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001772 if (auto *C = dyn_cast<Constant>(V)) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001773 if (C->isNullValue())
1774 return false;
1775 if (isa<ConstantInt>(C))
1776 // Must be non-zero due to null test above.
1777 return true;
Sanjay Patel23019d12016-05-24 14:18:49 +00001778
1779 // For constant vectors, check that all elements are undefined or known
1780 // non-zero to determine that the whole vector is known non-zero.
1781 if (auto *VecTy = dyn_cast<VectorType>(C->getType())) {
1782 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
1783 Constant *Elt = C->getAggregateElement(i);
1784 if (!Elt || Elt->isNullValue())
1785 return false;
1786 if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
1787 return false;
1788 }
1789 return true;
1790 }
1791
Duncan Sandsd3951082011-01-25 09:38:29 +00001792 return false;
1793 }
1794
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001795 if (auto *I = dyn_cast<Instruction>(V)) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001796 if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001797 // If the possible ranges don't contain zero, then the value is
1798 // definitely non-zero.
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001799 if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001800 const APInt ZeroValue(Ty->getBitWidth(), 0);
1801 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
1802 return true;
1803 }
1804 }
1805 }
1806
Duncan Sandsd3951082011-01-25 09:38:29 +00001807 // The remaining tests are all recursive, so bail out if we hit the limit.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001808 if (Depth++ >= MaxDepth)
Duncan Sandsd3951082011-01-25 09:38:29 +00001809 return false;
1810
Chandler Carruth80d3e562012-12-07 02:08:58 +00001811 // Check for pointer simplifications.
1812 if (V->getType()->isPointerTy()) {
Sanjay Patel97e4b9872017-02-12 15:35:34 +00001813 if (isKnownNonNullAt(V, Q.CxtI, Q.DT))
Sanjoy Das6082c1a2016-05-07 02:08:15 +00001814 return true;
Pete Cooper35b00d52016-08-13 01:05:32 +00001815 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001816 if (isGEPKnownNonNull(GEP, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001817 return true;
1818 }
1819
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001820 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001821
1822 // X | Y != 0 if X != 0 or Y != 0.
Craig Topper9f008862014-04-15 04:59:12 +00001823 Value *X = nullptr, *Y = nullptr;
Duncan Sandsd3951082011-01-25 09:38:29 +00001824 if (match(V, m_Or(m_Value(X), m_Value(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001825 return isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001826
1827 // ext X != 0 if X != 0.
1828 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001829 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001830
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001831 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd3951082011-01-25 09:38:29 +00001832 // if the lowest bit is shifted off the end.
Craig Topper6b3940a2017-05-03 22:25:19 +00001833 if (match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001834 // shl nuw can't remove any non-zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00001835 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001836 if (BO->hasNoUnsignedWrap())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001837 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001838
Craig Topperb45eabc2017-04-26 16:39:58 +00001839 KnownBits Known(BitWidth);
1840 computeKnownBits(X, Known, Depth, Q);
1841 if (Known.One[0])
Duncan Sandsd3951082011-01-25 09:38:29 +00001842 return true;
1843 }
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001844 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd3951082011-01-25 09:38:29 +00001845 // defined if the sign bit is shifted off the end.
1846 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001847 // shr exact can only shift out zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00001848 const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001849 if (BO->isExact())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001850 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001851
Craig Topper6e11a052017-05-08 16:22:48 +00001852 KnownBits Known = computeKnownBits(X, Depth, Q);
1853 if (Known.isNegative())
Duncan Sandsd3951082011-01-25 09:38:29 +00001854 return true;
James Molloyb6be1eb2015-09-24 16:06:32 +00001855
1856 // If the shifter operand is a constant, and all of the bits shifted
1857 // out are known to be zero, and X is known non-zero then at least one
1858 // non-zero bit must remain.
1859 if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
James Molloyb6be1eb2015-09-24 16:06:32 +00001860 auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
1861 // Is there a known one in the portion not shifted out?
Craig Topper8df66c62017-05-12 17:20:30 +00001862 if (Known.countMaxLeadingZeros() < BitWidth - ShiftVal)
James Molloyb6be1eb2015-09-24 16:06:32 +00001863 return true;
1864 // Are all the bits to be shifted out known zero?
Craig Topper8df66c62017-05-12 17:20:30 +00001865 if (Known.countMinTrailingZeros() >= ShiftVal)
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001866 return isKnownNonZero(X, Depth, Q);
James Molloyb6be1eb2015-09-24 16:06:32 +00001867 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001868 }
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001869 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001870 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001871 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001872 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001873 // X + Y.
1874 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Craig Topper6e11a052017-05-08 16:22:48 +00001875 KnownBits XKnown = computeKnownBits(X, Depth, Q);
1876 KnownBits YKnown = computeKnownBits(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001877
1878 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001879 // zero unless both X and Y are zero.
Craig Topper6e11a052017-05-08 16:22:48 +00001880 if (XKnown.isNonNegative() && YKnown.isNonNegative())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001881 if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q))
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001882 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00001883
1884 // If X and Y are both negative (as signed values) then their sum is not
1885 // zero unless both X and Y equal INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00001886 if (XKnown.isNegative() && YKnown.isNegative()) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001887 APInt Mask = APInt::getSignedMaxValue(BitWidth);
1888 // The sign bit of X is set. If some other bit is set then X is not equal
1889 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00001890 if (XKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00001891 return true;
1892 // The sign bit of Y is set. If some other bit is set then Y is not equal
1893 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00001894 if (YKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00001895 return true;
1896 }
1897
1898 // The sum of a non-negative number and a power of two is not zero.
Craig Topper6e11a052017-05-08 16:22:48 +00001899 if (XKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001900 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001901 return true;
Craig Topper6e11a052017-05-08 16:22:48 +00001902 if (YKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001903 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001904 return true;
1905 }
Duncan Sands7cb61e52011-10-27 19:16:21 +00001906 // X * Y.
1907 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001908 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Duncan Sands7cb61e52011-10-27 19:16:21 +00001909 // If X and Y are non-zero then so is X * Y as long as the multiplication
1910 // does not overflow.
1911 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001912 isKnownNonZero(X, Depth, Q) && isKnownNonZero(Y, Depth, Q))
Duncan Sands7cb61e52011-10-27 19:16:21 +00001913 return true;
1914 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001915 // (C ? X : Y) != 0 if X != 0 and Y != 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00001916 else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001917 if (isKnownNonZero(SI->getTrueValue(), Depth, Q) &&
1918 isKnownNonZero(SI->getFalseValue(), Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001919 return true;
1920 }
James Molloy897048b2015-09-29 14:08:45 +00001921 // PHI
Pete Cooper35b00d52016-08-13 01:05:32 +00001922 else if (const PHINode *PN = dyn_cast<PHINode>(V)) {
James Molloy897048b2015-09-29 14:08:45 +00001923 // Try and detect a recurrence that monotonically increases from a
1924 // starting value, as these are common as induction variables.
1925 if (PN->getNumIncomingValues() == 2) {
1926 Value *Start = PN->getIncomingValue(0);
1927 Value *Induction = PN->getIncomingValue(1);
1928 if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start))
1929 std::swap(Start, Induction);
1930 if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) {
1931 if (!C->isZero() && !C->isNegative()) {
1932 ConstantInt *X;
1933 if ((match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) ||
1934 match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) &&
1935 !X->isNegative())
1936 return true;
1937 }
1938 }
1939 }
Jun Bum Limca832662016-02-01 17:03:07 +00001940 // Check if all incoming values are non-zero constant.
1941 bool AllNonZeroConstants = all_of(PN->operands(), [](Value *V) {
1942 return isa<ConstantInt>(V) && !cast<ConstantInt>(V)->isZeroValue();
1943 });
1944 if (AllNonZeroConstants)
1945 return true;
James Molloy897048b2015-09-29 14:08:45 +00001946 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001947
Craig Topperb45eabc2017-04-26 16:39:58 +00001948 KnownBits Known(BitWidth);
1949 computeKnownBits(V, Known, Depth, Q);
1950 return Known.One != 0;
Duncan Sandsd3951082011-01-25 09:38:29 +00001951}
1952
James Molloy1d88d6f2015-10-22 13:18:42 +00001953/// Return true if V2 == V1 + X, where X is known non-zero.
Pete Cooper35b00d52016-08-13 01:05:32 +00001954static bool isAddOfNonZero(const Value *V1, const Value *V2, const Query &Q) {
1955 const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
James Molloy1d88d6f2015-10-22 13:18:42 +00001956 if (!BO || BO->getOpcode() != Instruction::Add)
1957 return false;
1958 Value *Op = nullptr;
1959 if (V2 == BO->getOperand(0))
1960 Op = BO->getOperand(1);
1961 else if (V2 == BO->getOperand(1))
1962 Op = BO->getOperand(0);
1963 else
1964 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001965 return isKnownNonZero(Op, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00001966}
1967
1968/// Return true if it is known that V1 != V2.
Pete Cooper35b00d52016-08-13 01:05:32 +00001969static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q) {
James Molloy1d88d6f2015-10-22 13:18:42 +00001970 if (V1->getType()->isVectorTy() || V1 == V2)
1971 return false;
1972 if (V1->getType() != V2->getType())
1973 // We can't look through casts yet.
1974 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001975 if (isAddOfNonZero(V1, V2, Q) || isAddOfNonZero(V2, V1, Q))
James Molloy1d88d6f2015-10-22 13:18:42 +00001976 return true;
1977
1978 if (IntegerType *Ty = dyn_cast<IntegerType>(V1->getType())) {
1979 // Are any known bits in V1 contradictory to known bits in V2? If V1
1980 // has a known zero where V2 has a known one, they must not be equal.
1981 auto BitWidth = Ty->getBitWidth();
Craig Topperb45eabc2017-04-26 16:39:58 +00001982 KnownBits Known1(BitWidth);
1983 computeKnownBits(V1, Known1, 0, Q);
1984 KnownBits Known2(BitWidth);
1985 computeKnownBits(V2, Known2, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00001986
Craig Topperb45eabc2017-04-26 16:39:58 +00001987 APInt OppositeBits = (Known1.Zero & Known2.One) |
1988 (Known2.Zero & Known1.One);
James Molloy1d88d6f2015-10-22 13:18:42 +00001989 if (OppositeBits.getBoolValue())
1990 return true;
1991 }
1992 return false;
1993}
1994
Sanjay Patelaee84212014-11-04 16:27:42 +00001995/// Return true if 'V & Mask' is known to be zero. We use this predicate to
1996/// simplify operations downstream. Mask is known to be zero for bits that V
1997/// cannot have.
Chris Lattner4bc28252009-09-08 00:06:16 +00001998///
1999/// This function is defined on values with integer type, values with pointer
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002000/// type, and vectors of integers. In the case
Chris Lattner4bc28252009-09-08 00:06:16 +00002001/// where V is a vector, the mask, known zero, and known one values are the
2002/// same width as the vector element, and the bit is set only if it is true
2003/// for all of the elements in the vector.
Pete Cooper35b00d52016-08-13 01:05:32 +00002004bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002005 const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002006 KnownBits Known(Mask.getBitWidth());
2007 computeKnownBits(V, Known, Depth, Q);
2008 return Mask.isSubsetOf(Known.Zero);
Chris Lattner965c7692008-06-02 01:18:21 +00002009}
2010
Sanjay Patela06d9892016-06-22 19:20:59 +00002011/// For vector constants, loop over the elements and find the constant with the
2012/// minimum number of sign bits. Return 0 if the value is not a vector constant
2013/// or if any element was not analyzed; otherwise, return the count for the
2014/// element with the minimum number of sign bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002015static unsigned computeNumSignBitsVectorConstant(const Value *V,
2016 unsigned TyBits) {
2017 const auto *CV = dyn_cast<Constant>(V);
Sanjay Patela06d9892016-06-22 19:20:59 +00002018 if (!CV || !CV->getType()->isVectorTy())
2019 return 0;
Chris Lattner965c7692008-06-02 01:18:21 +00002020
Sanjay Patela06d9892016-06-22 19:20:59 +00002021 unsigned MinSignBits = TyBits;
2022 unsigned NumElts = CV->getType()->getVectorNumElements();
2023 for (unsigned i = 0; i != NumElts; ++i) {
2024 // If we find a non-ConstantInt, bail out.
2025 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
2026 if (!Elt)
2027 return 0;
2028
2029 // If the sign bit is 1, flip the bits, so we always count leading zeros.
2030 APInt EltVal = Elt->getValue();
2031 if (EltVal.isNegative())
2032 EltVal = ~EltVal;
2033 MinSignBits = std::min(MinSignBits, EltVal.countLeadingZeros());
2034 }
2035
2036 return MinSignBits;
2037}
Chris Lattner965c7692008-06-02 01:18:21 +00002038
Sanjoy Das39a684d2017-02-25 20:30:45 +00002039static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2040 const Query &Q);
2041
2042static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
2043 const Query &Q) {
2044 unsigned Result = ComputeNumSignBitsImpl(V, Depth, Q);
2045 assert(Result > 0 && "At least one sign bit needs to be present!");
2046 return Result;
2047}
2048
Sanjay Patelaee84212014-11-04 16:27:42 +00002049/// Return the number of times the sign bit of the register is replicated into
2050/// the other bits. We know that at least 1 bit is always equal to the sign bit
2051/// (itself), but other cases can give us information. For example, immediately
2052/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
Sanjay Patela06d9892016-06-22 19:20:59 +00002053/// other, so we return 3. For vectors, return the number of sign bits for the
2054/// vector element with the mininum number of known sign bits.
Sanjoy Das39a684d2017-02-25 20:30:45 +00002055static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2056 const Query &Q) {
2057
2058 // We return the minimum number of sign bits that are guaranteed to be present
2059 // in V, so for undef we have to conservatively return 1. We don't have the
2060 // same behavior for poison though -- that's a FIXME today.
2061
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002062 unsigned TyBits = Q.DL.getTypeSizeInBits(V->getType()->getScalarType());
Chris Lattner965c7692008-06-02 01:18:21 +00002063 unsigned Tmp, Tmp2;
2064 unsigned FirstAnswer = 1;
2065
Jay Foada0653a32014-05-14 21:14:37 +00002066 // Note that ConstantInt is handled by the general computeKnownBits case
Chris Lattner2e01a692008-06-02 18:39:07 +00002067 // below.
2068
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002069 if (Depth == MaxDepth)
Chris Lattner965c7692008-06-02 01:18:21 +00002070 return 1; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002071
Pete Cooper35b00d52016-08-13 01:05:32 +00002072 const Operator *U = dyn_cast<Operator>(V);
Dan Gohman80ca01c2009-07-17 20:47:02 +00002073 switch (Operator::getOpcode(V)) {
Chris Lattner965c7692008-06-02 01:18:21 +00002074 default: break;
2075 case Instruction::SExt:
Mon P Wangbb3eac92009-12-02 04:59:58 +00002076 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002077 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
Craig Topper1bef2c82012-12-22 19:15:35 +00002078
Nadav Rotemc99a3872015-03-06 00:23:58 +00002079 case Instruction::SDiv: {
Nadav Rotem029c5c72015-03-03 21:39:02 +00002080 const APInt *Denominator;
2081 // sdiv X, C -> adds log(C) sign bits.
2082 if (match(U->getOperand(1), m_APInt(Denominator))) {
2083
2084 // Ignore non-positive denominator.
2085 if (!Denominator->isStrictlyPositive())
2086 break;
2087
2088 // Calculate the incoming numerator bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002089 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotem029c5c72015-03-03 21:39:02 +00002090
2091 // Add floor(log(C)) bits to the numerator bits.
2092 return std::min(TyBits, NumBits + Denominator->logBase2());
2093 }
2094 break;
Nadav Rotemc99a3872015-03-06 00:23:58 +00002095 }
2096
2097 case Instruction::SRem: {
2098 const APInt *Denominator;
Sanjoy Dase561fee2015-03-25 22:33:53 +00002099 // srem X, C -> we know that the result is within [-C+1,C) when C is a
2100 // positive constant. This let us put a lower bound on the number of sign
2101 // bits.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002102 if (match(U->getOperand(1), m_APInt(Denominator))) {
2103
2104 // Ignore non-positive denominator.
2105 if (!Denominator->isStrictlyPositive())
2106 break;
2107
2108 // Calculate the incoming numerator bits. SRem by a positive constant
2109 // can't lower the number of sign bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002110 unsigned NumrBits =
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002111 ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotemc99a3872015-03-06 00:23:58 +00002112
2113 // Calculate the leading sign bit constraints by examining the
Sanjoy Dase561fee2015-03-25 22:33:53 +00002114 // denominator. Given that the denominator is positive, there are two
2115 // cases:
2116 //
2117 // 1. the numerator is positive. The result range is [0,C) and [0,C) u<
2118 // (1 << ceilLogBase2(C)).
2119 //
2120 // 2. the numerator is negative. Then the result range is (-C,0] and
2121 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2122 //
2123 // Thus a lower bound on the number of sign bits is `TyBits -
2124 // ceilLogBase2(C)`.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002125
Sanjoy Dase561fee2015-03-25 22:33:53 +00002126 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
Nadav Rotemc99a3872015-03-06 00:23:58 +00002127 return std::max(NumrBits, ResBits);
2128 }
2129 break;
2130 }
Nadav Rotem029c5c72015-03-03 21:39:02 +00002131
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002132 case Instruction::AShr: {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002133 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002134 // ashr X, C -> adds C sign bits. Vectors too.
2135 const APInt *ShAmt;
2136 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Sanjoy Das39a684d2017-02-25 20:30:45 +00002137 unsigned ShAmtLimited = ShAmt->getZExtValue();
2138 if (ShAmtLimited >= TyBits)
2139 break; // Bad shift.
2140 Tmp += ShAmtLimited;
Chris Lattner965c7692008-06-02 01:18:21 +00002141 if (Tmp > TyBits) Tmp = TyBits;
2142 }
2143 return Tmp;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002144 }
2145 case Instruction::Shl: {
2146 const APInt *ShAmt;
2147 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner965c7692008-06-02 01:18:21 +00002148 // shl destroys sign bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002149 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002150 Tmp2 = ShAmt->getZExtValue();
2151 if (Tmp2 >= TyBits || // Bad shift.
2152 Tmp2 >= Tmp) break; // Shifted all sign bits out.
2153 return Tmp - Tmp2;
Chris Lattner965c7692008-06-02 01:18:21 +00002154 }
2155 break;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002156 }
Chris Lattner965c7692008-06-02 01:18:21 +00002157 case Instruction::And:
2158 case Instruction::Or:
2159 case Instruction::Xor: // NOT is handled here.
2160 // Logical binary ops preserve the number of sign bits at the worst.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002161 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002162 if (Tmp != 1) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002163 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002164 FirstAnswer = std::min(Tmp, Tmp2);
2165 // We computed what we know about the sign bits as our first
2166 // answer. Now proceed to the generic code that uses
Jay Foada0653a32014-05-14 21:14:37 +00002167 // computeKnownBits, and pick whichever answer is better.
Chris Lattner965c7692008-06-02 01:18:21 +00002168 }
2169 break;
2170
2171 case Instruction::Select:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002172 Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002173 if (Tmp == 1) return 1; // Early out.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002174 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002175 return std::min(Tmp, Tmp2);
Craig Topper1bef2c82012-12-22 19:15:35 +00002176
Chris Lattner965c7692008-06-02 01:18:21 +00002177 case Instruction::Add:
2178 // Add can have at most one carry bit. Thus we know that the output
2179 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002180 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002181 if (Tmp == 1) return 1; // Early out.
Craig Topper1bef2c82012-12-22 19:15:35 +00002182
Chris Lattner965c7692008-06-02 01:18:21 +00002183 // Special case decrementing a value (ADD X, -1):
David Majnemera55027f2014-12-26 09:20:17 +00002184 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
Chris Lattner965c7692008-06-02 01:18:21 +00002185 if (CRHS->isAllOnesValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002186 KnownBits Known(TyBits);
2187 computeKnownBits(U->getOperand(0), Known, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002188
Chris Lattner965c7692008-06-02 01:18:21 +00002189 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2190 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002191 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002192 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002193
Chris Lattner965c7692008-06-02 01:18:21 +00002194 // If we are subtracting one from a positive number, there is no carry
2195 // out of the result.
Craig Topperca48af32017-04-29 16:43:11 +00002196 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002197 return Tmp;
2198 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002199
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002200 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002201 if (Tmp2 == 1) return 1;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002202 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002203
Chris Lattner965c7692008-06-02 01:18:21 +00002204 case Instruction::Sub:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002205 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002206 if (Tmp2 == 1) return 1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002207
Chris Lattner965c7692008-06-02 01:18:21 +00002208 // Handle NEG.
David Majnemera55027f2014-12-26 09:20:17 +00002209 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
Chris Lattner965c7692008-06-02 01:18:21 +00002210 if (CLHS->isNullValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002211 KnownBits Known(TyBits);
2212 computeKnownBits(U->getOperand(1), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002213 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2214 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002215 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002216 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002217
Chris Lattner965c7692008-06-02 01:18:21 +00002218 // If the input is known to be positive (the sign bit is known clear),
2219 // the output of the NEG has the same number of sign bits as the input.
Craig Topperca48af32017-04-29 16:43:11 +00002220 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002221 return Tmp2;
Craig Topper1bef2c82012-12-22 19:15:35 +00002222
Chris Lattner965c7692008-06-02 01:18:21 +00002223 // Otherwise, we treat this like a SUB.
2224 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002225
Chris Lattner965c7692008-06-02 01:18:21 +00002226 // Sub can have at most one carry bit. Thus we know that the output
2227 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002228 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002229 if (Tmp == 1) return 1; // Early out.
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002230 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002231
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002232 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00002233 const PHINode *PN = cast<PHINode>(U);
David Majnemer6ee8d172015-01-04 07:06:53 +00002234 unsigned NumIncomingValues = PN->getNumIncomingValues();
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002235 // Don't analyze large in-degree PHIs.
David Majnemer6ee8d172015-01-04 07:06:53 +00002236 if (NumIncomingValues > 4) break;
2237 // Unreachable blocks may have zero-operand PHI nodes.
2238 if (NumIncomingValues == 0) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002239
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002240 // Take the minimum of all incoming values. This can't infinitely loop
2241 // because of our depth threshold.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002242 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), Depth + 1, Q);
David Majnemer6ee8d172015-01-04 07:06:53 +00002243 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002244 if (Tmp == 1) return Tmp;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002245 Tmp = std::min(
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002246 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, Q));
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002247 }
2248 return Tmp;
2249 }
2250
Chris Lattner965c7692008-06-02 01:18:21 +00002251 case Instruction::Trunc:
2252 // FIXME: it's tricky to do anything useful for this, but it is an important
2253 // case for targets like X86.
2254 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00002255
2256 case Instruction::ExtractElement:
2257 // Look through extract element. At the moment we keep this simple and skip
2258 // tracking the specific element. But at least we might find information
2259 // valid for all elements of the vector (for example if vector is sign
2260 // extended, shifted, etc).
2261 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002262 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002263
Chris Lattner965c7692008-06-02 01:18:21 +00002264 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2265 // use this information.
Sanjay Patela06d9892016-06-22 19:20:59 +00002266
2267 // If we can examine all elements of a vector constant successfully, we're
2268 // done (we can't do any better than that). If not, keep trying.
2269 if (unsigned VecSignBits = computeNumSignBitsVectorConstant(V, TyBits))
2270 return VecSignBits;
2271
Craig Topperb45eabc2017-04-26 16:39:58 +00002272 KnownBits Known(TyBits);
2273 computeKnownBits(V, Known, Depth, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002274
Sanjay Patele0536212016-06-23 17:41:59 +00002275 // If we know that the sign bit is either zero or one, determine the number of
2276 // identical bits in the top of the input value.
Craig Topper8df66c62017-05-12 17:20:30 +00002277 return std::max(FirstAnswer, Known.countMinSignBits());
Chris Lattner965c7692008-06-02 01:18:21 +00002278}
Chris Lattnera12a6de2008-06-02 01:29:46 +00002279
Sanjay Patelaee84212014-11-04 16:27:42 +00002280/// This function computes the integer multiple of Base that equals V.
2281/// If successful, it returns true and returns the multiple in
2282/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez47444882009-11-10 08:28:35 +00002283/// through SExt instructions only if LookThroughSExt is true.
2284bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman6a976bb2009-11-18 00:58:27 +00002285 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez47444882009-11-10 08:28:35 +00002286 const unsigned MaxDepth = 6;
2287
Dan Gohman6a976bb2009-11-18 00:58:27 +00002288 assert(V && "No Value?");
Victor Hernandez47444882009-11-10 08:28:35 +00002289 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002290 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez47444882009-11-10 08:28:35 +00002291
Chris Lattner229907c2011-07-18 04:54:35 +00002292 Type *T = V->getType();
Victor Hernandez47444882009-11-10 08:28:35 +00002293
Dan Gohman6a976bb2009-11-18 00:58:27 +00002294 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez47444882009-11-10 08:28:35 +00002295
2296 if (Base == 0)
2297 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002298
Victor Hernandez47444882009-11-10 08:28:35 +00002299 if (Base == 1) {
2300 Multiple = V;
2301 return true;
2302 }
2303
2304 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2305 Constant *BaseVal = ConstantInt::get(T, Base);
2306 if (CO && CO == BaseVal) {
2307 // Multiple is 1.
2308 Multiple = ConstantInt::get(T, 1);
2309 return true;
2310 }
2311
2312 if (CI && CI->getZExtValue() % Base == 0) {
2313 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
Craig Topper1bef2c82012-12-22 19:15:35 +00002314 return true;
Victor Hernandez47444882009-11-10 08:28:35 +00002315 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002316
Victor Hernandez47444882009-11-10 08:28:35 +00002317 if (Depth == MaxDepth) return false; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002318
Victor Hernandez47444882009-11-10 08:28:35 +00002319 Operator *I = dyn_cast<Operator>(V);
2320 if (!I) return false;
2321
2322 switch (I->getOpcode()) {
2323 default: break;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002324 case Instruction::SExt:
Victor Hernandez47444882009-11-10 08:28:35 +00002325 if (!LookThroughSExt) return false;
2326 // otherwise fall through to ZExt
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002327 case Instruction::ZExt:
Dan Gohman6a976bb2009-11-18 00:58:27 +00002328 return ComputeMultiple(I->getOperand(0), Base, Multiple,
2329 LookThroughSExt, Depth+1);
Victor Hernandez47444882009-11-10 08:28:35 +00002330 case Instruction::Shl:
2331 case Instruction::Mul: {
2332 Value *Op0 = I->getOperand(0);
2333 Value *Op1 = I->getOperand(1);
2334
2335 if (I->getOpcode() == Instruction::Shl) {
2336 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2337 if (!Op1CI) return false;
2338 // Turn Op0 << Op1 into Op0 * 2^Op1
2339 APInt Op1Int = Op1CI->getValue();
2340 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foad15084f02010-11-30 09:02:01 +00002341 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002342 API.setBit(BitToSet);
Jay Foad15084f02010-11-30 09:02:01 +00002343 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez47444882009-11-10 08:28:35 +00002344 }
2345
Craig Topper9f008862014-04-15 04:59:12 +00002346 Value *Mul0 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002347 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2348 if (Constant *Op1C = dyn_cast<Constant>(Op1))
2349 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002350 if (Op1C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002351 MulC->getType()->getPrimitiveSizeInBits())
2352 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002353 if (Op1C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002354 MulC->getType()->getPrimitiveSizeInBits())
2355 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002356
Chris Lattner72d283c2010-09-05 17:20:46 +00002357 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2358 Multiple = ConstantExpr::getMul(MulC, Op1C);
2359 return true;
2360 }
Victor Hernandez47444882009-11-10 08:28:35 +00002361
2362 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2363 if (Mul0CI->getValue() == 1) {
2364 // V == Base * Op1, so return Op1
2365 Multiple = Op1;
2366 return true;
2367 }
2368 }
2369
Craig Topper9f008862014-04-15 04:59:12 +00002370 Value *Mul1 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002371 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2372 if (Constant *Op0C = dyn_cast<Constant>(Op0))
2373 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002374 if (Op0C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002375 MulC->getType()->getPrimitiveSizeInBits())
2376 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002377 if (Op0C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002378 MulC->getType()->getPrimitiveSizeInBits())
2379 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002380
Chris Lattner72d283c2010-09-05 17:20:46 +00002381 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2382 Multiple = ConstantExpr::getMul(MulC, Op0C);
2383 return true;
2384 }
Victor Hernandez47444882009-11-10 08:28:35 +00002385
2386 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2387 if (Mul1CI->getValue() == 1) {
2388 // V == Base * Op0, so return Op0
2389 Multiple = Op0;
2390 return true;
2391 }
2392 }
Victor Hernandez47444882009-11-10 08:28:35 +00002393 }
2394 }
2395
2396 // We could not determine if V is a multiple of Base.
2397 return false;
2398}
2399
David Majnemerb4b27232016-04-19 19:10:21 +00002400Intrinsic::ID llvm::getIntrinsicForCallSite(ImmutableCallSite ICS,
2401 const TargetLibraryInfo *TLI) {
2402 const Function *F = ICS.getCalledFunction();
2403 if (!F)
2404 return Intrinsic::not_intrinsic;
2405
2406 if (F->isIntrinsic())
2407 return F->getIntrinsicID();
2408
2409 if (!TLI)
2410 return Intrinsic::not_intrinsic;
2411
David L. Jonesd21529f2017-01-23 23:16:46 +00002412 LibFunc Func;
David Majnemerb4b27232016-04-19 19:10:21 +00002413 // We're going to make assumptions on the semantics of the functions, check
2414 // that the target knows that it's available in this environment and it does
2415 // not have local linkage.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002416 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(*F, Func))
2417 return Intrinsic::not_intrinsic;
2418
2419 if (!ICS.onlyReadsMemory())
David Majnemerb4b27232016-04-19 19:10:21 +00002420 return Intrinsic::not_intrinsic;
2421
2422 // Otherwise check if we have a call to a function that can be turned into a
2423 // vector intrinsic.
2424 switch (Func) {
2425 default:
2426 break;
David L. Jonesd21529f2017-01-23 23:16:46 +00002427 case LibFunc_sin:
2428 case LibFunc_sinf:
2429 case LibFunc_sinl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002430 return Intrinsic::sin;
David L. Jonesd21529f2017-01-23 23:16:46 +00002431 case LibFunc_cos:
2432 case LibFunc_cosf:
2433 case LibFunc_cosl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002434 return Intrinsic::cos;
David L. Jonesd21529f2017-01-23 23:16:46 +00002435 case LibFunc_exp:
2436 case LibFunc_expf:
2437 case LibFunc_expl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002438 return Intrinsic::exp;
David L. Jonesd21529f2017-01-23 23:16:46 +00002439 case LibFunc_exp2:
2440 case LibFunc_exp2f:
2441 case LibFunc_exp2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002442 return Intrinsic::exp2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002443 case LibFunc_log:
2444 case LibFunc_logf:
2445 case LibFunc_logl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002446 return Intrinsic::log;
David L. Jonesd21529f2017-01-23 23:16:46 +00002447 case LibFunc_log10:
2448 case LibFunc_log10f:
2449 case LibFunc_log10l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002450 return Intrinsic::log10;
David L. Jonesd21529f2017-01-23 23:16:46 +00002451 case LibFunc_log2:
2452 case LibFunc_log2f:
2453 case LibFunc_log2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002454 return Intrinsic::log2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002455 case LibFunc_fabs:
2456 case LibFunc_fabsf:
2457 case LibFunc_fabsl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002458 return Intrinsic::fabs;
David L. Jonesd21529f2017-01-23 23:16:46 +00002459 case LibFunc_fmin:
2460 case LibFunc_fminf:
2461 case LibFunc_fminl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002462 return Intrinsic::minnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002463 case LibFunc_fmax:
2464 case LibFunc_fmaxf:
2465 case LibFunc_fmaxl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002466 return Intrinsic::maxnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002467 case LibFunc_copysign:
2468 case LibFunc_copysignf:
2469 case LibFunc_copysignl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002470 return Intrinsic::copysign;
David L. Jonesd21529f2017-01-23 23:16:46 +00002471 case LibFunc_floor:
2472 case LibFunc_floorf:
2473 case LibFunc_floorl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002474 return Intrinsic::floor;
David L. Jonesd21529f2017-01-23 23:16:46 +00002475 case LibFunc_ceil:
2476 case LibFunc_ceilf:
2477 case LibFunc_ceill:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002478 return Intrinsic::ceil;
David L. Jonesd21529f2017-01-23 23:16:46 +00002479 case LibFunc_trunc:
2480 case LibFunc_truncf:
2481 case LibFunc_truncl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002482 return Intrinsic::trunc;
David L. Jonesd21529f2017-01-23 23:16:46 +00002483 case LibFunc_rint:
2484 case LibFunc_rintf:
2485 case LibFunc_rintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002486 return Intrinsic::rint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002487 case LibFunc_nearbyint:
2488 case LibFunc_nearbyintf:
2489 case LibFunc_nearbyintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002490 return Intrinsic::nearbyint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002491 case LibFunc_round:
2492 case LibFunc_roundf:
2493 case LibFunc_roundl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002494 return Intrinsic::round;
David L. Jonesd21529f2017-01-23 23:16:46 +00002495 case LibFunc_pow:
2496 case LibFunc_powf:
2497 case LibFunc_powl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002498 return Intrinsic::pow;
David L. Jonesd21529f2017-01-23 23:16:46 +00002499 case LibFunc_sqrt:
2500 case LibFunc_sqrtf:
2501 case LibFunc_sqrtl:
David Majnemerb4b27232016-04-19 19:10:21 +00002502 if (ICS->hasNoNaNs())
Ahmed Bougachad765a822016-04-27 19:04:35 +00002503 return Intrinsic::sqrt;
David Majnemerb4b27232016-04-19 19:10:21 +00002504 return Intrinsic::not_intrinsic;
2505 }
2506
2507 return Intrinsic::not_intrinsic;
2508}
2509
Sanjay Patelaee84212014-11-04 16:27:42 +00002510/// Return true if we can prove that the specified FP value is never equal to
2511/// -0.0.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002512///
2513/// NOTE: this function will need to be revisited when we support non-default
2514/// rounding modes!
2515///
David Majnemer3ee5f342016-04-13 06:55:52 +00002516bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
2517 unsigned Depth) {
Chris Lattnera12a6de2008-06-02 01:29:46 +00002518 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2519 return !CFP->getValueAPF().isNegZero();
Craig Topper1bef2c82012-12-22 19:15:35 +00002520
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002521 if (Depth == MaxDepth)
Sanjay Patel40eaa8d2015-02-25 18:00:15 +00002522 return false; // Limit search depth.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002523
Dan Gohman80ca01c2009-07-17 20:47:02 +00002524 const Operator *I = dyn_cast<Operator>(V);
Craig Topper9f008862014-04-15 04:59:12 +00002525 if (!I) return false;
Michael Ilseman0f128372012-12-06 00:07:09 +00002526
2527 // Check if the nsz fast-math flag is set
2528 if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
2529 if (FPO->hasNoSignedZeros())
2530 return true;
2531
Chris Lattnera12a6de2008-06-02 01:29:46 +00002532 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Jakub Staszakb7129f22013-03-06 00:16:16 +00002533 if (I->getOpcode() == Instruction::FAdd)
2534 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
2535 if (CFP->isNullValue())
2536 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002537
Chris Lattnera12a6de2008-06-02 01:29:46 +00002538 // sitofp and uitofp turn into +0.0 for zero.
2539 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2540 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002541
David Majnemer3ee5f342016-04-13 06:55:52 +00002542 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
David Majnemerb4b27232016-04-19 19:10:21 +00002543 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002544 switch (IID) {
2545 default:
2546 break;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002547 // sqrt(-0.0) = -0.0, no other negative results are possible.
David Majnemer3ee5f342016-04-13 06:55:52 +00002548 case Intrinsic::sqrt:
2549 return CannotBeNegativeZero(CI->getArgOperand(0), TLI, Depth + 1);
2550 // fabs(x) != -0.0
2551 case Intrinsic::fabs:
2552 return true;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002553 }
David Majnemer3ee5f342016-04-13 06:55:52 +00002554 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002555
Chris Lattnera12a6de2008-06-02 01:29:46 +00002556 return false;
2557}
2558
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002559/// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
2560/// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
2561/// bit despite comparing equal.
2562static bool cannotBeOrderedLessThanZeroImpl(const Value *V,
2563 const TargetLibraryInfo *TLI,
2564 bool SignBitOnly,
2565 unsigned Depth) {
Justin Lebar322c1272017-01-27 00:58:34 +00002566 // TODO: This function does not do the right thing when SignBitOnly is true
2567 // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform
2568 // which flips the sign bits of NaNs. See
2569 // https://llvm.org/bugs/show_bug.cgi?id=31702.
2570
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002571 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2572 return !CFP->getValueAPF().isNegative() ||
2573 (!SignBitOnly && CFP->getValueAPF().isZero());
2574 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002575
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002576 if (Depth == MaxDepth)
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002577 return false; // Limit search depth.
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002578
2579 const Operator *I = dyn_cast<Operator>(V);
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002580 if (!I)
2581 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002582
2583 switch (I->getOpcode()) {
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002584 default:
2585 break;
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002586 // Unsigned integers are always nonnegative.
2587 case Instruction::UIToFP:
2588 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002589 case Instruction::FMul:
2590 // x*x is always non-negative or a NaN.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002591 if (I->getOperand(0) == I->getOperand(1) &&
2592 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002593 return true;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002594
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002595 LLVM_FALLTHROUGH;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002596 case Instruction::FAdd:
2597 case Instruction::FDiv:
2598 case Instruction::FRem:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002599 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2600 Depth + 1) &&
2601 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2602 Depth + 1);
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002603 case Instruction::Select:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002604 return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2605 Depth + 1) &&
2606 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2607 Depth + 1);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002608 case Instruction::FPExt:
2609 case Instruction::FPTrunc:
2610 // Widening/narrowing never change sign.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002611 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2612 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002613 case Instruction::Call:
Justin Lebar7e3184c2017-01-26 00:10:26 +00002614 const auto *CI = cast<CallInst>(I);
2615 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002616 switch (IID) {
2617 default:
2618 break;
2619 case Intrinsic::maxnum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002620 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2621 Depth + 1) ||
2622 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2623 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002624 case Intrinsic::minnum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002625 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2626 Depth + 1) &&
2627 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2628 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002629 case Intrinsic::exp:
2630 case Intrinsic::exp2:
2631 case Intrinsic::fabs:
David Majnemer3ee5f342016-04-13 06:55:52 +00002632 return true;
Justin Lebar7e3184c2017-01-26 00:10:26 +00002633
2634 case Intrinsic::sqrt:
2635 // sqrt(x) is always >= -0 or NaN. Moreover, sqrt(x) == -0 iff x == -0.
2636 if (!SignBitOnly)
2637 return true;
2638 return CI->hasNoNaNs() && (CI->hasNoSignedZeros() ||
2639 CannotBeNegativeZero(CI->getOperand(0), TLI));
2640
David Majnemer3ee5f342016-04-13 06:55:52 +00002641 case Intrinsic::powi:
Justin Lebar7e3184c2017-01-26 00:10:26 +00002642 if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) {
David Majnemer3ee5f342016-04-13 06:55:52 +00002643 // powi(x,n) is non-negative if n is even.
Justin Lebar7e3184c2017-01-26 00:10:26 +00002644 if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0)
David Majnemer3ee5f342016-04-13 06:55:52 +00002645 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002646 }
Justin Lebar322c1272017-01-27 00:58:34 +00002647 // TODO: This is not correct. Given that exp is an integer, here are the
2648 // ways that pow can return a negative value:
2649 //
2650 // pow(x, exp) --> negative if exp is odd and x is negative.
2651 // pow(-0, exp) --> -inf if exp is negative odd.
2652 // pow(-0, exp) --> -0 if exp is positive odd.
2653 // pow(-inf, exp) --> -0 if exp is negative odd.
2654 // pow(-inf, exp) --> -inf if exp is positive odd.
2655 //
2656 // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN,
2657 // but we must return false if x == -0. Unfortunately we do not currently
2658 // have a way of expressing this constraint. See details in
2659 // https://llvm.org/bugs/show_bug.cgi?id=31702.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002660 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2661 Depth + 1);
Justin Lebar322c1272017-01-27 00:58:34 +00002662
David Majnemer3ee5f342016-04-13 06:55:52 +00002663 case Intrinsic::fma:
2664 case Intrinsic::fmuladd:
2665 // x*x+y is non-negative if y is non-negative.
2666 return I->getOperand(0) == I->getOperand(1) &&
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002667 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
2668 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2669 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002670 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002671 break;
2672 }
Sanjoy Das6082c1a2016-05-07 02:08:15 +00002673 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002674}
2675
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002676bool llvm::CannotBeOrderedLessThanZero(const Value *V,
2677 const TargetLibraryInfo *TLI) {
2678 return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0);
2679}
2680
2681bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) {
2682 return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0);
2683}
2684
Sanjay Patelaee84212014-11-04 16:27:42 +00002685/// If the specified value can be set by repeating the same byte in memory,
2686/// return the i8 value that it is represented with. This is
Chris Lattner9cb10352010-12-26 20:15:01 +00002687/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2688/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
2689/// byte store (e.g. i16 0x1234), return null.
2690Value *llvm::isBytewiseValue(Value *V) {
2691 // All byte-wide stores are splatable, even of arbitrary variables.
2692 if (V->getType()->isIntegerTy(8)) return V;
Chris Lattneracf6b072011-02-19 19:35:49 +00002693
2694 // Handle 'null' ConstantArrayZero etc.
2695 if (Constant *C = dyn_cast<Constant>(V))
2696 if (C->isNullValue())
2697 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
Craig Topper1bef2c82012-12-22 19:15:35 +00002698
Chris Lattner9cb10352010-12-26 20:15:01 +00002699 // Constant float and double values can be handled as integer values if the
Craig Topper1bef2c82012-12-22 19:15:35 +00002700 // corresponding integer value is "byteable". An important case is 0.0.
Chris Lattner9cb10352010-12-26 20:15:01 +00002701 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2702 if (CFP->getType()->isFloatTy())
2703 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2704 if (CFP->getType()->isDoubleTy())
2705 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2706 // Don't handle long double formats, which have strange constraints.
2707 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002708
Benjamin Kramer17d90152015-02-07 19:29:02 +00002709 // We can handle constant integers that are multiple of 8 bits.
Chris Lattner9cb10352010-12-26 20:15:01 +00002710 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Benjamin Kramer17d90152015-02-07 19:29:02 +00002711 if (CI->getBitWidth() % 8 == 0) {
2712 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
Craig Topper1bef2c82012-12-22 19:15:35 +00002713
Benjamin Kramerb4b51502015-03-25 16:49:59 +00002714 if (!CI->getValue().isSplat(8))
Benjamin Kramer17d90152015-02-07 19:29:02 +00002715 return nullptr;
2716 return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
Chris Lattner9cb10352010-12-26 20:15:01 +00002717 }
2718 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002719
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002720 // A ConstantDataArray/Vector is splatable if all its members are equal and
2721 // also splatable.
2722 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2723 Value *Elt = CA->getElementAsConstant(0);
2724 Value *Val = isBytewiseValue(Elt);
Chris Lattner9cb10352010-12-26 20:15:01 +00002725 if (!Val)
Craig Topper9f008862014-04-15 04:59:12 +00002726 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002727
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002728 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2729 if (CA->getElementAsConstant(I) != Elt)
Craig Topper9f008862014-04-15 04:59:12 +00002730 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002731
Chris Lattner9cb10352010-12-26 20:15:01 +00002732 return Val;
2733 }
Chad Rosier8abf65a2011-12-06 00:19:08 +00002734
Chris Lattner9cb10352010-12-26 20:15:01 +00002735 // Conceptually, we could handle things like:
2736 // %a = zext i8 %X to i16
2737 // %b = shl i16 %a, 8
2738 // %c = or i16 %a, %b
2739 // but until there is an example that actually needs this, it doesn't seem
2740 // worth worrying about.
Craig Topper9f008862014-04-15 04:59:12 +00002741 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00002742}
2743
2744
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002745// This is the recursive version of BuildSubAggregate. It takes a few different
2746// arguments. Idxs is the index within the nested struct From that we are
2747// looking at now (which is of type IndexedType). IdxSkip is the number of
2748// indices from Idxs that should be left out when inserting into the resulting
2749// struct. To is the result struct built so far, new insertvalue instructions
2750// build on that.
Chris Lattner229907c2011-07-18 04:54:35 +00002751static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Craig Topper2cd5ff82013-07-11 16:22:38 +00002752 SmallVectorImpl<unsigned> &Idxs,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002753 unsigned IdxSkip,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002754 Instruction *InsertBefore) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +00002755 llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002756 if (STy) {
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002757 // Save the original To argument so we can modify it
2758 Value *OrigTo = To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002759 // General case, the type indexed by Idxs is a struct
2760 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2761 // Process each struct element recursively
2762 Idxs.push_back(i);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002763 Value *PrevTo = To;
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002764 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002765 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002766 Idxs.pop_back();
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002767 if (!To) {
2768 // Couldn't find any inserted value for this index? Cleanup
2769 while (PrevTo != OrigTo) {
2770 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
2771 PrevTo = Del->getAggregateOperand();
2772 Del->eraseFromParent();
2773 }
2774 // Stop processing elements
2775 break;
2776 }
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002777 }
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002778 // If we successfully found a value for each of our subaggregates
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002779 if (To)
2780 return To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002781 }
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002782 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
2783 // the struct's elements had a value that was inserted directly. In the latter
2784 // case, perhaps we can't determine each of the subelements individually, but
2785 // we might be able to find the complete struct somewhere.
Craig Topper1bef2c82012-12-22 19:15:35 +00002786
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002787 // Find the value that is at that particular spot
Jay Foad57aa6362011-07-13 10:26:04 +00002788 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002789
2790 if (!V)
Craig Topper9f008862014-04-15 04:59:12 +00002791 return nullptr;
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002792
2793 // Insert the value in the new (sub) aggregrate
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002794 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
Jay Foad57aa6362011-07-13 10:26:04 +00002795 "tmp", InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002796}
2797
2798// This helper takes a nested struct and extracts a part of it (which is again a
2799// struct) into a new value. For example, given the struct:
2800// { a, { b, { c, d }, e } }
2801// and the indices "1, 1" this returns
2802// { c, d }.
2803//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002804// It does this by inserting an insertvalue for each element in the resulting
2805// struct, as opposed to just inserting a single struct. This will only work if
2806// each of the elements of the substruct are known (ie, inserted into From by an
2807// insertvalue instruction somewhere).
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002808//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002809// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foad57aa6362011-07-13 10:26:04 +00002810static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002811 Instruction *InsertBefore) {
Matthijs Kooijman69801d42008-06-16 13:28:31 +00002812 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattner229907c2011-07-18 04:54:35 +00002813 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foad57aa6362011-07-13 10:26:04 +00002814 idx_range);
Owen Andersonb292b8c2009-07-30 23:03:37 +00002815 Value *To = UndefValue::get(IndexedType);
Jay Foad57aa6362011-07-13 10:26:04 +00002816 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002817 unsigned IdxSkip = Idxs.size();
2818
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002819 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002820}
2821
Sanjay Patelaee84212014-11-04 16:27:42 +00002822/// Given an aggregrate and an sequence of indices, see if
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002823/// the scalar value indexed is already around as a register, for example if it
2824/// were inserted directly into the aggregrate.
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002825///
2826/// If InsertBefore is not null, this function will duplicate (modified)
2827/// insertvalues when a part of a nested struct is extracted.
Jay Foad57aa6362011-07-13 10:26:04 +00002828Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
2829 Instruction *InsertBefore) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002830 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002831 // recursion).
Jay Foad57aa6362011-07-13 10:26:04 +00002832 if (idx_range.empty())
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002833 return V;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002834 // We have indices, so V should have an indexable type.
2835 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
2836 "Not looking at a struct or array?");
2837 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
2838 "Invalid indices for type?");
Owen Andersonf1f17432009-07-06 22:37:39 +00002839
Chris Lattner67058832012-01-25 06:48:06 +00002840 if (Constant *C = dyn_cast<Constant>(V)) {
2841 C = C->getAggregateElement(idx_range[0]);
Craig Topper9f008862014-04-15 04:59:12 +00002842 if (!C) return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00002843 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
2844 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002845
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002846 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002847 // Loop the indices for the insertvalue instruction in parallel with the
2848 // requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00002849 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002850 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
2851 i != e; ++i, ++req_idx) {
Jay Foad57aa6362011-07-13 10:26:04 +00002852 if (req_idx == idx_range.end()) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002853 // We can't handle this without inserting insertvalues
2854 if (!InsertBefore)
Craig Topper9f008862014-04-15 04:59:12 +00002855 return nullptr;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002856
2857 // The requested index identifies a part of a nested aggregate. Handle
2858 // this specially. For example,
2859 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
2860 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
2861 // %C = extractvalue {i32, { i32, i32 } } %B, 1
2862 // This can be changed into
2863 // %A = insertvalue {i32, i32 } undef, i32 10, 0
2864 // %C = insertvalue {i32, i32 } %A, i32 11, 1
2865 // which allows the unused 0,0 element from the nested struct to be
2866 // removed.
2867 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
2868 InsertBefore);
Duncan Sandsdb356ee2008-06-19 08:47:31 +00002869 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002870
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002871 // This insert value inserts something else than what we are looking for.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002872 // See if the (aggregate) value inserted into has the value we are
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002873 // looking for, then.
2874 if (*req_idx != *i)
Jay Foad57aa6362011-07-13 10:26:04 +00002875 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002876 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002877 }
2878 // If we end up here, the indices of the insertvalue match with those
2879 // requested (though possibly only partially). Now we recursively look at
2880 // the inserted value, passing any remaining indices.
Jay Foad57aa6362011-07-13 10:26:04 +00002881 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002882 makeArrayRef(req_idx, idx_range.end()),
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002883 InsertBefore);
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002884 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002885
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002886 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002887 // If we're extracting a value from an aggregate that was extracted from
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002888 // something else, we can extract from that something else directly instead.
2889 // However, we will need to chain I's indices with the requested indices.
Craig Topper1bef2c82012-12-22 19:15:35 +00002890
2891 // Calculate the number of indices required
Jay Foad57aa6362011-07-13 10:26:04 +00002892 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002893 // Allocate some space to put the new indices in
Matthijs Kooijman8369c672008-06-17 08:24:37 +00002894 SmallVector<unsigned, 5> Idxs;
2895 Idxs.reserve(size);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002896 // Add indices from the extract value instruction
Jay Foad57aa6362011-07-13 10:26:04 +00002897 Idxs.append(I->idx_begin(), I->idx_end());
Craig Topper1bef2c82012-12-22 19:15:35 +00002898
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002899 // Add requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00002900 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002901
Craig Topper1bef2c82012-12-22 19:15:35 +00002902 assert(Idxs.size() == size
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002903 && "Number of indices added not correct?");
Craig Topper1bef2c82012-12-22 19:15:35 +00002904
Jay Foad57aa6362011-07-13 10:26:04 +00002905 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002906 }
2907 // Otherwise, we don't know (such as, extracting from a function return value
2908 // or load instruction)
Craig Topper9f008862014-04-15 04:59:12 +00002909 return nullptr;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002910}
Evan Chengda3db112008-06-30 07:31:25 +00002911
Sanjay Patelaee84212014-11-04 16:27:42 +00002912/// Analyze the specified pointer to see if it can be expressed as a base
2913/// pointer plus a constant offset. Return the base and offset to the caller.
Chris Lattnere28618d2010-11-30 22:25:26 +00002914Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002915 const DataLayout &DL) {
2916 unsigned BitWidth = DL.getPointerTypeSizeInBits(Ptr->getType());
Nuno Lopes368c4d02012-12-31 20:48:35 +00002917 APInt ByteOffset(BitWidth, 0);
Chandler Carruth76641272016-01-04 07:23:12 +00002918
2919 // We walk up the defs but use a visited set to handle unreachable code. In
2920 // that case, we stop after accumulating the cycle once (not that it
2921 // matters).
2922 SmallPtrSet<Value *, 16> Visited;
2923 while (Visited.insert(Ptr).second) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002924 if (Ptr->getType()->isVectorTy())
2925 break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002926
Nuno Lopes368c4d02012-12-31 20:48:35 +00002927 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
Tom Stellard17eb3412016-10-07 14:23:29 +00002928 // If one of the values we have visited is an addrspacecast, then
2929 // the pointer type of this GEP may be different from the type
2930 // of the Ptr parameter which was passed to this function. This
2931 // means when we construct GEPOffset, we need to use the size
2932 // of GEP's pointer type rather than the size of the original
2933 // pointer type.
2934 APInt GEPOffset(DL.getPointerTypeSizeInBits(Ptr->getType()), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002935 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
2936 break;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00002937
Tom Stellard17eb3412016-10-07 14:23:29 +00002938 ByteOffset += GEPOffset.getSExtValue();
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00002939
Nuno Lopes368c4d02012-12-31 20:48:35 +00002940 Ptr = GEP->getPointerOperand();
Tom Stellard17eb3412016-10-07 14:23:29 +00002941 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
2942 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002943 Ptr = cast<Operator>(Ptr)->getOperand(0);
2944 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00002945 if (GA->isInterposable())
Nuno Lopes368c4d02012-12-31 20:48:35 +00002946 break;
2947 Ptr = GA->getAliasee();
Chris Lattnere28618d2010-11-30 22:25:26 +00002948 } else {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002949 break;
Chris Lattnere28618d2010-11-30 22:25:26 +00002950 }
2951 }
Nuno Lopes368c4d02012-12-31 20:48:35 +00002952 Offset = ByteOffset.getSExtValue();
2953 return Ptr;
Chris Lattnere28618d2010-11-30 22:25:26 +00002954}
2955
David L Kreitzer752c1442016-04-13 14:31:06 +00002956bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP) {
2957 // Make sure the GEP has exactly three arguments.
2958 if (GEP->getNumOperands() != 3)
2959 return false;
2960
2961 // Make sure the index-ee is a pointer to array of i8.
2962 ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
2963 if (!AT || !AT->getElementType()->isIntegerTy(8))
2964 return false;
2965
2966 // Check to make sure that the first operand of the GEP is an integer and
2967 // has value 0 so that we are sure we're indexing into the initializer.
2968 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
2969 if (!FirstIdx || !FirstIdx->isZero())
2970 return false;
2971
2972 return true;
Sanjoy Das6082c1a2016-05-07 02:08:15 +00002973}
Chris Lattnere28618d2010-11-30 22:25:26 +00002974
Sanjay Patelaee84212014-11-04 16:27:42 +00002975/// This function computes the length of a null-terminated C string pointed to
2976/// by V. If successful, it returns true and returns the string in Str.
2977/// If unsuccessful, it returns false.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002978bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
2979 uint64_t Offset, bool TrimAtNul) {
2980 assert(V);
Evan Chengda3db112008-06-30 07:31:25 +00002981
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002982 // Look through bitcast instructions and geps.
2983 V = V->stripPointerCasts();
Craig Topper1bef2c82012-12-22 19:15:35 +00002984
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00002985 // If the value is a GEP instruction or constant expression, treat it as an
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002986 // offset.
2987 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
David L Kreitzer752c1442016-04-13 14:31:06 +00002988 // The GEP operator should be based on a pointer to string constant, and is
2989 // indexing into the string constant.
2990 if (!isGEPBasedOnPointerToString(GEP))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002991 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002992
Evan Chengda3db112008-06-30 07:31:25 +00002993 // If the second index isn't a ConstantInt, then this is a variable index
2994 // into the array. If this occurs, we can't say anything meaningful about
2995 // the string.
2996 uint64_t StartIdx = 0;
Dan Gohman0b4df042010-04-14 22:20:45 +00002997 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Chengda3db112008-06-30 07:31:25 +00002998 StartIdx = CI->getZExtValue();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002999 else
3000 return false;
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00003001 return getConstantStringInfo(GEP->getOperand(0), Str, StartIdx + Offset,
3002 TrimAtNul);
Evan Chengda3db112008-06-30 07:31:25 +00003003 }
Nick Lewycky46209882011-10-20 00:34:35 +00003004
Evan Chengda3db112008-06-30 07:31:25 +00003005 // The GEP instruction, constant or instruction, must reference a global
3006 // variable that is a constant and is initialized. The referenced constant
3007 // initializer is the array that we'll use for optimization.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003008 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00003009 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003010 return false;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003011
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00003012 // Handle the all-zeros case.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003013 if (GV->getInitializer()->isNullValue()) {
Evan Chengda3db112008-06-30 07:31:25 +00003014 // This is a degenerate case. The initializer is constant zero so the
3015 // length of the string must be zero.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003016 Str = "";
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003017 return true;
3018 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003019
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00003020 // This must be a ConstantDataArray.
3021 const auto *Array = dyn_cast<ConstantDataArray>(GV->getInitializer());
Craig Topper9f008862014-04-15 04:59:12 +00003022 if (!Array || !Array->isString())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003023 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003024
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00003025 // Get the number of elements in the array.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003026 uint64_t NumElts = Array->getType()->getArrayNumElements();
3027
3028 // Start out with the entire array in the StringRef.
3029 Str = Array->getAsString();
3030
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003031 if (Offset > NumElts)
3032 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003033
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003034 // Skip over 'offset' bytes.
3035 Str = Str.substr(Offset);
Craig Topper1bef2c82012-12-22 19:15:35 +00003036
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003037 if (TrimAtNul) {
3038 // Trim off the \0 and anything after it. If the array is not nul
3039 // terminated, we just return the whole end of string. The client may know
3040 // some other way that the string is length-bound.
3041 Str = Str.substr(0, Str.find('\0'));
3042 }
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003043 return true;
Evan Chengda3db112008-06-30 07:31:25 +00003044}
Eric Christopher4899cbc2010-03-05 06:58:57 +00003045
3046// These next two are very similar to the above, but also look through PHI
3047// nodes.
3048// TODO: See if we can integrate these two together.
3049
Sanjay Patelaee84212014-11-04 16:27:42 +00003050/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003051/// the specified pointer, return 'len+1'. If we can't, return 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00003052static uint64_t GetStringLengthH(const Value *V,
3053 SmallPtrSetImpl<const PHINode*> &PHIs) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003054 // Look through noop bitcast instructions.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003055 V = V->stripPointerCasts();
Eric Christopher4899cbc2010-03-05 06:58:57 +00003056
3057 // If this is a PHI node, there are two cases: either we have already seen it
3058 // or we haven't.
Pete Cooper35b00d52016-08-13 01:05:32 +00003059 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
David Blaikie70573dc2014-11-19 07:49:26 +00003060 if (!PHIs.insert(PN).second)
Eric Christopher4899cbc2010-03-05 06:58:57 +00003061 return ~0ULL; // already in the set.
3062
3063 // If it was new, see if all the input strings are the same length.
3064 uint64_t LenSoFar = ~0ULL;
Pete Cooper833f34d2015-05-12 20:05:31 +00003065 for (Value *IncValue : PN->incoming_values()) {
3066 uint64_t Len = GetStringLengthH(IncValue, PHIs);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003067 if (Len == 0) return 0; // Unknown length -> unknown.
3068
3069 if (Len == ~0ULL) continue;
3070
3071 if (Len != LenSoFar && LenSoFar != ~0ULL)
3072 return 0; // Disagree -> unknown.
3073 LenSoFar = Len;
3074 }
3075
3076 // Success, all agree.
3077 return LenSoFar;
3078 }
3079
3080 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
Pete Cooper35b00d52016-08-13 01:05:32 +00003081 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003082 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
3083 if (Len1 == 0) return 0;
3084 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
3085 if (Len2 == 0) return 0;
3086 if (Len1 == ~0ULL) return Len2;
3087 if (Len2 == ~0ULL) return Len1;
3088 if (Len1 != Len2) return 0;
3089 return Len1;
3090 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003091
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003092 // Otherwise, see if we can read the string.
3093 StringRef StrData;
3094 if (!getConstantStringInfo(V, StrData))
Eric Christopher4899cbc2010-03-05 06:58:57 +00003095 return 0;
3096
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003097 return StrData.size()+1;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003098}
3099
Sanjay Patelaee84212014-11-04 16:27:42 +00003100/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003101/// the specified pointer, return 'len+1'. If we can't, return 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00003102uint64_t llvm::GetStringLength(const Value *V) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003103 if (!V->getType()->isPointerTy()) return 0;
3104
Pete Cooper35b00d52016-08-13 01:05:32 +00003105 SmallPtrSet<const PHINode*, 32> PHIs;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003106 uint64_t Len = GetStringLengthH(V, PHIs);
3107 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
3108 // an empty string as a length.
3109 return Len == ~0ULL ? 1 : Len;
3110}
Dan Gohmana4fcd242010-12-15 20:02:24 +00003111
Adam Nemete2b885c2015-04-23 20:09:20 +00003112/// \brief \p PN defines a loop-variant pointer to an object. Check if the
3113/// previous iteration of the loop was referring to the same object as \p PN.
Pete Cooper35b00d52016-08-13 01:05:32 +00003114static bool isSameUnderlyingObjectInLoop(const PHINode *PN,
3115 const LoopInfo *LI) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003116 // Find the loop-defined value.
3117 Loop *L = LI->getLoopFor(PN->getParent());
3118 if (PN->getNumIncomingValues() != 2)
3119 return true;
3120
3121 // Find the value from previous iteration.
3122 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
3123 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3124 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
3125 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3126 return true;
3127
3128 // If a new pointer is loaded in the loop, the pointer references a different
3129 // object in every iteration. E.g.:
3130 // for (i)
3131 // int *p = a[i];
3132 // ...
3133 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
3134 if (!L->isLoopInvariant(Load->getPointerOperand()))
3135 return false;
3136 return true;
3137}
3138
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003139Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
3140 unsigned MaxLookup) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003141 if (!V->getType()->isPointerTy())
3142 return V;
3143 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
3144 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3145 V = GEP->getPointerOperand();
Matt Arsenault70f4db882014-07-15 00:56:40 +00003146 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
3147 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003148 V = cast<Operator>(V)->getOperand(0);
3149 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00003150 if (GA->isInterposable())
Dan Gohmana4fcd242010-12-15 20:02:24 +00003151 return V;
3152 V = GA->getAliasee();
Craig Topper85482412017-04-12 22:29:23 +00003153 } else if (isa<AllocaInst>(V)) {
3154 // An alloca can't be further simplified.
3155 return V;
Dan Gohmana4fcd242010-12-15 20:02:24 +00003156 } else {
Hal Finkel5c12d8f2016-07-11 01:32:20 +00003157 if (auto CS = CallSite(V))
3158 if (Value *RV = CS.getReturnedArgOperand()) {
3159 V = RV;
3160 continue;
3161 }
3162
Dan Gohman05b18f12010-12-15 20:49:55 +00003163 // See if InstructionSimplify knows any relevant tricks.
3164 if (Instruction *I = dyn_cast<Instruction>(V))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003165 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00003166 if (Value *Simplified = SimplifyInstruction(I, {DL, I})) {
Dan Gohman05b18f12010-12-15 20:49:55 +00003167 V = Simplified;
3168 continue;
3169 }
3170
Dan Gohmana4fcd242010-12-15 20:02:24 +00003171 return V;
3172 }
3173 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
3174 }
3175 return V;
3176}
Nick Lewycky3e334a42011-06-27 04:20:45 +00003177
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003178void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
Adam Nemete2b885c2015-04-23 20:09:20 +00003179 const DataLayout &DL, LoopInfo *LI,
3180 unsigned MaxLookup) {
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003181 SmallPtrSet<Value *, 4> Visited;
3182 SmallVector<Value *, 4> Worklist;
3183 Worklist.push_back(V);
3184 do {
3185 Value *P = Worklist.pop_back_val();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003186 P = GetUnderlyingObject(P, DL, MaxLookup);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003187
David Blaikie70573dc2014-11-19 07:49:26 +00003188 if (!Visited.insert(P).second)
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003189 continue;
3190
3191 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
3192 Worklist.push_back(SI->getTrueValue());
3193 Worklist.push_back(SI->getFalseValue());
3194 continue;
3195 }
3196
3197 if (PHINode *PN = dyn_cast<PHINode>(P)) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003198 // If this PHI changes the underlying object in every iteration of the
3199 // loop, don't look through it. Consider:
3200 // int **A;
3201 // for (i) {
3202 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
3203 // Curr = A[i];
3204 // *Prev, *Curr;
3205 //
3206 // Prev is tracking Curr one iteration behind so they refer to different
3207 // underlying objects.
3208 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
3209 isSameUnderlyingObjectInLoop(PN, LI))
Pete Cooper833f34d2015-05-12 20:05:31 +00003210 for (Value *IncValue : PN->incoming_values())
3211 Worklist.push_back(IncValue);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003212 continue;
3213 }
3214
3215 Objects.push_back(P);
3216 } while (!Worklist.empty());
3217}
3218
Sanjay Patelaee84212014-11-04 16:27:42 +00003219/// Return true if the only users of this pointer are lifetime markers.
Nick Lewycky3e334a42011-06-27 04:20:45 +00003220bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003221 for (const User *U : V->users()) {
3222 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Nick Lewycky3e334a42011-06-27 04:20:45 +00003223 if (!II) return false;
3224
3225 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
3226 II->getIntrinsicID() != Intrinsic::lifetime_end)
3227 return false;
3228 }
3229 return true;
3230}
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003231
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003232bool llvm::isSafeToSpeculativelyExecute(const Value *V,
3233 const Instruction *CtxI,
Sean Silva45835e72016-07-02 23:47:27 +00003234 const DominatorTree *DT) {
Dan Gohman7ac046a2012-01-04 23:01:09 +00003235 const Operator *Inst = dyn_cast<Operator>(V);
3236 if (!Inst)
3237 return false;
3238
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003239 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3240 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3241 if (C->canTrap())
3242 return false;
3243
3244 switch (Inst->getOpcode()) {
3245 default:
3246 return true;
3247 case Instruction::UDiv:
David Majnemerf20d7c42014-11-04 23:49:08 +00003248 case Instruction::URem: {
3249 // x / y is undefined if y == 0.
3250 const APInt *V;
3251 if (match(Inst->getOperand(1), m_APInt(V)))
3252 return *V != 0;
3253 return false;
3254 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003255 case Instruction::SDiv:
3256 case Instruction::SRem: {
David Majnemerf20d7c42014-11-04 23:49:08 +00003257 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
David Majnemer8a6578a2015-02-01 19:10:19 +00003258 const APInt *Numerator, *Denominator;
3259 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3260 return false;
3261 // We cannot hoist this division if the denominator is 0.
3262 if (*Denominator == 0)
3263 return false;
3264 // It's safe to hoist if the denominator is not 0 or -1.
3265 if (*Denominator != -1)
3266 return true;
3267 // At this point we know that the denominator is -1. It is safe to hoist as
3268 // long we know that the numerator is not INT_MIN.
3269 if (match(Inst->getOperand(0), m_APInt(Numerator)))
3270 return !Numerator->isMinSignedValue();
3271 // The numerator *might* be MinSignedValue.
David Majnemerf20d7c42014-11-04 23:49:08 +00003272 return false;
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003273 }
3274 case Instruction::Load: {
3275 const LoadInst *LI = cast<LoadInst>(Inst);
Kostya Serebryany0b458282013-11-21 07:29:28 +00003276 if (!LI->isUnordered() ||
3277 // Speculative load may create a race that did not exist in the source.
Sanjoy Dasb66374c2016-07-14 20:19:01 +00003278 LI->getFunction()->hasFnAttribute(Attribute::SanitizeThread) ||
Kostya Serebryany5cb86d52015-10-14 00:21:05 +00003279 // Speculative load may load data from dirty regions.
Sanjoy Dasb66374c2016-07-14 20:19:01 +00003280 LI->getFunction()->hasFnAttribute(Attribute::SanitizeAddress))
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003281 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003282 const DataLayout &DL = LI->getModule()->getDataLayout();
Sean Silva45835e72016-07-02 23:47:27 +00003283 return isDereferenceableAndAlignedPointer(LI->getPointerOperand(),
3284 LI->getAlignment(), DL, CtxI, DT);
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003285 }
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003286 case Instruction::Call: {
Matt Arsenaultcf5e7fe2017-04-28 21:13:09 +00003287 auto *CI = cast<const CallInst>(Inst);
3288 const Function *Callee = CI->getCalledFunction();
David Majnemer0a92f862015-08-28 21:13:39 +00003289
Matt Arsenault6a288c12017-05-03 02:26:10 +00003290 // The called function could have undefined behavior or side-effects, even
3291 // if marked readnone nounwind.
3292 return Callee && Callee->isSpeculatable();
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003293 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003294 case Instruction::VAArg:
3295 case Instruction::Alloca:
3296 case Instruction::Invoke:
3297 case Instruction::PHI:
3298 case Instruction::Store:
3299 case Instruction::Ret:
3300 case Instruction::Br:
3301 case Instruction::IndirectBr:
3302 case Instruction::Switch:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003303 case Instruction::Unreachable:
3304 case Instruction::Fence:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003305 case Instruction::AtomicRMW:
3306 case Instruction::AtomicCmpXchg:
David Majnemer654e1302015-07-31 17:58:14 +00003307 case Instruction::LandingPad:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003308 case Instruction::Resume:
David Majnemer8a1c45d2015-12-12 05:38:55 +00003309 case Instruction::CatchSwitch:
David Majnemer654e1302015-07-31 17:58:14 +00003310 case Instruction::CatchPad:
David Majnemer654e1302015-07-31 17:58:14 +00003311 case Instruction::CatchRet:
3312 case Instruction::CleanupPad:
3313 case Instruction::CleanupRet:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003314 return false; // Misc instructions which have effects
3315 }
3316}
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003317
Quentin Colombet6443cce2015-08-06 18:44:34 +00003318bool llvm::mayBeMemoryDependent(const Instruction &I) {
3319 return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
3320}
3321
Sanjay Patelaee84212014-11-04 16:27:42 +00003322/// Return true if we know that the specified value is never null.
Sean Silva45835e72016-07-02 23:47:27 +00003323bool llvm::isKnownNonNull(const Value *V) {
Chen Li0d043b52015-09-14 18:10:43 +00003324 assert(V->getType()->isPointerTy() && "V must be pointer type");
3325
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003326 // Alloca never returns null, malloc might.
3327 if (isa<AllocaInst>(V)) return true;
3328
Nick Lewyckyd52b1522014-05-20 01:23:40 +00003329 // A byval, inalloca, or nonnull argument is never null.
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003330 if (const Argument *A = dyn_cast<Argument>(V))
Nick Lewyckyd52b1522014-05-20 01:23:40 +00003331 return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003332
Peter Collingbourne235c2752016-12-08 19:01:00 +00003333 // A global variable in address space 0 is non null unless extern weak
3334 // or an absolute symbol reference. Other address spaces may have null as a
3335 // valid address for a global, so we can't assume anything.
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003336 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Peter Collingbourne235c2752016-12-08 19:01:00 +00003337 return !GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
Pete Cooper6b716212015-08-27 03:16:29 +00003338 GV->getType()->getAddressSpace() == 0;
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00003339
Sanjoy Das5056e192016-05-07 02:08:22 +00003340 // A Load tagged with nonnull metadata is never null.
Philip Reamescdb72f32014-10-20 22:40:55 +00003341 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
Philip Reames5a3f5f72014-10-21 00:13:20 +00003342 return LI->getMetadata(LLVMContext::MD_nonnull);
Philip Reamescdb72f32014-10-20 22:40:55 +00003343
Benjamin Kramer3a09ef62015-04-10 14:50:08 +00003344 if (auto CS = ImmutableCallSite(V))
Hal Finkelb0407ba2014-07-18 15:51:28 +00003345 if (CS.isReturnNonNull())
Nick Lewyckyec373542014-05-20 05:13:21 +00003346 return true;
3347
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003348 return false;
3349}
David Majnemer491331a2015-01-02 07:29:43 +00003350
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003351static bool isKnownNonNullFromDominatingCondition(const Value *V,
3352 const Instruction *CtxI,
3353 const DominatorTree *DT) {
Chen Li0d043b52015-09-14 18:10:43 +00003354 assert(V->getType()->isPointerTy() && "V must be pointer type");
Duncan P. N. Exon Smithb4798732016-09-24 19:39:47 +00003355 assert(!isa<ConstantData>(V) && "Did not expect ConstantPointerNull");
Sanjay Patel7fd779f2016-12-31 17:37:01 +00003356 assert(CtxI && "Context instruction required for analysis");
3357 assert(DT && "Dominator tree required for analysis");
Chen Li0d043b52015-09-14 18:10:43 +00003358
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003359 unsigned NumUsesExplored = 0;
Sanjoy Das987aaa12016-05-07 02:08:24 +00003360 for (auto *U : V->users()) {
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003361 // Avoid massive lists
3362 if (NumUsesExplored >= DomConditionsMaxUses)
3363 break;
3364 NumUsesExplored++;
Sanjay Patel97e4b9872017-02-12 15:35:34 +00003365
3366 // If the value is used as an argument to a call or invoke, then argument
3367 // attributes may provide an answer about null-ness.
3368 if (auto CS = ImmutableCallSite(U))
3369 if (auto *CalledFunc = CS.getCalledFunction())
3370 for (const Argument &Arg : CalledFunc->args())
3371 if (CS.getArgOperand(Arg.getArgNo()) == V &&
3372 Arg.hasNonNullAttr() && DT->dominates(CS.getInstruction(), CtxI))
3373 return true;
3374
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003375 // Consider only compare instructions uniquely controlling a branch
Sanjoy Das987aaa12016-05-07 02:08:24 +00003376 CmpInst::Predicate Pred;
3377 if (!match(const_cast<User *>(U),
3378 m_c_ICmp(Pred, m_Specific(V), m_Zero())) ||
3379 (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE))
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003380 continue;
3381
Sanjoy Das987aaa12016-05-07 02:08:24 +00003382 for (auto *CmpU : U->users()) {
Sanjoy Das12c91dc2016-05-10 02:35:44 +00003383 if (const BranchInst *BI = dyn_cast<BranchInst>(CmpU)) {
3384 assert(BI->isConditional() && "uses a comparison!");
Sanjoy Das6082c1a2016-05-07 02:08:15 +00003385
Sanjoy Das12c91dc2016-05-10 02:35:44 +00003386 BasicBlock *NonNullSuccessor =
3387 BI->getSuccessor(Pred == ICmpInst::ICMP_EQ ? 1 : 0);
3388 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3389 if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
3390 return true;
3391 } else if (Pred == ICmpInst::ICMP_NE &&
3392 match(CmpU, m_Intrinsic<Intrinsic::experimental_guard>()) &&
3393 DT->dominates(cast<Instruction>(CmpU), CtxI)) {
Sanjoy Das987aaa12016-05-07 02:08:24 +00003394 return true;
Sanjoy Das12c91dc2016-05-10 02:35:44 +00003395 }
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003396 }
3397 }
3398
3399 return false;
3400}
3401
3402bool llvm::isKnownNonNullAt(const Value *V, const Instruction *CtxI,
Sean Silva45835e72016-07-02 23:47:27 +00003403 const DominatorTree *DT) {
Duncan P. N. Exon Smithb4798732016-09-24 19:39:47 +00003404 if (isa<ConstantPointerNull>(V) || isa<UndefValue>(V))
3405 return false;
3406
Sean Silva45835e72016-07-02 23:47:27 +00003407 if (isKnownNonNull(V))
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003408 return true;
3409
Sanjay Patel7fd779f2016-12-31 17:37:01 +00003410 if (!CtxI || !DT)
3411 return false;
3412
3413 return ::isKnownNonNullFromDominatingCondition(V, CtxI, DT);
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003414}
3415
Pete Cooper35b00d52016-08-13 01:05:32 +00003416OverflowResult llvm::computeOverflowForUnsignedMul(const Value *LHS,
3417 const Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003418 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003419 AssumptionCache *AC,
David Majnemer491331a2015-01-02 07:29:43 +00003420 const Instruction *CxtI,
3421 const DominatorTree *DT) {
3422 // Multiplying n * m significant bits yields a result of n + m significant
3423 // bits. If the total number of significant bits does not exceed the
3424 // result bit width (minus 1), there is no overflow.
3425 // This means if we have enough leading zero bits in the operands
3426 // we can guarantee that the result does not overflow.
3427 // Ref: "Hacker's Delight" by Henry Warren
3428 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00003429 KnownBits LHSKnown(BitWidth);
3430 KnownBits RHSKnown(BitWidth);
3431 computeKnownBits(LHS, LHSKnown, DL, /*Depth=*/0, AC, CxtI, DT);
3432 computeKnownBits(RHS, RHSKnown, DL, /*Depth=*/0, AC, CxtI, DT);
David Majnemer491331a2015-01-02 07:29:43 +00003433 // Note that underestimating the number of zero bits gives a more
3434 // conservative answer.
Craig Topper8df66c62017-05-12 17:20:30 +00003435 unsigned ZeroBits = LHSKnown.countMinLeadingZeros() +
3436 RHSKnown.countMinLeadingZeros();
David Majnemer491331a2015-01-02 07:29:43 +00003437 // First handle the easy case: if we have enough zero bits there's
3438 // definitely no overflow.
3439 if (ZeroBits >= BitWidth)
3440 return OverflowResult::NeverOverflows;
3441
3442 // Get the largest possible values for each operand.
Craig Topperb45eabc2017-04-26 16:39:58 +00003443 APInt LHSMax = ~LHSKnown.Zero;
3444 APInt RHSMax = ~RHSKnown.Zero;
David Majnemer491331a2015-01-02 07:29:43 +00003445
3446 // We know the multiply operation doesn't overflow if the maximum values for
3447 // each operand will not overflow after we multiply them together.
David Majnemerc8a576b2015-01-02 07:29:47 +00003448 bool MaxOverflow;
Craig Topper9b71a402017-04-19 21:09:45 +00003449 (void)LHSMax.umul_ov(RHSMax, MaxOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00003450 if (!MaxOverflow)
3451 return OverflowResult::NeverOverflows;
David Majnemer491331a2015-01-02 07:29:43 +00003452
David Majnemerc8a576b2015-01-02 07:29:47 +00003453 // We know it always overflows if multiplying the smallest possible values for
3454 // the operands also results in overflow.
3455 bool MinOverflow;
Craig Topperb45eabc2017-04-26 16:39:58 +00003456 (void)LHSKnown.One.umul_ov(RHSKnown.One, MinOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00003457 if (MinOverflow)
3458 return OverflowResult::AlwaysOverflows;
3459
3460 return OverflowResult::MayOverflow;
David Majnemer491331a2015-01-02 07:29:43 +00003461}
David Majnemer5310c1e2015-01-07 00:39:50 +00003462
Pete Cooper35b00d52016-08-13 01:05:32 +00003463OverflowResult llvm::computeOverflowForUnsignedAdd(const Value *LHS,
3464 const Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003465 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003466 AssumptionCache *AC,
David Majnemer5310c1e2015-01-07 00:39:50 +00003467 const Instruction *CxtI,
3468 const DominatorTree *DT) {
Craig Topper6e11a052017-05-08 16:22:48 +00003469 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
3470 if (LHSKnown.isNonNegative() || LHSKnown.isNegative()) {
3471 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
David Majnemer5310c1e2015-01-07 00:39:50 +00003472
Craig Topper6e11a052017-05-08 16:22:48 +00003473 if (LHSKnown.isNegative() && RHSKnown.isNegative()) {
David Majnemer5310c1e2015-01-07 00:39:50 +00003474 // The sign bit is set in both cases: this MUST overflow.
3475 // Create a simple add instruction, and insert it into the struct.
3476 return OverflowResult::AlwaysOverflows;
3477 }
3478
Craig Topper6e11a052017-05-08 16:22:48 +00003479 if (LHSKnown.isNonNegative() && RHSKnown.isNonNegative()) {
David Majnemer5310c1e2015-01-07 00:39:50 +00003480 // The sign bit is clear in both cases: this CANNOT overflow.
3481 // Create a simple add instruction, and insert it into the struct.
3482 return OverflowResult::NeverOverflows;
3483 }
3484 }
3485
3486 return OverflowResult::MayOverflow;
3487}
James Molloy71b91c22015-05-11 14:42:20 +00003488
Craig Topperbb973722017-05-15 02:44:08 +00003489/// \brief Return true if we can prove that adding the two values of the
3490/// knownbits will not overflow.
3491/// Otherwise return false.
3492static bool checkRippleForSignedAdd(const KnownBits &LHSKnown,
3493 const KnownBits &RHSKnown) {
3494 // Addition of two 2's complement numbers having opposite signs will never
3495 // overflow.
3496 if ((LHSKnown.isNegative() && RHSKnown.isNonNegative()) ||
3497 (LHSKnown.isNonNegative() && RHSKnown.isNegative()))
3498 return true;
3499
3500 // If either of the values is known to be non-negative, adding them can only
3501 // overflow if the second is also non-negative, so we can assume that.
3502 // Two non-negative numbers will only overflow if there is a carry to the
3503 // sign bit, so we can check if even when the values are as big as possible
3504 // there is no overflow to the sign bit.
3505 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative()) {
3506 APInt MaxLHS = ~LHSKnown.Zero;
3507 MaxLHS.clearSignBit();
3508 APInt MaxRHS = ~RHSKnown.Zero;
3509 MaxRHS.clearSignBit();
3510 APInt Result = std::move(MaxLHS) + std::move(MaxRHS);
3511 return Result.isSignBitClear();
3512 }
3513
3514 // If either of the values is known to be negative, adding them can only
3515 // overflow if the second is also negative, so we can assume that.
3516 // Two negative number will only overflow if there is no carry to the sign
3517 // bit, so we can check if even when the values are as small as possible
3518 // there is overflow to the sign bit.
3519 if (LHSKnown.isNegative() || RHSKnown.isNegative()) {
3520 APInt MinLHS = LHSKnown.One;
3521 MinLHS.clearSignBit();
3522 APInt MinRHS = RHSKnown.One;
3523 MinRHS.clearSignBit();
3524 APInt Result = std::move(MinLHS) + std::move(MinRHS);
3525 return Result.isSignBitSet();
3526 }
3527
3528 // If we reached here it means that we know nothing about the sign bits.
3529 // In this case we can't know if there will be an overflow, since by
3530 // changing the sign bits any two values can be made to overflow.
3531 return false;
3532}
3533
Pete Cooper35b00d52016-08-13 01:05:32 +00003534static OverflowResult computeOverflowForSignedAdd(const Value *LHS,
3535 const Value *RHS,
3536 const AddOperator *Add,
3537 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003538 AssumptionCache *AC,
Pete Cooper35b00d52016-08-13 01:05:32 +00003539 const Instruction *CxtI,
3540 const DominatorTree *DT) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00003541 if (Add && Add->hasNoSignedWrap()) {
3542 return OverflowResult::NeverOverflows;
3543 }
3544
Craig Topperbb973722017-05-15 02:44:08 +00003545 // If LHS and RHS each have at least two sign bits, the addition will look
3546 // like
3547 //
3548 // XX..... +
3549 // YY.....
3550 //
3551 // If the carry into the most significant position is 0, X and Y can't both
3552 // be 1 and therefore the carry out of the addition is also 0.
3553 //
3554 // If the carry into the most significant position is 1, X and Y can't both
3555 // be 0 and therefore the carry out of the addition is also 1.
3556 //
3557 // Since the carry into the most significant position is always equal to
3558 // the carry out of the addition, there is no signed overflow.
3559 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
3560 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
3561 return OverflowResult::NeverOverflows;
3562
Craig Topper6e11a052017-05-08 16:22:48 +00003563 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
3564 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003565
Craig Topperbb973722017-05-15 02:44:08 +00003566 if (checkRippleForSignedAdd(LHSKnown, RHSKnown))
Jingyue Wu10fcea52015-08-20 18:27:04 +00003567 return OverflowResult::NeverOverflows;
Jingyue Wu10fcea52015-08-20 18:27:04 +00003568
3569 // The remaining code needs Add to be available. Early returns if not so.
3570 if (!Add)
3571 return OverflowResult::MayOverflow;
3572
3573 // If the sign of Add is the same as at least one of the operands, this add
3574 // CANNOT overflow. This is particularly useful when the sum is
3575 // @llvm.assume'ed non-negative rather than proved so from analyzing its
3576 // operands.
3577 bool LHSOrRHSKnownNonNegative =
Craig Topper6e11a052017-05-08 16:22:48 +00003578 (LHSKnown.isNonNegative() || RHSKnown.isNonNegative());
Craig Topperbb973722017-05-15 02:44:08 +00003579 bool LHSOrRHSKnownNegative =
3580 (LHSKnown.isNegative() || RHSKnown.isNegative());
Jingyue Wu10fcea52015-08-20 18:27:04 +00003581 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
Craig Topper6e11a052017-05-08 16:22:48 +00003582 KnownBits AddKnown = computeKnownBits(Add, DL, /*Depth=*/0, AC, CxtI, DT);
3583 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
3584 (AddKnown.isNegative() && LHSOrRHSKnownNegative)) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00003585 return OverflowResult::NeverOverflows;
3586 }
3587 }
3588
3589 return OverflowResult::MayOverflow;
3590}
3591
Pete Cooper35b00d52016-08-13 01:05:32 +00003592bool llvm::isOverflowIntrinsicNoWrap(const IntrinsicInst *II,
3593 const DominatorTree &DT) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003594#ifndef NDEBUG
3595 auto IID = II->getIntrinsicID();
3596 assert((IID == Intrinsic::sadd_with_overflow ||
3597 IID == Intrinsic::uadd_with_overflow ||
3598 IID == Intrinsic::ssub_with_overflow ||
3599 IID == Intrinsic::usub_with_overflow ||
3600 IID == Intrinsic::smul_with_overflow ||
3601 IID == Intrinsic::umul_with_overflow) &&
3602 "Not an overflow intrinsic!");
3603#endif
3604
Pete Cooper35b00d52016-08-13 01:05:32 +00003605 SmallVector<const BranchInst *, 2> GuardingBranches;
3606 SmallVector<const ExtractValueInst *, 2> Results;
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003607
Pete Cooper35b00d52016-08-13 01:05:32 +00003608 for (const User *U : II->users()) {
3609 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003610 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
3611
3612 if (EVI->getIndices()[0] == 0)
3613 Results.push_back(EVI);
3614 else {
3615 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
3616
Pete Cooper35b00d52016-08-13 01:05:32 +00003617 for (const auto *U : EVI->users())
3618 if (const auto *B = dyn_cast<BranchInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003619 assert(B->isConditional() && "How else is it using an i1?");
3620 GuardingBranches.push_back(B);
3621 }
3622 }
3623 } else {
3624 // We are using the aggregate directly in a way we don't want to analyze
3625 // here (storing it to a global, say).
3626 return false;
3627 }
3628 }
3629
Pete Cooper35b00d52016-08-13 01:05:32 +00003630 auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003631 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
3632 if (!NoWrapEdge.isSingleEdge())
3633 return false;
3634
3635 // Check if all users of the add are provably no-wrap.
Pete Cooper35b00d52016-08-13 01:05:32 +00003636 for (const auto *Result : Results) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003637 // If the extractvalue itself is not executed on overflow, the we don't
3638 // need to check each use separately, since domination is transitive.
3639 if (DT.dominates(NoWrapEdge, Result->getParent()))
3640 continue;
3641
3642 for (auto &RU : Result->uses())
3643 if (!DT.dominates(NoWrapEdge, RU))
3644 return false;
3645 }
3646
3647 return true;
3648 };
3649
3650 return any_of(GuardingBranches, AllUsesGuardedByBranch);
3651}
3652
3653
Pete Cooper35b00d52016-08-13 01:05:32 +00003654OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003655 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003656 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003657 const Instruction *CxtI,
3658 const DominatorTree *DT) {
3659 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003660 Add, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003661}
3662
Pete Cooper35b00d52016-08-13 01:05:32 +00003663OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS,
3664 const Value *RHS,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003665 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003666 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003667 const Instruction *CxtI,
3668 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003669 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003670}
3671
Jingyue Wu42f1d672015-07-28 18:22:40 +00003672bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003673 // A memory operation returns normally if it isn't volatile. A volatile
3674 // operation is allowed to trap.
3675 //
3676 // An atomic operation isn't guaranteed to return in a reasonable amount of
3677 // time because it's possible for another thread to interfere with it for an
3678 // arbitrary length of time, but programs aren't allowed to rely on that.
3679 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
3680 return !LI->isVolatile();
3681 if (const StoreInst *SI = dyn_cast<StoreInst>(I))
3682 return !SI->isVolatile();
3683 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
3684 return !CXI->isVolatile();
3685 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
3686 return !RMWI->isVolatile();
3687 if (const MemIntrinsic *MII = dyn_cast<MemIntrinsic>(I))
3688 return !MII->isVolatile();
Jingyue Wu42f1d672015-07-28 18:22:40 +00003689
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003690 // If there is no successor, then execution can't transfer to it.
3691 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I))
3692 return !CRI->unwindsToCaller();
3693 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I))
3694 return !CatchSwitch->unwindsToCaller();
3695 if (isa<ResumeInst>(I))
3696 return false;
3697 if (isa<ReturnInst>(I))
3698 return false;
Sebastian Pop4a4d2452017-03-08 01:54:50 +00003699 if (isa<UnreachableInst>(I))
3700 return false;
Sanjoy Das9a65cd22016-06-08 17:48:36 +00003701
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003702 // Calls can throw, or contain an infinite loop, or kill the process.
Sanjoy Das09455302016-12-31 22:12:31 +00003703 if (auto CS = ImmutableCallSite(I)) {
Sanjoy Das3bb2dbd2016-12-31 22:12:34 +00003704 // Call sites that throw have implicit non-local control flow.
3705 if (!CS.doesNotThrow())
3706 return false;
3707
3708 // Non-throwing call sites can loop infinitely, call exit/pthread_exit
3709 // etc. and thus not return. However, LLVM already assumes that
3710 //
3711 // - Thread exiting actions are modeled as writes to memory invisible to
3712 // the program.
3713 //
3714 // - Loops that don't have side effects (side effects are volatile/atomic
3715 // stores and IO) always terminate (see http://llvm.org/PR965).
3716 // Furthermore IO itself is also modeled as writes to memory invisible to
3717 // the program.
3718 //
3719 // We rely on those assumptions here, and use the memory effects of the call
3720 // target as a proxy for checking that it always returns.
3721
3722 // FIXME: This isn't aggressive enough; a call which only writes to a global
3723 // is guaranteed to return.
Sanjoy Dasd7e82062016-06-14 20:23:16 +00003724 return CS.onlyReadsMemory() || CS.onlyAccessesArgMemory() ||
3725 match(I, m_Intrinsic<Intrinsic::assume>());
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003726 }
3727
3728 // Other instructions return normally.
3729 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003730}
3731
3732bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
3733 const Loop *L) {
3734 // The loop header is guaranteed to be executed for every iteration.
3735 //
3736 // FIXME: Relax this constraint to cover all basic blocks that are
3737 // guaranteed to be executed at every iteration.
3738 if (I->getParent() != L->getHeader()) return false;
3739
3740 for (const Instruction &LI : *L->getHeader()) {
3741 if (&LI == I) return true;
3742 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
3743 }
3744 llvm_unreachable("Instruction not contained in its own parent basic block.");
3745}
3746
3747bool llvm::propagatesFullPoison(const Instruction *I) {
3748 switch (I->getOpcode()) {
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003749 case Instruction::Add:
3750 case Instruction::Sub:
3751 case Instruction::Xor:
3752 case Instruction::Trunc:
3753 case Instruction::BitCast:
3754 case Instruction::AddrSpaceCast:
Sanjoy Das5cd6c5ca2017-02-22 06:52:32 +00003755 case Instruction::Mul:
3756 case Instruction::Shl:
3757 case Instruction::GetElementPtr:
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003758 // These operations all propagate poison unconditionally. Note that poison
3759 // is not any particular value, so xor or subtraction of poison with
3760 // itself still yields poison, not zero.
3761 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003762
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003763 case Instruction::AShr:
3764 case Instruction::SExt:
3765 // For these operations, one bit of the input is replicated across
3766 // multiple output bits. A replicated poison bit is still poison.
3767 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003768
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003769 case Instruction::ICmp:
3770 // Comparing poison with any value yields poison. This is why, for
3771 // instance, x s< (x +nsw 1) can be folded to true.
3772 return true;
Sanjoy Das70c2bbd2016-05-29 00:31:18 +00003773
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003774 default:
3775 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003776 }
3777}
3778
3779const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
3780 switch (I->getOpcode()) {
3781 case Instruction::Store:
3782 return cast<StoreInst>(I)->getPointerOperand();
3783
3784 case Instruction::Load:
3785 return cast<LoadInst>(I)->getPointerOperand();
3786
3787 case Instruction::AtomicCmpXchg:
3788 return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
3789
3790 case Instruction::AtomicRMW:
3791 return cast<AtomicRMWInst>(I)->getPointerOperand();
3792
3793 case Instruction::UDiv:
3794 case Instruction::SDiv:
3795 case Instruction::URem:
3796 case Instruction::SRem:
3797 return I->getOperand(1);
3798
3799 default:
3800 return nullptr;
3801 }
3802}
3803
Sanjoy Das08989c72017-04-30 19:41:19 +00003804bool llvm::programUndefinedIfFullPoison(const Instruction *PoisonI) {
Jingyue Wu42f1d672015-07-28 18:22:40 +00003805 // We currently only look for uses of poison values within the same basic
3806 // block, as that makes it easier to guarantee that the uses will be
3807 // executed given that PoisonI is executed.
3808 //
3809 // FIXME: Expand this to consider uses beyond the same basic block. To do
3810 // this, look out for the distinction between post-dominance and strong
3811 // post-dominance.
3812 const BasicBlock *BB = PoisonI->getParent();
3813
3814 // Set of instructions that we have proved will yield poison if PoisonI
3815 // does.
3816 SmallSet<const Value *, 16> YieldsPoison;
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003817 SmallSet<const BasicBlock *, 4> Visited;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003818 YieldsPoison.insert(PoisonI);
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003819 Visited.insert(PoisonI->getParent());
Jingyue Wu42f1d672015-07-28 18:22:40 +00003820
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003821 BasicBlock::const_iterator Begin = PoisonI->getIterator(), End = BB->end();
Jingyue Wu42f1d672015-07-28 18:22:40 +00003822
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003823 unsigned Iter = 0;
3824 while (Iter++ < MaxDepth) {
3825 for (auto &I : make_range(Begin, End)) {
3826 if (&I != PoisonI) {
3827 const Value *NotPoison = getGuaranteedNonFullPoisonOp(&I);
3828 if (NotPoison != nullptr && YieldsPoison.count(NotPoison))
3829 return true;
3830 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
3831 return false;
3832 }
3833
3834 // Mark poison that propagates from I through uses of I.
3835 if (YieldsPoison.count(&I)) {
3836 for (const User *User : I.users()) {
3837 const Instruction *UserI = cast<Instruction>(User);
3838 if (propagatesFullPoison(UserI))
3839 YieldsPoison.insert(User);
3840 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003841 }
3842 }
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003843
3844 if (auto *NextBB = BB->getSingleSuccessor()) {
3845 if (Visited.insert(NextBB).second) {
3846 BB = NextBB;
3847 Begin = BB->getFirstNonPHI()->getIterator();
3848 End = BB->end();
3849 continue;
3850 }
3851 }
3852
3853 break;
3854 };
Jingyue Wu42f1d672015-07-28 18:22:40 +00003855 return false;
3856}
3857
Pete Cooper35b00d52016-08-13 01:05:32 +00003858static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
James Molloy134bec22015-08-11 09:12:57 +00003859 if (FMF.noNaNs())
3860 return true;
3861
3862 if (auto *C = dyn_cast<ConstantFP>(V))
3863 return !C->isNaN();
3864 return false;
3865}
3866
Pete Cooper35b00d52016-08-13 01:05:32 +00003867static bool isKnownNonZero(const Value *V) {
James Molloy134bec22015-08-11 09:12:57 +00003868 if (auto *C = dyn_cast<ConstantFP>(V))
3869 return !C->isZero();
3870 return false;
3871}
3872
Sanjay Patel819f0962016-11-13 19:30:19 +00003873/// Match non-obvious integer minimum and maximum sequences.
3874static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
3875 Value *CmpLHS, Value *CmpRHS,
3876 Value *TrueVal, Value *FalseVal,
3877 Value *&LHS, Value *&RHS) {
Sanjay Patel24c6f882017-01-21 17:51:25 +00003878 // Assume success. If there's no match, callers should not use these anyway.
3879 LHS = TrueVal;
3880 RHS = FalseVal;
3881
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003882 // Recognize variations of:
3883 // CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
3884 const APInt *C1;
3885 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
3886 const APInt *C2;
3887
3888 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
3889 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003890 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003891 return {SPF_SMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003892
3893 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
3894 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003895 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003896 return {SPF_SMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003897
3898 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
3899 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003900 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003901 return {SPF_UMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003902
3903 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
3904 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003905 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003906 return {SPF_UMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003907 }
3908
Sanjay Patel819f0962016-11-13 19:30:19 +00003909 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
3910 return {SPF_UNKNOWN, SPNB_NA, false};
3911
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00003912 // Z = X -nsw Y
3913 // (X >s Y) ? 0 : Z ==> (Z >s 0) ? 0 : Z ==> SMIN(Z, 0)
3914 // (X <s Y) ? 0 : Z ==> (Z <s 0) ? 0 : Z ==> SMAX(Z, 0)
3915 if (match(TrueVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003916 match(FalseVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00003917 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00003918
3919 // Z = X -nsw Y
3920 // (X >s Y) ? Z : 0 ==> (Z >s 0) ? Z : 0 ==> SMAX(Z, 0)
3921 // (X <s Y) ? Z : 0 ==> (Z <s 0) ? Z : 0 ==> SMIN(Z, 0)
3922 if (match(FalseVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003923 match(TrueVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00003924 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00003925
Sanjay Patel819f0962016-11-13 19:30:19 +00003926 if (!match(CmpRHS, m_APInt(C1)))
3927 return {SPF_UNKNOWN, SPNB_NA, false};
3928
3929 // An unsigned min/max can be written with a signed compare.
3930 const APInt *C2;
3931 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
3932 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
3933 // Is the sign bit set?
3934 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
3935 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
Sanjay Patel24c6f882017-01-21 17:51:25 +00003936 if (Pred == CmpInst::ICMP_SLT && *C1 == 0 && C2->isMaxSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00003937 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00003938
3939 // Is the sign bit clear?
3940 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
3941 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
3942 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnesValue() &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003943 C2->isMinSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00003944 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00003945 }
3946
3947 // Look through 'not' ops to find disguised signed min/max.
3948 // (X >s C) ? ~X : ~C ==> (~X <s ~C) ? ~X : ~C ==> SMIN(~X, ~C)
3949 // (X <s C) ? ~X : ~C ==> (~X >s ~C) ? ~X : ~C ==> SMAX(~X, ~C)
3950 if (match(TrueVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003951 match(FalseVal, m_APInt(C2)) && ~(*C1) == *C2)
Sanjay Patel819f0962016-11-13 19:30:19 +00003952 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00003953
3954 // (X >s C) ? ~C : ~X ==> (~X <s ~C) ? ~C : ~X ==> SMAX(~C, ~X)
3955 // (X <s C) ? ~C : ~X ==> (~X >s ~C) ? ~C : ~X ==> SMIN(~C, ~X)
3956 if (match(FalseVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003957 match(TrueVal, m_APInt(C2)) && ~(*C1) == *C2)
Sanjay Patel819f0962016-11-13 19:30:19 +00003958 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00003959
3960 return {SPF_UNKNOWN, SPNB_NA, false};
3961}
3962
James Molloy134bec22015-08-11 09:12:57 +00003963static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
3964 FastMathFlags FMF,
James Molloy270ef8c2015-05-15 16:04:50 +00003965 Value *CmpLHS, Value *CmpRHS,
3966 Value *TrueVal, Value *FalseVal,
3967 Value *&LHS, Value *&RHS) {
James Molloy71b91c22015-05-11 14:42:20 +00003968 LHS = CmpLHS;
3969 RHS = CmpRHS;
3970
James Molloy134bec22015-08-11 09:12:57 +00003971 // If the predicate is an "or-equal" (FP) predicate, then signed zeroes may
3972 // return inconsistent results between implementations.
3973 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
3974 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
3975 // Therefore we behave conservatively and only proceed if at least one of the
3976 // operands is known to not be zero, or if we don't care about signed zeroes.
3977 switch (Pred) {
3978 default: break;
3979 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
3980 case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
3981 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
3982 !isKnownNonZero(CmpRHS))
3983 return {SPF_UNKNOWN, SPNB_NA, false};
3984 }
3985
3986 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
3987 bool Ordered = false;
3988
3989 // When given one NaN and one non-NaN input:
3990 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
3991 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
3992 // ordered comparison fails), which could be NaN or non-NaN.
3993 // so here we discover exactly what NaN behavior is required/accepted.
3994 if (CmpInst::isFPPredicate(Pred)) {
3995 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
3996 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
3997
3998 if (LHSSafe && RHSSafe) {
3999 // Both operands are known non-NaN.
4000 NaNBehavior = SPNB_RETURNS_ANY;
4001 } else if (CmpInst::isOrdered(Pred)) {
4002 // An ordered comparison will return false when given a NaN, so it
4003 // returns the RHS.
4004 Ordered = true;
4005 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004006 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004007 NaNBehavior = SPNB_RETURNS_NAN;
4008 else if (RHSSafe)
4009 NaNBehavior = SPNB_RETURNS_OTHER;
4010 else
4011 // Completely unsafe.
4012 return {SPF_UNKNOWN, SPNB_NA, false};
4013 } else {
4014 Ordered = false;
4015 // An unordered comparison will return true when given a NaN, so it
4016 // returns the LHS.
4017 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004018 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004019 NaNBehavior = SPNB_RETURNS_OTHER;
4020 else if (RHSSafe)
4021 NaNBehavior = SPNB_RETURNS_NAN;
4022 else
4023 // Completely unsafe.
4024 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004025 }
4026 }
4027
James Molloy71b91c22015-05-11 14:42:20 +00004028 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
James Molloy134bec22015-08-11 09:12:57 +00004029 std::swap(CmpLHS, CmpRHS);
4030 Pred = CmpInst::getSwappedPredicate(Pred);
4031 if (NaNBehavior == SPNB_RETURNS_NAN)
4032 NaNBehavior = SPNB_RETURNS_OTHER;
4033 else if (NaNBehavior == SPNB_RETURNS_OTHER)
4034 NaNBehavior = SPNB_RETURNS_NAN;
4035 Ordered = !Ordered;
4036 }
4037
4038 // ([if]cmp X, Y) ? X : Y
4039 if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
James Molloy71b91c22015-05-11 14:42:20 +00004040 switch (Pred) {
James Molloy134bec22015-08-11 09:12:57 +00004041 default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
James Molloy71b91c22015-05-11 14:42:20 +00004042 case ICmpInst::ICMP_UGT:
James Molloy134bec22015-08-11 09:12:57 +00004043 case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004044 case ICmpInst::ICMP_SGT:
James Molloy134bec22015-08-11 09:12:57 +00004045 case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004046 case ICmpInst::ICMP_ULT:
James Molloy134bec22015-08-11 09:12:57 +00004047 case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004048 case ICmpInst::ICMP_SLT:
James Molloy134bec22015-08-11 09:12:57 +00004049 case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
4050 case FCmpInst::FCMP_UGT:
4051 case FCmpInst::FCMP_UGE:
4052 case FCmpInst::FCMP_OGT:
4053 case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
4054 case FCmpInst::FCMP_ULT:
4055 case FCmpInst::FCMP_ULE:
4056 case FCmpInst::FCMP_OLT:
4057 case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
James Molloy71b91c22015-05-11 14:42:20 +00004058 }
4059 }
4060
Sanjay Patele372aec2016-10-27 15:26:10 +00004061 const APInt *C1;
4062 if (match(CmpRHS, m_APInt(C1))) {
James Molloy71b91c22015-05-11 14:42:20 +00004063 if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) ||
4064 (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) {
4065
4066 // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X
4067 // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X
Sanjay Patele372aec2016-10-27 15:26:10 +00004068 if (Pred == ICmpInst::ICMP_SGT && (*C1 == 0 || C1->isAllOnesValue())) {
James Molloy134bec22015-08-11 09:12:57 +00004069 return {(CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004070 }
4071
4072 // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X
4073 // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X
Sanjay Patele372aec2016-10-27 15:26:10 +00004074 if (Pred == ICmpInst::ICMP_SLT && (*C1 == 0 || *C1 == 1)) {
James Molloy134bec22015-08-11 09:12:57 +00004075 return {(CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004076 }
4077 }
James Molloy71b91c22015-05-11 14:42:20 +00004078 }
4079
Sanjay Patel819f0962016-11-13 19:30:19 +00004080 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
James Molloy71b91c22015-05-11 14:42:20 +00004081}
James Molloy270ef8c2015-05-15 16:04:50 +00004082
James Molloy569cea62015-09-02 17:25:25 +00004083static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
4084 Instruction::CastOps *CastOp) {
Sanjay Patel14a4b812017-01-29 16:34:57 +00004085 auto *Cast1 = dyn_cast<CastInst>(V1);
4086 if (!Cast1)
James Molloy270ef8c2015-05-15 16:04:50 +00004087 return nullptr;
James Molloy270ef8c2015-05-15 16:04:50 +00004088
Sanjay Patel14a4b812017-01-29 16:34:57 +00004089 *CastOp = Cast1->getOpcode();
4090 Type *SrcTy = Cast1->getSrcTy();
4091 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
4092 // If V1 and V2 are both the same cast from the same type, look through V1.
4093 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
4094 return Cast2->getOperand(0);
James Molloy569cea62015-09-02 17:25:25 +00004095 return nullptr;
4096 }
4097
Sanjay Patel14a4b812017-01-29 16:34:57 +00004098 auto *C = dyn_cast<Constant>(V2);
4099 if (!C)
4100 return nullptr;
4101
David Majnemerd2a074b2016-04-29 18:40:34 +00004102 Constant *CastedTo = nullptr;
Sanjay Patel14a4b812017-01-29 16:34:57 +00004103 switch (*CastOp) {
4104 case Instruction::ZExt:
4105 if (CmpI->isUnsigned())
4106 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
4107 break;
4108 case Instruction::SExt:
4109 if (CmpI->isSigned())
4110 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
4111 break;
4112 case Instruction::Trunc:
4113 CastedTo = ConstantExpr::getIntegerCast(C, SrcTy, CmpI->isSigned());
4114 break;
4115 case Instruction::FPTrunc:
4116 CastedTo = ConstantExpr::getFPExtend(C, SrcTy, true);
4117 break;
4118 case Instruction::FPExt:
4119 CastedTo = ConstantExpr::getFPTrunc(C, SrcTy, true);
4120 break;
4121 case Instruction::FPToUI:
4122 CastedTo = ConstantExpr::getUIToFP(C, SrcTy, true);
4123 break;
4124 case Instruction::FPToSI:
4125 CastedTo = ConstantExpr::getSIToFP(C, SrcTy, true);
4126 break;
4127 case Instruction::UIToFP:
4128 CastedTo = ConstantExpr::getFPToUI(C, SrcTy, true);
4129 break;
4130 case Instruction::SIToFP:
4131 CastedTo = ConstantExpr::getFPToSI(C, SrcTy, true);
4132 break;
4133 default:
4134 break;
4135 }
David Majnemerd2a074b2016-04-29 18:40:34 +00004136
4137 if (!CastedTo)
4138 return nullptr;
4139
David Majnemerd2a074b2016-04-29 18:40:34 +00004140 // Make sure the cast doesn't lose any information.
Sanjay Patel14a4b812017-01-29 16:34:57 +00004141 Constant *CastedBack =
4142 ConstantExpr::getCast(*CastOp, CastedTo, C->getType(), true);
David Majnemerd2a074b2016-04-29 18:40:34 +00004143 if (CastedBack != C)
4144 return nullptr;
4145
4146 return CastedTo;
James Molloy270ef8c2015-05-15 16:04:50 +00004147}
4148
Sanjay Patele8dc0902016-05-23 17:57:54 +00004149SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004150 Instruction::CastOps *CastOp) {
4151 SelectInst *SI = dyn_cast<SelectInst>(V);
James Molloy134bec22015-08-11 09:12:57 +00004152 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004153
James Molloy134bec22015-08-11 09:12:57 +00004154 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
4155 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004156
James Molloy134bec22015-08-11 09:12:57 +00004157 CmpInst::Predicate Pred = CmpI->getPredicate();
James Molloy270ef8c2015-05-15 16:04:50 +00004158 Value *CmpLHS = CmpI->getOperand(0);
4159 Value *CmpRHS = CmpI->getOperand(1);
4160 Value *TrueVal = SI->getTrueValue();
4161 Value *FalseVal = SI->getFalseValue();
James Molloy134bec22015-08-11 09:12:57 +00004162 FastMathFlags FMF;
4163 if (isa<FPMathOperator>(CmpI))
4164 FMF = CmpI->getFastMathFlags();
James Molloy270ef8c2015-05-15 16:04:50 +00004165
4166 // Bail out early.
4167 if (CmpI->isEquality())
James Molloy134bec22015-08-11 09:12:57 +00004168 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004169
4170 // Deal with type mismatches.
4171 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
James Molloy569cea62015-09-02 17:25:25 +00004172 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp))
James Molloy134bec22015-08-11 09:12:57 +00004173 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004174 cast<CastInst>(TrueVal)->getOperand(0), C,
4175 LHS, RHS);
James Molloy569cea62015-09-02 17:25:25 +00004176 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp))
James Molloy134bec22015-08-11 09:12:57 +00004177 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004178 C, cast<CastInst>(FalseVal)->getOperand(0),
4179 LHS, RHS);
4180 }
James Molloy134bec22015-08-11 09:12:57 +00004181 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
James Molloy270ef8c2015-05-15 16:04:50 +00004182 LHS, RHS);
4183}
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004184
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004185/// Return true if "icmp Pred LHS RHS" is always true.
Pete Cooper35b00d52016-08-13 01:05:32 +00004186static bool isTruePredicate(CmpInst::Predicate Pred,
4187 const Value *LHS, const Value *RHS,
Sanjoy Das55ea67c2015-11-06 19:01:08 +00004188 const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004189 AssumptionCache *AC, const Instruction *CxtI,
4190 const DominatorTree *DT) {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004191 assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004192 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
4193 return true;
4194
4195 switch (Pred) {
4196 default:
4197 return false;
4198
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004199 case CmpInst::ICMP_SLE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004200 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004201
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004202 // LHS s<= LHS +_{nsw} C if C >= 0
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004203 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004204 return !C->isNegative();
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004205 return false;
4206 }
4207
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004208 case CmpInst::ICMP_ULE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004209 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004210
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004211 // LHS u<= LHS +_{nuw} C for any C
4212 if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasc01b4d22015-11-06 19:01:03 +00004213 return true;
Sanjoy Das92568102015-11-10 23:56:20 +00004214
4215 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
Pete Cooper35b00d52016-08-13 01:05:32 +00004216 auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B,
4217 const Value *&X,
Sanjoy Das92568102015-11-10 23:56:20 +00004218 const APInt *&CA, const APInt *&CB) {
4219 if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
4220 match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
4221 return true;
4222
4223 // If X & C == 0 then (X | C) == X +_{nuw} C
4224 if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
4225 match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
Craig Topperb45eabc2017-04-26 16:39:58 +00004226 KnownBits Known(CA->getBitWidth());
4227 computeKnownBits(X, Known, DL, Depth + 1, AC, CxtI, DT);
Sanjoy Das92568102015-11-10 23:56:20 +00004228
Craig Topperb45eabc2017-04-26 16:39:58 +00004229 if (CA->isSubsetOf(Known.Zero) && CB->isSubsetOf(Known.Zero))
Sanjoy Das92568102015-11-10 23:56:20 +00004230 return true;
4231 }
4232
4233 return false;
4234 };
4235
Pete Cooper35b00d52016-08-13 01:05:32 +00004236 const Value *X;
Sanjoy Das92568102015-11-10 23:56:20 +00004237 const APInt *CLHS, *CRHS;
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004238 if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
4239 return CLHS->ule(*CRHS);
Sanjoy Das92568102015-11-10 23:56:20 +00004240
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004241 return false;
4242 }
4243 }
4244}
4245
4246/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
Chad Rosier41dd31f2016-04-20 19:15:26 +00004247/// ALHS ARHS" is true. Otherwise, return None.
4248static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00004249isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS,
4250 const Value *ARHS, const Value *BLHS,
4251 const Value *BRHS, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004252 unsigned Depth, AssumptionCache *AC,
4253 const Instruction *CxtI, const DominatorTree *DT) {
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004254 switch (Pred) {
4255 default:
Chad Rosier41dd31f2016-04-20 19:15:26 +00004256 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004257
4258 case CmpInst::ICMP_SLT:
4259 case CmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004260 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth, AC, CxtI,
Chad Rosier41dd31f2016-04-20 19:15:26 +00004261 DT) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004262 isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth, AC, CxtI, DT))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004263 return true;
4264 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004265
4266 case CmpInst::ICMP_ULT:
4267 case CmpInst::ICMP_ULE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004268 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth, AC, CxtI,
4269 DT) &&
4270 isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth, AC, CxtI, DT))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004271 return true;
4272 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004273 }
4274}
4275
Chad Rosier226a7342016-05-05 17:41:19 +00004276/// Return true if the operands of the two compares match. IsSwappedOps is true
4277/// when the operands match, but are swapped.
Pete Cooper35b00d52016-08-13 01:05:32 +00004278static bool isMatchingOps(const Value *ALHS, const Value *ARHS,
4279 const Value *BLHS, const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00004280 bool &IsSwappedOps) {
4281
4282 bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS);
4283 IsSwappedOps = (ALHS == BRHS && ARHS == BLHS);
4284 return IsMatchingOps || IsSwappedOps;
4285}
4286
Chad Rosier41dd31f2016-04-20 19:15:26 +00004287/// Return true if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS BRHS" is
4288/// true. Return false if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS
4289/// BRHS" is false. Otherwise, return None if we can't infer anything.
4290static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred,
Pete Cooper35b00d52016-08-13 01:05:32 +00004291 const Value *ALHS,
4292 const Value *ARHS,
Chad Rosier41dd31f2016-04-20 19:15:26 +00004293 CmpInst::Predicate BPred,
Pete Cooper35b00d52016-08-13 01:05:32 +00004294 const Value *BLHS,
4295 const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00004296 bool IsSwappedOps) {
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004297 // Canonicalize the operands so they're matching.
4298 if (IsSwappedOps) {
4299 std::swap(BLHS, BRHS);
4300 BPred = ICmpInst::getSwappedPredicate(BPred);
4301 }
Chad Rosier99bc4802016-04-21 16:18:02 +00004302 if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred))
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004303 return true;
Chad Rosier99bc4802016-04-21 16:18:02 +00004304 if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004305 return false;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004306
Chad Rosier41dd31f2016-04-20 19:15:26 +00004307 return None;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004308}
4309
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004310/// Return true if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS C2" is
4311/// true. Return false if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS
4312/// C2" is false. Otherwise, return None if we can't infer anything.
4313static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00004314isImpliedCondMatchingImmOperands(CmpInst::Predicate APred, const Value *ALHS,
4315 const ConstantInt *C1,
4316 CmpInst::Predicate BPred,
4317 const Value *BLHS, const ConstantInt *C2) {
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004318 assert(ALHS == BLHS && "LHS operands must match.");
4319 ConstantRange DomCR =
4320 ConstantRange::makeExactICmpRegion(APred, C1->getValue());
4321 ConstantRange CR =
4322 ConstantRange::makeAllowedICmpRegion(BPred, C2->getValue());
4323 ConstantRange Intersection = DomCR.intersectWith(CR);
4324 ConstantRange Difference = DomCR.difference(CR);
4325 if (Intersection.isEmptySet())
4326 return false;
4327 if (Difference.isEmptySet())
4328 return true;
4329 return None;
4330}
4331
Pete Cooper35b00d52016-08-13 01:05:32 +00004332Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
Chad Rosiere2cbd132016-04-25 17:23:36 +00004333 const DataLayout &DL, bool InvertAPred,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004334 unsigned Depth, AssumptionCache *AC,
4335 const Instruction *CxtI,
Chad Rosier41dd31f2016-04-20 19:15:26 +00004336 const DominatorTree *DT) {
Chad Rosiercd62bf52016-04-29 21:12:31 +00004337 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for example.
4338 if (LHS->getType() != RHS->getType())
4339 return None;
4340
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004341 Type *OpTy = LHS->getType();
4342 assert(OpTy->getScalarType()->isIntegerTy(1));
4343
4344 // LHS ==> RHS by definition
Chad Rosiere2cbd132016-04-25 17:23:36 +00004345 if (!InvertAPred && LHS == RHS)
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004346 return true;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004347
4348 if (OpTy->isVectorTy())
4349 // TODO: extending the code below to handle vectors
Chad Rosier41dd31f2016-04-20 19:15:26 +00004350 return None;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004351 assert(OpTy->isIntegerTy(1) && "implied by above");
4352
4353 ICmpInst::Predicate APred, BPred;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004354 Value *ALHS, *ARHS;
4355 Value *BLHS, *BRHS;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004356
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004357 if (!match(LHS, m_ICmp(APred, m_Value(ALHS), m_Value(ARHS))) ||
4358 !match(RHS, m_ICmp(BPred, m_Value(BLHS), m_Value(BRHS))))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004359 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004360
Chad Rosiere2cbd132016-04-25 17:23:36 +00004361 if (InvertAPred)
4362 APred = CmpInst::getInversePredicate(APred);
4363
Chad Rosier226a7342016-05-05 17:41:19 +00004364 // Can we infer anything when the two compares have matching operands?
4365 bool IsSwappedOps;
4366 if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, IsSwappedOps)) {
4367 if (Optional<bool> Implication = isImpliedCondMatchingOperands(
4368 APred, ALHS, ARHS, BPred, BLHS, BRHS, IsSwappedOps))
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004369 return Implication;
Chad Rosier226a7342016-05-05 17:41:19 +00004370 // No amount of additional analysis will infer the second condition, so
4371 // early exit.
4372 return None;
4373 }
4374
4375 // Can we infer anything when the LHS operands match and the RHS operands are
4376 // constants (not necessarily matching)?
4377 if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) {
4378 if (Optional<bool> Implication = isImpliedCondMatchingImmOperands(
4379 APred, ALHS, cast<ConstantInt>(ARHS), BPred, BLHS,
4380 cast<ConstantInt>(BRHS)))
4381 return Implication;
4382 // No amount of additional analysis will infer the second condition, so
4383 // early exit.
4384 return None;
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004385 }
4386
Chad Rosier41dd31f2016-04-20 19:15:26 +00004387 if (APred == BPred)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004388 return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth, AC,
4389 CxtI, DT);
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004390
Chad Rosier41dd31f2016-04-20 19:15:26 +00004391 return None;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004392}