blob: fd6e3a643bf03a0d073e49935fe109e8b712d45a [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"
Artur Pilipenko31bcca42016-02-24 12:49:04 +000020#include "llvm/Analysis/Loads.h"
Adam Nemete2b885c2015-04-23 20:09:20 +000021#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000022#include "llvm/Analysis/MemoryBuiltins.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"
Matthias Braun50ec0b52017-05-19 22:37:09 +000029#include "llvm/IR/DerivedTypes.h"
Hal Finkel60db0582014-09-07 18:57:58 +000030#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000031#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/GlobalAlias.h"
33#include "llvm/IR/GlobalVariable.h"
34#include "llvm/IR/Instructions.h"
35#include "llvm/IR/IntrinsicInst.h"
36#include "llvm/IR/LLVMContext.h"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000039#include "llvm/IR/PatternMatch.h"
Philip Reames5461d452015-04-23 17:36:48 +000040#include "llvm/IR/Statepoint.h"
Matt Arsenaultf1a7e622014-07-15 01:55:03 +000041#include "llvm/Support/Debug.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000042#include "llvm/Support/KnownBits.h"
Chris Lattner965c7692008-06-02 01:18:21 +000043#include "llvm/Support/MathExtras.h"
Matthias Braun37e5d792016-01-28 06:29:33 +000044#include <algorithm>
45#include <array>
Chris Lattner64496902008-06-04 04:46:14 +000046#include <cstring>
Chris Lattner965c7692008-06-02 01:18:21 +000047using namespace llvm;
Duncan Sandsd3951082011-01-25 09:38:29 +000048using namespace llvm::PatternMatch;
49
50const unsigned MaxDepth = 6;
51
Philip Reames1c292272015-03-10 22:43:20 +000052// Controls the number of uses of the value searched for possible
53// dominating comparisons.
54static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
Igor Laevskycea9ede2015-09-29 14:57:52 +000055 cl::Hidden, cl::init(20));
Philip Reames1c292272015-03-10 22:43:20 +000056
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +000057// This optimization is known to cause performance regressions is some cases,
58// keep it under a temporary flag for now.
59static cl::opt<bool>
60DontImproveNonNegativePhiBits("dont-improve-non-negative-phi-bits",
61 cl::Hidden, cl::init(true));
62
Craig Topper6b3940a2017-05-03 22:25:19 +000063/// Returns the bitwidth of the given scalar or pointer type. For vector types,
64/// returns the element type's bitwidth.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000065static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
Duncan Sandsd3951082011-01-25 09:38:29 +000066 if (unsigned BitWidth = Ty->getScalarSizeInBits())
67 return BitWidth;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +000068
Mehdi Aminia28d91d2015-03-10 02:37:25 +000069 return DL.getPointerTypeSizeInBits(Ty);
Duncan Sandsd3951082011-01-25 09:38:29 +000070}
Chris Lattner965c7692008-06-02 01:18:21 +000071
Benjamin Kramercfd8d902014-09-12 08:56:53 +000072namespace {
Hal Finkel60db0582014-09-07 18:57:58 +000073// Simplifying using an assume can only be done in a particular control-flow
74// context (the context instruction provides that context). If an assume and
75// the context instruction are not in the same block then the DT helps in
76// figuring out if we can use it.
77struct Query {
Matthias Braunfeb81bc2016-01-15 22:22:04 +000078 const DataLayout &DL;
Daniel Jasperaec2fa32016-12-19 08:22:17 +000079 AssumptionCache *AC;
Hal Finkel60db0582014-09-07 18:57:58 +000080 const Instruction *CxtI;
81 const DominatorTree *DT;
Sanjay Patel54656ca2017-02-06 18:26:06 +000082 // Unlike the other analyses, this may be a nullptr because not all clients
83 // provide it currently.
84 OptimizationRemarkEmitter *ORE;
Hal Finkel60db0582014-09-07 18:57:58 +000085
Matthias Braun37e5d792016-01-28 06:29:33 +000086 /// Set of assumptions that should be excluded from further queries.
87 /// This is because of the potential for mutual recursion to cause
88 /// computeKnownBits to repeatedly visit the same assume intrinsic. The
89 /// classic case of this is assume(x = y), which will attempt to determine
90 /// bits in x from bits in y, which will attempt to determine bits in y from
91 /// bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
Craig Topper6e11a052017-05-08 16:22:48 +000092 /// isKnownNonZero, which calls computeKnownBits and isKnownToBeAPowerOfTwo
93 /// (all of which can call computeKnownBits), and so on.
Li Huang755f75f2016-10-15 19:00:04 +000094 std::array<const Value *, MaxDepth> Excluded;
Matthias Braun37e5d792016-01-28 06:29:33 +000095 unsigned NumExcluded;
96
Daniel Jasperaec2fa32016-12-19 08:22:17 +000097 Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI,
Sanjay Patel54656ca2017-02-06 18:26:06 +000098 const DominatorTree *DT, OptimizationRemarkEmitter *ORE = nullptr)
99 : DL(DL), AC(AC), CxtI(CxtI), DT(DT), ORE(ORE), NumExcluded(0) {}
Hal Finkel60db0582014-09-07 18:57:58 +0000100
101 Query(const Query &Q, const Value *NewExcl)
Sanjay Patel54656ca2017-02-06 18:26:06 +0000102 : DL(Q.DL), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT), ORE(Q.ORE),
103 NumExcluded(Q.NumExcluded) {
Matthias Braun37e5d792016-01-28 06:29:33 +0000104 Excluded = Q.Excluded;
105 Excluded[NumExcluded++] = NewExcl;
106 assert(NumExcluded <= Excluded.size());
107 }
108
109 bool isExcluded(const Value *Value) const {
110 if (NumExcluded == 0)
111 return false;
112 auto End = Excluded.begin() + NumExcluded;
113 return std::find(Excluded.begin(), End, Value) != End;
Hal Finkel60db0582014-09-07 18:57:58 +0000114 }
115};
Benjamin Kramercfd8d902014-09-12 08:56:53 +0000116} // end anonymous namespace
Hal Finkel60db0582014-09-07 18:57:58 +0000117
Sanjay Patel547e9752014-11-04 16:09:50 +0000118// Given the provided Value and, potentially, a context instruction, return
Hal Finkel60db0582014-09-07 18:57:58 +0000119// the preferred context instruction (if any).
120static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
121 // If we've been provided with a context instruction, then use that (provided
122 // it has been inserted).
123 if (CxtI && CxtI->getParent())
124 return CxtI;
125
126 // If the value is really an already-inserted instruction, then use that.
127 CxtI = dyn_cast<Instruction>(V);
128 if (CxtI && CxtI->getParent())
129 return CxtI;
130
131 return nullptr;
132}
133
Craig Topperb45eabc2017-04-26 16:39:58 +0000134static void computeKnownBits(const Value *V, KnownBits &Known,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000135 unsigned Depth, const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000136
Craig Topperb45eabc2017-04-26 16:39:58 +0000137void llvm::computeKnownBits(const Value *V, KnownBits &Known,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000138 const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000139 AssumptionCache *AC, const Instruction *CxtI,
Sanjay Patel54656ca2017-02-06 18:26:06 +0000140 const DominatorTree *DT,
141 OptimizationRemarkEmitter *ORE) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000142 ::computeKnownBits(V, Known, Depth,
Sanjay Patel54656ca2017-02-06 18:26:06 +0000143 Query(DL, AC, safeCxtI(V, CxtI), DT, ORE));
Hal Finkel60db0582014-09-07 18:57:58 +0000144}
145
Craig Topper6e11a052017-05-08 16:22:48 +0000146static KnownBits computeKnownBits(const Value *V, unsigned Depth,
147 const Query &Q);
148
149KnownBits llvm::computeKnownBits(const Value *V, const DataLayout &DL,
150 unsigned Depth, AssumptionCache *AC,
151 const Instruction *CxtI,
Craig Toppera2025ea2017-05-24 16:53:03 +0000152 const DominatorTree *DT,
153 OptimizationRemarkEmitter *ORE) {
154 return ::computeKnownBits(V, Depth,
155 Query(DL, AC, safeCxtI(V, CxtI), DT, ORE));
Craig Topper6e11a052017-05-08 16:22:48 +0000156}
157
Pete Cooper35b00d52016-08-13 01:05:32 +0000158bool llvm::haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
159 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000160 AssumptionCache *AC, const Instruction *CxtI,
Jingyue Wuca321902015-05-14 23:53:19 +0000161 const DominatorTree *DT) {
162 assert(LHS->getType() == RHS->getType() &&
163 "LHS and RHS should have the same type");
164 assert(LHS->getType()->isIntOrIntVectorTy() &&
165 "LHS and RHS should be integers");
166 IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
Craig Topperb45eabc2017-04-26 16:39:58 +0000167 KnownBits LHSKnown(IT->getBitWidth());
168 KnownBits RHSKnown(IT->getBitWidth());
169 computeKnownBits(LHS, LHSKnown, DL, 0, AC, CxtI, DT);
170 computeKnownBits(RHS, RHSKnown, DL, 0, AC, CxtI, DT);
171 return (LHSKnown.Zero | RHSKnown.Zero).isAllOnesValue();
Jingyue Wuca321902015-05-14 23:53:19 +0000172}
173
Hal Finkel60db0582014-09-07 18:57:58 +0000174
Zaara Syeda3a7578c2017-05-31 17:12:38 +0000175bool llvm::isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI) {
176 for (const User *U : CxtI->users()) {
177 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
178 if (IC->isEquality())
179 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
180 if (C->isNullValue())
181 continue;
182 return false;
183 }
184 return true;
185}
186
Pete Cooper35b00d52016-08-13 01:05:32 +0000187static bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000188 const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000189
Pete Cooper35b00d52016-08-13 01:05:32 +0000190bool llvm::isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
191 bool OrZero,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000192 unsigned Depth, AssumptionCache *AC,
193 const Instruction *CxtI,
Hal Finkel60db0582014-09-07 18:57:58 +0000194 const DominatorTree *DT) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000195 return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000196 Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000197}
198
Pete Cooper35b00d52016-08-13 01:05:32 +0000199static bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000200
Pete Cooper35b00d52016-08-13 01:05:32 +0000201bool llvm::isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000202 AssumptionCache *AC, const Instruction *CxtI,
203 const DominatorTree *DT) {
204 return ::isKnownNonZero(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000205}
206
Pete Cooper35b00d52016-08-13 01:05:32 +0000207bool llvm::isKnownNonNegative(const Value *V, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000208 unsigned Depth,
209 AssumptionCache *AC, const Instruction *CxtI,
Jingyue Wu10fcea52015-08-20 18:27:04 +0000210 const DominatorTree *DT) {
Craig Topper6e11a052017-05-08 16:22:48 +0000211 KnownBits Known = computeKnownBits(V, DL, Depth, AC, CxtI, DT);
212 return Known.isNonNegative();
Jingyue Wu10fcea52015-08-20 18:27:04 +0000213}
214
Pete Cooper35b00d52016-08-13 01:05:32 +0000215bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000216 AssumptionCache *AC, const Instruction *CxtI,
217 const DominatorTree *DT) {
Philip Reames8f12eba2016-03-09 21:31:47 +0000218 if (auto *CI = dyn_cast<ConstantInt>(V))
219 return CI->getValue().isStrictlyPositive();
Sanjoy Das6082c1a2016-05-07 02:08:15 +0000220
Philip Reames8f12eba2016-03-09 21:31:47 +0000221 // TODO: We'd doing two recursive queries here. We should factor this such
222 // that only a single query is needed.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000223 return isKnownNonNegative(V, DL, Depth, AC, CxtI, DT) &&
224 isKnownNonZero(V, DL, Depth, AC, CxtI, DT);
Philip Reames8f12eba2016-03-09 21:31:47 +0000225}
226
Pete Cooper35b00d52016-08-13 01:05:32 +0000227bool llvm::isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000228 AssumptionCache *AC, const Instruction *CxtI,
229 const DominatorTree *DT) {
Craig Topper6e11a052017-05-08 16:22:48 +0000230 KnownBits Known = computeKnownBits(V, DL, Depth, AC, CxtI, DT);
231 return Known.isNegative();
Nick Lewycky762f8a82016-04-21 00:53:14 +0000232}
233
Pete Cooper35b00d52016-08-13 01:05:32 +0000234static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q);
James Molloy1d88d6f2015-10-22 13:18:42 +0000235
Pete Cooper35b00d52016-08-13 01:05:32 +0000236bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000237 const DataLayout &DL,
238 AssumptionCache *AC, const Instruction *CxtI,
Pete Cooper35b00d52016-08-13 01:05:32 +0000239 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000240 return ::isKnownNonEqual(V1, V2, Query(DL, AC,
241 safeCxtI(V1, safeCxtI(V2, CxtI)),
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000242 DT));
James Molloy1d88d6f2015-10-22 13:18:42 +0000243}
244
Pete Cooper35b00d52016-08-13 01:05:32 +0000245static bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000246 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000247
Pete Cooper35b00d52016-08-13 01:05:32 +0000248bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
249 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000250 unsigned Depth, AssumptionCache *AC,
251 const Instruction *CxtI, const DominatorTree *DT) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000252 return ::MaskedValueIsZero(V, Mask, Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000253 Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000254}
255
Pete Cooper35b00d52016-08-13 01:05:32 +0000256static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
257 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000258
Pete Cooper35b00d52016-08-13 01:05:32 +0000259unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000260 unsigned Depth, AssumptionCache *AC,
261 const Instruction *CxtI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000262 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000263 return ::ComputeNumSignBits(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
Hal Finkel60db0582014-09-07 18:57:58 +0000264}
265
Craig Topper8fbb74b2017-03-24 22:12:10 +0000266static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
267 bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000268 KnownBits &KnownOut, KnownBits &Known2,
Craig Topper8fbb74b2017-03-24 22:12:10 +0000269 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000270 unsigned BitWidth = KnownOut.getBitWidth();
Craig Topper8fbb74b2017-03-24 22:12:10 +0000271
272 // If an initial sequence of bits in the result is not needed, the
273 // corresponding bits in the operands are not needed.
Craig Topperb45eabc2017-04-26 16:39:58 +0000274 KnownBits LHSKnown(BitWidth);
275 computeKnownBits(Op0, LHSKnown, Depth + 1, Q);
276 computeKnownBits(Op1, Known2, Depth + 1, Q);
Craig Topper8fbb74b2017-03-24 22:12:10 +0000277
David Majnemer97ddca32014-08-22 00:40:43 +0000278 // Carry in a 1 for a subtract, rather than a 0.
Craig Topper059b98e2017-03-24 05:38:09 +0000279 uint64_t CarryIn = 0;
David Majnemer97ddca32014-08-22 00:40:43 +0000280 if (!Add) {
281 // Sum = LHS + ~RHS + 1
Craig Topperb45eabc2017-04-26 16:39:58 +0000282 std::swap(Known2.Zero, Known2.One);
Craig Topper059b98e2017-03-24 05:38:09 +0000283 CarryIn = 1;
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000284 }
285
Craig Topperb45eabc2017-04-26 16:39:58 +0000286 APInt PossibleSumZero = ~LHSKnown.Zero + ~Known2.Zero + CarryIn;
287 APInt PossibleSumOne = LHSKnown.One + Known2.One + CarryIn;
David Majnemer97ddca32014-08-22 00:40:43 +0000288
289 // Compute known bits of the carry.
Craig Topperb45eabc2017-04-26 16:39:58 +0000290 APInt CarryKnownZero = ~(PossibleSumZero ^ LHSKnown.Zero ^ Known2.Zero);
291 APInt CarryKnownOne = PossibleSumOne ^ LHSKnown.One ^ Known2.One;
David Majnemer97ddca32014-08-22 00:40:43 +0000292
293 // Compute set of known bits (where all three relevant bits are known).
Craig Topperb45eabc2017-04-26 16:39:58 +0000294 APInt LHSKnownUnion = LHSKnown.Zero | LHSKnown.One;
295 APInt RHSKnownUnion = Known2.Zero | Known2.One;
296 APInt CarryKnownUnion = CarryKnownZero | CarryKnownOne;
297 APInt Known = LHSKnownUnion & RHSKnownUnion & CarryKnownUnion;
David Majnemer97ddca32014-08-22 00:40:43 +0000298
299 assert((PossibleSumZero & Known) == (PossibleSumOne & Known) &&
300 "known bits of sum differ");
301
302 // Compute known bits of the result.
Craig Topperb45eabc2017-04-26 16:39:58 +0000303 KnownOut.Zero = ~PossibleSumOne & Known;
304 KnownOut.One = PossibleSumOne & Known;
David Majnemer97ddca32014-08-22 00:40:43 +0000305
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000306 // Are we still trying to solve for the sign bit?
Craig Topperd23004c2017-04-17 16:38:20 +0000307 if (!Known.isSignBitSet()) {
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000308 if (NSW) {
David Majnemer97ddca32014-08-22 00:40:43 +0000309 // Adding two non-negative numbers, or subtracting a negative number from
310 // a non-negative one, can't wrap into negative.
Craig Topperca48af32017-04-29 16:43:11 +0000311 if (LHSKnown.isNonNegative() && Known2.isNonNegative())
312 KnownOut.makeNonNegative();
David Majnemer97ddca32014-08-22 00:40:43 +0000313 // Adding two negative numbers, or subtracting a non-negative number from
314 // a negative one, can't wrap into non-negative.
Craig Topperca48af32017-04-29 16:43:11 +0000315 else if (LHSKnown.isNegative() && Known2.isNegative())
316 KnownOut.makeNegative();
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000317 }
318 }
319}
320
Pete Cooper35b00d52016-08-13 01:05:32 +0000321static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000322 KnownBits &Known, KnownBits &Known2,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000323 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000324 unsigned BitWidth = Known.getBitWidth();
325 computeKnownBits(Op1, Known, Depth + 1, Q);
326 computeKnownBits(Op0, Known2, Depth + 1, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000327
328 bool isKnownNegative = false;
329 bool isKnownNonNegative = false;
330 // If the multiplication is known not to overflow, compute the sign bit.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000331 if (NSW) {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000332 if (Op0 == Op1) {
333 // The product of a number with itself is non-negative.
334 isKnownNonNegative = true;
335 } else {
Craig Topperca48af32017-04-29 16:43:11 +0000336 bool isKnownNonNegativeOp1 = Known.isNonNegative();
337 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
338 bool isKnownNegativeOp1 = Known.isNegative();
339 bool isKnownNegativeOp0 = Known2.isNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000340 // The product of two numbers with the same sign is non-negative.
341 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
342 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
343 // The product of a negative number and a non-negative number is either
344 // negative or zero.
345 if (!isKnownNonNegative)
346 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000347 isKnownNonZero(Op0, Depth, Q)) ||
Nick Lewyckyfa306072012-03-18 23:28:48 +0000348 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000349 isKnownNonZero(Op1, Depth, Q));
Nick Lewyckyfa306072012-03-18 23:28:48 +0000350 }
351 }
352
353 // If low bits are zero in either operand, output low known-0 bits.
Sanjay Patel5dd66c32015-09-17 20:51:50 +0000354 // Also compute a conservative estimate for high known-0 bits.
Nick Lewyckyfa306072012-03-18 23:28:48 +0000355 // More trickiness is possible, but this is sufficient for the
356 // interesting case of alignment computation.
Craig Topper8df66c62017-05-12 17:20:30 +0000357 unsigned TrailZ = Known.countMinTrailingZeros() +
358 Known2.countMinTrailingZeros();
359 unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
360 Known2.countMinLeadingZeros(),
Nick Lewyckyfa306072012-03-18 23:28:48 +0000361 BitWidth) - BitWidth;
362
363 TrailZ = std::min(TrailZ, BitWidth);
364 LeadZ = std::min(LeadZ, BitWidth);
Craig Topperf0aeee02017-05-05 17:36:09 +0000365 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000366 Known.Zero.setLowBits(TrailZ);
367 Known.Zero.setHighBits(LeadZ);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000368
369 // Only make use of no-wrap flags if we failed to compute the sign bit
370 // directly. This matters if the multiplication always overflows, in
371 // which case we prefer to follow the result of the direct computation,
372 // though as the program is invoking undefined behaviour we can choose
373 // whatever we like here.
Craig Topperca48af32017-04-29 16:43:11 +0000374 if (isKnownNonNegative && !Known.isNegative())
375 Known.makeNonNegative();
376 else if (isKnownNegative && !Known.isNonNegative())
377 Known.makeNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000378}
379
Jingyue Wu37fcb592014-06-19 16:50:16 +0000380void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
Craig Topperf42b23f2017-04-28 06:28:56 +0000381 KnownBits &Known) {
382 unsigned BitWidth = Known.getBitWidth();
Rafael Espindola53190532012-03-30 15:52:11 +0000383 unsigned NumRanges = Ranges.getNumOperands() / 2;
384 assert(NumRanges >= 1);
385
Craig Topperf42b23f2017-04-28 06:28:56 +0000386 Known.Zero.setAllBits();
387 Known.One.setAllBits();
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000388
Rafael Espindola53190532012-03-30 15:52:11 +0000389 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000390 ConstantInt *Lower =
391 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
392 ConstantInt *Upper =
393 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
Rafael Espindola53190532012-03-30 15:52:11 +0000394 ConstantRange Range(Lower->getValue(), Upper->getValue());
Rafael Espindola53190532012-03-30 15:52:11 +0000395
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000396 // The first CommonPrefixBits of all values in Range are equal.
397 unsigned CommonPrefixBits =
398 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
399
400 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
Craig Topperf42b23f2017-04-28 06:28:56 +0000401 Known.One &= Range.getUnsignedMax() & Mask;
402 Known.Zero &= ~Range.getUnsignedMax() & Mask;
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000403 }
Rafael Espindola53190532012-03-30 15:52:11 +0000404}
Jay Foad5a29c362014-05-15 12:12:55 +0000405
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000406static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
Hal Finkel60db0582014-09-07 18:57:58 +0000407 SmallVector<const Value *, 16> WorkSet(1, I);
408 SmallPtrSet<const Value *, 32> Visited;
409 SmallPtrSet<const Value *, 16> EphValues;
410
Hal Finkelf2199b22015-10-23 20:37:08 +0000411 // The instruction defining an assumption's condition itself is always
412 // considered ephemeral to that assumption (even if it has other
413 // non-ephemeral users). See r246696's test case for an example.
David Majnemer0a16c222016-08-11 21:15:00 +0000414 if (is_contained(I->operands(), E))
Hal Finkelf2199b22015-10-23 20:37:08 +0000415 return true;
416
Hal Finkel60db0582014-09-07 18:57:58 +0000417 while (!WorkSet.empty()) {
418 const Value *V = WorkSet.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +0000419 if (!Visited.insert(V).second)
Hal Finkel60db0582014-09-07 18:57:58 +0000420 continue;
421
422 // If all uses of this value are ephemeral, then so is this value.
David Majnemer0a16c222016-08-11 21:15:00 +0000423 if (all_of(V->users(), [&](const User *U) { return EphValues.count(U); })) {
Hal Finkel60db0582014-09-07 18:57:58 +0000424 if (V == E)
425 return true;
426
427 EphValues.insert(V);
428 if (const User *U = dyn_cast<User>(V))
429 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
430 J != JE; ++J) {
431 if (isSafeToSpeculativelyExecute(*J))
432 WorkSet.push_back(*J);
433 }
434 }
435 }
436
437 return false;
438}
439
440// Is this an intrinsic that cannot be speculated but also cannot trap?
441static bool isAssumeLikeIntrinsic(const Instruction *I) {
442 if (const CallInst *CI = dyn_cast<CallInst>(I))
443 if (Function *F = CI->getCalledFunction())
444 switch (F->getIntrinsicID()) {
445 default: break;
446 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
447 case Intrinsic::assume:
448 case Intrinsic::dbg_declare:
449 case Intrinsic::dbg_value:
450 case Intrinsic::invariant_start:
451 case Intrinsic::invariant_end:
452 case Intrinsic::lifetime_start:
453 case Intrinsic::lifetime_end:
454 case Intrinsic::objectsize:
455 case Intrinsic::ptr_annotation:
456 case Intrinsic::var_annotation:
457 return true;
458 }
459
460 return false;
461}
462
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000463bool llvm::isValidAssumeForContext(const Instruction *Inv,
464 const Instruction *CxtI,
465 const DominatorTree *DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000466
467 // There are two restrictions on the use of an assume:
468 // 1. The assume must dominate the context (or the control flow must
469 // reach the assume whenever it reaches the context).
470 // 2. The context must not be in the assume's set of ephemeral values
471 // (otherwise we will use the assume to prove that the condition
472 // feeding the assume is trivially true, thus causing the removal of
473 // the assume).
474
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000475 if (DT) {
Pete Cooper54a02552016-08-12 01:00:15 +0000476 if (DT->dominates(Inv, CxtI))
Hal Finkel60db0582014-09-07 18:57:58 +0000477 return true;
Pete Cooper54a02552016-08-12 01:00:15 +0000478 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
479 // We don't have a DT, but this trivially dominates.
480 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000481 }
482
Pete Cooper54a02552016-08-12 01:00:15 +0000483 // With or without a DT, the only remaining case we will check is if the
484 // instructions are in the same BB. Give up if that is not the case.
485 if (Inv->getParent() != CxtI->getParent())
486 return false;
487
488 // If we have a dom tree, then we now know that the assume doens't dominate
489 // the other instruction. If we don't have a dom tree then we can check if
490 // the assume is first in the BB.
491 if (!DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000492 // Search forward from the assume until we reach the context (or the end
493 // of the block); the common case is that the assume will come first.
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000494 for (auto I = std::next(BasicBlock::const_iterator(Inv)),
Hal Finkel60db0582014-09-07 18:57:58 +0000495 IE = Inv->getParent()->end(); I != IE; ++I)
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000496 if (&*I == CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000497 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000498 }
499
Pete Cooper54a02552016-08-12 01:00:15 +0000500 // The context comes first, but they're both in the same block. Make sure
501 // there is nothing in between that might interrupt the control flow.
502 for (BasicBlock::const_iterator I =
503 std::next(BasicBlock::const_iterator(CxtI)), IE(Inv);
504 I != IE; ++I)
505 if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
506 return false;
507
508 return !isEphemeralValueOf(Inv, CxtI);
Hal Finkel60db0582014-09-07 18:57:58 +0000509}
510
Craig Topperb45eabc2017-04-26 16:39:58 +0000511static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known,
512 unsigned Depth, const Query &Q) {
Hal Finkel60db0582014-09-07 18:57:58 +0000513 // Use of assumptions is context-sensitive. If we don't have a context, we
514 // cannot use them!
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000515 if (!Q.AC || !Q.CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000516 return;
517
Craig Topperb45eabc2017-04-26 16:39:58 +0000518 unsigned BitWidth = Known.getBitWidth();
Hal Finkel60db0582014-09-07 18:57:58 +0000519
Hal Finkel8a9a7832017-01-11 13:24:24 +0000520 // Note that the patterns below need to be kept in sync with the code
521 // in AssumptionCache::updateAffectedValues.
522
523 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000524 if (!AssumeVH)
Chandler Carruth66b31302015-01-04 12:03:27 +0000525 continue;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000526 CallInst *I = cast<CallInst>(AssumeVH);
527 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
528 "Got assumption for the wrong function!");
529 if (Q.isExcluded(I))
Hal Finkel60db0582014-09-07 18:57:58 +0000530 continue;
531
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000532 // Warning: This loop can end up being somewhat performance sensetive.
533 // We're running this loop for once for each value queried resulting in a
534 // runtime of ~O(#assumes * #values).
Philip Reames00d3b272014-11-24 23:44:28 +0000535
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000536 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
537 "must be an assume intrinsic");
538
539 Value *Arg = I->getArgOperand(0);
540
541 if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000542 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000543 Known.setAllOnes();
Hal Finkel60db0582014-09-07 18:57:58 +0000544 return;
545 }
Sanjay Patel96669962017-01-17 18:15:49 +0000546 if (match(Arg, m_Not(m_Specific(V))) &&
547 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
548 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000549 Known.setAllZero();
Sanjay Patel96669962017-01-17 18:15:49 +0000550 return;
551 }
Hal Finkel60db0582014-09-07 18:57:58 +0000552
David Majnemer9b609752014-12-12 23:59:29 +0000553 // The remaining tests are all recursive, so bail out if we hit the limit.
554 if (Depth == MaxDepth)
555 continue;
556
Hal Finkel60db0582014-09-07 18:57:58 +0000557 Value *A, *B;
558 auto m_V = m_CombineOr(m_Specific(V),
559 m_CombineOr(m_PtrToInt(m_Specific(V)),
560 m_BitCast(m_Specific(V))));
561
562 CmpInst::Predicate Pred;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000563 ConstantInt *C;
Hal Finkel60db0582014-09-07 18:57:58 +0000564 // assume(v = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000565 if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000566 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000567 KnownBits RHSKnown(BitWidth);
568 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
569 Known.Zero |= RHSKnown.Zero;
570 Known.One |= RHSKnown.One;
Hal Finkel60db0582014-09-07 18:57:58 +0000571 // assume(v & b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000572 } else if (match(Arg,
573 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000574 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000575 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000576 KnownBits RHSKnown(BitWidth);
577 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
578 KnownBits MaskKnown(BitWidth);
579 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel60db0582014-09-07 18:57:58 +0000580
581 // For those bits in the mask that are known to be one, we can propagate
582 // known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000583 Known.Zero |= RHSKnown.Zero & MaskKnown.One;
584 Known.One |= RHSKnown.One & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000585 // assume(~(v & b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000586 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
587 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000588 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000589 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000590 KnownBits RHSKnown(BitWidth);
591 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
592 KnownBits MaskKnown(BitWidth);
593 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000594
595 // For those bits in the mask that are known to be one, we can propagate
596 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000597 Known.Zero |= RHSKnown.One & MaskKnown.One;
598 Known.One |= RHSKnown.Zero & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000599 // assume(v | b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000600 } else if (match(Arg,
601 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000602 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000603 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000604 KnownBits RHSKnown(BitWidth);
605 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
606 KnownBits BKnown(BitWidth);
607 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000608
609 // For those bits in B that are known to be zero, we can propagate known
610 // bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000611 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
612 Known.One |= RHSKnown.One & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000613 // assume(~(v | b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000614 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
615 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000616 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000617 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000618 KnownBits RHSKnown(BitWidth);
619 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
620 KnownBits BKnown(BitWidth);
621 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000622
623 // For those bits in B that are known to be zero, we can propagate
624 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000625 Known.Zero |= RHSKnown.One & BKnown.Zero;
626 Known.One |= RHSKnown.Zero & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000627 // assume(v ^ b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000628 } else if (match(Arg,
629 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000630 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000631 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000632 KnownBits RHSKnown(BitWidth);
633 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
634 KnownBits BKnown(BitWidth);
635 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000636
637 // For those bits in B that are known to be zero, we can propagate known
638 // bits from the RHS to V. For those bits in B that are known to be one,
639 // we can propagate inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000640 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
641 Known.One |= RHSKnown.One & BKnown.Zero;
642 Known.Zero |= RHSKnown.One & BKnown.One;
643 Known.One |= RHSKnown.Zero & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000644 // assume(~(v ^ b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000645 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
646 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000647 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000648 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000649 KnownBits RHSKnown(BitWidth);
650 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
651 KnownBits BKnown(BitWidth);
652 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000653
654 // For those bits in B that are known to be zero, we can propagate
655 // inverted known bits from the RHS to V. For those bits in B that are
656 // known to be one, we can propagate known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000657 Known.Zero |= RHSKnown.One & BKnown.Zero;
658 Known.One |= RHSKnown.Zero & BKnown.Zero;
659 Known.Zero |= RHSKnown.Zero & BKnown.One;
660 Known.One |= RHSKnown.One & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000661 // assume(v << c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000662 } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
663 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000664 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000665 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000666 KnownBits RHSKnown(BitWidth);
667 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000668 // For those bits in RHS that are known, we can propagate them to known
669 // bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000670 RHSKnown.Zero.lshrInPlace(C->getZExtValue());
671 Known.Zero |= RHSKnown.Zero;
672 RHSKnown.One.lshrInPlace(C->getZExtValue());
673 Known.One |= RHSKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000674 // assume(~(v << c) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000675 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(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 inverted
682 // to known bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000683 RHSKnown.One.lshrInPlace(C->getZExtValue());
684 Known.Zero |= RHSKnown.One;
685 RHSKnown.Zero.lshrInPlace(C->getZExtValue());
686 Known.One |= RHSKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000687 // assume(v >> c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000688 } else if (match(Arg,
Craig Topper7b66ffe2017-06-24 06:24:04 +0000689 m_c_ICmp(Pred, m_Shr(m_V, m_ConstantInt(C)),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000690 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000691 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000692 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000693 KnownBits RHSKnown(BitWidth);
694 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000695 // For those bits in RHS that are known, we can propagate them to known
696 // bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000697 Known.Zero |= RHSKnown.Zero << C->getZExtValue();
698 Known.One |= RHSKnown.One << C->getZExtValue();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000699 // assume(~(v >> c) = a)
Craig Topper7b66ffe2017-06-24 06:24:04 +0000700 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shr(m_V, m_ConstantInt(C))),
Philip Reames00d3b272014-11-24 23:44:28 +0000701 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000702 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000703 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000704 KnownBits RHSKnown(BitWidth);
705 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000706 // For those bits in RHS that are known, we can propagate them inverted
707 // to known bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000708 Known.Zero |= RHSKnown.One << C->getZExtValue();
709 Known.One |= RHSKnown.Zero << C->getZExtValue();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000710 // assume(v >=_s c) where c is non-negative
Philip Reames00d3b272014-11-24 23:44:28 +0000711 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000712 Pred == ICmpInst::ICMP_SGE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000713 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000714 KnownBits RHSKnown(BitWidth);
715 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000716
Craig Topperca48af32017-04-29 16:43:11 +0000717 if (RHSKnown.isNonNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000718 // We know that the sign bit is zero.
Craig Topperca48af32017-04-29 16:43:11 +0000719 Known.makeNonNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000720 }
721 // assume(v >_s c) where c is at least -1.
Philip Reames00d3b272014-11-24 23:44:28 +0000722 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000723 Pred == ICmpInst::ICMP_SGT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000724 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000725 KnownBits RHSKnown(BitWidth);
726 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000727
Craig Topperf0aeee02017-05-05 17:36:09 +0000728 if (RHSKnown.isAllOnes() || RHSKnown.isNonNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000729 // We know that the sign bit is zero.
Craig Topperca48af32017-04-29 16:43:11 +0000730 Known.makeNonNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000731 }
732 // assume(v <=_s c) where c is negative
Philip Reames00d3b272014-11-24 23:44:28 +0000733 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000734 Pred == ICmpInst::ICMP_SLE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000735 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000736 KnownBits RHSKnown(BitWidth);
737 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000738
Craig Topperca48af32017-04-29 16:43:11 +0000739 if (RHSKnown.isNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000740 // We know that the sign bit is one.
Craig Topperca48af32017-04-29 16:43:11 +0000741 Known.makeNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000742 }
743 // assume(v <_s c) where c is non-positive
Philip Reames00d3b272014-11-24 23:44:28 +0000744 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000745 Pred == ICmpInst::ICMP_SLT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000746 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000747 KnownBits RHSKnown(BitWidth);
748 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000749
Craig Topperf0aeee02017-05-05 17:36:09 +0000750 if (RHSKnown.isZero() || RHSKnown.isNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000751 // We know that the sign bit is one.
Craig Topperca48af32017-04-29 16:43:11 +0000752 Known.makeNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000753 }
754 // assume(v <=_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000755 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000756 Pred == ICmpInst::ICMP_ULE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000757 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000758 KnownBits RHSKnown(BitWidth);
759 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000760
761 // Whatever high bits in c are zero are known to be zero.
Craig Topper8df66c62017-05-12 17:20:30 +0000762 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
763 // assume(v <_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000764 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000765 Pred == ICmpInst::ICMP_ULT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000766 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000767 KnownBits RHSKnown(BitWidth);
768 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000769
770 // Whatever high bits in c are zero are known to be zero (if c is a power
771 // of 2, then one more).
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000772 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I)))
Craig Topper8df66c62017-05-12 17:20:30 +0000773 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros() + 1);
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000774 else
Craig Topper8df66c62017-05-12 17:20:30 +0000775 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
Hal Finkel60db0582014-09-07 18:57:58 +0000776 }
777 }
Sanjay Patel25f6d712017-02-01 15:41:32 +0000778
779 // If assumptions conflict with each other or previous known bits, then we
Sanjay Patel54656ca2017-02-06 18:26:06 +0000780 // have a logical fallacy. It's possible that the assumption is not reachable,
781 // so this isn't a real bug. On the other hand, the program may have undefined
782 // behavior, or we might have a bug in the compiler. We can't assert/crash, so
783 // clear out the known bits, try to warn the user, and hope for the best.
Craig Topperb45eabc2017-04-26 16:39:58 +0000784 if (Known.Zero.intersects(Known.One)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000785 Known.resetAll();
Sanjay Patel54656ca2017-02-06 18:26:06 +0000786
787 if (Q.ORE) {
788 auto *CxtI = const_cast<Instruction *>(Q.CxtI);
789 OptimizationRemarkAnalysis ORA("value-tracking", "BadAssumption", CxtI);
790 Q.ORE->emit(ORA << "Detected conflicting code assumptions. Program may "
791 "have undefined behavior, or compiler may have "
792 "internal error.");
793 }
Sanjay Patel25f6d712017-02-01 15:41:32 +0000794 }
Hal Finkel60db0582014-09-07 18:57:58 +0000795}
796
Hal Finkelf2199b22015-10-23 20:37:08 +0000797// Compute known bits from a shift operator, including those with a
Craig Topperb45eabc2017-04-26 16:39:58 +0000798// non-constant shift amount. Known is the outputs of this function. Known2 is a
799// pre-allocated temporary with the/ same bit width as Known. KZF and KOF are
800// operator-specific functors that, given the known-zero or known-one bits
801// respectively, and a shift amount, compute the implied known-zero or known-one
802// bits of the shift operator's result respectively for that shift amount. The
803// results from calling KZF and KOF are conservatively combined for all
804// permitted shift amounts.
David Majnemer54690dc2016-08-23 20:52:00 +0000805static void computeKnownBitsFromShiftOperator(
Craig Topperb45eabc2017-04-26 16:39:58 +0000806 const Operator *I, KnownBits &Known, KnownBits &Known2,
807 unsigned Depth, const Query &Q,
David Majnemer54690dc2016-08-23 20:52:00 +0000808 function_ref<APInt(const APInt &, unsigned)> KZF,
809 function_ref<APInt(const APInt &, unsigned)> KOF) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000810 unsigned BitWidth = Known.getBitWidth();
Hal Finkelf2199b22015-10-23 20:37:08 +0000811
812 if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
813 unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1);
814
Craig Topperb45eabc2017-04-26 16:39:58 +0000815 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
816 Known.Zero = KZF(Known.Zero, ShiftAmt);
817 Known.One = KOF(Known.One, ShiftAmt);
818 // If there is conflict between Known.Zero and Known.One, this must be an
819 // overflowing left shift, so the shift result is undefined. Clear Known
820 // bits so that other code could propagate this undef.
Craig Topperf0aeee02017-05-05 17:36:09 +0000821 if ((Known.Zero & Known.One) != 0)
822 Known.resetAll();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +0000823
Hal Finkelf2199b22015-10-23 20:37:08 +0000824 return;
825 }
826
Craig Topperb45eabc2017-04-26 16:39:58 +0000827 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000828
Oliver Stannard06204112017-03-14 10:13:17 +0000829 // If the shift amount could be greater than or equal to the bit-width of the LHS, the
830 // value could be undef, so we don't know anything about it.
Craig Topperb45eabc2017-04-26 16:39:58 +0000831 if ((~Known.Zero).uge(BitWidth)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000832 Known.resetAll();
Oliver Stannard06204112017-03-14 10:13:17 +0000833 return;
834 }
835
Craig Topperb45eabc2017-04-26 16:39:58 +0000836 // Note: We cannot use Known.Zero.getLimitedValue() here, because if
Hal Finkelf2199b22015-10-23 20:37:08 +0000837 // BitWidth > 64 and any upper bits are known, we'll end up returning the
838 // limit value (which implies all bits are known).
Craig Topperb45eabc2017-04-26 16:39:58 +0000839 uint64_t ShiftAmtKZ = Known.Zero.zextOrTrunc(64).getZExtValue();
840 uint64_t ShiftAmtKO = Known.One.zextOrTrunc(64).getZExtValue();
Hal Finkelf2199b22015-10-23 20:37:08 +0000841
842 // It would be more-clearly correct to use the two temporaries for this
843 // calculation. Reusing the APInts here to prevent unnecessary allocations.
Craig Topperf0aeee02017-05-05 17:36:09 +0000844 Known.resetAll();
Hal Finkelf2199b22015-10-23 20:37:08 +0000845
James Molloy493e57d2015-10-26 14:10:46 +0000846 // If we know the shifter operand is nonzero, we can sometimes infer more
847 // known bits. However this is expensive to compute, so be lazy about it and
848 // only compute it when absolutely necessary.
849 Optional<bool> ShifterOperandIsNonZero;
850
Hal Finkelf2199b22015-10-23 20:37:08 +0000851 // Early exit if we can't constrain any well-defined shift amount.
Craig Topperf93b7b12017-06-14 17:04:59 +0000852 if (!(ShiftAmtKZ & (PowerOf2Ceil(BitWidth) - 1)) &&
853 !(ShiftAmtKO & (PowerOf2Ceil(BitWidth) - 1))) {
James Molloy493e57d2015-10-26 14:10:46 +0000854 ShifterOperandIsNonZero =
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000855 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000856 if (!*ShifterOperandIsNonZero)
857 return;
858 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000859
Craig Topperb45eabc2017-04-26 16:39:58 +0000860 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000861
Craig Topperb45eabc2017-04-26 16:39:58 +0000862 Known.Zero.setAllBits();
863 Known.One.setAllBits();
Hal Finkelf2199b22015-10-23 20:37:08 +0000864 for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
865 // Combine the shifted known input bits only for those shift amounts
866 // compatible with its known constraints.
867 if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
868 continue;
869 if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
870 continue;
James Molloy493e57d2015-10-26 14:10:46 +0000871 // If we know the shifter is nonzero, we may be able to infer more known
872 // bits. This check is sunk down as far as possible to avoid the expensive
873 // call to isKnownNonZero if the cheaper checks above fail.
874 if (ShiftAmt == 0) {
875 if (!ShifterOperandIsNonZero.hasValue())
876 ShifterOperandIsNonZero =
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000877 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000878 if (*ShifterOperandIsNonZero)
879 continue;
880 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000881
Craig Topperb45eabc2017-04-26 16:39:58 +0000882 Known.Zero &= KZF(Known2.Zero, ShiftAmt);
883 Known.One &= KOF(Known2.One, ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +0000884 }
885
886 // If there are no compatible shift amounts, then we've proven that the shift
887 // amount must be >= the BitWidth, and the result is undefined. We could
888 // return anything we'd like, but we need to make sure the sets of known bits
889 // stay disjoint (it should be better for some other code to actually
890 // propagate the undef than to pick a value here using known bits).
Craig Topperf0aeee02017-05-05 17:36:09 +0000891 if (Known.Zero.intersects(Known.One))
892 Known.resetAll();
Hal Finkelf2199b22015-10-23 20:37:08 +0000893}
894
Craig Topperb45eabc2017-04-26 16:39:58 +0000895static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known,
896 unsigned Depth, const Query &Q) {
897 unsigned BitWidth = Known.getBitWidth();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000898
Craig Topperb45eabc2017-04-26 16:39:58 +0000899 KnownBits Known2(Known);
Dan Gohman80ca01c2009-07-17 20:47:02 +0000900 switch (I->getOpcode()) {
Chris Lattner965c7692008-06-02 01:18:21 +0000901 default: break;
Rafael Espindola53190532012-03-30 15:52:11 +0000902 case Instruction::Load:
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000903 if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +0000904 computeKnownBitsFromRangeMetadata(*MD, Known);
Jay Foad5a29c362014-05-15 12:12:55 +0000905 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000906 case Instruction::And: {
907 // If either the LHS or the RHS are Zero, the result is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +0000908 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
909 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000910
Chris Lattner965c7692008-06-02 01:18:21 +0000911 // Output known-1 bits are only known if set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000912 Known.One &= Known2.One;
Chris Lattner965c7692008-06-02 01:18:21 +0000913 // Output known-0 are known to be clear if zero in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000914 Known.Zero |= Known2.Zero;
Philip Reames2d858742015-11-10 18:46:14 +0000915
916 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
917 // here we handle the more general case of adding any odd number by
918 // matching the form add(x, add(x, y)) where y is odd.
919 // TODO: This could be generalized to clearing any bit set in y where the
920 // following bit is known to be unset in y.
921 Value *Y = nullptr;
Craig Topperb45eabc2017-04-26 16:39:58 +0000922 if (!Known.Zero[0] && !Known.One[0] &&
Craig Toppera80f2042017-04-13 19:04:45 +0000923 (match(I->getOperand(0), m_Add(m_Specific(I->getOperand(1)),
924 m_Value(Y))) ||
925 match(I->getOperand(1), m_Add(m_Specific(I->getOperand(0)),
926 m_Value(Y))))) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000927 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000928 computeKnownBits(Y, Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +0000929 if (Known2.countMinTrailingOnes() > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +0000930 Known.Zero.setBit(0);
Philip Reames2d858742015-11-10 18:46:14 +0000931 }
Jay Foad5a29c362014-05-15 12:12:55 +0000932 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000933 }
934 case Instruction::Or: {
Craig Topperb45eabc2017-04-26 16:39:58 +0000935 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
936 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000937
Chris Lattner965c7692008-06-02 01:18:21 +0000938 // Output known-0 bits are only known if clear in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000939 Known.Zero &= Known2.Zero;
Chris Lattner965c7692008-06-02 01:18:21 +0000940 // Output known-1 are known to be set if set in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000941 Known.One |= Known2.One;
Jay Foad5a29c362014-05-15 12:12:55 +0000942 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000943 }
944 case Instruction::Xor: {
Craig Topperb45eabc2017-04-26 16:39:58 +0000945 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
946 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000947
Chris Lattner965c7692008-06-02 01:18:21 +0000948 // Output known-0 bits are known if clear or set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000949 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
Chris Lattner965c7692008-06-02 01:18:21 +0000950 // Output known-1 are known to be set if set in only one of the LHS, RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000951 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
952 Known.Zero = std::move(KnownZeroOut);
Jay Foad5a29c362014-05-15 12:12:55 +0000953 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000954 }
955 case Instruction::Mul: {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000956 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Craig Topperb45eabc2017-04-26 16:39:58 +0000957 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, Known,
958 Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000959 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000960 }
961 case Instruction::UDiv: {
962 // For the purposes of computing leading zeros we can conservatively
963 // treat a udiv as a logical right shift by the power of 2 known to
964 // be less than the denominator.
Craig Topperb45eabc2017-04-26 16:39:58 +0000965 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +0000966 unsigned LeadZ = Known2.countMinLeadingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +0000967
Craig Topperf0aeee02017-05-05 17:36:09 +0000968 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000969 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +0000970 unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
971 if (RHSMaxLeadingZeros != BitWidth)
972 LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
Chris Lattner965c7692008-06-02 01:18:21 +0000973
Craig Topperb45eabc2017-04-26 16:39:58 +0000974 Known.Zero.setHighBits(LeadZ);
Jay Foad5a29c362014-05-15 12:12:55 +0000975 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000976 }
David Majnemera19d0f22016-08-06 08:16:00 +0000977 case Instruction::Select: {
Craig Toppere953dec2017-04-13 20:39:37 +0000978 const Value *LHS, *RHS;
David Majnemera19d0f22016-08-06 08:16:00 +0000979 SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
980 if (SelectPatternResult::isMinOrMax(SPF)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000981 computeKnownBits(RHS, Known, Depth + 1, Q);
982 computeKnownBits(LHS, Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +0000983 } else {
Craig Topperb45eabc2017-04-26 16:39:58 +0000984 computeKnownBits(I->getOperand(2), Known, Depth + 1, Q);
985 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +0000986 }
987
988 unsigned MaxHighOnes = 0;
989 unsigned MaxHighZeros = 0;
990 if (SPF == SPF_SMAX) {
991 // If both sides are negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +0000992 if (Known.isNegative() && Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +0000993 // We can derive a lower bound on the result by taking the max of the
994 // leading one bits.
Craig Topper8df66c62017-05-12 17:20:30 +0000995 MaxHighOnes =
996 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +0000997 // If either side is non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +0000998 else if (Known.isNonNegative() || Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +0000999 MaxHighZeros = 1;
1000 } else if (SPF == SPF_SMIN) {
1001 // If both sides are non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +00001002 if (Known.isNonNegative() && Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001003 // We can derive an upper bound on the result by taking the max of the
1004 // leading zero bits.
Craig Topper8df66c62017-05-12 17:20:30 +00001005 MaxHighZeros = std::max(Known.countMinLeadingZeros(),
1006 Known2.countMinLeadingZeros());
David Majnemera19d0f22016-08-06 08:16:00 +00001007 // If either side is negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +00001008 else if (Known.isNegative() || Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001009 MaxHighOnes = 1;
1010 } else if (SPF == SPF_UMAX) {
1011 // We can derive a lower bound on the result by taking the max of the
1012 // leading one bits.
1013 MaxHighOnes =
Craig Topper8df66c62017-05-12 17:20:30 +00001014 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001015 } else if (SPF == SPF_UMIN) {
1016 // We can derive an upper bound on the result by taking the max of the
1017 // leading zero bits.
1018 MaxHighZeros =
Craig Topper8df66c62017-05-12 17:20:30 +00001019 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
David Majnemera19d0f22016-08-06 08:16:00 +00001020 }
1021
Chris Lattner965c7692008-06-02 01:18:21 +00001022 // Only known if known in both the LHS and RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001023 Known.One &= Known2.One;
1024 Known.Zero &= Known2.Zero;
David Majnemera19d0f22016-08-06 08:16:00 +00001025 if (MaxHighOnes > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001026 Known.One.setHighBits(MaxHighOnes);
David Majnemera19d0f22016-08-06 08:16:00 +00001027 if (MaxHighZeros > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001028 Known.Zero.setHighBits(MaxHighZeros);
Jay Foad5a29c362014-05-15 12:12:55 +00001029 break;
David Majnemera19d0f22016-08-06 08:16:00 +00001030 }
Chris Lattner965c7692008-06-02 01:18:21 +00001031 case Instruction::FPTrunc:
1032 case Instruction::FPExt:
1033 case Instruction::FPToUI:
1034 case Instruction::FPToSI:
1035 case Instruction::SIToFP:
1036 case Instruction::UIToFP:
Jay Foad5a29c362014-05-15 12:12:55 +00001037 break; // Can't work with floating point.
Chris Lattner965c7692008-06-02 01:18:21 +00001038 case Instruction::PtrToInt:
1039 case Instruction::IntToPtr:
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001040 // Fall through and handle them the same as zext/trunc.
1041 LLVM_FALLTHROUGH;
Chris Lattner965c7692008-06-02 01:18:21 +00001042 case Instruction::ZExt:
1043 case Instruction::Trunc: {
Chris Lattner229907c2011-07-18 04:54:35 +00001044 Type *SrcTy = I->getOperand(0)->getType();
Nadav Rotem15198e92012-10-26 17:17:05 +00001045
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001046 unsigned SrcBitWidth;
Chris Lattner965c7692008-06-02 01:18:21 +00001047 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1048 // which fall through here.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001049 SrcBitWidth = Q.DL.getTypeSizeInBits(SrcTy->getScalarType());
Nadav Rotem15198e92012-10-26 17:17:05 +00001050
1051 assert(SrcBitWidth && "SrcBitWidth can't be zero");
Craig Topperd938fd12017-05-03 22:07:25 +00001052 Known = Known.zextOrTrunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001053 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Craig Topperd938fd12017-05-03 22:07:25 +00001054 Known = Known.zextOrTrunc(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +00001055 // Any top bits are known to be zero.
1056 if (BitWidth > SrcBitWidth)
Craig Topperb45eabc2017-04-26 16:39:58 +00001057 Known.Zero.setBitsFrom(SrcBitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001058 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001059 }
1060 case Instruction::BitCast: {
Chris Lattner229907c2011-07-18 04:54:35 +00001061 Type *SrcTy = I->getOperand(0)->getType();
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001062 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattneredb84072009-07-02 16:04:08 +00001063 // TODO: For now, not handling conversions like:
1064 // (bitcast i64 %x to <2 x i32>)
Duncan Sands19d0b472010-02-16 11:11:14 +00001065 !I->getType()->isVectorTy()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001066 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Jay Foad5a29c362014-05-15 12:12:55 +00001067 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001068 }
1069 break;
1070 }
1071 case Instruction::SExt: {
1072 // Compute the bits in the result that are not present in the input.
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001073 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Craig Topper1bef2c82012-12-22 19:15:35 +00001074
Craig Topperd938fd12017-05-03 22:07:25 +00001075 Known = Known.trunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001076 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001077 // If the sign bit of the input is known set or clear, then we know the
1078 // top bits of the result.
Craig Topperd938fd12017-05-03 22:07:25 +00001079 Known = Known.sext(BitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001080 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001081 }
Hal Finkelf2199b22015-10-23 20:37:08 +00001082 case Instruction::Shl: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001083 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001084 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Craig Topperd73c6b42017-03-23 07:06:39 +00001085 auto KZF = [NSW](const APInt &KnownZero, unsigned ShiftAmt) {
1086 APInt KZResult = KnownZero << ShiftAmt;
1087 KZResult.setLowBits(ShiftAmt); // Low bits known 0.
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001088 // If this shift has "nsw" keyword, then the result is either a poison
1089 // value or has the same sign bit as the first operand.
Craig Topperd23004c2017-04-17 16:38:20 +00001090 if (NSW && KnownZero.isSignBitSet())
Craig Topperd73c6b42017-03-23 07:06:39 +00001091 KZResult.setSignBit();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001092 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001093 };
1094
Craig Topperd73c6b42017-03-23 07:06:39 +00001095 auto KOF = [NSW](const APInt &KnownOne, unsigned ShiftAmt) {
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001096 APInt KOResult = KnownOne << ShiftAmt;
Craig Topperd23004c2017-04-17 16:38:20 +00001097 if (NSW && KnownOne.isSignBitSet())
Craig Topperd73c6b42017-03-23 07:06:39 +00001098 KOResult.setSignBit();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001099 return KOResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001100 };
1101
Craig Topperb45eabc2017-04-26 16:39:58 +00001102 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001103 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001104 }
1105 case Instruction::LShr: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001106 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Craig Topperfc947bc2017-04-18 17:14:21 +00001107 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1108 APInt KZResult = KnownZero.lshr(ShiftAmt);
1109 // High bits known zero.
1110 KZResult.setHighBits(ShiftAmt);
1111 return KZResult;
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.lshr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001116 };
1117
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 }
1121 case Instruction::AShr: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001122 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Malcolm Parsons17d266b2017-01-13 17:12:16 +00001123 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
Craig Topper885fa122017-03-31 20:01:16 +00001124 return KnownZero.ashr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001125 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001126
Malcolm Parsons17d266b2017-01-13 17:12:16 +00001127 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
Craig Topper885fa122017-03-31 20:01:16 +00001128 return KnownOne.ashr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001129 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001130
Craig Topperb45eabc2017-04-26 16:39:58 +00001131 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001132 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001133 }
Chris Lattner965c7692008-06-02 01:18:21 +00001134 case Instruction::Sub: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001135 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001136 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001137 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001138 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001139 }
Chris Lattner965c7692008-06-02 01:18:21 +00001140 case Instruction::Add: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001141 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001142 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001143 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001144 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001145 }
1146 case Instruction::SRem:
1147 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001148 APInt RA = Rem->getValue().abs();
1149 if (RA.isPowerOf2()) {
1150 APInt LowBits = RA - 1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001151 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001152
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001153 // The low bits of the first operand are unchanged by the srem.
Craig Topperb45eabc2017-04-26 16:39:58 +00001154 Known.Zero = Known2.Zero & LowBits;
1155 Known.One = Known2.One & LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001156
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001157 // If the first operand is non-negative or has all low bits zero, then
1158 // the upper bits are all zero.
Craig Topperca48af32017-04-29 16:43:11 +00001159 if (Known2.isNonNegative() || LowBits.isSubsetOf(Known2.Zero))
Craig Topperb45eabc2017-04-26 16:39:58 +00001160 Known.Zero |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001161
1162 // If the first operand is negative and not all low bits are zero, then
1163 // the upper bits are all one.
Craig Topperca48af32017-04-29 16:43:11 +00001164 if (Known2.isNegative() && LowBits.intersects(Known2.One))
Craig Topperb45eabc2017-04-26 16:39:58 +00001165 Known.One |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001166
Craig Topperb45eabc2017-04-26 16:39:58 +00001167 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Craig Topperda886c62017-04-16 21:46:12 +00001168 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001169 }
1170 }
Nick Lewyckye4679792011-03-07 01:50:10 +00001171
1172 // The sign bit is the LHS's sign bit, except when the result of the
1173 // remainder is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +00001174 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topperda886c62017-04-16 21:46:12 +00001175 // If it's known zero, our sign bit is also zero.
Craig Topperca48af32017-04-29 16:43:11 +00001176 if (Known2.isNonNegative())
1177 Known.makeNonNegative();
Nick Lewyckye4679792011-03-07 01:50:10 +00001178
Chris Lattner965c7692008-06-02 01:18:21 +00001179 break;
1180 case Instruction::URem: {
1181 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001182 const APInt &RA = Rem->getValue();
Chris Lattner965c7692008-06-02 01:18:21 +00001183 if (RA.isPowerOf2()) {
1184 APInt LowBits = (RA - 1);
Craig Topperb45eabc2017-04-26 16:39:58 +00001185 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1186 Known.Zero |= ~LowBits;
1187 Known.One &= LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001188 break;
1189 }
1190 }
1191
1192 // Since the result is less than or equal to either operand, any leading
1193 // zero bits in either operand must also exist in the result.
Craig Topperb45eabc2017-04-26 16:39:58 +00001194 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1195 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001196
Craig Topper8df66c62017-05-12 17:20:30 +00001197 unsigned Leaders =
1198 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
Craig Topperf0aeee02017-05-05 17:36:09 +00001199 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001200 Known.Zero.setHighBits(Leaders);
Chris Lattner965c7692008-06-02 01:18:21 +00001201 break;
1202 }
1203
Victor Hernandeza3aaf852009-10-17 01:18:07 +00001204 case Instruction::Alloca: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001205 const AllocaInst *AI = cast<AllocaInst>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001206 unsigned Align = AI->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001207 if (Align == 0)
Eduard Burtescu90c44492016-01-18 00:10:01 +00001208 Align = Q.DL.getABITypeAlignment(AI->getAllocatedType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001209
Chris Lattner965c7692008-06-02 01:18:21 +00001210 if (Align > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001211 Known.Zero.setLowBits(countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +00001212 break;
1213 }
1214 case Instruction::GetElementPtr: {
1215 // Analyze all of the subscripts of this getelementptr instruction
1216 // to determine if we can prove known low zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001217 KnownBits LocalKnown(BitWidth);
1218 computeKnownBits(I->getOperand(0), LocalKnown, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001219 unsigned TrailZ = LocalKnown.countMinTrailingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +00001220
1221 gep_type_iterator GTI = gep_type_begin(I);
1222 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1223 Value *Index = I->getOperand(i);
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001224 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chris Lattner965c7692008-06-02 01:18:21 +00001225 // Handle struct member offset arithmetic.
Matt Arsenault74742a12013-08-19 21:43:16 +00001226
1227 // Handle case when index is vector zeroinitializer
1228 Constant *CIndex = cast<Constant>(Index);
1229 if (CIndex->isZeroValue())
1230 continue;
1231
1232 if (CIndex->getType()->isVectorTy())
1233 Index = CIndex->getSplatValue();
1234
Chris Lattner965c7692008-06-02 01:18:21 +00001235 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001236 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chris Lattner965c7692008-06-02 01:18:21 +00001237 uint64_t Offset = SL->getElementOffset(Idx);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001238 TrailZ = std::min<unsigned>(TrailZ,
1239 countTrailingZeros(Offset));
Chris Lattner965c7692008-06-02 01:18:21 +00001240 } else {
1241 // Handle array index arithmetic.
Chris Lattner229907c2011-07-18 04:54:35 +00001242 Type *IndexedTy = GTI.getIndexedType();
Jay Foad5a29c362014-05-15 12:12:55 +00001243 if (!IndexedTy->isSized()) {
1244 TrailZ = 0;
1245 break;
1246 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001247 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001248 uint64_t TypeSize = Q.DL.getTypeAllocSize(IndexedTy);
Craig Topperb45eabc2017-04-26 16:39:58 +00001249 LocalKnown.Zero = LocalKnown.One = APInt(GEPOpiBits, 0);
1250 computeKnownBits(Index, LocalKnown, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001251 TrailZ = std::min(TrailZ,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001252 unsigned(countTrailingZeros(TypeSize) +
Craig Topper8df66c62017-05-12 17:20:30 +00001253 LocalKnown.countMinTrailingZeros()));
Chris Lattner965c7692008-06-02 01:18:21 +00001254 }
1255 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001256
Craig Topperb45eabc2017-04-26 16:39:58 +00001257 Known.Zero.setLowBits(TrailZ);
Chris Lattner965c7692008-06-02 01:18:21 +00001258 break;
1259 }
1260 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001261 const PHINode *P = cast<PHINode>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001262 // Handle the case of a simple two-predecessor recurrence PHI.
1263 // There's a lot more that could theoretically be done here, but
1264 // this is sufficient to catch some interesting cases.
1265 if (P->getNumIncomingValues() == 2) {
1266 for (unsigned i = 0; i != 2; ++i) {
1267 Value *L = P->getIncomingValue(i);
1268 Value *R = P->getIncomingValue(!i);
Dan Gohman80ca01c2009-07-17 20:47:02 +00001269 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner965c7692008-06-02 01:18:21 +00001270 if (!LU)
1271 continue;
Dan Gohman80ca01c2009-07-17 20:47:02 +00001272 unsigned Opcode = LU->getOpcode();
Chris Lattner965c7692008-06-02 01:18:21 +00001273 // Check for operations that have the property that if
1274 // both their operands have low zero bits, the result
Artur Pilipenkobc76eca2016-08-22 13:14:07 +00001275 // will have low zero bits.
Chris Lattner965c7692008-06-02 01:18:21 +00001276 if (Opcode == Instruction::Add ||
1277 Opcode == Instruction::Sub ||
1278 Opcode == Instruction::And ||
1279 Opcode == Instruction::Or ||
1280 Opcode == Instruction::Mul) {
1281 Value *LL = LU->getOperand(0);
1282 Value *LR = LU->getOperand(1);
1283 // Find a recurrence.
1284 if (LL == I)
1285 L = LR;
1286 else if (LR == I)
1287 L = LL;
1288 else
1289 break;
1290 // Ok, we have a PHI of the form L op= R. Check for low
1291 // zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001292 computeKnownBits(R, Known2, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001293
1294 // We need to take the minimum number of known bits
Craig Topperb45eabc2017-04-26 16:39:58 +00001295 KnownBits Known3(Known);
1296 computeKnownBits(L, Known3, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001297
Craig Topper8df66c62017-05-12 17:20:30 +00001298 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1299 Known3.countMinTrailingZeros()));
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001300
1301 if (DontImproveNonNegativePhiBits)
1302 break;
1303
1304 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(LU);
1305 if (OverflowOp && OverflowOp->hasNoSignedWrap()) {
1306 // If initial value of recurrence is nonnegative, and we are adding
1307 // a nonnegative number with nsw, the result can only be nonnegative
1308 // or poison value regardless of the number of times we execute the
1309 // add in phi recurrence. If initial value is negative and we are
1310 // adding a negative number with nsw, the result can only be
1311 // negative or poison value. Similar arguments apply to sub and mul.
1312 //
1313 // (add non-negative, non-negative) --> non-negative
1314 // (add negative, negative) --> negative
1315 if (Opcode == Instruction::Add) {
Craig Topperca48af32017-04-29 16:43:11 +00001316 if (Known2.isNonNegative() && Known3.isNonNegative())
1317 Known.makeNonNegative();
1318 else if (Known2.isNegative() && Known3.isNegative())
1319 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001320 }
1321
1322 // (sub nsw non-negative, negative) --> non-negative
1323 // (sub nsw negative, non-negative) --> negative
1324 else if (Opcode == Instruction::Sub && LL == I) {
Craig Topperca48af32017-04-29 16:43:11 +00001325 if (Known2.isNonNegative() && Known3.isNegative())
1326 Known.makeNonNegative();
1327 else if (Known2.isNegative() && Known3.isNonNegative())
1328 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001329 }
1330
1331 // (mul nsw non-negative, non-negative) --> non-negative
Craig Topperca48af32017-04-29 16:43:11 +00001332 else if (Opcode == Instruction::Mul && Known2.isNonNegative() &&
1333 Known3.isNonNegative())
1334 Known.makeNonNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001335 }
1336
Chris Lattner965c7692008-06-02 01:18:21 +00001337 break;
1338 }
1339 }
1340 }
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001341
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001342 // Unreachable blocks may have zero-operand PHI nodes.
1343 if (P->getNumIncomingValues() == 0)
Jay Foad5a29c362014-05-15 12:12:55 +00001344 break;
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001345
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001346 // Otherwise take the unions of the known bit sets of the operands,
1347 // taking conservative care to avoid excessive recursion.
Craig Topperb45eabc2017-04-26 16:39:58 +00001348 if (Depth < MaxDepth - 1 && !Known.Zero && !Known.One) {
Duncan Sands7dc3d472011-03-08 12:39:03 +00001349 // Skip if every incoming value references to ourself.
Nuno Lopes0d44a502012-07-03 21:15:40 +00001350 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
Duncan Sands7dc3d472011-03-08 12:39:03 +00001351 break;
1352
Craig Topperb45eabc2017-04-26 16:39:58 +00001353 Known.Zero.setAllBits();
1354 Known.One.setAllBits();
Pete Cooper833f34d2015-05-12 20:05:31 +00001355 for (Value *IncValue : P->incoming_values()) {
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001356 // Skip direct self references.
Pete Cooper833f34d2015-05-12 20:05:31 +00001357 if (IncValue == P) continue;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001358
Craig Topperb45eabc2017-04-26 16:39:58 +00001359 Known2 = KnownBits(BitWidth);
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001360 // Recurse, but cap the recursion to one level, because we don't
1361 // want to waste time spinning around in loops.
Craig Topperb45eabc2017-04-26 16:39:58 +00001362 computeKnownBits(IncValue, Known2, MaxDepth - 1, Q);
1363 Known.Zero &= Known2.Zero;
1364 Known.One &= Known2.One;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001365 // If all bits have been ruled out, there's no need to check
1366 // more operands.
Craig Topperb45eabc2017-04-26 16:39:58 +00001367 if (!Known.Zero && !Known.One)
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001368 break;
1369 }
1370 }
Chris Lattner965c7692008-06-02 01:18:21 +00001371 break;
1372 }
1373 case Instruction::Call:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001374 case Instruction::Invoke:
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001375 // If range metadata is attached to this call, set known bits from that,
1376 // and then intersect with known bits based on other properties of the
1377 // function.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001378 if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +00001379 computeKnownBitsFromRangeMetadata(*MD, Known);
Pete Cooper35b00d52016-08-13 01:05:32 +00001380 if (const Value *RV = ImmutableCallSite(I).getReturnedArgOperand()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001381 computeKnownBits(RV, Known2, Depth + 1, Q);
1382 Known.Zero |= Known2.Zero;
1383 Known.One |= Known2.One;
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001384 }
Pete Cooper35b00d52016-08-13 01:05:32 +00001385 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001386 switch (II->getIntrinsicID()) {
1387 default: break;
Chad Rosier85204292017-01-17 17:23:51 +00001388 case Intrinsic::bitreverse:
Craig Topperb45eabc2017-04-26 16:39:58 +00001389 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1390 Known.Zero |= Known2.Zero.reverseBits();
1391 Known.One |= Known2.One.reverseBits();
Chad Rosier85204292017-01-17 17:23:51 +00001392 break;
Philip Reames675418e2015-10-06 20:20:45 +00001393 case Intrinsic::bswap:
Craig Topperb45eabc2017-04-26 16:39:58 +00001394 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1395 Known.Zero |= Known2.Zero.byteSwap();
1396 Known.One |= Known2.One.byteSwap();
Philip Reames675418e2015-10-06 20:20:45 +00001397 break;
Craig Topper868813f2017-05-08 17:22:34 +00001398 case Intrinsic::ctlz: {
1399 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1400 // If we have a known 1, its position is our upper bound.
1401 unsigned PossibleLZ = Known2.One.countLeadingZeros();
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001402 // If this call is undefined for 0, the result will be less than 2^n.
1403 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
Craig Topper868813f2017-05-08 17:22:34 +00001404 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
1405 unsigned LowBits = Log2_32(PossibleLZ)+1;
1406 Known.Zero.setBitsFrom(LowBits);
1407 break;
1408 }
1409 case Intrinsic::cttz: {
1410 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1411 // If we have a known 1, its position is our upper bound.
1412 unsigned PossibleTZ = Known2.One.countTrailingZeros();
1413 // If this call is undefined for 0, the result will be less than 2^n.
1414 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1415 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
1416 unsigned LowBits = Log2_32(PossibleTZ)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001417 Known.Zero.setBitsFrom(LowBits);
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001418 break;
1419 }
1420 case Intrinsic::ctpop: {
Craig Topperb45eabc2017-04-26 16:39:58 +00001421 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001422 // We can bound the space the count needs. Also, bits known to be zero
1423 // can't contribute to the population.
Craig Topper8df66c62017-05-12 17:20:30 +00001424 unsigned BitsPossiblySet = Known2.countMaxPopulation();
Craig Topper66df10f2017-04-14 06:43:34 +00001425 unsigned LowBits = Log2_32(BitsPossiblySet)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001426 Known.Zero.setBitsFrom(LowBits);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001427 // TODO: we could bound KnownOne using the lower bound on the number
1428 // of bits which might be set provided by popcnt KnownOne2.
Chris Lattner965c7692008-06-02 01:18:21 +00001429 break;
1430 }
Chad Rosierb3628842011-05-26 23:13:19 +00001431 case Intrinsic::x86_sse42_crc32_64_64:
Craig Topperb45eabc2017-04-26 16:39:58 +00001432 Known.Zero.setBitsFrom(32);
Evan Cheng2a746bf2011-05-22 18:25:30 +00001433 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001434 }
1435 }
1436 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00001437 case Instruction::ExtractElement:
1438 // Look through extract element. At the moment we keep this simple and skip
1439 // tracking the specific element. But at least we might find information
1440 // valid for all elements of the vector (for example if vector is sign
1441 // extended, shifted, etc).
Craig Topperb45eabc2017-04-26 16:39:58 +00001442 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Bjorn Pettersson39616032016-10-06 09:56:21 +00001443 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001444 case Instruction::ExtractValue:
1445 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001446 const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001447 if (EVI->getNumIndices() != 1) break;
1448 if (EVI->getIndices()[0] == 0) {
1449 switch (II->getIntrinsicID()) {
1450 default: break;
1451 case Intrinsic::uadd_with_overflow:
1452 case Intrinsic::sadd_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001453 computeKnownBitsAddSub(true, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001454 II->getArgOperand(1), false, Known, Known2,
1455 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001456 break;
1457 case Intrinsic::usub_with_overflow:
1458 case Intrinsic::ssub_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001459 computeKnownBitsAddSub(false, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001460 II->getArgOperand(1), false, Known, Known2,
1461 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001462 break;
Nick Lewyckyfa306072012-03-18 23:28:48 +00001463 case Intrinsic::umul_with_overflow:
1464 case Intrinsic::smul_with_overflow:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001465 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
Craig Topperb45eabc2017-04-26 16:39:58 +00001466 Known, Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001467 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001468 }
1469 }
1470 }
Chris Lattner965c7692008-06-02 01:18:21 +00001471 }
Jingyue Wu12b0c282015-06-15 05:46:29 +00001472}
1473
1474/// Determine which bits of V are known to be either zero or one and return
Craig Topper6e11a052017-05-08 16:22:48 +00001475/// them.
1476KnownBits computeKnownBits(const Value *V, unsigned Depth, const Query &Q) {
1477 KnownBits Known(getBitWidth(V->getType(), Q.DL));
1478 computeKnownBits(V, Known, Depth, Q);
1479 return Known;
1480}
1481
1482/// Determine which bits of V are known to be either zero or one and return
Craig Topperb45eabc2017-04-26 16:39:58 +00001483/// them in the Known bit set.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001484///
1485/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
1486/// we cannot optimize based on the assumption that it is zero without changing
1487/// it to be an explicit zero. If we don't change it to zero, other code could
1488/// optimized based on the contradictory assumption that it is non-zero.
1489/// Because instcombine aggressively folds operations with undef args anyway,
1490/// this won't lose us code quality.
1491///
1492/// This function is defined on values with integer type, values with pointer
1493/// type, and vectors of integers. In the case
1494/// where V is a vector, known zero, and known one values are the
1495/// same width as the vector element, and the bit is set only if it is true
1496/// for all of the elements in the vector.
Craig Topperb45eabc2017-04-26 16:39:58 +00001497void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
1498 const Query &Q) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001499 assert(V && "No Value?");
1500 assert(Depth <= MaxDepth && "Limit Search Depth");
Craig Topperb45eabc2017-04-26 16:39:58 +00001501 unsigned BitWidth = Known.getBitWidth();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001502
1503 assert((V->getType()->isIntOrIntVectorTy() ||
1504 V->getType()->getScalarType()->isPointerTy()) &&
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001505 "Not integer or pointer type!");
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001506 assert((Q.DL.getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth) &&
Jingyue Wu12b0c282015-06-15 05:46:29 +00001507 (!V->getType()->isIntOrIntVectorTy() ||
1508 V->getType()->getScalarSizeInBits() == BitWidth) &&
Craig Topperb45eabc2017-04-26 16:39:58 +00001509 "V and Known should have same BitWidth");
Craig Topperd73c6b42017-03-23 07:06:39 +00001510 (void)BitWidth;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001511
Sanjay Patelc96f6db2016-09-16 21:20:36 +00001512 const APInt *C;
1513 if (match(V, m_APInt(C))) {
1514 // We know all of the bits for a scalar constant or a splat vector constant!
Craig Topperb45eabc2017-04-26 16:39:58 +00001515 Known.One = *C;
1516 Known.Zero = ~Known.One;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001517 return;
1518 }
1519 // Null and aggregate-zero are all-zeros.
Sanjay Patele8dc0902016-05-23 17:57:54 +00001520 if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001521 Known.setAllZero();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001522 return;
1523 }
1524 // Handle a constant vector by taking the intersection of the known bits of
David Majnemer3918cdd2016-05-04 06:13:33 +00001525 // each element.
Pete Cooper35b00d52016-08-13 01:05:32 +00001526 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001527 // We know that CDS 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();
Craig Topper9c932d32017-04-25 16:48:03 +00001530 APInt Elt(BitWidth, 0);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001531 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1532 Elt = CDS->getElementAsInteger(i);
Craig Topperb45eabc2017-04-26 16:39:58 +00001533 Known.Zero &= ~Elt;
1534 Known.One &= Elt;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001535 }
1536 return;
1537 }
1538
Pete Cooper35b00d52016-08-13 01:05:32 +00001539 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
David Majnemer3918cdd2016-05-04 06:13:33 +00001540 // We know that CV must be a vector of integers. Take the intersection of
1541 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001542 Known.Zero.setAllBits(); Known.One.setAllBits();
1543 APInt Elt(BitWidth, 0);
David Majnemer3918cdd2016-05-04 06:13:33 +00001544 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1545 Constant *Element = CV->getAggregateElement(i);
1546 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
1547 if (!ElementCI) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001548 Known.resetAll();
David Majnemer3918cdd2016-05-04 06:13:33 +00001549 return;
1550 }
1551 Elt = ElementCI->getValue();
Craig Topperb45eabc2017-04-26 16:39:58 +00001552 Known.Zero &= ~Elt;
1553 Known.One &= Elt;
David Majnemer3918cdd2016-05-04 06:13:33 +00001554 }
1555 return;
1556 }
1557
Jingyue Wu12b0c282015-06-15 05:46:29 +00001558 // Start out not knowing anything.
Craig Topperf0aeee02017-05-05 17:36:09 +00001559 Known.resetAll();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001560
Duncan P. N. Exon Smithb1b208a2016-09-24 20:42:02 +00001561 // We can't imply anything about undefs.
1562 if (isa<UndefValue>(V))
1563 return;
1564
1565 // There's no point in looking through other users of ConstantData for
1566 // assumptions. Confirm that we've handled them all.
1567 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
1568
Jingyue Wu12b0c282015-06-15 05:46:29 +00001569 // Limit search depth.
1570 // All recursive calls that increase depth must come after this.
1571 if (Depth == MaxDepth)
1572 return;
1573
1574 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1575 // the bits of its aliasee.
Pete Cooper35b00d52016-08-13 01:05:32 +00001576 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001577 if (!GA->isInterposable())
Craig Topperb45eabc2017-04-26 16:39:58 +00001578 computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001579 return;
1580 }
1581
Pete Cooper35b00d52016-08-13 01:05:32 +00001582 if (const Operator *I = dyn_cast<Operator>(V))
Craig Topperb45eabc2017-04-26 16:39:58 +00001583 computeKnownBitsFromOperator(I, Known, Depth, Q);
Sanjay Patela67559c2015-09-25 20:12:43 +00001584
Craig Topperb45eabc2017-04-26 16:39:58 +00001585 // Aligned pointers have trailing zeros - refine Known.Zero set
Artur Pilipenko029d8532015-09-30 11:55:45 +00001586 if (V->getType()->isPointerTy()) {
Artur Pilipenkoae51afc2016-02-24 12:25:10 +00001587 unsigned Align = V->getPointerAlignment(Q.DL);
Artur Pilipenko029d8532015-09-30 11:55:45 +00001588 if (Align)
Craig Topperb45eabc2017-04-26 16:39:58 +00001589 Known.Zero.setLowBits(countTrailingZeros(Align));
Artur Pilipenko029d8532015-09-30 11:55:45 +00001590 }
1591
Craig Topperb45eabc2017-04-26 16:39:58 +00001592 // computeKnownBitsFromAssume strictly refines Known.
1593 // Therefore, we run them after computeKnownBitsFromOperator.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001594
1595 // Check whether a nearby assume intrinsic can determine some known bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001596 computeKnownBitsFromAssume(V, Known, Depth, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001597
Craig Topperb45eabc2017-04-26 16:39:58 +00001598 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001599}
1600
Sanjay Patelaee84212014-11-04 16:27:42 +00001601/// Return true if the given value is known to have exactly one
Duncan Sandsd3951082011-01-25 09:38:29 +00001602/// bit set when defined. For vectors return true if every element is known to
Sanjay Patelaee84212014-11-04 16:27:42 +00001603/// be a power of two when defined. Supports values with integer or pointer
Duncan Sandsd3951082011-01-25 09:38:29 +00001604/// types and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001605bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001606 const Query &Q) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001607 if (const Constant *C = dyn_cast<Constant>(V)) {
Duncan Sandsba286d72011-10-26 20:55:21 +00001608 if (C->isNullValue())
1609 return OrZero;
Sanjay Patele2e89ef2016-05-22 15:41:53 +00001610
1611 const APInt *ConstIntOrConstSplatInt;
1612 if (match(C, m_APInt(ConstIntOrConstSplatInt)))
1613 return ConstIntOrConstSplatInt->isPowerOf2();
Duncan Sandsba286d72011-10-26 20:55:21 +00001614 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001615
1616 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1617 // it is shifted off the end then the result is undefined.
1618 if (match(V, m_Shl(m_One(), m_Value())))
1619 return true;
1620
Craig Topperbcfd2d12017-04-20 16:56:25 +00001621 // (signmask) >>l X is clearly a power of two if the one is not shifted off
1622 // the bottom. If it is shifted off the bottom then the result is undefined.
1623 if (match(V, m_LShr(m_SignMask(), m_Value())))
Duncan Sandsd3951082011-01-25 09:38:29 +00001624 return true;
1625
1626 // The remaining tests are all recursive, so bail out if we hit the limit.
1627 if (Depth++ == MaxDepth)
1628 return false;
1629
Craig Topper9f008862014-04-15 04:59:12 +00001630 Value *X = nullptr, *Y = nullptr;
Sanjay Patel41160c22015-12-30 22:40:52 +00001631 // A shift left or a logical shift right of a power of two is a power of two
1632 // or zero.
Duncan Sands985ba632011-10-28 18:30:05 +00001633 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
Sanjay Patel41160c22015-12-30 22:40:52 +00001634 match(V, m_LShr(m_Value(X), m_Value()))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001635 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
Duncan Sands985ba632011-10-28 18:30:05 +00001636
Pete Cooper35b00d52016-08-13 01:05:32 +00001637 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001638 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001639
Pete Cooper35b00d52016-08-13 01:05:32 +00001640 if (const SelectInst *SI = dyn_cast<SelectInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001641 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1642 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
Duncan Sandsba286d72011-10-26 20:55:21 +00001643
Duncan Sandsba286d72011-10-26 20:55:21 +00001644 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1645 // A power of two and'd with anything is a power of two or zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001646 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
1647 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
Duncan Sandsba286d72011-10-26 20:55:21 +00001648 return true;
1649 // X & (-X) is always a power of two or zero.
1650 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1651 return true;
1652 return false;
1653 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001654
David Majnemerb7d54092013-07-30 21:01:36 +00001655 // Adding a power-of-two or zero to the same power-of-two or zero yields
1656 // either the original power-of-two, a larger power-of-two or zero.
1657 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001658 const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
David Majnemerb7d54092013-07-30 21:01:36 +00001659 if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1660 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1661 match(X, m_And(m_Value(), m_Specific(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001662 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001663 return true;
1664 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1665 match(Y, m_And(m_Value(), m_Specific(X))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001666 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001667 return true;
1668
1669 unsigned BitWidth = V->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00001670 KnownBits LHSBits(BitWidth);
1671 computeKnownBits(X, LHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001672
Craig Topperb45eabc2017-04-26 16:39:58 +00001673 KnownBits RHSBits(BitWidth);
1674 computeKnownBits(Y, RHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001675 // If i8 V is a power of two or zero:
1676 // ZeroBits: 1 1 1 0 1 1 1 1
1677 // ~ZeroBits: 0 0 0 1 0 0 0 0
Craig Topperb45eabc2017-04-26 16:39:58 +00001678 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
David Majnemerb7d54092013-07-30 21:01:36 +00001679 // If OrZero isn't set, we cannot give back a zero result.
1680 // Make sure either the LHS or RHS has a bit set.
Craig Topperb45eabc2017-04-26 16:39:58 +00001681 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
David Majnemerb7d54092013-07-30 21:01:36 +00001682 return true;
1683 }
1684 }
David Majnemerbeab5672013-05-18 19:30:37 +00001685
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001686 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewyckyf0469af2011-03-21 21:40:32 +00001687 // is a power of two only if the first operand is a power of two and not
1688 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001689 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1690 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
Hal Finkel60db0582014-09-07 18:57:58 +00001691 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001692 Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001693 }
1694
Duncan Sandsd3951082011-01-25 09:38:29 +00001695 return false;
1696}
1697
Chandler Carruth80d3e562012-12-07 02:08:58 +00001698/// \brief Test whether a GEP's result is known to be non-null.
1699///
1700/// Uses properties inherent in a GEP to try to determine whether it is known
1701/// to be non-null.
1702///
1703/// Currently this routine does not support vector GEPs.
Pete Cooper35b00d52016-08-13 01:05:32 +00001704static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001705 const Query &Q) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001706 if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1707 return false;
1708
1709 // FIXME: Support vector-GEPs.
1710 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1711
1712 // If the base pointer is non-null, we cannot walk to a null address with an
1713 // inbounds GEP in address space zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001714 if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001715 return true;
1716
Chandler Carruth80d3e562012-12-07 02:08:58 +00001717 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1718 // If so, then the GEP cannot produce a null pointer, as doing so would
1719 // inherently violate the inbounds contract within address space zero.
1720 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1721 GTI != GTE; ++GTI) {
1722 // Struct types are easy -- they must always be indexed by a constant.
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001723 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001724 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1725 unsigned ElementIdx = OpC->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001726 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chandler Carruth80d3e562012-12-07 02:08:58 +00001727 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1728 if (ElementOffset > 0)
1729 return true;
1730 continue;
1731 }
1732
1733 // If we have a zero-sized type, the index doesn't matter. Keep looping.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001734 if (Q.DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
Chandler Carruth80d3e562012-12-07 02:08:58 +00001735 continue;
1736
1737 // Fast path the constant operand case both for efficiency and so we don't
1738 // increment Depth when just zipping down an all-constant GEP.
1739 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1740 if (!OpC->isZero())
1741 return true;
1742 continue;
1743 }
1744
1745 // We post-increment Depth here because while isKnownNonZero increments it
1746 // as well, when we pop back up that increment won't persist. We don't want
1747 // to recurse 10k times just because we have 10k GEP operands. We don't
1748 // bail completely out because we want to handle constant GEPs regardless
1749 // of depth.
1750 if (Depth++ >= MaxDepth)
1751 continue;
1752
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001753 if (isKnownNonZero(GTI.getOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001754 return true;
1755 }
1756
1757 return false;
1758}
1759
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001760/// Does the 'Range' metadata (which must be a valid MD_range operand list)
1761/// ensure that the value it's attached to is never Value? 'RangeType' is
1762/// is the type of the value described by the range.
Pete Cooper35b00d52016-08-13 01:05:32 +00001763static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001764 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1765 assert(NumRanges >= 1);
1766 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001767 ConstantInt *Lower =
1768 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1769 ConstantInt *Upper =
1770 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001771 ConstantRange Range(Lower->getValue(), Upper->getValue());
1772 if (Range.contains(Value))
1773 return false;
1774 }
1775 return true;
1776}
1777
Sanjay Patel97e4b9872017-02-12 15:35:34 +00001778/// Return true if the given value is known to be non-zero when defined. For
1779/// vectors, return true if every element is known to be non-zero when
1780/// defined. For pointers, if the context instruction and dominator tree are
1781/// specified, perform context-sensitive analysis and return true if the
1782/// pointer couldn't possibly be null at the specified instruction.
1783/// Supports values with integer or pointer type and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001784bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q) {
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001785 if (auto *C = dyn_cast<Constant>(V)) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001786 if (C->isNullValue())
1787 return false;
1788 if (isa<ConstantInt>(C))
1789 // Must be non-zero due to null test above.
1790 return true;
Sanjay Patel23019d12016-05-24 14:18:49 +00001791
1792 // For constant vectors, check that all elements are undefined or known
1793 // non-zero to determine that the whole vector is known non-zero.
1794 if (auto *VecTy = dyn_cast<VectorType>(C->getType())) {
1795 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
1796 Constant *Elt = C->getAggregateElement(i);
1797 if (!Elt || Elt->isNullValue())
1798 return false;
1799 if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
1800 return false;
1801 }
1802 return true;
1803 }
1804
Duncan Sandsd3951082011-01-25 09:38:29 +00001805 return false;
1806 }
1807
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001808 if (auto *I = dyn_cast<Instruction>(V)) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001809 if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001810 // If the possible ranges don't contain zero, then the value is
1811 // definitely non-zero.
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001812 if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001813 const APInt ZeroValue(Ty->getBitWidth(), 0);
1814 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
1815 return true;
1816 }
1817 }
1818 }
1819
Duncan Sandsd3951082011-01-25 09:38:29 +00001820 // The remaining tests are all recursive, so bail out if we hit the limit.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001821 if (Depth++ >= MaxDepth)
Duncan Sandsd3951082011-01-25 09:38:29 +00001822 return false;
1823
Chandler Carruth80d3e562012-12-07 02:08:58 +00001824 // Check for pointer simplifications.
1825 if (V->getType()->isPointerTy()) {
Sanjay Patel97e4b9872017-02-12 15:35:34 +00001826 if (isKnownNonNullAt(V, Q.CxtI, Q.DT))
Sanjoy Das6082c1a2016-05-07 02:08:15 +00001827 return true;
Pete Cooper35b00d52016-08-13 01:05:32 +00001828 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001829 if (isGEPKnownNonNull(GEP, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001830 return true;
1831 }
1832
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001833 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001834
1835 // X | Y != 0 if X != 0 or Y != 0.
Craig Topper9f008862014-04-15 04:59:12 +00001836 Value *X = nullptr, *Y = nullptr;
Duncan Sandsd3951082011-01-25 09:38:29 +00001837 if (match(V, m_Or(m_Value(X), m_Value(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001838 return isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001839
1840 // ext X != 0 if X != 0.
1841 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001842 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001843
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001844 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd3951082011-01-25 09:38:29 +00001845 // if the lowest bit is shifted off the end.
Craig Topper6b3940a2017-05-03 22:25:19 +00001846 if (match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001847 // shl nuw can't remove any non-zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00001848 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001849 if (BO->hasNoUnsignedWrap())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001850 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001851
Craig Topperb45eabc2017-04-26 16:39:58 +00001852 KnownBits Known(BitWidth);
1853 computeKnownBits(X, Known, Depth, Q);
1854 if (Known.One[0])
Duncan Sandsd3951082011-01-25 09:38:29 +00001855 return true;
1856 }
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001857 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd3951082011-01-25 09:38:29 +00001858 // defined if the sign bit is shifted off the end.
1859 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001860 // shr exact can only shift out zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00001861 const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001862 if (BO->isExact())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001863 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001864
Craig Topper6e11a052017-05-08 16:22:48 +00001865 KnownBits Known = computeKnownBits(X, Depth, Q);
1866 if (Known.isNegative())
Duncan Sandsd3951082011-01-25 09:38:29 +00001867 return true;
James Molloyb6be1eb2015-09-24 16:06:32 +00001868
1869 // If the shifter operand is a constant, and all of the bits shifted
1870 // out are known to be zero, and X is known non-zero then at least one
1871 // non-zero bit must remain.
1872 if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
James Molloyb6be1eb2015-09-24 16:06:32 +00001873 auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
1874 // Is there a known one in the portion not shifted out?
Craig Topper8df66c62017-05-12 17:20:30 +00001875 if (Known.countMaxLeadingZeros() < BitWidth - ShiftVal)
James Molloyb6be1eb2015-09-24 16:06:32 +00001876 return true;
1877 // Are all the bits to be shifted out known zero?
Craig Topper8df66c62017-05-12 17:20:30 +00001878 if (Known.countMinTrailingZeros() >= ShiftVal)
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001879 return isKnownNonZero(X, Depth, Q);
James Molloyb6be1eb2015-09-24 16:06:32 +00001880 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001881 }
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001882 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001883 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001884 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001885 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001886 // X + Y.
1887 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Craig Topper6e11a052017-05-08 16:22:48 +00001888 KnownBits XKnown = computeKnownBits(X, Depth, Q);
1889 KnownBits YKnown = computeKnownBits(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001890
1891 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001892 // zero unless both X and Y are zero.
Craig Topper6e11a052017-05-08 16:22:48 +00001893 if (XKnown.isNonNegative() && YKnown.isNonNegative())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001894 if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q))
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001895 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00001896
1897 // If X and Y are both negative (as signed values) then their sum is not
1898 // zero unless both X and Y equal INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00001899 if (XKnown.isNegative() && YKnown.isNegative()) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001900 APInt Mask = APInt::getSignedMaxValue(BitWidth);
1901 // The sign bit of X is set. If some other bit is set then X is not equal
1902 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00001903 if (XKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00001904 return true;
1905 // The sign bit of Y is set. If some other bit is set then Y is not equal
1906 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00001907 if (YKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00001908 return true;
1909 }
1910
1911 // The sum of a non-negative number and a power of two is not zero.
Craig Topper6e11a052017-05-08 16:22:48 +00001912 if (XKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001913 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001914 return true;
Craig Topper6e11a052017-05-08 16:22:48 +00001915 if (YKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001916 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001917 return true;
1918 }
Duncan Sands7cb61e52011-10-27 19:16:21 +00001919 // X * Y.
1920 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001921 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Duncan Sands7cb61e52011-10-27 19:16:21 +00001922 // If X and Y are non-zero then so is X * Y as long as the multiplication
1923 // does not overflow.
1924 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001925 isKnownNonZero(X, Depth, Q) && isKnownNonZero(Y, Depth, Q))
Duncan Sands7cb61e52011-10-27 19:16:21 +00001926 return true;
1927 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001928 // (C ? X : Y) != 0 if X != 0 and Y != 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00001929 else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001930 if (isKnownNonZero(SI->getTrueValue(), Depth, Q) &&
1931 isKnownNonZero(SI->getFalseValue(), Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001932 return true;
1933 }
James Molloy897048b2015-09-29 14:08:45 +00001934 // PHI
Pete Cooper35b00d52016-08-13 01:05:32 +00001935 else if (const PHINode *PN = dyn_cast<PHINode>(V)) {
James Molloy897048b2015-09-29 14:08:45 +00001936 // Try and detect a recurrence that monotonically increases from a
1937 // starting value, as these are common as induction variables.
1938 if (PN->getNumIncomingValues() == 2) {
1939 Value *Start = PN->getIncomingValue(0);
1940 Value *Induction = PN->getIncomingValue(1);
1941 if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start))
1942 std::swap(Start, Induction);
1943 if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) {
1944 if (!C->isZero() && !C->isNegative()) {
1945 ConstantInt *X;
1946 if ((match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) ||
1947 match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) &&
1948 !X->isNegative())
1949 return true;
1950 }
1951 }
1952 }
Jun Bum Limca832662016-02-01 17:03:07 +00001953 // Check if all incoming values are non-zero constant.
1954 bool AllNonZeroConstants = all_of(PN->operands(), [](Value *V) {
1955 return isa<ConstantInt>(V) && !cast<ConstantInt>(V)->isZeroValue();
1956 });
1957 if (AllNonZeroConstants)
1958 return true;
James Molloy897048b2015-09-29 14:08:45 +00001959 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001960
Craig Topperb45eabc2017-04-26 16:39:58 +00001961 KnownBits Known(BitWidth);
1962 computeKnownBits(V, Known, Depth, Q);
1963 return Known.One != 0;
Duncan Sandsd3951082011-01-25 09:38:29 +00001964}
1965
James Molloy1d88d6f2015-10-22 13:18:42 +00001966/// Return true if V2 == V1 + X, where X is known non-zero.
Pete Cooper35b00d52016-08-13 01:05:32 +00001967static bool isAddOfNonZero(const Value *V1, const Value *V2, const Query &Q) {
1968 const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
James Molloy1d88d6f2015-10-22 13:18:42 +00001969 if (!BO || BO->getOpcode() != Instruction::Add)
1970 return false;
1971 Value *Op = nullptr;
1972 if (V2 == BO->getOperand(0))
1973 Op = BO->getOperand(1);
1974 else if (V2 == BO->getOperand(1))
1975 Op = BO->getOperand(0);
1976 else
1977 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001978 return isKnownNonZero(Op, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00001979}
1980
1981/// Return true if it is known that V1 != V2.
Pete Cooper35b00d52016-08-13 01:05:32 +00001982static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q) {
Craig Topper3002d5b2017-06-06 07:13:15 +00001983 if (V1 == V2)
James Molloy1d88d6f2015-10-22 13:18:42 +00001984 return false;
1985 if (V1->getType() != V2->getType())
1986 // We can't look through casts yet.
1987 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001988 if (isAddOfNonZero(V1, V2, Q) || isAddOfNonZero(V2, V1, Q))
James Molloy1d88d6f2015-10-22 13:18:42 +00001989 return true;
1990
Craig Topper3002d5b2017-06-06 07:13:15 +00001991 if (V1->getType()->isIntOrIntVectorTy()) {
James Molloy1d88d6f2015-10-22 13:18:42 +00001992 // Are any known bits in V1 contradictory to known bits in V2? If V1
1993 // has a known zero where V2 has a known one, they must not be equal.
Craig Topper8e662f72017-06-06 07:13:11 +00001994 KnownBits Known1 = computeKnownBits(V1, 0, Q);
1995 KnownBits Known2 = computeKnownBits(V2, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00001996
Craig Topper8365df82017-06-06 07:13:09 +00001997 if (Known1.Zero.intersects(Known2.One) ||
1998 Known2.Zero.intersects(Known1.One))
James Molloy1d88d6f2015-10-22 13:18:42 +00001999 return true;
2000 }
2001 return false;
2002}
2003
Sanjay Patelaee84212014-11-04 16:27:42 +00002004/// Return true if 'V & Mask' is known to be zero. We use this predicate to
2005/// simplify operations downstream. Mask is known to be zero for bits that V
2006/// cannot have.
Chris Lattner4bc28252009-09-08 00:06:16 +00002007///
2008/// This function is defined on values with integer type, values with pointer
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002009/// type, and vectors of integers. In the case
Chris Lattner4bc28252009-09-08 00:06:16 +00002010/// where V is a vector, the mask, known zero, and known one values are the
2011/// same width as the vector element, and the bit is set only if it is true
2012/// for all of the elements in the vector.
Pete Cooper35b00d52016-08-13 01:05:32 +00002013bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002014 const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002015 KnownBits Known(Mask.getBitWidth());
2016 computeKnownBits(V, Known, Depth, Q);
2017 return Mask.isSubsetOf(Known.Zero);
Chris Lattner965c7692008-06-02 01:18:21 +00002018}
2019
Sanjay Patela06d9892016-06-22 19:20:59 +00002020/// For vector constants, loop over the elements and find the constant with the
2021/// minimum number of sign bits. Return 0 if the value is not a vector constant
2022/// or if any element was not analyzed; otherwise, return the count for the
2023/// element with the minimum number of sign bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002024static unsigned computeNumSignBitsVectorConstant(const Value *V,
2025 unsigned TyBits) {
2026 const auto *CV = dyn_cast<Constant>(V);
Sanjay Patela06d9892016-06-22 19:20:59 +00002027 if (!CV || !CV->getType()->isVectorTy())
2028 return 0;
Chris Lattner965c7692008-06-02 01:18:21 +00002029
Sanjay Patela06d9892016-06-22 19:20:59 +00002030 unsigned MinSignBits = TyBits;
2031 unsigned NumElts = CV->getType()->getVectorNumElements();
2032 for (unsigned i = 0; i != NumElts; ++i) {
2033 // If we find a non-ConstantInt, bail out.
2034 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
2035 if (!Elt)
2036 return 0;
2037
2038 // If the sign bit is 1, flip the bits, so we always count leading zeros.
2039 APInt EltVal = Elt->getValue();
2040 if (EltVal.isNegative())
2041 EltVal = ~EltVal;
2042 MinSignBits = std::min(MinSignBits, EltVal.countLeadingZeros());
2043 }
2044
2045 return MinSignBits;
2046}
Chris Lattner965c7692008-06-02 01:18:21 +00002047
Sanjoy Das39a684d2017-02-25 20:30:45 +00002048static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2049 const Query &Q);
2050
2051static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
2052 const Query &Q) {
2053 unsigned Result = ComputeNumSignBitsImpl(V, Depth, Q);
2054 assert(Result > 0 && "At least one sign bit needs to be present!");
2055 return Result;
2056}
2057
Sanjay Patelaee84212014-11-04 16:27:42 +00002058/// Return the number of times the sign bit of the register is replicated into
2059/// the other bits. We know that at least 1 bit is always equal to the sign bit
2060/// (itself), but other cases can give us information. For example, immediately
2061/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
Sanjay Patela06d9892016-06-22 19:20:59 +00002062/// other, so we return 3. For vectors, return the number of sign bits for the
2063/// vector element with the mininum number of known sign bits.
Sanjoy Das39a684d2017-02-25 20:30:45 +00002064static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2065 const Query &Q) {
2066
2067 // We return the minimum number of sign bits that are guaranteed to be present
2068 // in V, so for undef we have to conservatively return 1. We don't have the
2069 // same behavior for poison though -- that's a FIXME today.
2070
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002071 unsigned TyBits = Q.DL.getTypeSizeInBits(V->getType()->getScalarType());
Chris Lattner965c7692008-06-02 01:18:21 +00002072 unsigned Tmp, Tmp2;
2073 unsigned FirstAnswer = 1;
2074
Jay Foada0653a32014-05-14 21:14:37 +00002075 // Note that ConstantInt is handled by the general computeKnownBits case
Chris Lattner2e01a692008-06-02 18:39:07 +00002076 // below.
2077
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002078 if (Depth == MaxDepth)
Chris Lattner965c7692008-06-02 01:18:21 +00002079 return 1; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002080
Pete Cooper35b00d52016-08-13 01:05:32 +00002081 const Operator *U = dyn_cast<Operator>(V);
Dan Gohman80ca01c2009-07-17 20:47:02 +00002082 switch (Operator::getOpcode(V)) {
Chris Lattner965c7692008-06-02 01:18:21 +00002083 default: break;
2084 case Instruction::SExt:
Mon P Wangbb3eac92009-12-02 04:59:58 +00002085 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002086 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
Craig Topper1bef2c82012-12-22 19:15:35 +00002087
Nadav Rotemc99a3872015-03-06 00:23:58 +00002088 case Instruction::SDiv: {
Nadav Rotem029c5c72015-03-03 21:39:02 +00002089 const APInt *Denominator;
2090 // sdiv X, C -> adds log(C) sign bits.
2091 if (match(U->getOperand(1), m_APInt(Denominator))) {
2092
2093 // Ignore non-positive denominator.
2094 if (!Denominator->isStrictlyPositive())
2095 break;
2096
2097 // Calculate the incoming numerator bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002098 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotem029c5c72015-03-03 21:39:02 +00002099
2100 // Add floor(log(C)) bits to the numerator bits.
2101 return std::min(TyBits, NumBits + Denominator->logBase2());
2102 }
2103 break;
Nadav Rotemc99a3872015-03-06 00:23:58 +00002104 }
2105
2106 case Instruction::SRem: {
2107 const APInt *Denominator;
Sanjoy Dase561fee2015-03-25 22:33:53 +00002108 // srem X, C -> we know that the result is within [-C+1,C) when C is a
2109 // positive constant. This let us put a lower bound on the number of sign
2110 // bits.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002111 if (match(U->getOperand(1), m_APInt(Denominator))) {
2112
2113 // Ignore non-positive denominator.
2114 if (!Denominator->isStrictlyPositive())
2115 break;
2116
2117 // Calculate the incoming numerator bits. SRem by a positive constant
2118 // can't lower the number of sign bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002119 unsigned NumrBits =
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002120 ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotemc99a3872015-03-06 00:23:58 +00002121
2122 // Calculate the leading sign bit constraints by examining the
Sanjoy Dase561fee2015-03-25 22:33:53 +00002123 // denominator. Given that the denominator is positive, there are two
2124 // cases:
2125 //
2126 // 1. the numerator is positive. The result range is [0,C) and [0,C) u<
2127 // (1 << ceilLogBase2(C)).
2128 //
2129 // 2. the numerator is negative. Then the result range is (-C,0] and
2130 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2131 //
2132 // Thus a lower bound on the number of sign bits is `TyBits -
2133 // ceilLogBase2(C)`.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002134
Sanjoy Dase561fee2015-03-25 22:33:53 +00002135 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
Nadav Rotemc99a3872015-03-06 00:23:58 +00002136 return std::max(NumrBits, ResBits);
2137 }
2138 break;
2139 }
Nadav Rotem029c5c72015-03-03 21:39:02 +00002140
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002141 case Instruction::AShr: {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002142 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002143 // ashr X, C -> adds C sign bits. Vectors too.
2144 const APInt *ShAmt;
2145 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Sanjoy Das39a684d2017-02-25 20:30:45 +00002146 unsigned ShAmtLimited = ShAmt->getZExtValue();
2147 if (ShAmtLimited >= TyBits)
2148 break; // Bad shift.
2149 Tmp += ShAmtLimited;
Chris Lattner965c7692008-06-02 01:18:21 +00002150 if (Tmp > TyBits) Tmp = TyBits;
2151 }
2152 return Tmp;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002153 }
2154 case Instruction::Shl: {
2155 const APInt *ShAmt;
2156 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner965c7692008-06-02 01:18:21 +00002157 // shl destroys sign bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002158 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002159 Tmp2 = ShAmt->getZExtValue();
2160 if (Tmp2 >= TyBits || // Bad shift.
2161 Tmp2 >= Tmp) break; // Shifted all sign bits out.
2162 return Tmp - Tmp2;
Chris Lattner965c7692008-06-02 01:18:21 +00002163 }
2164 break;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002165 }
Chris Lattner965c7692008-06-02 01:18:21 +00002166 case Instruction::And:
2167 case Instruction::Or:
2168 case Instruction::Xor: // NOT is handled here.
2169 // Logical binary ops preserve the number of sign bits at the worst.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002170 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002171 if (Tmp != 1) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002172 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002173 FirstAnswer = std::min(Tmp, Tmp2);
2174 // We computed what we know about the sign bits as our first
2175 // answer. Now proceed to the generic code that uses
Jay Foada0653a32014-05-14 21:14:37 +00002176 // computeKnownBits, and pick whichever answer is better.
Chris Lattner965c7692008-06-02 01:18:21 +00002177 }
2178 break;
2179
2180 case Instruction::Select:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002181 Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002182 if (Tmp == 1) return 1; // Early out.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002183 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002184 return std::min(Tmp, Tmp2);
Craig Topper1bef2c82012-12-22 19:15:35 +00002185
Chris Lattner965c7692008-06-02 01:18:21 +00002186 case Instruction::Add:
2187 // Add can have at most one carry bit. Thus we know that the output
2188 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002189 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002190 if (Tmp == 1) return 1; // Early out.
Craig Topper1bef2c82012-12-22 19:15:35 +00002191
Chris Lattner965c7692008-06-02 01:18:21 +00002192 // Special case decrementing a value (ADD X, -1):
David Majnemera55027f2014-12-26 09:20:17 +00002193 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
Chris Lattner965c7692008-06-02 01:18:21 +00002194 if (CRHS->isAllOnesValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002195 KnownBits Known(TyBits);
2196 computeKnownBits(U->getOperand(0), Known, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002197
Chris Lattner965c7692008-06-02 01:18:21 +00002198 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2199 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002200 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002201 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002202
Chris Lattner965c7692008-06-02 01:18:21 +00002203 // If we are subtracting one from a positive number, there is no carry
2204 // out of the result.
Craig Topperca48af32017-04-29 16:43:11 +00002205 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002206 return Tmp;
2207 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002208
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002209 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002210 if (Tmp2 == 1) return 1;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002211 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002212
Chris Lattner965c7692008-06-02 01:18:21 +00002213 case Instruction::Sub:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002214 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002215 if (Tmp2 == 1) return 1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002216
Chris Lattner965c7692008-06-02 01:18:21 +00002217 // Handle NEG.
David Majnemera55027f2014-12-26 09:20:17 +00002218 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
Chris Lattner965c7692008-06-02 01:18:21 +00002219 if (CLHS->isNullValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002220 KnownBits Known(TyBits);
2221 computeKnownBits(U->getOperand(1), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002222 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2223 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002224 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002225 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002226
Chris Lattner965c7692008-06-02 01:18:21 +00002227 // If the input is known to be positive (the sign bit is known clear),
2228 // the output of the NEG has the same number of sign bits as the input.
Craig Topperca48af32017-04-29 16:43:11 +00002229 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002230 return Tmp2;
Craig Topper1bef2c82012-12-22 19:15:35 +00002231
Chris Lattner965c7692008-06-02 01:18:21 +00002232 // Otherwise, we treat this like a SUB.
2233 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002234
Chris Lattner965c7692008-06-02 01:18:21 +00002235 // Sub can have at most one carry bit. Thus we know that the output
2236 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002237 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002238 if (Tmp == 1) return 1; // Early out.
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002239 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002240
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002241 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00002242 const PHINode *PN = cast<PHINode>(U);
David Majnemer6ee8d172015-01-04 07:06:53 +00002243 unsigned NumIncomingValues = PN->getNumIncomingValues();
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002244 // Don't analyze large in-degree PHIs.
David Majnemer6ee8d172015-01-04 07:06:53 +00002245 if (NumIncomingValues > 4) break;
2246 // Unreachable blocks may have zero-operand PHI nodes.
2247 if (NumIncomingValues == 0) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002248
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002249 // Take the minimum of all incoming values. This can't infinitely loop
2250 // because of our depth threshold.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002251 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), Depth + 1, Q);
David Majnemer6ee8d172015-01-04 07:06:53 +00002252 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002253 if (Tmp == 1) return Tmp;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002254 Tmp = std::min(
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002255 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, Q));
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002256 }
2257 return Tmp;
2258 }
2259
Chris Lattner965c7692008-06-02 01:18:21 +00002260 case Instruction::Trunc:
2261 // FIXME: it's tricky to do anything useful for this, but it is an important
2262 // case for targets like X86.
2263 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00002264
2265 case Instruction::ExtractElement:
2266 // Look through extract element. At the moment we keep this simple and skip
2267 // tracking the specific element. But at least we might find information
2268 // valid for all elements of the vector (for example if vector is sign
2269 // extended, shifted, etc).
2270 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002271 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002272
Chris Lattner965c7692008-06-02 01:18:21 +00002273 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2274 // use this information.
Sanjay Patela06d9892016-06-22 19:20:59 +00002275
2276 // If we can examine all elements of a vector constant successfully, we're
2277 // done (we can't do any better than that). If not, keep trying.
2278 if (unsigned VecSignBits = computeNumSignBitsVectorConstant(V, TyBits))
2279 return VecSignBits;
2280
Craig Topperb45eabc2017-04-26 16:39:58 +00002281 KnownBits Known(TyBits);
2282 computeKnownBits(V, Known, Depth, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002283
Sanjay Patele0536212016-06-23 17:41:59 +00002284 // If we know that the sign bit is either zero or one, determine the number of
2285 // identical bits in the top of the input value.
Craig Topper8df66c62017-05-12 17:20:30 +00002286 return std::max(FirstAnswer, Known.countMinSignBits());
Chris Lattner965c7692008-06-02 01:18:21 +00002287}
Chris Lattnera12a6de2008-06-02 01:29:46 +00002288
Sanjay Patelaee84212014-11-04 16:27:42 +00002289/// This function computes the integer multiple of Base that equals V.
2290/// If successful, it returns true and returns the multiple in
2291/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez47444882009-11-10 08:28:35 +00002292/// through SExt instructions only if LookThroughSExt is true.
2293bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman6a976bb2009-11-18 00:58:27 +00002294 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez47444882009-11-10 08:28:35 +00002295 const unsigned MaxDepth = 6;
2296
Dan Gohman6a976bb2009-11-18 00:58:27 +00002297 assert(V && "No Value?");
Victor Hernandez47444882009-11-10 08:28:35 +00002298 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002299 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez47444882009-11-10 08:28:35 +00002300
Chris Lattner229907c2011-07-18 04:54:35 +00002301 Type *T = V->getType();
Victor Hernandez47444882009-11-10 08:28:35 +00002302
Dan Gohman6a976bb2009-11-18 00:58:27 +00002303 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez47444882009-11-10 08:28:35 +00002304
2305 if (Base == 0)
2306 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002307
Victor Hernandez47444882009-11-10 08:28:35 +00002308 if (Base == 1) {
2309 Multiple = V;
2310 return true;
2311 }
2312
2313 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2314 Constant *BaseVal = ConstantInt::get(T, Base);
2315 if (CO && CO == BaseVal) {
2316 // Multiple is 1.
2317 Multiple = ConstantInt::get(T, 1);
2318 return true;
2319 }
2320
2321 if (CI && CI->getZExtValue() % Base == 0) {
2322 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
Craig Topper1bef2c82012-12-22 19:15:35 +00002323 return true;
Victor Hernandez47444882009-11-10 08:28:35 +00002324 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002325
Victor Hernandez47444882009-11-10 08:28:35 +00002326 if (Depth == MaxDepth) return false; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002327
Victor Hernandez47444882009-11-10 08:28:35 +00002328 Operator *I = dyn_cast<Operator>(V);
2329 if (!I) return false;
2330
2331 switch (I->getOpcode()) {
2332 default: break;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002333 case Instruction::SExt:
Victor Hernandez47444882009-11-10 08:28:35 +00002334 if (!LookThroughSExt) return false;
2335 // otherwise fall through to ZExt
Galina Kistanova244621f2017-05-31 22:16:24 +00002336 LLVM_FALLTHROUGH;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002337 case Instruction::ZExt:
Dan Gohman6a976bb2009-11-18 00:58:27 +00002338 return ComputeMultiple(I->getOperand(0), Base, Multiple,
2339 LookThroughSExt, Depth+1);
Victor Hernandez47444882009-11-10 08:28:35 +00002340 case Instruction::Shl:
2341 case Instruction::Mul: {
2342 Value *Op0 = I->getOperand(0);
2343 Value *Op1 = I->getOperand(1);
2344
2345 if (I->getOpcode() == Instruction::Shl) {
2346 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2347 if (!Op1CI) return false;
2348 // Turn Op0 << Op1 into Op0 * 2^Op1
2349 APInt Op1Int = Op1CI->getValue();
2350 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foad15084f02010-11-30 09:02:01 +00002351 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002352 API.setBit(BitToSet);
Jay Foad15084f02010-11-30 09:02:01 +00002353 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez47444882009-11-10 08:28:35 +00002354 }
2355
Craig Topper9f008862014-04-15 04:59:12 +00002356 Value *Mul0 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002357 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2358 if (Constant *Op1C = dyn_cast<Constant>(Op1))
2359 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002360 if (Op1C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002361 MulC->getType()->getPrimitiveSizeInBits())
2362 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002363 if (Op1C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002364 MulC->getType()->getPrimitiveSizeInBits())
2365 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002366
Chris Lattner72d283c2010-09-05 17:20:46 +00002367 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2368 Multiple = ConstantExpr::getMul(MulC, Op1C);
2369 return true;
2370 }
Victor Hernandez47444882009-11-10 08:28:35 +00002371
2372 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2373 if (Mul0CI->getValue() == 1) {
2374 // V == Base * Op1, so return Op1
2375 Multiple = Op1;
2376 return true;
2377 }
2378 }
2379
Craig Topper9f008862014-04-15 04:59:12 +00002380 Value *Mul1 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002381 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2382 if (Constant *Op0C = dyn_cast<Constant>(Op0))
2383 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002384 if (Op0C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002385 MulC->getType()->getPrimitiveSizeInBits())
2386 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002387 if (Op0C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002388 MulC->getType()->getPrimitiveSizeInBits())
2389 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002390
Chris Lattner72d283c2010-09-05 17:20:46 +00002391 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2392 Multiple = ConstantExpr::getMul(MulC, Op0C);
2393 return true;
2394 }
Victor Hernandez47444882009-11-10 08:28:35 +00002395
2396 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2397 if (Mul1CI->getValue() == 1) {
2398 // V == Base * Op0, so return Op0
2399 Multiple = Op0;
2400 return true;
2401 }
2402 }
Victor Hernandez47444882009-11-10 08:28:35 +00002403 }
2404 }
2405
2406 // We could not determine if V is a multiple of Base.
2407 return false;
2408}
2409
David Majnemerb4b27232016-04-19 19:10:21 +00002410Intrinsic::ID llvm::getIntrinsicForCallSite(ImmutableCallSite ICS,
2411 const TargetLibraryInfo *TLI) {
2412 const Function *F = ICS.getCalledFunction();
2413 if (!F)
2414 return Intrinsic::not_intrinsic;
2415
2416 if (F->isIntrinsic())
2417 return F->getIntrinsicID();
2418
2419 if (!TLI)
2420 return Intrinsic::not_intrinsic;
2421
David L. Jonesd21529f2017-01-23 23:16:46 +00002422 LibFunc Func;
David Majnemerb4b27232016-04-19 19:10:21 +00002423 // We're going to make assumptions on the semantics of the functions, check
2424 // that the target knows that it's available in this environment and it does
2425 // not have local linkage.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002426 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(*F, Func))
2427 return Intrinsic::not_intrinsic;
2428
2429 if (!ICS.onlyReadsMemory())
David Majnemerb4b27232016-04-19 19:10:21 +00002430 return Intrinsic::not_intrinsic;
2431
2432 // Otherwise check if we have a call to a function that can be turned into a
2433 // vector intrinsic.
2434 switch (Func) {
2435 default:
2436 break;
David L. Jonesd21529f2017-01-23 23:16:46 +00002437 case LibFunc_sin:
2438 case LibFunc_sinf:
2439 case LibFunc_sinl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002440 return Intrinsic::sin;
David L. Jonesd21529f2017-01-23 23:16:46 +00002441 case LibFunc_cos:
2442 case LibFunc_cosf:
2443 case LibFunc_cosl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002444 return Intrinsic::cos;
David L. Jonesd21529f2017-01-23 23:16:46 +00002445 case LibFunc_exp:
2446 case LibFunc_expf:
2447 case LibFunc_expl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002448 return Intrinsic::exp;
David L. Jonesd21529f2017-01-23 23:16:46 +00002449 case LibFunc_exp2:
2450 case LibFunc_exp2f:
2451 case LibFunc_exp2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002452 return Intrinsic::exp2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002453 case LibFunc_log:
2454 case LibFunc_logf:
2455 case LibFunc_logl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002456 return Intrinsic::log;
David L. Jonesd21529f2017-01-23 23:16:46 +00002457 case LibFunc_log10:
2458 case LibFunc_log10f:
2459 case LibFunc_log10l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002460 return Intrinsic::log10;
David L. Jonesd21529f2017-01-23 23:16:46 +00002461 case LibFunc_log2:
2462 case LibFunc_log2f:
2463 case LibFunc_log2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002464 return Intrinsic::log2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002465 case LibFunc_fabs:
2466 case LibFunc_fabsf:
2467 case LibFunc_fabsl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002468 return Intrinsic::fabs;
David L. Jonesd21529f2017-01-23 23:16:46 +00002469 case LibFunc_fmin:
2470 case LibFunc_fminf:
2471 case LibFunc_fminl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002472 return Intrinsic::minnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002473 case LibFunc_fmax:
2474 case LibFunc_fmaxf:
2475 case LibFunc_fmaxl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002476 return Intrinsic::maxnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002477 case LibFunc_copysign:
2478 case LibFunc_copysignf:
2479 case LibFunc_copysignl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002480 return Intrinsic::copysign;
David L. Jonesd21529f2017-01-23 23:16:46 +00002481 case LibFunc_floor:
2482 case LibFunc_floorf:
2483 case LibFunc_floorl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002484 return Intrinsic::floor;
David L. Jonesd21529f2017-01-23 23:16:46 +00002485 case LibFunc_ceil:
2486 case LibFunc_ceilf:
2487 case LibFunc_ceill:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002488 return Intrinsic::ceil;
David L. Jonesd21529f2017-01-23 23:16:46 +00002489 case LibFunc_trunc:
2490 case LibFunc_truncf:
2491 case LibFunc_truncl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002492 return Intrinsic::trunc;
David L. Jonesd21529f2017-01-23 23:16:46 +00002493 case LibFunc_rint:
2494 case LibFunc_rintf:
2495 case LibFunc_rintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002496 return Intrinsic::rint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002497 case LibFunc_nearbyint:
2498 case LibFunc_nearbyintf:
2499 case LibFunc_nearbyintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002500 return Intrinsic::nearbyint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002501 case LibFunc_round:
2502 case LibFunc_roundf:
2503 case LibFunc_roundl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002504 return Intrinsic::round;
David L. Jonesd21529f2017-01-23 23:16:46 +00002505 case LibFunc_pow:
2506 case LibFunc_powf:
2507 case LibFunc_powl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002508 return Intrinsic::pow;
David L. Jonesd21529f2017-01-23 23:16:46 +00002509 case LibFunc_sqrt:
2510 case LibFunc_sqrtf:
2511 case LibFunc_sqrtl:
David Majnemerb4b27232016-04-19 19:10:21 +00002512 if (ICS->hasNoNaNs())
Ahmed Bougachad765a822016-04-27 19:04:35 +00002513 return Intrinsic::sqrt;
David Majnemerb4b27232016-04-19 19:10:21 +00002514 return Intrinsic::not_intrinsic;
2515 }
2516
2517 return Intrinsic::not_intrinsic;
2518}
2519
Sanjay Patelaee84212014-11-04 16:27:42 +00002520/// Return true if we can prove that the specified FP value is never equal to
2521/// -0.0.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002522///
2523/// NOTE: this function will need to be revisited when we support non-default
2524/// rounding modes!
2525///
David Majnemer3ee5f342016-04-13 06:55:52 +00002526bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
2527 unsigned Depth) {
Chris Lattnera12a6de2008-06-02 01:29:46 +00002528 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2529 return !CFP->getValueAPF().isNegZero();
Craig Topper1bef2c82012-12-22 19:15:35 +00002530
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002531 if (Depth == MaxDepth)
Sanjay Patel40eaa8d2015-02-25 18:00:15 +00002532 return false; // Limit search depth.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002533
Dan Gohman80ca01c2009-07-17 20:47:02 +00002534 const Operator *I = dyn_cast<Operator>(V);
Craig Topper9f008862014-04-15 04:59:12 +00002535 if (!I) return false;
Michael Ilseman0f128372012-12-06 00:07:09 +00002536
2537 // Check if the nsz fast-math flag is set
2538 if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
2539 if (FPO->hasNoSignedZeros())
2540 return true;
2541
Chris Lattnera12a6de2008-06-02 01:29:46 +00002542 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Jakub Staszakb7129f22013-03-06 00:16:16 +00002543 if (I->getOpcode() == Instruction::FAdd)
2544 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
2545 if (CFP->isNullValue())
2546 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002547
Chris Lattnera12a6de2008-06-02 01:29:46 +00002548 // sitofp and uitofp turn into +0.0 for zero.
2549 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2550 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002551
David Majnemer3ee5f342016-04-13 06:55:52 +00002552 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
David Majnemerb4b27232016-04-19 19:10:21 +00002553 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002554 switch (IID) {
2555 default:
2556 break;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002557 // sqrt(-0.0) = -0.0, no other negative results are possible.
David Majnemer3ee5f342016-04-13 06:55:52 +00002558 case Intrinsic::sqrt:
2559 return CannotBeNegativeZero(CI->getArgOperand(0), TLI, Depth + 1);
2560 // fabs(x) != -0.0
2561 case Intrinsic::fabs:
2562 return true;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002563 }
David Majnemer3ee5f342016-04-13 06:55:52 +00002564 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002565
Chris Lattnera12a6de2008-06-02 01:29:46 +00002566 return false;
2567}
2568
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002569/// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
2570/// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
2571/// bit despite comparing equal.
2572static bool cannotBeOrderedLessThanZeroImpl(const Value *V,
2573 const TargetLibraryInfo *TLI,
2574 bool SignBitOnly,
2575 unsigned Depth) {
Justin Lebar322c1272017-01-27 00:58:34 +00002576 // TODO: This function does not do the right thing when SignBitOnly is true
2577 // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform
2578 // which flips the sign bits of NaNs. See
2579 // https://llvm.org/bugs/show_bug.cgi?id=31702.
2580
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002581 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2582 return !CFP->getValueAPF().isNegative() ||
2583 (!SignBitOnly && CFP->getValueAPF().isZero());
2584 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002585
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002586 if (Depth == MaxDepth)
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002587 return false; // Limit search depth.
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002588
2589 const Operator *I = dyn_cast<Operator>(V);
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002590 if (!I)
2591 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002592
2593 switch (I->getOpcode()) {
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002594 default:
2595 break;
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002596 // Unsigned integers are always nonnegative.
2597 case Instruction::UIToFP:
2598 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002599 case Instruction::FMul:
2600 // x*x is always non-negative or a NaN.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002601 if (I->getOperand(0) == I->getOperand(1) &&
2602 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002603 return true;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002604
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002605 LLVM_FALLTHROUGH;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002606 case Instruction::FAdd:
2607 case Instruction::FDiv:
2608 case Instruction::FRem:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002609 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2610 Depth + 1) &&
2611 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2612 Depth + 1);
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002613 case Instruction::Select:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002614 return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2615 Depth + 1) &&
2616 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2617 Depth + 1);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002618 case Instruction::FPExt:
2619 case Instruction::FPTrunc:
2620 // Widening/narrowing never change sign.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002621 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2622 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002623 case Instruction::Call:
Justin Lebar7e3184c2017-01-26 00:10:26 +00002624 const auto *CI = cast<CallInst>(I);
2625 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002626 switch (IID) {
2627 default:
2628 break;
2629 case Intrinsic::maxnum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002630 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2631 Depth + 1) ||
2632 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2633 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002634 case Intrinsic::minnum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002635 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2636 Depth + 1) &&
2637 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2638 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002639 case Intrinsic::exp:
2640 case Intrinsic::exp2:
2641 case Intrinsic::fabs:
David Majnemer3ee5f342016-04-13 06:55:52 +00002642 return true;
Justin Lebar7e3184c2017-01-26 00:10:26 +00002643
2644 case Intrinsic::sqrt:
2645 // sqrt(x) is always >= -0 or NaN. Moreover, sqrt(x) == -0 iff x == -0.
2646 if (!SignBitOnly)
2647 return true;
2648 return CI->hasNoNaNs() && (CI->hasNoSignedZeros() ||
2649 CannotBeNegativeZero(CI->getOperand(0), TLI));
2650
David Majnemer3ee5f342016-04-13 06:55:52 +00002651 case Intrinsic::powi:
Justin Lebar7e3184c2017-01-26 00:10:26 +00002652 if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) {
David Majnemer3ee5f342016-04-13 06:55:52 +00002653 // powi(x,n) is non-negative if n is even.
Justin Lebar7e3184c2017-01-26 00:10:26 +00002654 if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0)
David Majnemer3ee5f342016-04-13 06:55:52 +00002655 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002656 }
Justin Lebar322c1272017-01-27 00:58:34 +00002657 // TODO: This is not correct. Given that exp is an integer, here are the
2658 // ways that pow can return a negative value:
2659 //
2660 // pow(x, exp) --> negative if exp is odd and x is negative.
2661 // pow(-0, exp) --> -inf if exp is negative odd.
2662 // pow(-0, exp) --> -0 if exp is positive odd.
2663 // pow(-inf, exp) --> -0 if exp is negative odd.
2664 // pow(-inf, exp) --> -inf if exp is positive odd.
2665 //
2666 // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN,
2667 // but we must return false if x == -0. Unfortunately we do not currently
2668 // have a way of expressing this constraint. See details in
2669 // https://llvm.org/bugs/show_bug.cgi?id=31702.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002670 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2671 Depth + 1);
Justin Lebar322c1272017-01-27 00:58:34 +00002672
David Majnemer3ee5f342016-04-13 06:55:52 +00002673 case Intrinsic::fma:
2674 case Intrinsic::fmuladd:
2675 // x*x+y is non-negative if y is non-negative.
2676 return I->getOperand(0) == I->getOperand(1) &&
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002677 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
2678 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2679 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002680 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002681 break;
2682 }
Sanjoy Das6082c1a2016-05-07 02:08:15 +00002683 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002684}
2685
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002686bool llvm::CannotBeOrderedLessThanZero(const Value *V,
2687 const TargetLibraryInfo *TLI) {
2688 return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0);
2689}
2690
2691bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) {
2692 return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0);
2693}
2694
Sanjay Patelaee84212014-11-04 16:27:42 +00002695/// If the specified value can be set by repeating the same byte in memory,
2696/// return the i8 value that it is represented with. This is
Chris Lattner9cb10352010-12-26 20:15:01 +00002697/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2698/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
2699/// byte store (e.g. i16 0x1234), return null.
2700Value *llvm::isBytewiseValue(Value *V) {
2701 // All byte-wide stores are splatable, even of arbitrary variables.
2702 if (V->getType()->isIntegerTy(8)) return V;
Chris Lattneracf6b072011-02-19 19:35:49 +00002703
2704 // Handle 'null' ConstantArrayZero etc.
2705 if (Constant *C = dyn_cast<Constant>(V))
2706 if (C->isNullValue())
2707 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
Craig Topper1bef2c82012-12-22 19:15:35 +00002708
Chris Lattner9cb10352010-12-26 20:15:01 +00002709 // Constant float and double values can be handled as integer values if the
Craig Topper1bef2c82012-12-22 19:15:35 +00002710 // corresponding integer value is "byteable". An important case is 0.0.
Chris Lattner9cb10352010-12-26 20:15:01 +00002711 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2712 if (CFP->getType()->isFloatTy())
2713 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2714 if (CFP->getType()->isDoubleTy())
2715 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2716 // Don't handle long double formats, which have strange constraints.
2717 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002718
Benjamin Kramer17d90152015-02-07 19:29:02 +00002719 // We can handle constant integers that are multiple of 8 bits.
Chris Lattner9cb10352010-12-26 20:15:01 +00002720 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Benjamin Kramer17d90152015-02-07 19:29:02 +00002721 if (CI->getBitWidth() % 8 == 0) {
2722 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
Craig Topper1bef2c82012-12-22 19:15:35 +00002723
Benjamin Kramerb4b51502015-03-25 16:49:59 +00002724 if (!CI->getValue().isSplat(8))
Benjamin Kramer17d90152015-02-07 19:29:02 +00002725 return nullptr;
2726 return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
Chris Lattner9cb10352010-12-26 20:15:01 +00002727 }
2728 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002729
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002730 // A ConstantDataArray/Vector is splatable if all its members are equal and
2731 // also splatable.
2732 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2733 Value *Elt = CA->getElementAsConstant(0);
2734 Value *Val = isBytewiseValue(Elt);
Chris Lattner9cb10352010-12-26 20:15:01 +00002735 if (!Val)
Craig Topper9f008862014-04-15 04:59:12 +00002736 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002737
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002738 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2739 if (CA->getElementAsConstant(I) != Elt)
Craig Topper9f008862014-04-15 04:59:12 +00002740 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002741
Chris Lattner9cb10352010-12-26 20:15:01 +00002742 return Val;
2743 }
Chad Rosier8abf65a2011-12-06 00:19:08 +00002744
Chris Lattner9cb10352010-12-26 20:15:01 +00002745 // Conceptually, we could handle things like:
2746 // %a = zext i8 %X to i16
2747 // %b = shl i16 %a, 8
2748 // %c = or i16 %a, %b
2749 // but until there is an example that actually needs this, it doesn't seem
2750 // worth worrying about.
Craig Topper9f008862014-04-15 04:59:12 +00002751 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00002752}
2753
2754
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002755// This is the recursive version of BuildSubAggregate. It takes a few different
2756// arguments. Idxs is the index within the nested struct From that we are
2757// looking at now (which is of type IndexedType). IdxSkip is the number of
2758// indices from Idxs that should be left out when inserting into the resulting
2759// struct. To is the result struct built so far, new insertvalue instructions
2760// build on that.
Chris Lattner229907c2011-07-18 04:54:35 +00002761static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Craig Topper2cd5ff82013-07-11 16:22:38 +00002762 SmallVectorImpl<unsigned> &Idxs,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002763 unsigned IdxSkip,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002764 Instruction *InsertBefore) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +00002765 llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002766 if (STy) {
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002767 // Save the original To argument so we can modify it
2768 Value *OrigTo = To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002769 // General case, the type indexed by Idxs is a struct
2770 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2771 // Process each struct element recursively
2772 Idxs.push_back(i);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002773 Value *PrevTo = To;
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002774 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002775 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002776 Idxs.pop_back();
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002777 if (!To) {
2778 // Couldn't find any inserted value for this index? Cleanup
2779 while (PrevTo != OrigTo) {
2780 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
2781 PrevTo = Del->getAggregateOperand();
2782 Del->eraseFromParent();
2783 }
2784 // Stop processing elements
2785 break;
2786 }
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002787 }
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002788 // If we successfully found a value for each of our subaggregates
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002789 if (To)
2790 return To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002791 }
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002792 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
2793 // the struct's elements had a value that was inserted directly. In the latter
2794 // case, perhaps we can't determine each of the subelements individually, but
2795 // we might be able to find the complete struct somewhere.
Craig Topper1bef2c82012-12-22 19:15:35 +00002796
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002797 // Find the value that is at that particular spot
Jay Foad57aa6362011-07-13 10:26:04 +00002798 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002799
2800 if (!V)
Craig Topper9f008862014-04-15 04:59:12 +00002801 return nullptr;
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002802
2803 // Insert the value in the new (sub) aggregrate
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002804 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
Jay Foad57aa6362011-07-13 10:26:04 +00002805 "tmp", InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002806}
2807
2808// This helper takes a nested struct and extracts a part of it (which is again a
2809// struct) into a new value. For example, given the struct:
2810// { a, { b, { c, d }, e } }
2811// and the indices "1, 1" this returns
2812// { c, d }.
2813//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002814// It does this by inserting an insertvalue for each element in the resulting
2815// struct, as opposed to just inserting a single struct. This will only work if
2816// each of the elements of the substruct are known (ie, inserted into From by an
2817// insertvalue instruction somewhere).
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002818//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002819// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foad57aa6362011-07-13 10:26:04 +00002820static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002821 Instruction *InsertBefore) {
Matthijs Kooijman69801d42008-06-16 13:28:31 +00002822 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattner229907c2011-07-18 04:54:35 +00002823 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foad57aa6362011-07-13 10:26:04 +00002824 idx_range);
Owen Andersonb292b8c2009-07-30 23:03:37 +00002825 Value *To = UndefValue::get(IndexedType);
Jay Foad57aa6362011-07-13 10:26:04 +00002826 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002827 unsigned IdxSkip = Idxs.size();
2828
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002829 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002830}
2831
Sanjay Patelaee84212014-11-04 16:27:42 +00002832/// Given an aggregrate and an sequence of indices, see if
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002833/// the scalar value indexed is already around as a register, for example if it
2834/// were inserted directly into the aggregrate.
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002835///
2836/// If InsertBefore is not null, this function will duplicate (modified)
2837/// insertvalues when a part of a nested struct is extracted.
Jay Foad57aa6362011-07-13 10:26:04 +00002838Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
2839 Instruction *InsertBefore) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002840 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002841 // recursion).
Jay Foad57aa6362011-07-13 10:26:04 +00002842 if (idx_range.empty())
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002843 return V;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002844 // We have indices, so V should have an indexable type.
2845 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
2846 "Not looking at a struct or array?");
2847 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
2848 "Invalid indices for type?");
Owen Andersonf1f17432009-07-06 22:37:39 +00002849
Chris Lattner67058832012-01-25 06:48:06 +00002850 if (Constant *C = dyn_cast<Constant>(V)) {
2851 C = C->getAggregateElement(idx_range[0]);
Craig Topper9f008862014-04-15 04:59:12 +00002852 if (!C) return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00002853 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
2854 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002855
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002856 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002857 // Loop the indices for the insertvalue instruction in parallel with the
2858 // requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00002859 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002860 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
2861 i != e; ++i, ++req_idx) {
Jay Foad57aa6362011-07-13 10:26:04 +00002862 if (req_idx == idx_range.end()) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002863 // We can't handle this without inserting insertvalues
2864 if (!InsertBefore)
Craig Topper9f008862014-04-15 04:59:12 +00002865 return nullptr;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002866
2867 // The requested index identifies a part of a nested aggregate. Handle
2868 // this specially. For example,
2869 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
2870 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
2871 // %C = extractvalue {i32, { i32, i32 } } %B, 1
2872 // This can be changed into
2873 // %A = insertvalue {i32, i32 } undef, i32 10, 0
2874 // %C = insertvalue {i32, i32 } %A, i32 11, 1
2875 // which allows the unused 0,0 element from the nested struct to be
2876 // removed.
2877 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
2878 InsertBefore);
Duncan Sandsdb356ee2008-06-19 08:47:31 +00002879 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002880
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002881 // This insert value inserts something else than what we are looking for.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002882 // See if the (aggregate) value inserted into has the value we are
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002883 // looking for, then.
2884 if (*req_idx != *i)
Jay Foad57aa6362011-07-13 10:26:04 +00002885 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002886 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002887 }
2888 // If we end up here, the indices of the insertvalue match with those
2889 // requested (though possibly only partially). Now we recursively look at
2890 // the inserted value, passing any remaining indices.
Jay Foad57aa6362011-07-13 10:26:04 +00002891 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002892 makeArrayRef(req_idx, idx_range.end()),
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002893 InsertBefore);
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002894 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002895
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002896 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002897 // If we're extracting a value from an aggregate that was extracted from
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002898 // something else, we can extract from that something else directly instead.
2899 // However, we will need to chain I's indices with the requested indices.
Craig Topper1bef2c82012-12-22 19:15:35 +00002900
2901 // Calculate the number of indices required
Jay Foad57aa6362011-07-13 10:26:04 +00002902 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002903 // Allocate some space to put the new indices in
Matthijs Kooijman8369c672008-06-17 08:24:37 +00002904 SmallVector<unsigned, 5> Idxs;
2905 Idxs.reserve(size);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002906 // Add indices from the extract value instruction
Jay Foad57aa6362011-07-13 10:26:04 +00002907 Idxs.append(I->idx_begin(), I->idx_end());
Craig Topper1bef2c82012-12-22 19:15:35 +00002908
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002909 // Add requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00002910 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002911
Craig Topper1bef2c82012-12-22 19:15:35 +00002912 assert(Idxs.size() == size
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002913 && "Number of indices added not correct?");
Craig Topper1bef2c82012-12-22 19:15:35 +00002914
Jay Foad57aa6362011-07-13 10:26:04 +00002915 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002916 }
2917 // Otherwise, we don't know (such as, extracting from a function return value
2918 // or load instruction)
Craig Topper9f008862014-04-15 04:59:12 +00002919 return nullptr;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002920}
Evan Chengda3db112008-06-30 07:31:25 +00002921
Sanjay Patelaee84212014-11-04 16:27:42 +00002922/// Analyze the specified pointer to see if it can be expressed as a base
2923/// pointer plus a constant offset. Return the base and offset to the caller.
Chris Lattnere28618d2010-11-30 22:25:26 +00002924Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002925 const DataLayout &DL) {
2926 unsigned BitWidth = DL.getPointerTypeSizeInBits(Ptr->getType());
Nuno Lopes368c4d02012-12-31 20:48:35 +00002927 APInt ByteOffset(BitWidth, 0);
Chandler Carruth76641272016-01-04 07:23:12 +00002928
2929 // We walk up the defs but use a visited set to handle unreachable code. In
2930 // that case, we stop after accumulating the cycle once (not that it
2931 // matters).
2932 SmallPtrSet<Value *, 16> Visited;
2933 while (Visited.insert(Ptr).second) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002934 if (Ptr->getType()->isVectorTy())
2935 break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002936
Nuno Lopes368c4d02012-12-31 20:48:35 +00002937 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
Tom Stellard17eb3412016-10-07 14:23:29 +00002938 // If one of the values we have visited is an addrspacecast, then
2939 // the pointer type of this GEP may be different from the type
2940 // of the Ptr parameter which was passed to this function. This
2941 // means when we construct GEPOffset, we need to use the size
2942 // of GEP's pointer type rather than the size of the original
2943 // pointer type.
2944 APInt GEPOffset(DL.getPointerTypeSizeInBits(Ptr->getType()), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002945 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
2946 break;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00002947
Tom Stellard17eb3412016-10-07 14:23:29 +00002948 ByteOffset += GEPOffset.getSExtValue();
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00002949
Nuno Lopes368c4d02012-12-31 20:48:35 +00002950 Ptr = GEP->getPointerOperand();
Tom Stellard17eb3412016-10-07 14:23:29 +00002951 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
2952 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002953 Ptr = cast<Operator>(Ptr)->getOperand(0);
2954 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00002955 if (GA->isInterposable())
Nuno Lopes368c4d02012-12-31 20:48:35 +00002956 break;
2957 Ptr = GA->getAliasee();
Chris Lattnere28618d2010-11-30 22:25:26 +00002958 } else {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002959 break;
Chris Lattnere28618d2010-11-30 22:25:26 +00002960 }
2961 }
Nuno Lopes368c4d02012-12-31 20:48:35 +00002962 Offset = ByteOffset.getSExtValue();
2963 return Ptr;
Chris Lattnere28618d2010-11-30 22:25:26 +00002964}
2965
Matthias Braun50ec0b52017-05-19 22:37:09 +00002966bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP,
2967 unsigned CharSize) {
David L Kreitzer752c1442016-04-13 14:31:06 +00002968 // Make sure the GEP has exactly three arguments.
2969 if (GEP->getNumOperands() != 3)
2970 return false;
2971
Matthias Braun50ec0b52017-05-19 22:37:09 +00002972 // Make sure the index-ee is a pointer to array of \p CharSize integers.
2973 // CharSize.
David L Kreitzer752c1442016-04-13 14:31:06 +00002974 ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
Matthias Braun50ec0b52017-05-19 22:37:09 +00002975 if (!AT || !AT->getElementType()->isIntegerTy(CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +00002976 return false;
2977
2978 // Check to make sure that the first operand of the GEP is an integer and
2979 // has value 0 so that we are sure we're indexing into the initializer.
2980 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
2981 if (!FirstIdx || !FirstIdx->isZero())
2982 return false;
2983
2984 return true;
Sanjoy Das6082c1a2016-05-07 02:08:15 +00002985}
Chris Lattnere28618d2010-11-30 22:25:26 +00002986
Matthias Braun50ec0b52017-05-19 22:37:09 +00002987bool llvm::getConstantDataArrayInfo(const Value *V,
2988 ConstantDataArraySlice &Slice,
2989 unsigned ElementSize, uint64_t Offset) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002990 assert(V);
Evan Chengda3db112008-06-30 07:31:25 +00002991
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002992 // Look through bitcast instructions and geps.
2993 V = V->stripPointerCasts();
Craig Topper1bef2c82012-12-22 19:15:35 +00002994
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00002995 // If the value is a GEP instruction or constant expression, treat it as an
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002996 // offset.
2997 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
David L Kreitzer752c1442016-04-13 14:31:06 +00002998 // The GEP operator should be based on a pointer to string constant, and is
2999 // indexing into the string constant.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003000 if (!isGEPBasedOnPointerToString(GEP, ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003001 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003002
Evan Chengda3db112008-06-30 07:31:25 +00003003 // If the second index isn't a ConstantInt, then this is a variable index
3004 // into the array. If this occurs, we can't say anything meaningful about
3005 // the string.
3006 uint64_t StartIdx = 0;
Dan Gohman0b4df042010-04-14 22:20:45 +00003007 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Chengda3db112008-06-30 07:31:25 +00003008 StartIdx = CI->getZExtValue();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003009 else
3010 return false;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003011 return getConstantDataArrayInfo(GEP->getOperand(0), Slice, ElementSize,
3012 StartIdx + Offset);
Evan Chengda3db112008-06-30 07:31:25 +00003013 }
Nick Lewycky46209882011-10-20 00:34:35 +00003014
Evan Chengda3db112008-06-30 07:31:25 +00003015 // The GEP instruction, constant or instruction, must reference a global
3016 // variable that is a constant and is initialized. The referenced constant
3017 // initializer is the array that we'll use for optimization.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003018 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00003019 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003020 return false;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003021
Matthias Braun50ec0b52017-05-19 22:37:09 +00003022 const ConstantDataArray *Array;
3023 ArrayType *ArrayTy;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003024 if (GV->getInitializer()->isNullValue()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003025 Type *GVTy = GV->getValueType();
3026 if ( (ArrayTy = dyn_cast<ArrayType>(GVTy)) ) {
Sanjay Patel2ad88f82017-06-12 22:34:37 +00003027 // A zeroinitializer for the array; there is no ConstantDataArray.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003028 Array = nullptr;
3029 } else {
3030 const DataLayout &DL = GV->getParent()->getDataLayout();
3031 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy);
3032 uint64_t Length = SizeInBytes / (ElementSize / 8);
3033 if (Length <= Offset)
3034 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003035
Matthias Braun50ec0b52017-05-19 22:37:09 +00003036 Slice.Array = nullptr;
3037 Slice.Offset = 0;
3038 Slice.Length = Length - Offset;
3039 return true;
3040 }
3041 } else {
3042 // This must be a ConstantDataArray.
3043 Array = dyn_cast<ConstantDataArray>(GV->getInitializer());
3044 if (!Array)
3045 return false;
3046 ArrayTy = Array->getType();
3047 }
3048 if (!ArrayTy->getElementType()->isIntegerTy(ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003049 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003050
Matthias Braun50ec0b52017-05-19 22:37:09 +00003051 uint64_t NumElts = ArrayTy->getArrayNumElements();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003052 if (Offset > NumElts)
3053 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003054
Matthias Braun50ec0b52017-05-19 22:37:09 +00003055 Slice.Array = Array;
3056 Slice.Offset = Offset;
3057 Slice.Length = NumElts - Offset;
3058 return true;
3059}
3060
3061/// This function computes the length of a null-terminated C string pointed to
3062/// by V. If successful, it returns true and returns the string in Str.
3063/// If unsuccessful, it returns false.
3064bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
3065 uint64_t Offset, bool TrimAtNul) {
3066 ConstantDataArraySlice Slice;
3067 if (!getConstantDataArrayInfo(V, Slice, 8, Offset))
3068 return false;
3069
3070 if (Slice.Array == nullptr) {
3071 if (TrimAtNul) {
3072 Str = StringRef();
3073 return true;
3074 }
3075 if (Slice.Length == 1) {
3076 Str = StringRef("", 1);
3077 return true;
3078 }
Sanjay Patelfef83e82017-06-09 14:21:18 +00003079 // We cannot instantiate a StringRef as we do not have an appropriate string
Matthias Braun50ec0b52017-05-19 22:37:09 +00003080 // of 0s at hand.
3081 return false;
3082 }
3083
3084 // Start out with the entire array in the StringRef.
3085 Str = Slice.Array->getAsString();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003086 // Skip over 'offset' bytes.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003087 Str = Str.substr(Slice.Offset);
Craig Topper1bef2c82012-12-22 19:15:35 +00003088
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003089 if (TrimAtNul) {
3090 // Trim off the \0 and anything after it. If the array is not nul
3091 // terminated, we just return the whole end of string. The client may know
3092 // some other way that the string is length-bound.
3093 Str = Str.substr(0, Str.find('\0'));
3094 }
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003095 return true;
Evan Chengda3db112008-06-30 07:31:25 +00003096}
Eric Christopher4899cbc2010-03-05 06:58:57 +00003097
3098// These next two are very similar to the above, but also look through PHI
3099// nodes.
3100// TODO: See if we can integrate these two together.
3101
Sanjay Patelaee84212014-11-04 16:27:42 +00003102/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003103/// the specified pointer, return 'len+1'. If we can't, return 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00003104static uint64_t GetStringLengthH(const Value *V,
Matthias Braun50ec0b52017-05-19 22:37:09 +00003105 SmallPtrSetImpl<const PHINode*> &PHIs,
3106 unsigned CharSize) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003107 // Look through noop bitcast instructions.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003108 V = V->stripPointerCasts();
Eric Christopher4899cbc2010-03-05 06:58:57 +00003109
3110 // If this is a PHI node, there are two cases: either we have already seen it
3111 // or we haven't.
Pete Cooper35b00d52016-08-13 01:05:32 +00003112 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
David Blaikie70573dc2014-11-19 07:49:26 +00003113 if (!PHIs.insert(PN).second)
Eric Christopher4899cbc2010-03-05 06:58:57 +00003114 return ~0ULL; // already in the set.
3115
3116 // If it was new, see if all the input strings are the same length.
3117 uint64_t LenSoFar = ~0ULL;
Pete Cooper833f34d2015-05-12 20:05:31 +00003118 for (Value *IncValue : PN->incoming_values()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003119 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003120 if (Len == 0) return 0; // Unknown length -> unknown.
3121
3122 if (Len == ~0ULL) continue;
3123
3124 if (Len != LenSoFar && LenSoFar != ~0ULL)
3125 return 0; // Disagree -> unknown.
3126 LenSoFar = Len;
3127 }
3128
3129 // Success, all agree.
3130 return LenSoFar;
3131 }
3132
3133 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
Pete Cooper35b00d52016-08-13 01:05:32 +00003134 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003135 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003136 if (Len1 == 0) return 0;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003137 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003138 if (Len2 == 0) return 0;
3139 if (Len1 == ~0ULL) return Len2;
3140 if (Len2 == ~0ULL) return Len1;
3141 if (Len1 != Len2) return 0;
3142 return Len1;
3143 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003144
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003145 // Otherwise, see if we can read the string.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003146 ConstantDataArraySlice Slice;
3147 if (!getConstantDataArrayInfo(V, Slice, CharSize))
Eric Christopher4899cbc2010-03-05 06:58:57 +00003148 return 0;
3149
Matthias Braun50ec0b52017-05-19 22:37:09 +00003150 if (Slice.Array == nullptr)
3151 return 1;
3152
3153 // Search for nul characters
3154 unsigned NullIndex = 0;
3155 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
3156 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
3157 break;
3158 }
3159
3160 return NullIndex + 1;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003161}
3162
Sanjay Patelaee84212014-11-04 16:27:42 +00003163/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003164/// the specified pointer, return 'len+1'. If we can't, return 0.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003165uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003166 if (!V->getType()->isPointerTy()) return 0;
3167
Pete Cooper35b00d52016-08-13 01:05:32 +00003168 SmallPtrSet<const PHINode*, 32> PHIs;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003169 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003170 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
3171 // an empty string as a length.
3172 return Len == ~0ULL ? 1 : Len;
3173}
Dan Gohmana4fcd242010-12-15 20:02:24 +00003174
Adam Nemete2b885c2015-04-23 20:09:20 +00003175/// \brief \p PN defines a loop-variant pointer to an object. Check if the
3176/// previous iteration of the loop was referring to the same object as \p PN.
Pete Cooper35b00d52016-08-13 01:05:32 +00003177static bool isSameUnderlyingObjectInLoop(const PHINode *PN,
3178 const LoopInfo *LI) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003179 // Find the loop-defined value.
3180 Loop *L = LI->getLoopFor(PN->getParent());
3181 if (PN->getNumIncomingValues() != 2)
3182 return true;
3183
3184 // Find the value from previous iteration.
3185 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
3186 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3187 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
3188 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3189 return true;
3190
3191 // If a new pointer is loaded in the loop, the pointer references a different
3192 // object in every iteration. E.g.:
3193 // for (i)
3194 // int *p = a[i];
3195 // ...
3196 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
3197 if (!L->isLoopInvariant(Load->getPointerOperand()))
3198 return false;
3199 return true;
3200}
3201
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003202Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
3203 unsigned MaxLookup) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003204 if (!V->getType()->isPointerTy())
3205 return V;
3206 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
3207 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3208 V = GEP->getPointerOperand();
Matt Arsenault70f4db882014-07-15 00:56:40 +00003209 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
3210 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003211 V = cast<Operator>(V)->getOperand(0);
3212 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00003213 if (GA->isInterposable())
Dan Gohmana4fcd242010-12-15 20:02:24 +00003214 return V;
3215 V = GA->getAliasee();
Craig Topper85482412017-04-12 22:29:23 +00003216 } else if (isa<AllocaInst>(V)) {
3217 // An alloca can't be further simplified.
3218 return V;
Dan Gohmana4fcd242010-12-15 20:02:24 +00003219 } else {
Hal Finkel5c12d8f2016-07-11 01:32:20 +00003220 if (auto CS = CallSite(V))
3221 if (Value *RV = CS.getReturnedArgOperand()) {
3222 V = RV;
3223 continue;
3224 }
3225
Dan Gohman05b18f12010-12-15 20:49:55 +00003226 // See if InstructionSimplify knows any relevant tricks.
3227 if (Instruction *I = dyn_cast<Instruction>(V))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003228 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00003229 if (Value *Simplified = SimplifyInstruction(I, {DL, I})) {
Dan Gohman05b18f12010-12-15 20:49:55 +00003230 V = Simplified;
3231 continue;
3232 }
3233
Dan Gohmana4fcd242010-12-15 20:02:24 +00003234 return V;
3235 }
3236 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
3237 }
3238 return V;
3239}
Nick Lewycky3e334a42011-06-27 04:20:45 +00003240
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003241void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
Adam Nemete2b885c2015-04-23 20:09:20 +00003242 const DataLayout &DL, LoopInfo *LI,
3243 unsigned MaxLookup) {
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003244 SmallPtrSet<Value *, 4> Visited;
3245 SmallVector<Value *, 4> Worklist;
3246 Worklist.push_back(V);
3247 do {
3248 Value *P = Worklist.pop_back_val();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003249 P = GetUnderlyingObject(P, DL, MaxLookup);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003250
David Blaikie70573dc2014-11-19 07:49:26 +00003251 if (!Visited.insert(P).second)
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003252 continue;
3253
3254 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
3255 Worklist.push_back(SI->getTrueValue());
3256 Worklist.push_back(SI->getFalseValue());
3257 continue;
3258 }
3259
3260 if (PHINode *PN = dyn_cast<PHINode>(P)) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003261 // If this PHI changes the underlying object in every iteration of the
3262 // loop, don't look through it. Consider:
3263 // int **A;
3264 // for (i) {
3265 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
3266 // Curr = A[i];
3267 // *Prev, *Curr;
3268 //
3269 // Prev is tracking Curr one iteration behind so they refer to different
3270 // underlying objects.
3271 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
3272 isSameUnderlyingObjectInLoop(PN, LI))
Pete Cooper833f34d2015-05-12 20:05:31 +00003273 for (Value *IncValue : PN->incoming_values())
3274 Worklist.push_back(IncValue);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003275 continue;
3276 }
3277
3278 Objects.push_back(P);
3279 } while (!Worklist.empty());
3280}
3281
Sanjay Patelaee84212014-11-04 16:27:42 +00003282/// Return true if the only users of this pointer are lifetime markers.
Nick Lewycky3e334a42011-06-27 04:20:45 +00003283bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003284 for (const User *U : V->users()) {
3285 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Nick Lewycky3e334a42011-06-27 04:20:45 +00003286 if (!II) return false;
3287
3288 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
3289 II->getIntrinsicID() != Intrinsic::lifetime_end)
3290 return false;
3291 }
3292 return true;
3293}
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003294
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003295bool llvm::isSafeToSpeculativelyExecute(const Value *V,
3296 const Instruction *CtxI,
Sean Silva45835e72016-07-02 23:47:27 +00003297 const DominatorTree *DT) {
Dan Gohman7ac046a2012-01-04 23:01:09 +00003298 const Operator *Inst = dyn_cast<Operator>(V);
3299 if (!Inst)
3300 return false;
3301
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003302 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3303 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3304 if (C->canTrap())
3305 return false;
3306
3307 switch (Inst->getOpcode()) {
3308 default:
3309 return true;
3310 case Instruction::UDiv:
David Majnemerf20d7c42014-11-04 23:49:08 +00003311 case Instruction::URem: {
3312 // x / y is undefined if y == 0.
3313 const APInt *V;
3314 if (match(Inst->getOperand(1), m_APInt(V)))
3315 return *V != 0;
3316 return false;
3317 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003318 case Instruction::SDiv:
3319 case Instruction::SRem: {
David Majnemerf20d7c42014-11-04 23:49:08 +00003320 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
David Majnemer8a6578a2015-02-01 19:10:19 +00003321 const APInt *Numerator, *Denominator;
3322 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3323 return false;
3324 // We cannot hoist this division if the denominator is 0.
3325 if (*Denominator == 0)
3326 return false;
3327 // It's safe to hoist if the denominator is not 0 or -1.
3328 if (*Denominator != -1)
3329 return true;
3330 // At this point we know that the denominator is -1. It is safe to hoist as
3331 // long we know that the numerator is not INT_MIN.
3332 if (match(Inst->getOperand(0), m_APInt(Numerator)))
3333 return !Numerator->isMinSignedValue();
3334 // The numerator *might* be MinSignedValue.
David Majnemerf20d7c42014-11-04 23:49:08 +00003335 return false;
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003336 }
3337 case Instruction::Load: {
3338 const LoadInst *LI = cast<LoadInst>(Inst);
Kostya Serebryany0b458282013-11-21 07:29:28 +00003339 if (!LI->isUnordered() ||
3340 // Speculative load may create a race that did not exist in the source.
Sanjoy Dasb66374c2016-07-14 20:19:01 +00003341 LI->getFunction()->hasFnAttribute(Attribute::SanitizeThread) ||
Kostya Serebryany5cb86d52015-10-14 00:21:05 +00003342 // Speculative load may load data from dirty regions.
Sanjoy Dasb66374c2016-07-14 20:19:01 +00003343 LI->getFunction()->hasFnAttribute(Attribute::SanitizeAddress))
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003344 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003345 const DataLayout &DL = LI->getModule()->getDataLayout();
Sean Silva45835e72016-07-02 23:47:27 +00003346 return isDereferenceableAndAlignedPointer(LI->getPointerOperand(),
3347 LI->getAlignment(), DL, CtxI, DT);
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003348 }
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003349 case Instruction::Call: {
Matt Arsenaultcf5e7fe2017-04-28 21:13:09 +00003350 auto *CI = cast<const CallInst>(Inst);
3351 const Function *Callee = CI->getCalledFunction();
David Majnemer0a92f862015-08-28 21:13:39 +00003352
Matt Arsenault6a288c12017-05-03 02:26:10 +00003353 // The called function could have undefined behavior or side-effects, even
3354 // if marked readnone nounwind.
3355 return Callee && Callee->isSpeculatable();
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003356 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003357 case Instruction::VAArg:
3358 case Instruction::Alloca:
3359 case Instruction::Invoke:
3360 case Instruction::PHI:
3361 case Instruction::Store:
3362 case Instruction::Ret:
3363 case Instruction::Br:
3364 case Instruction::IndirectBr:
3365 case Instruction::Switch:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003366 case Instruction::Unreachable:
3367 case Instruction::Fence:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003368 case Instruction::AtomicRMW:
3369 case Instruction::AtomicCmpXchg:
David Majnemer654e1302015-07-31 17:58:14 +00003370 case Instruction::LandingPad:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003371 case Instruction::Resume:
David Majnemer8a1c45d2015-12-12 05:38:55 +00003372 case Instruction::CatchSwitch:
David Majnemer654e1302015-07-31 17:58:14 +00003373 case Instruction::CatchPad:
David Majnemer654e1302015-07-31 17:58:14 +00003374 case Instruction::CatchRet:
3375 case Instruction::CleanupPad:
3376 case Instruction::CleanupRet:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003377 return false; // Misc instructions which have effects
3378 }
3379}
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003380
Quentin Colombet6443cce2015-08-06 18:44:34 +00003381bool llvm::mayBeMemoryDependent(const Instruction &I) {
3382 return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
3383}
3384
Sanjay Patelaee84212014-11-04 16:27:42 +00003385/// Return true if we know that the specified value is never null.
Sean Silva45835e72016-07-02 23:47:27 +00003386bool llvm::isKnownNonNull(const Value *V) {
Chen Li0d043b52015-09-14 18:10:43 +00003387 assert(V->getType()->isPointerTy() && "V must be pointer type");
3388
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003389 // Alloca never returns null, malloc might.
3390 if (isa<AllocaInst>(V)) return true;
3391
Nick Lewyckyd52b1522014-05-20 01:23:40 +00003392 // A byval, inalloca, or nonnull argument is never null.
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003393 if (const Argument *A = dyn_cast<Argument>(V))
Nick Lewyckyd52b1522014-05-20 01:23:40 +00003394 return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003395
Peter Collingbourne235c2752016-12-08 19:01:00 +00003396 // A global variable in address space 0 is non null unless extern weak
3397 // or an absolute symbol reference. Other address spaces may have null as a
3398 // valid address for a global, so we can't assume anything.
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003399 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Peter Collingbourne235c2752016-12-08 19:01:00 +00003400 return !GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
Pete Cooper6b716212015-08-27 03:16:29 +00003401 GV->getType()->getAddressSpace() == 0;
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00003402
Sanjoy Das5056e192016-05-07 02:08:22 +00003403 // A Load tagged with nonnull metadata is never null.
Philip Reamescdb72f32014-10-20 22:40:55 +00003404 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
Philip Reames5a3f5f72014-10-21 00:13:20 +00003405 return LI->getMetadata(LLVMContext::MD_nonnull);
Philip Reamescdb72f32014-10-20 22:40:55 +00003406
Benjamin Kramer3a09ef62015-04-10 14:50:08 +00003407 if (auto CS = ImmutableCallSite(V))
Hal Finkelb0407ba2014-07-18 15:51:28 +00003408 if (CS.isReturnNonNull())
Nick Lewyckyec373542014-05-20 05:13:21 +00003409 return true;
3410
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003411 return false;
3412}
David Majnemer491331a2015-01-02 07:29:43 +00003413
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003414static bool isKnownNonNullFromDominatingCondition(const Value *V,
3415 const Instruction *CtxI,
3416 const DominatorTree *DT) {
Chen Li0d043b52015-09-14 18:10:43 +00003417 assert(V->getType()->isPointerTy() && "V must be pointer type");
Duncan P. N. Exon Smithb4798732016-09-24 19:39:47 +00003418 assert(!isa<ConstantData>(V) && "Did not expect ConstantPointerNull");
Sanjay Patel7fd779f2016-12-31 17:37:01 +00003419 assert(CtxI && "Context instruction required for analysis");
3420 assert(DT && "Dominator tree required for analysis");
Chen Li0d043b52015-09-14 18:10:43 +00003421
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003422 unsigned NumUsesExplored = 0;
Sanjoy Das987aaa12016-05-07 02:08:24 +00003423 for (auto *U : V->users()) {
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003424 // Avoid massive lists
3425 if (NumUsesExplored >= DomConditionsMaxUses)
3426 break;
3427 NumUsesExplored++;
Sanjay Patel97e4b9872017-02-12 15:35:34 +00003428
3429 // If the value is used as an argument to a call or invoke, then argument
3430 // attributes may provide an answer about null-ness.
3431 if (auto CS = ImmutableCallSite(U))
3432 if (auto *CalledFunc = CS.getCalledFunction())
3433 for (const Argument &Arg : CalledFunc->args())
3434 if (CS.getArgOperand(Arg.getArgNo()) == V &&
3435 Arg.hasNonNullAttr() && DT->dominates(CS.getInstruction(), CtxI))
3436 return true;
3437
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003438 // Consider only compare instructions uniquely controlling a branch
Sanjoy Das987aaa12016-05-07 02:08:24 +00003439 CmpInst::Predicate Pred;
3440 if (!match(const_cast<User *>(U),
3441 m_c_ICmp(Pred, m_Specific(V), m_Zero())) ||
3442 (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE))
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003443 continue;
3444
Sanjoy Das987aaa12016-05-07 02:08:24 +00003445 for (auto *CmpU : U->users()) {
Sanjoy Das12c91dc2016-05-10 02:35:44 +00003446 if (const BranchInst *BI = dyn_cast<BranchInst>(CmpU)) {
3447 assert(BI->isConditional() && "uses a comparison!");
Sanjoy Das6082c1a2016-05-07 02:08:15 +00003448
Sanjoy Das12c91dc2016-05-10 02:35:44 +00003449 BasicBlock *NonNullSuccessor =
3450 BI->getSuccessor(Pred == ICmpInst::ICMP_EQ ? 1 : 0);
3451 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3452 if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
3453 return true;
3454 } else if (Pred == ICmpInst::ICMP_NE &&
3455 match(CmpU, m_Intrinsic<Intrinsic::experimental_guard>()) &&
3456 DT->dominates(cast<Instruction>(CmpU), CtxI)) {
Sanjoy Das987aaa12016-05-07 02:08:24 +00003457 return true;
Sanjoy Das12c91dc2016-05-10 02:35:44 +00003458 }
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003459 }
3460 }
3461
3462 return false;
3463}
3464
3465bool llvm::isKnownNonNullAt(const Value *V, const Instruction *CtxI,
Sean Silva45835e72016-07-02 23:47:27 +00003466 const DominatorTree *DT) {
Duncan P. N. Exon Smithb4798732016-09-24 19:39:47 +00003467 if (isa<ConstantPointerNull>(V) || isa<UndefValue>(V))
3468 return false;
3469
Sean Silva45835e72016-07-02 23:47:27 +00003470 if (isKnownNonNull(V))
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003471 return true;
3472
Sanjay Patel7fd779f2016-12-31 17:37:01 +00003473 if (!CtxI || !DT)
3474 return false;
3475
3476 return ::isKnownNonNullFromDominatingCondition(V, CtxI, DT);
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003477}
3478
Pete Cooper35b00d52016-08-13 01:05:32 +00003479OverflowResult llvm::computeOverflowForUnsignedMul(const Value *LHS,
3480 const Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003481 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003482 AssumptionCache *AC,
David Majnemer491331a2015-01-02 07:29:43 +00003483 const Instruction *CxtI,
3484 const DominatorTree *DT) {
3485 // Multiplying n * m significant bits yields a result of n + m significant
3486 // bits. If the total number of significant bits does not exceed the
3487 // result bit width (minus 1), there is no overflow.
3488 // This means if we have enough leading zero bits in the operands
3489 // we can guarantee that the result does not overflow.
3490 // Ref: "Hacker's Delight" by Henry Warren
3491 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00003492 KnownBits LHSKnown(BitWidth);
3493 KnownBits RHSKnown(BitWidth);
3494 computeKnownBits(LHS, LHSKnown, DL, /*Depth=*/0, AC, CxtI, DT);
3495 computeKnownBits(RHS, RHSKnown, DL, /*Depth=*/0, AC, CxtI, DT);
David Majnemer491331a2015-01-02 07:29:43 +00003496 // Note that underestimating the number of zero bits gives a more
3497 // conservative answer.
Craig Topper8df66c62017-05-12 17:20:30 +00003498 unsigned ZeroBits = LHSKnown.countMinLeadingZeros() +
3499 RHSKnown.countMinLeadingZeros();
David Majnemer491331a2015-01-02 07:29:43 +00003500 // First handle the easy case: if we have enough zero bits there's
3501 // definitely no overflow.
3502 if (ZeroBits >= BitWidth)
3503 return OverflowResult::NeverOverflows;
3504
3505 // Get the largest possible values for each operand.
Craig Topperb45eabc2017-04-26 16:39:58 +00003506 APInt LHSMax = ~LHSKnown.Zero;
3507 APInt RHSMax = ~RHSKnown.Zero;
David Majnemer491331a2015-01-02 07:29:43 +00003508
3509 // We know the multiply operation doesn't overflow if the maximum values for
3510 // each operand will not overflow after we multiply them together.
David Majnemerc8a576b2015-01-02 07:29:47 +00003511 bool MaxOverflow;
Craig Topper9b71a402017-04-19 21:09:45 +00003512 (void)LHSMax.umul_ov(RHSMax, MaxOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00003513 if (!MaxOverflow)
3514 return OverflowResult::NeverOverflows;
David Majnemer491331a2015-01-02 07:29:43 +00003515
David Majnemerc8a576b2015-01-02 07:29:47 +00003516 // We know it always overflows if multiplying the smallest possible values for
3517 // the operands also results in overflow.
3518 bool MinOverflow;
Craig Topperb45eabc2017-04-26 16:39:58 +00003519 (void)LHSKnown.One.umul_ov(RHSKnown.One, MinOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00003520 if (MinOverflow)
3521 return OverflowResult::AlwaysOverflows;
3522
3523 return OverflowResult::MayOverflow;
David Majnemer491331a2015-01-02 07:29:43 +00003524}
David Majnemer5310c1e2015-01-07 00:39:50 +00003525
Pete Cooper35b00d52016-08-13 01:05:32 +00003526OverflowResult llvm::computeOverflowForUnsignedAdd(const Value *LHS,
3527 const Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003528 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003529 AssumptionCache *AC,
David Majnemer5310c1e2015-01-07 00:39:50 +00003530 const Instruction *CxtI,
3531 const DominatorTree *DT) {
Craig Topper6e11a052017-05-08 16:22:48 +00003532 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
3533 if (LHSKnown.isNonNegative() || LHSKnown.isNegative()) {
3534 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
David Majnemer5310c1e2015-01-07 00:39:50 +00003535
Craig Topper6e11a052017-05-08 16:22:48 +00003536 if (LHSKnown.isNegative() && RHSKnown.isNegative()) {
David Majnemer5310c1e2015-01-07 00:39:50 +00003537 // The sign bit is set in both cases: this MUST overflow.
3538 // Create a simple add instruction, and insert it into the struct.
3539 return OverflowResult::AlwaysOverflows;
3540 }
3541
Craig Topper6e11a052017-05-08 16:22:48 +00003542 if (LHSKnown.isNonNegative() && RHSKnown.isNonNegative()) {
David Majnemer5310c1e2015-01-07 00:39:50 +00003543 // The sign bit is clear in both cases: this CANNOT overflow.
3544 // Create a simple add instruction, and insert it into the struct.
3545 return OverflowResult::NeverOverflows;
3546 }
3547 }
3548
3549 return OverflowResult::MayOverflow;
3550}
James Molloy71b91c22015-05-11 14:42:20 +00003551
Craig Topperbb973722017-05-15 02:44:08 +00003552/// \brief Return true if we can prove that adding the two values of the
3553/// knownbits will not overflow.
3554/// Otherwise return false.
3555static bool checkRippleForSignedAdd(const KnownBits &LHSKnown,
3556 const KnownBits &RHSKnown) {
3557 // Addition of two 2's complement numbers having opposite signs will never
3558 // overflow.
3559 if ((LHSKnown.isNegative() && RHSKnown.isNonNegative()) ||
3560 (LHSKnown.isNonNegative() && RHSKnown.isNegative()))
3561 return true;
3562
3563 // If either of the values is known to be non-negative, adding them can only
3564 // overflow if the second is also non-negative, so we can assume that.
3565 // Two non-negative numbers will only overflow if there is a carry to the
3566 // sign bit, so we can check if even when the values are as big as possible
3567 // there is no overflow to the sign bit.
3568 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative()) {
3569 APInt MaxLHS = ~LHSKnown.Zero;
3570 MaxLHS.clearSignBit();
3571 APInt MaxRHS = ~RHSKnown.Zero;
3572 MaxRHS.clearSignBit();
3573 APInt Result = std::move(MaxLHS) + std::move(MaxRHS);
3574 return Result.isSignBitClear();
3575 }
3576
3577 // If either of the values is known to be negative, adding them can only
3578 // overflow if the second is also negative, so we can assume that.
3579 // Two negative number will only overflow if there is no carry to the sign
3580 // bit, so we can check if even when the values are as small as possible
3581 // there is overflow to the sign bit.
3582 if (LHSKnown.isNegative() || RHSKnown.isNegative()) {
3583 APInt MinLHS = LHSKnown.One;
3584 MinLHS.clearSignBit();
3585 APInt MinRHS = RHSKnown.One;
3586 MinRHS.clearSignBit();
3587 APInt Result = std::move(MinLHS) + std::move(MinRHS);
3588 return Result.isSignBitSet();
3589 }
3590
3591 // If we reached here it means that we know nothing about the sign bits.
3592 // In this case we can't know if there will be an overflow, since by
3593 // changing the sign bits any two values can be made to overflow.
3594 return false;
3595}
3596
Pete Cooper35b00d52016-08-13 01:05:32 +00003597static OverflowResult computeOverflowForSignedAdd(const Value *LHS,
3598 const Value *RHS,
3599 const AddOperator *Add,
3600 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003601 AssumptionCache *AC,
Pete Cooper35b00d52016-08-13 01:05:32 +00003602 const Instruction *CxtI,
3603 const DominatorTree *DT) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00003604 if (Add && Add->hasNoSignedWrap()) {
3605 return OverflowResult::NeverOverflows;
3606 }
3607
Craig Topperbb973722017-05-15 02:44:08 +00003608 // If LHS and RHS each have at least two sign bits, the addition will look
3609 // like
3610 //
3611 // XX..... +
3612 // YY.....
3613 //
3614 // If the carry into the most significant position is 0, X and Y can't both
3615 // be 1 and therefore the carry out of the addition is also 0.
3616 //
3617 // If the carry into the most significant position is 1, X and Y can't both
3618 // be 0 and therefore the carry out of the addition is also 1.
3619 //
3620 // Since the carry into the most significant position is always equal to
3621 // the carry out of the addition, there is no signed overflow.
3622 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
3623 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
3624 return OverflowResult::NeverOverflows;
3625
Craig Topper6e11a052017-05-08 16:22:48 +00003626 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
3627 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003628
Craig Topperbb973722017-05-15 02:44:08 +00003629 if (checkRippleForSignedAdd(LHSKnown, RHSKnown))
Jingyue Wu10fcea52015-08-20 18:27:04 +00003630 return OverflowResult::NeverOverflows;
Jingyue Wu10fcea52015-08-20 18:27:04 +00003631
3632 // The remaining code needs Add to be available. Early returns if not so.
3633 if (!Add)
3634 return OverflowResult::MayOverflow;
3635
3636 // If the sign of Add is the same as at least one of the operands, this add
3637 // CANNOT overflow. This is particularly useful when the sum is
3638 // @llvm.assume'ed non-negative rather than proved so from analyzing its
3639 // operands.
3640 bool LHSOrRHSKnownNonNegative =
Craig Topper6e11a052017-05-08 16:22:48 +00003641 (LHSKnown.isNonNegative() || RHSKnown.isNonNegative());
Craig Topperbb973722017-05-15 02:44:08 +00003642 bool LHSOrRHSKnownNegative =
3643 (LHSKnown.isNegative() || RHSKnown.isNegative());
Jingyue Wu10fcea52015-08-20 18:27:04 +00003644 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
Craig Topper6e11a052017-05-08 16:22:48 +00003645 KnownBits AddKnown = computeKnownBits(Add, DL, /*Depth=*/0, AC, CxtI, DT);
3646 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
3647 (AddKnown.isNegative() && LHSOrRHSKnownNegative)) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00003648 return OverflowResult::NeverOverflows;
3649 }
3650 }
3651
3652 return OverflowResult::MayOverflow;
3653}
3654
Pete Cooper35b00d52016-08-13 01:05:32 +00003655bool llvm::isOverflowIntrinsicNoWrap(const IntrinsicInst *II,
3656 const DominatorTree &DT) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003657#ifndef NDEBUG
3658 auto IID = II->getIntrinsicID();
3659 assert((IID == Intrinsic::sadd_with_overflow ||
3660 IID == Intrinsic::uadd_with_overflow ||
3661 IID == Intrinsic::ssub_with_overflow ||
3662 IID == Intrinsic::usub_with_overflow ||
3663 IID == Intrinsic::smul_with_overflow ||
3664 IID == Intrinsic::umul_with_overflow) &&
3665 "Not an overflow intrinsic!");
3666#endif
3667
Pete Cooper35b00d52016-08-13 01:05:32 +00003668 SmallVector<const BranchInst *, 2> GuardingBranches;
3669 SmallVector<const ExtractValueInst *, 2> Results;
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003670
Pete Cooper35b00d52016-08-13 01:05:32 +00003671 for (const User *U : II->users()) {
3672 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003673 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
3674
3675 if (EVI->getIndices()[0] == 0)
3676 Results.push_back(EVI);
3677 else {
3678 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
3679
Pete Cooper35b00d52016-08-13 01:05:32 +00003680 for (const auto *U : EVI->users())
3681 if (const auto *B = dyn_cast<BranchInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003682 assert(B->isConditional() && "How else is it using an i1?");
3683 GuardingBranches.push_back(B);
3684 }
3685 }
3686 } else {
3687 // We are using the aggregate directly in a way we don't want to analyze
3688 // here (storing it to a global, say).
3689 return false;
3690 }
3691 }
3692
Pete Cooper35b00d52016-08-13 01:05:32 +00003693 auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003694 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
3695 if (!NoWrapEdge.isSingleEdge())
3696 return false;
3697
3698 // Check if all users of the add are provably no-wrap.
Pete Cooper35b00d52016-08-13 01:05:32 +00003699 for (const auto *Result : Results) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003700 // If the extractvalue itself is not executed on overflow, the we don't
3701 // need to check each use separately, since domination is transitive.
3702 if (DT.dominates(NoWrapEdge, Result->getParent()))
3703 continue;
3704
3705 for (auto &RU : Result->uses())
3706 if (!DT.dominates(NoWrapEdge, RU))
3707 return false;
3708 }
3709
3710 return true;
3711 };
3712
3713 return any_of(GuardingBranches, AllUsesGuardedByBranch);
3714}
3715
3716
Pete Cooper35b00d52016-08-13 01:05:32 +00003717OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003718 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003719 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003720 const Instruction *CxtI,
3721 const DominatorTree *DT) {
3722 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003723 Add, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003724}
3725
Pete Cooper35b00d52016-08-13 01:05:32 +00003726OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS,
3727 const Value *RHS,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003728 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003729 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003730 const Instruction *CxtI,
3731 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003732 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003733}
3734
Jingyue Wu42f1d672015-07-28 18:22:40 +00003735bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003736 // A memory operation returns normally if it isn't volatile. A volatile
3737 // operation is allowed to trap.
3738 //
3739 // An atomic operation isn't guaranteed to return in a reasonable amount of
3740 // time because it's possible for another thread to interfere with it for an
3741 // arbitrary length of time, but programs aren't allowed to rely on that.
3742 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
3743 return !LI->isVolatile();
3744 if (const StoreInst *SI = dyn_cast<StoreInst>(I))
3745 return !SI->isVolatile();
3746 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
3747 return !CXI->isVolatile();
3748 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
3749 return !RMWI->isVolatile();
3750 if (const MemIntrinsic *MII = dyn_cast<MemIntrinsic>(I))
3751 return !MII->isVolatile();
Jingyue Wu42f1d672015-07-28 18:22:40 +00003752
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003753 // If there is no successor, then execution can't transfer to it.
3754 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I))
3755 return !CRI->unwindsToCaller();
3756 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I))
3757 return !CatchSwitch->unwindsToCaller();
3758 if (isa<ResumeInst>(I))
3759 return false;
3760 if (isa<ReturnInst>(I))
3761 return false;
Sebastian Pop4a4d2452017-03-08 01:54:50 +00003762 if (isa<UnreachableInst>(I))
3763 return false;
Sanjoy Das9a65cd22016-06-08 17:48:36 +00003764
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003765 // Calls can throw, or contain an infinite loop, or kill the process.
Sanjoy Das09455302016-12-31 22:12:31 +00003766 if (auto CS = ImmutableCallSite(I)) {
Sanjoy Das3bb2dbd2016-12-31 22:12:34 +00003767 // Call sites that throw have implicit non-local control flow.
3768 if (!CS.doesNotThrow())
3769 return false;
3770
3771 // Non-throwing call sites can loop infinitely, call exit/pthread_exit
3772 // etc. and thus not return. However, LLVM already assumes that
3773 //
3774 // - Thread exiting actions are modeled as writes to memory invisible to
3775 // the program.
3776 //
3777 // - Loops that don't have side effects (side effects are volatile/atomic
3778 // stores and IO) always terminate (see http://llvm.org/PR965).
3779 // Furthermore IO itself is also modeled as writes to memory invisible to
3780 // the program.
3781 //
3782 // We rely on those assumptions here, and use the memory effects of the call
3783 // target as a proxy for checking that it always returns.
3784
3785 // FIXME: This isn't aggressive enough; a call which only writes to a global
3786 // is guaranteed to return.
Sanjoy Dasd7e82062016-06-14 20:23:16 +00003787 return CS.onlyReadsMemory() || CS.onlyAccessesArgMemory() ||
3788 match(I, m_Intrinsic<Intrinsic::assume>());
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003789 }
3790
3791 // Other instructions return normally.
3792 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003793}
3794
3795bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
3796 const Loop *L) {
3797 // The loop header is guaranteed to be executed for every iteration.
3798 //
3799 // FIXME: Relax this constraint to cover all basic blocks that are
3800 // guaranteed to be executed at every iteration.
3801 if (I->getParent() != L->getHeader()) return false;
3802
3803 for (const Instruction &LI : *L->getHeader()) {
3804 if (&LI == I) return true;
3805 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
3806 }
3807 llvm_unreachable("Instruction not contained in its own parent basic block.");
3808}
3809
3810bool llvm::propagatesFullPoison(const Instruction *I) {
3811 switch (I->getOpcode()) {
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003812 case Instruction::Add:
3813 case Instruction::Sub:
3814 case Instruction::Xor:
3815 case Instruction::Trunc:
3816 case Instruction::BitCast:
3817 case Instruction::AddrSpaceCast:
Sanjoy Das5cd6c5ca2017-02-22 06:52:32 +00003818 case Instruction::Mul:
3819 case Instruction::Shl:
3820 case Instruction::GetElementPtr:
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003821 // These operations all propagate poison unconditionally. Note that poison
3822 // is not any particular value, so xor or subtraction of poison with
3823 // itself still yields poison, not zero.
3824 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003825
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003826 case Instruction::AShr:
3827 case Instruction::SExt:
3828 // For these operations, one bit of the input is replicated across
3829 // multiple output bits. A replicated poison bit is still poison.
3830 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003831
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003832 case Instruction::ICmp:
3833 // Comparing poison with any value yields poison. This is why, for
3834 // instance, x s< (x +nsw 1) can be folded to true.
3835 return true;
Sanjoy Das70c2bbd2016-05-29 00:31:18 +00003836
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003837 default:
3838 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003839 }
3840}
3841
3842const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
3843 switch (I->getOpcode()) {
3844 case Instruction::Store:
3845 return cast<StoreInst>(I)->getPointerOperand();
3846
3847 case Instruction::Load:
3848 return cast<LoadInst>(I)->getPointerOperand();
3849
3850 case Instruction::AtomicCmpXchg:
3851 return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
3852
3853 case Instruction::AtomicRMW:
3854 return cast<AtomicRMWInst>(I)->getPointerOperand();
3855
3856 case Instruction::UDiv:
3857 case Instruction::SDiv:
3858 case Instruction::URem:
3859 case Instruction::SRem:
3860 return I->getOperand(1);
3861
3862 default:
3863 return nullptr;
3864 }
3865}
3866
Sanjoy Das08989c72017-04-30 19:41:19 +00003867bool llvm::programUndefinedIfFullPoison(const Instruction *PoisonI) {
Jingyue Wu42f1d672015-07-28 18:22:40 +00003868 // We currently only look for uses of poison values within the same basic
3869 // block, as that makes it easier to guarantee that the uses will be
3870 // executed given that PoisonI is executed.
3871 //
3872 // FIXME: Expand this to consider uses beyond the same basic block. To do
3873 // this, look out for the distinction between post-dominance and strong
3874 // post-dominance.
3875 const BasicBlock *BB = PoisonI->getParent();
3876
3877 // Set of instructions that we have proved will yield poison if PoisonI
3878 // does.
3879 SmallSet<const Value *, 16> YieldsPoison;
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003880 SmallSet<const BasicBlock *, 4> Visited;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003881 YieldsPoison.insert(PoisonI);
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003882 Visited.insert(PoisonI->getParent());
Jingyue Wu42f1d672015-07-28 18:22:40 +00003883
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003884 BasicBlock::const_iterator Begin = PoisonI->getIterator(), End = BB->end();
Jingyue Wu42f1d672015-07-28 18:22:40 +00003885
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003886 unsigned Iter = 0;
3887 while (Iter++ < MaxDepth) {
3888 for (auto &I : make_range(Begin, End)) {
3889 if (&I != PoisonI) {
3890 const Value *NotPoison = getGuaranteedNonFullPoisonOp(&I);
3891 if (NotPoison != nullptr && YieldsPoison.count(NotPoison))
3892 return true;
3893 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
3894 return false;
3895 }
3896
3897 // Mark poison that propagates from I through uses of I.
3898 if (YieldsPoison.count(&I)) {
3899 for (const User *User : I.users()) {
3900 const Instruction *UserI = cast<Instruction>(User);
3901 if (propagatesFullPoison(UserI))
3902 YieldsPoison.insert(User);
3903 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003904 }
3905 }
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003906
3907 if (auto *NextBB = BB->getSingleSuccessor()) {
3908 if (Visited.insert(NextBB).second) {
3909 BB = NextBB;
3910 Begin = BB->getFirstNonPHI()->getIterator();
3911 End = BB->end();
3912 continue;
3913 }
3914 }
3915
3916 break;
3917 };
Jingyue Wu42f1d672015-07-28 18:22:40 +00003918 return false;
3919}
3920
Pete Cooper35b00d52016-08-13 01:05:32 +00003921static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
James Molloy134bec22015-08-11 09:12:57 +00003922 if (FMF.noNaNs())
3923 return true;
3924
3925 if (auto *C = dyn_cast<ConstantFP>(V))
3926 return !C->isNaN();
3927 return false;
3928}
3929
Pete Cooper35b00d52016-08-13 01:05:32 +00003930static bool isKnownNonZero(const Value *V) {
James Molloy134bec22015-08-11 09:12:57 +00003931 if (auto *C = dyn_cast<ConstantFP>(V))
3932 return !C->isZero();
3933 return false;
3934}
3935
Sanjay Patel819f0962016-11-13 19:30:19 +00003936/// Match non-obvious integer minimum and maximum sequences.
3937static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
3938 Value *CmpLHS, Value *CmpRHS,
3939 Value *TrueVal, Value *FalseVal,
3940 Value *&LHS, Value *&RHS) {
Sanjay Patel24c6f882017-01-21 17:51:25 +00003941 // Assume success. If there's no match, callers should not use these anyway.
3942 LHS = TrueVal;
3943 RHS = FalseVal;
3944
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003945 // Recognize variations of:
3946 // CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
3947 const APInt *C1;
3948 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
3949 const APInt *C2;
3950
3951 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
3952 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003953 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003954 return {SPF_SMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003955
3956 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
3957 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003958 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003959 return {SPF_SMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003960
3961 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
3962 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003963 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003964 return {SPF_UMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003965
3966 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
3967 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003968 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003969 return {SPF_UMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00003970 }
3971
Sanjay Patel819f0962016-11-13 19:30:19 +00003972 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
3973 return {SPF_UNKNOWN, SPNB_NA, false};
3974
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00003975 // Z = X -nsw Y
3976 // (X >s Y) ? 0 : Z ==> (Z >s 0) ? 0 : Z ==> SMIN(Z, 0)
3977 // (X <s Y) ? 0 : Z ==> (Z <s 0) ? 0 : Z ==> SMAX(Z, 0)
3978 if (match(TrueVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003979 match(FalseVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00003980 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00003981
3982 // Z = X -nsw Y
3983 // (X >s Y) ? Z : 0 ==> (Z >s 0) ? Z : 0 ==> SMAX(Z, 0)
3984 // (X <s Y) ? Z : 0 ==> (Z <s 0) ? Z : 0 ==> SMIN(Z, 0)
3985 if (match(FalseVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00003986 match(TrueVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00003987 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00003988
Sanjay Patel819f0962016-11-13 19:30:19 +00003989 if (!match(CmpRHS, m_APInt(C1)))
3990 return {SPF_UNKNOWN, SPNB_NA, false};
3991
3992 // An unsigned min/max can be written with a signed compare.
3993 const APInt *C2;
3994 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
3995 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
3996 // Is the sign bit set?
3997 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
3998 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
Sanjay Patel24c6f882017-01-21 17:51:25 +00003999 if (Pred == CmpInst::ICMP_SLT && *C1 == 0 && C2->isMaxSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004000 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004001
4002 // Is the sign bit clear?
4003 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
4004 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
4005 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnesValue() &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004006 C2->isMinSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004007 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004008 }
4009
4010 // Look through 'not' ops to find disguised signed min/max.
4011 // (X >s C) ? ~X : ~C ==> (~X <s ~C) ? ~X : ~C ==> SMIN(~X, ~C)
4012 // (X <s C) ? ~X : ~C ==> (~X >s ~C) ? ~X : ~C ==> SMAX(~X, ~C)
4013 if (match(TrueVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004014 match(FalseVal, m_APInt(C2)) && ~(*C1) == *C2)
Sanjay Patel819f0962016-11-13 19:30:19 +00004015 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004016
4017 // (X >s C) ? ~C : ~X ==> (~X <s ~C) ? ~C : ~X ==> SMAX(~C, ~X)
4018 // (X <s C) ? ~C : ~X ==> (~X >s ~C) ? ~C : ~X ==> SMIN(~C, ~X)
4019 if (match(FalseVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004020 match(TrueVal, m_APInt(C2)) && ~(*C1) == *C2)
Sanjay Patel819f0962016-11-13 19:30:19 +00004021 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004022
4023 return {SPF_UNKNOWN, SPNB_NA, false};
4024}
4025
James Molloy134bec22015-08-11 09:12:57 +00004026static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
4027 FastMathFlags FMF,
James Molloy270ef8c2015-05-15 16:04:50 +00004028 Value *CmpLHS, Value *CmpRHS,
4029 Value *TrueVal, Value *FalseVal,
4030 Value *&LHS, Value *&RHS) {
James Molloy71b91c22015-05-11 14:42:20 +00004031 LHS = CmpLHS;
4032 RHS = CmpRHS;
4033
James Molloy134bec22015-08-11 09:12:57 +00004034 // If the predicate is an "or-equal" (FP) predicate, then signed zeroes may
4035 // return inconsistent results between implementations.
4036 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
4037 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
4038 // Therefore we behave conservatively and only proceed if at least one of the
4039 // operands is known to not be zero, or if we don't care about signed zeroes.
4040 switch (Pred) {
4041 default: break;
4042 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
4043 case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
4044 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4045 !isKnownNonZero(CmpRHS))
4046 return {SPF_UNKNOWN, SPNB_NA, false};
4047 }
4048
4049 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
4050 bool Ordered = false;
4051
4052 // When given one NaN and one non-NaN input:
4053 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
4054 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
4055 // ordered comparison fails), which could be NaN or non-NaN.
4056 // so here we discover exactly what NaN behavior is required/accepted.
4057 if (CmpInst::isFPPredicate(Pred)) {
4058 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
4059 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
4060
4061 if (LHSSafe && RHSSafe) {
4062 // Both operands are known non-NaN.
4063 NaNBehavior = SPNB_RETURNS_ANY;
4064 } else if (CmpInst::isOrdered(Pred)) {
4065 // An ordered comparison will return false when given a NaN, so it
4066 // returns the RHS.
4067 Ordered = true;
4068 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004069 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004070 NaNBehavior = SPNB_RETURNS_NAN;
4071 else if (RHSSafe)
4072 NaNBehavior = SPNB_RETURNS_OTHER;
4073 else
4074 // Completely unsafe.
4075 return {SPF_UNKNOWN, SPNB_NA, false};
4076 } else {
4077 Ordered = false;
4078 // An unordered comparison will return true when given a NaN, so it
4079 // returns the LHS.
4080 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004081 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004082 NaNBehavior = SPNB_RETURNS_OTHER;
4083 else if (RHSSafe)
4084 NaNBehavior = SPNB_RETURNS_NAN;
4085 else
4086 // Completely unsafe.
4087 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004088 }
4089 }
4090
James Molloy71b91c22015-05-11 14:42:20 +00004091 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
James Molloy134bec22015-08-11 09:12:57 +00004092 std::swap(CmpLHS, CmpRHS);
4093 Pred = CmpInst::getSwappedPredicate(Pred);
4094 if (NaNBehavior == SPNB_RETURNS_NAN)
4095 NaNBehavior = SPNB_RETURNS_OTHER;
4096 else if (NaNBehavior == SPNB_RETURNS_OTHER)
4097 NaNBehavior = SPNB_RETURNS_NAN;
4098 Ordered = !Ordered;
4099 }
4100
4101 // ([if]cmp X, Y) ? X : Y
4102 if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
James Molloy71b91c22015-05-11 14:42:20 +00004103 switch (Pred) {
James Molloy134bec22015-08-11 09:12:57 +00004104 default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
James Molloy71b91c22015-05-11 14:42:20 +00004105 case ICmpInst::ICMP_UGT:
James Molloy134bec22015-08-11 09:12:57 +00004106 case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004107 case ICmpInst::ICMP_SGT:
James Molloy134bec22015-08-11 09:12:57 +00004108 case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004109 case ICmpInst::ICMP_ULT:
James Molloy134bec22015-08-11 09:12:57 +00004110 case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004111 case ICmpInst::ICMP_SLT:
James Molloy134bec22015-08-11 09:12:57 +00004112 case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
4113 case FCmpInst::FCMP_UGT:
4114 case FCmpInst::FCMP_UGE:
4115 case FCmpInst::FCMP_OGT:
4116 case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
4117 case FCmpInst::FCMP_ULT:
4118 case FCmpInst::FCMP_ULE:
4119 case FCmpInst::FCMP_OLT:
4120 case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
James Molloy71b91c22015-05-11 14:42:20 +00004121 }
4122 }
4123
Sanjay Patele372aec2016-10-27 15:26:10 +00004124 const APInt *C1;
4125 if (match(CmpRHS, m_APInt(C1))) {
James Molloy71b91c22015-05-11 14:42:20 +00004126 if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) ||
4127 (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) {
4128
4129 // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X
4130 // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X
Sanjay Patele372aec2016-10-27 15:26:10 +00004131 if (Pred == ICmpInst::ICMP_SGT && (*C1 == 0 || C1->isAllOnesValue())) {
James Molloy134bec22015-08-11 09:12:57 +00004132 return {(CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004133 }
4134
4135 // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X
4136 // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X
Sanjay Patele372aec2016-10-27 15:26:10 +00004137 if (Pred == ICmpInst::ICMP_SLT && (*C1 == 0 || *C1 == 1)) {
James Molloy134bec22015-08-11 09:12:57 +00004138 return {(CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004139 }
4140 }
James Molloy71b91c22015-05-11 14:42:20 +00004141 }
4142
Sanjay Patel819f0962016-11-13 19:30:19 +00004143 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
James Molloy71b91c22015-05-11 14:42:20 +00004144}
James Molloy270ef8c2015-05-15 16:04:50 +00004145
James Molloy569cea62015-09-02 17:25:25 +00004146static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
4147 Instruction::CastOps *CastOp) {
Sanjay Patel14a4b812017-01-29 16:34:57 +00004148 auto *Cast1 = dyn_cast<CastInst>(V1);
4149 if (!Cast1)
James Molloy270ef8c2015-05-15 16:04:50 +00004150 return nullptr;
James Molloy270ef8c2015-05-15 16:04:50 +00004151
Sanjay Patel14a4b812017-01-29 16:34:57 +00004152 *CastOp = Cast1->getOpcode();
4153 Type *SrcTy = Cast1->getSrcTy();
4154 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
4155 // If V1 and V2 are both the same cast from the same type, look through V1.
4156 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
4157 return Cast2->getOperand(0);
James Molloy569cea62015-09-02 17:25:25 +00004158 return nullptr;
4159 }
4160
Sanjay Patel14a4b812017-01-29 16:34:57 +00004161 auto *C = dyn_cast<Constant>(V2);
4162 if (!C)
4163 return nullptr;
4164
David Majnemerd2a074b2016-04-29 18:40:34 +00004165 Constant *CastedTo = nullptr;
Sanjay Patel14a4b812017-01-29 16:34:57 +00004166 switch (*CastOp) {
4167 case Instruction::ZExt:
4168 if (CmpI->isUnsigned())
4169 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
4170 break;
4171 case Instruction::SExt:
4172 if (CmpI->isSigned())
4173 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
4174 break;
4175 case Instruction::Trunc:
4176 CastedTo = ConstantExpr::getIntegerCast(C, SrcTy, CmpI->isSigned());
4177 break;
4178 case Instruction::FPTrunc:
4179 CastedTo = ConstantExpr::getFPExtend(C, SrcTy, true);
4180 break;
4181 case Instruction::FPExt:
4182 CastedTo = ConstantExpr::getFPTrunc(C, SrcTy, true);
4183 break;
4184 case Instruction::FPToUI:
4185 CastedTo = ConstantExpr::getUIToFP(C, SrcTy, true);
4186 break;
4187 case Instruction::FPToSI:
4188 CastedTo = ConstantExpr::getSIToFP(C, SrcTy, true);
4189 break;
4190 case Instruction::UIToFP:
4191 CastedTo = ConstantExpr::getFPToUI(C, SrcTy, true);
4192 break;
4193 case Instruction::SIToFP:
4194 CastedTo = ConstantExpr::getFPToSI(C, SrcTy, true);
4195 break;
4196 default:
4197 break;
4198 }
David Majnemerd2a074b2016-04-29 18:40:34 +00004199
4200 if (!CastedTo)
4201 return nullptr;
4202
David Majnemerd2a074b2016-04-29 18:40:34 +00004203 // Make sure the cast doesn't lose any information.
Sanjay Patel14a4b812017-01-29 16:34:57 +00004204 Constant *CastedBack =
4205 ConstantExpr::getCast(*CastOp, CastedTo, C->getType(), true);
David Majnemerd2a074b2016-04-29 18:40:34 +00004206 if (CastedBack != C)
4207 return nullptr;
4208
4209 return CastedTo;
James Molloy270ef8c2015-05-15 16:04:50 +00004210}
4211
Sanjay Patele8dc0902016-05-23 17:57:54 +00004212SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004213 Instruction::CastOps *CastOp) {
4214 SelectInst *SI = dyn_cast<SelectInst>(V);
James Molloy134bec22015-08-11 09:12:57 +00004215 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004216
James Molloy134bec22015-08-11 09:12:57 +00004217 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
4218 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004219
James Molloy134bec22015-08-11 09:12:57 +00004220 CmpInst::Predicate Pred = CmpI->getPredicate();
James Molloy270ef8c2015-05-15 16:04:50 +00004221 Value *CmpLHS = CmpI->getOperand(0);
4222 Value *CmpRHS = CmpI->getOperand(1);
4223 Value *TrueVal = SI->getTrueValue();
4224 Value *FalseVal = SI->getFalseValue();
James Molloy134bec22015-08-11 09:12:57 +00004225 FastMathFlags FMF;
4226 if (isa<FPMathOperator>(CmpI))
4227 FMF = CmpI->getFastMathFlags();
James Molloy270ef8c2015-05-15 16:04:50 +00004228
4229 // Bail out early.
4230 if (CmpI->isEquality())
James Molloy134bec22015-08-11 09:12:57 +00004231 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004232
4233 // Deal with type mismatches.
4234 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
James Molloy569cea62015-09-02 17:25:25 +00004235 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp))
James Molloy134bec22015-08-11 09:12:57 +00004236 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004237 cast<CastInst>(TrueVal)->getOperand(0), C,
4238 LHS, RHS);
James Molloy569cea62015-09-02 17:25:25 +00004239 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp))
James Molloy134bec22015-08-11 09:12:57 +00004240 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004241 C, cast<CastInst>(FalseVal)->getOperand(0),
4242 LHS, RHS);
4243 }
James Molloy134bec22015-08-11 09:12:57 +00004244 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
James Molloy270ef8c2015-05-15 16:04:50 +00004245 LHS, RHS);
4246}
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004247
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004248/// Return true if "icmp Pred LHS RHS" is always true.
Pete Cooper35b00d52016-08-13 01:05:32 +00004249static bool isTruePredicate(CmpInst::Predicate Pred,
4250 const Value *LHS, const Value *RHS,
Sanjoy Das55ea67c2015-11-06 19:01:08 +00004251 const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004252 AssumptionCache *AC, const Instruction *CxtI,
4253 const DominatorTree *DT) {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004254 assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004255 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
4256 return true;
4257
4258 switch (Pred) {
4259 default:
4260 return false;
4261
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004262 case CmpInst::ICMP_SLE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004263 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004264
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004265 // LHS s<= LHS +_{nsw} C if C >= 0
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004266 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004267 return !C->isNegative();
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004268 return false;
4269 }
4270
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004271 case CmpInst::ICMP_ULE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004272 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004273
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004274 // LHS u<= LHS +_{nuw} C for any C
4275 if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasc01b4d22015-11-06 19:01:03 +00004276 return true;
Sanjoy Das92568102015-11-10 23:56:20 +00004277
4278 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
Pete Cooper35b00d52016-08-13 01:05:32 +00004279 auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B,
4280 const Value *&X,
Sanjoy Das92568102015-11-10 23:56:20 +00004281 const APInt *&CA, const APInt *&CB) {
4282 if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
4283 match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
4284 return true;
4285
4286 // If X & C == 0 then (X | C) == X +_{nuw} C
4287 if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
4288 match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
Craig Topperb45eabc2017-04-26 16:39:58 +00004289 KnownBits Known(CA->getBitWidth());
4290 computeKnownBits(X, Known, DL, Depth + 1, AC, CxtI, DT);
Sanjoy Das92568102015-11-10 23:56:20 +00004291
Craig Topperb45eabc2017-04-26 16:39:58 +00004292 if (CA->isSubsetOf(Known.Zero) && CB->isSubsetOf(Known.Zero))
Sanjoy Das92568102015-11-10 23:56:20 +00004293 return true;
4294 }
4295
4296 return false;
4297 };
4298
Pete Cooper35b00d52016-08-13 01:05:32 +00004299 const Value *X;
Sanjoy Das92568102015-11-10 23:56:20 +00004300 const APInt *CLHS, *CRHS;
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004301 if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
4302 return CLHS->ule(*CRHS);
Sanjoy Das92568102015-11-10 23:56:20 +00004303
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004304 return false;
4305 }
4306 }
4307}
4308
4309/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
Chad Rosier41dd31f2016-04-20 19:15:26 +00004310/// ALHS ARHS" is true. Otherwise, return None.
4311static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00004312isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS,
4313 const Value *ARHS, const Value *BLHS,
4314 const Value *BRHS, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004315 unsigned Depth, AssumptionCache *AC,
4316 const Instruction *CxtI, const DominatorTree *DT) {
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004317 switch (Pred) {
4318 default:
Chad Rosier41dd31f2016-04-20 19:15:26 +00004319 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004320
4321 case CmpInst::ICMP_SLT:
4322 case CmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004323 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth, AC, CxtI,
Chad Rosier41dd31f2016-04-20 19:15:26 +00004324 DT) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004325 isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth, AC, CxtI, DT))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004326 return true;
4327 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004328
4329 case CmpInst::ICMP_ULT:
4330 case CmpInst::ICMP_ULE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004331 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth, AC, CxtI,
4332 DT) &&
4333 isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth, AC, CxtI, DT))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004334 return true;
4335 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004336 }
4337}
4338
Chad Rosier226a7342016-05-05 17:41:19 +00004339/// Return true if the operands of the two compares match. IsSwappedOps is true
4340/// when the operands match, but are swapped.
Pete Cooper35b00d52016-08-13 01:05:32 +00004341static bool isMatchingOps(const Value *ALHS, const Value *ARHS,
4342 const Value *BLHS, const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00004343 bool &IsSwappedOps) {
4344
4345 bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS);
4346 IsSwappedOps = (ALHS == BRHS && ARHS == BLHS);
4347 return IsMatchingOps || IsSwappedOps;
4348}
4349
Chad Rosier41dd31f2016-04-20 19:15:26 +00004350/// Return true if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS BRHS" is
4351/// true. Return false if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS
4352/// BRHS" is false. Otherwise, return None if we can't infer anything.
4353static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred,
Pete Cooper35b00d52016-08-13 01:05:32 +00004354 const Value *ALHS,
4355 const Value *ARHS,
Chad Rosier41dd31f2016-04-20 19:15:26 +00004356 CmpInst::Predicate BPred,
Pete Cooper35b00d52016-08-13 01:05:32 +00004357 const Value *BLHS,
4358 const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00004359 bool IsSwappedOps) {
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004360 // Canonicalize the operands so they're matching.
4361 if (IsSwappedOps) {
4362 std::swap(BLHS, BRHS);
4363 BPred = ICmpInst::getSwappedPredicate(BPred);
4364 }
Chad Rosier99bc4802016-04-21 16:18:02 +00004365 if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred))
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004366 return true;
Chad Rosier99bc4802016-04-21 16:18:02 +00004367 if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004368 return false;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004369
Chad Rosier41dd31f2016-04-20 19:15:26 +00004370 return None;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004371}
4372
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004373/// Return true if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS C2" is
4374/// true. Return false if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS
4375/// C2" is false. Otherwise, return None if we can't infer anything.
4376static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00004377isImpliedCondMatchingImmOperands(CmpInst::Predicate APred, const Value *ALHS,
4378 const ConstantInt *C1,
4379 CmpInst::Predicate BPred,
4380 const Value *BLHS, const ConstantInt *C2) {
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004381 assert(ALHS == BLHS && "LHS operands must match.");
4382 ConstantRange DomCR =
4383 ConstantRange::makeExactICmpRegion(APred, C1->getValue());
4384 ConstantRange CR =
4385 ConstantRange::makeAllowedICmpRegion(BPred, C2->getValue());
4386 ConstantRange Intersection = DomCR.intersectWith(CR);
4387 ConstantRange Difference = DomCR.difference(CR);
4388 if (Intersection.isEmptySet())
4389 return false;
4390 if (Difference.isEmptySet())
4391 return true;
4392 return None;
4393}
4394
Pete Cooper35b00d52016-08-13 01:05:32 +00004395Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
Chad Rosiere2cbd132016-04-25 17:23:36 +00004396 const DataLayout &DL, bool InvertAPred,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004397 unsigned Depth, AssumptionCache *AC,
4398 const Instruction *CxtI,
Chad Rosier41dd31f2016-04-20 19:15:26 +00004399 const DominatorTree *DT) {
Chad Rosiercd62bf52016-04-29 21:12:31 +00004400 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for example.
4401 if (LHS->getType() != RHS->getType())
4402 return None;
4403
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004404 Type *OpTy = LHS->getType();
4405 assert(OpTy->getScalarType()->isIntegerTy(1));
4406
4407 // LHS ==> RHS by definition
Chad Rosiere2cbd132016-04-25 17:23:36 +00004408 if (!InvertAPred && LHS == RHS)
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004409 return true;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004410
4411 if (OpTy->isVectorTy())
4412 // TODO: extending the code below to handle vectors
Chad Rosier41dd31f2016-04-20 19:15:26 +00004413 return None;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004414 assert(OpTy->isIntegerTy(1) && "implied by above");
4415
4416 ICmpInst::Predicate APred, BPred;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004417 Value *ALHS, *ARHS;
4418 Value *BLHS, *BRHS;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004419
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004420 if (!match(LHS, m_ICmp(APred, m_Value(ALHS), m_Value(ARHS))) ||
4421 !match(RHS, m_ICmp(BPred, m_Value(BLHS), m_Value(BRHS))))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004422 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004423
Chad Rosiere2cbd132016-04-25 17:23:36 +00004424 if (InvertAPred)
4425 APred = CmpInst::getInversePredicate(APred);
4426
Chad Rosier226a7342016-05-05 17:41:19 +00004427 // Can we infer anything when the two compares have matching operands?
4428 bool IsSwappedOps;
4429 if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, IsSwappedOps)) {
4430 if (Optional<bool> Implication = isImpliedCondMatchingOperands(
4431 APred, ALHS, ARHS, BPred, BLHS, BRHS, IsSwappedOps))
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004432 return Implication;
Chad Rosier226a7342016-05-05 17:41:19 +00004433 // No amount of additional analysis will infer the second condition, so
4434 // early exit.
4435 return None;
4436 }
4437
4438 // Can we infer anything when the LHS operands match and the RHS operands are
4439 // constants (not necessarily matching)?
4440 if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) {
4441 if (Optional<bool> Implication = isImpliedCondMatchingImmOperands(
4442 APred, ALHS, cast<ConstantInt>(ARHS), BPred, BLHS,
4443 cast<ConstantInt>(BRHS)))
4444 return Implication;
4445 // No amount of additional analysis will infer the second condition, so
4446 // early exit.
4447 return None;
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004448 }
4449
Chad Rosier41dd31f2016-04-20 19:15:26 +00004450 if (APred == BPred)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004451 return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth, AC,
4452 CxtI, DT);
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004453
Chad Rosier41dd31f2016-04-20 19:15:26 +00004454 return None;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004455}