blob: 4bf17b1502b926207c2c433a95bc92dd064b3337 [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
Chandler Carruth37c7b082017-08-14 07:03:24 +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
Craig Topperb498a232017-08-08 16:29:35 +0000278 KnownOut = KnownBits::computeForAddSub(Add, NSW, LHSKnown, Known2);
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000279}
280
Pete Cooper35b00d52016-08-13 01:05:32 +0000281static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000282 KnownBits &Known, KnownBits &Known2,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000283 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000284 unsigned BitWidth = Known.getBitWidth();
285 computeKnownBits(Op1, Known, Depth + 1, Q);
286 computeKnownBits(Op0, Known2, Depth + 1, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000287
288 bool isKnownNegative = false;
289 bool isKnownNonNegative = false;
290 // If the multiplication is known not to overflow, compute the sign bit.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000291 if (NSW) {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000292 if (Op0 == Op1) {
293 // The product of a number with itself is non-negative.
294 isKnownNonNegative = true;
295 } else {
Craig Topperca48af32017-04-29 16:43:11 +0000296 bool isKnownNonNegativeOp1 = Known.isNonNegative();
297 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
298 bool isKnownNegativeOp1 = Known.isNegative();
299 bool isKnownNegativeOp0 = Known2.isNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000300 // The product of two numbers with the same sign is non-negative.
301 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
302 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
303 // The product of a negative number and a non-negative number is either
304 // negative or zero.
305 if (!isKnownNonNegative)
306 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000307 isKnownNonZero(Op0, Depth, Q)) ||
Nick Lewyckyfa306072012-03-18 23:28:48 +0000308 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000309 isKnownNonZero(Op1, Depth, Q));
Nick Lewyckyfa306072012-03-18 23:28:48 +0000310 }
311 }
312
313 // If low bits are zero in either operand, output low known-0 bits.
Sanjay Patel5dd66c32015-09-17 20:51:50 +0000314 // Also compute a conservative estimate for high known-0 bits.
Nick Lewyckyfa306072012-03-18 23:28:48 +0000315 // More trickiness is possible, but this is sufficient for the
316 // interesting case of alignment computation.
Craig Topper8df66c62017-05-12 17:20:30 +0000317 unsigned TrailZ = Known.countMinTrailingZeros() +
318 Known2.countMinTrailingZeros();
319 unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
320 Known2.countMinLeadingZeros(),
Nick Lewyckyfa306072012-03-18 23:28:48 +0000321 BitWidth) - BitWidth;
322
323 TrailZ = std::min(TrailZ, BitWidth);
324 LeadZ = std::min(LeadZ, BitWidth);
Craig Topperf0aeee02017-05-05 17:36:09 +0000325 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000326 Known.Zero.setLowBits(TrailZ);
327 Known.Zero.setHighBits(LeadZ);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000328
329 // Only make use of no-wrap flags if we failed to compute the sign bit
330 // directly. This matters if the multiplication always overflows, in
331 // which case we prefer to follow the result of the direct computation,
332 // though as the program is invoking undefined behaviour we can choose
333 // whatever we like here.
Craig Topperca48af32017-04-29 16:43:11 +0000334 if (isKnownNonNegative && !Known.isNegative())
335 Known.makeNonNegative();
336 else if (isKnownNegative && !Known.isNonNegative())
337 Known.makeNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000338}
339
Jingyue Wu37fcb592014-06-19 16:50:16 +0000340void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
Craig Topperf42b23f2017-04-28 06:28:56 +0000341 KnownBits &Known) {
342 unsigned BitWidth = Known.getBitWidth();
Rafael Espindola53190532012-03-30 15:52:11 +0000343 unsigned NumRanges = Ranges.getNumOperands() / 2;
344 assert(NumRanges >= 1);
345
Craig Topperf42b23f2017-04-28 06:28:56 +0000346 Known.Zero.setAllBits();
347 Known.One.setAllBits();
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000348
Rafael Espindola53190532012-03-30 15:52:11 +0000349 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000350 ConstantInt *Lower =
351 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
352 ConstantInt *Upper =
353 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
Rafael Espindola53190532012-03-30 15:52:11 +0000354 ConstantRange Range(Lower->getValue(), Upper->getValue());
Rafael Espindola53190532012-03-30 15:52:11 +0000355
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000356 // The first CommonPrefixBits of all values in Range are equal.
357 unsigned CommonPrefixBits =
358 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
359
360 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
Craig Topperf42b23f2017-04-28 06:28:56 +0000361 Known.One &= Range.getUnsignedMax() & Mask;
362 Known.Zero &= ~Range.getUnsignedMax() & Mask;
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000363 }
Rafael Espindola53190532012-03-30 15:52:11 +0000364}
Jay Foad5a29c362014-05-15 12:12:55 +0000365
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000366static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
Hal Finkel60db0582014-09-07 18:57:58 +0000367 SmallVector<const Value *, 16> WorkSet(1, I);
368 SmallPtrSet<const Value *, 32> Visited;
369 SmallPtrSet<const Value *, 16> EphValues;
370
Hal Finkelf2199b22015-10-23 20:37:08 +0000371 // The instruction defining an assumption's condition itself is always
372 // considered ephemeral to that assumption (even if it has other
373 // non-ephemeral users). See r246696's test case for an example.
David Majnemer0a16c222016-08-11 21:15:00 +0000374 if (is_contained(I->operands(), E))
Hal Finkelf2199b22015-10-23 20:37:08 +0000375 return true;
376
Hal Finkel60db0582014-09-07 18:57:58 +0000377 while (!WorkSet.empty()) {
378 const Value *V = WorkSet.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +0000379 if (!Visited.insert(V).second)
Hal Finkel60db0582014-09-07 18:57:58 +0000380 continue;
381
382 // If all uses of this value are ephemeral, then so is this value.
David Majnemer0a16c222016-08-11 21:15:00 +0000383 if (all_of(V->users(), [&](const User *U) { return EphValues.count(U); })) {
Hal Finkel60db0582014-09-07 18:57:58 +0000384 if (V == E)
385 return true;
386
Hal Finkelb03dd4b2017-08-14 17:11:43 +0000387 if (V == I || isSafeToSpeculativelyExecute(V)) {
388 EphValues.insert(V);
389 if (const User *U = dyn_cast<User>(V))
390 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
391 J != JE; ++J)
392 WorkSet.push_back(*J);
393 }
Hal Finkel60db0582014-09-07 18:57:58 +0000394 }
395 }
396
397 return false;
398}
399
400// Is this an intrinsic that cannot be speculated but also cannot trap?
401static bool isAssumeLikeIntrinsic(const Instruction *I) {
402 if (const CallInst *CI = dyn_cast<CallInst>(I))
403 if (Function *F = CI->getCalledFunction())
404 switch (F->getIntrinsicID()) {
405 default: break;
406 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
407 case Intrinsic::assume:
408 case Intrinsic::dbg_declare:
409 case Intrinsic::dbg_value:
410 case Intrinsic::invariant_start:
411 case Intrinsic::invariant_end:
412 case Intrinsic::lifetime_start:
413 case Intrinsic::lifetime_end:
414 case Intrinsic::objectsize:
415 case Intrinsic::ptr_annotation:
416 case Intrinsic::var_annotation:
417 return true;
418 }
419
420 return false;
421}
422
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000423bool llvm::isValidAssumeForContext(const Instruction *Inv,
424 const Instruction *CxtI,
425 const DominatorTree *DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000426
427 // There are two restrictions on the use of an assume:
428 // 1. The assume must dominate the context (or the control flow must
429 // reach the assume whenever it reaches the context).
430 // 2. The context must not be in the assume's set of ephemeral values
431 // (otherwise we will use the assume to prove that the condition
432 // feeding the assume is trivially true, thus causing the removal of
433 // the assume).
434
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000435 if (DT) {
Pete Cooper54a02552016-08-12 01:00:15 +0000436 if (DT->dominates(Inv, CxtI))
Hal Finkel60db0582014-09-07 18:57:58 +0000437 return true;
Pete Cooper54a02552016-08-12 01:00:15 +0000438 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
439 // We don't have a DT, but this trivially dominates.
440 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000441 }
442
Pete Cooper54a02552016-08-12 01:00:15 +0000443 // With or without a DT, the only remaining case we will check is if the
444 // instructions are in the same BB. Give up if that is not the case.
445 if (Inv->getParent() != CxtI->getParent())
446 return false;
447
448 // If we have a dom tree, then we now know that the assume doens't dominate
449 // the other instruction. If we don't have a dom tree then we can check if
450 // the assume is first in the BB.
451 if (!DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000452 // Search forward from the assume until we reach the context (or the end
453 // of the block); the common case is that the assume will come first.
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000454 for (auto I = std::next(BasicBlock::const_iterator(Inv)),
Hal Finkel60db0582014-09-07 18:57:58 +0000455 IE = Inv->getParent()->end(); I != IE; ++I)
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000456 if (&*I == CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000457 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000458 }
459
Pete Cooper54a02552016-08-12 01:00:15 +0000460 // The context comes first, but they're both in the same block. Make sure
461 // there is nothing in between that might interrupt the control flow.
462 for (BasicBlock::const_iterator I =
463 std::next(BasicBlock::const_iterator(CxtI)), IE(Inv);
464 I != IE; ++I)
465 if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
466 return false;
467
468 return !isEphemeralValueOf(Inv, CxtI);
Hal Finkel60db0582014-09-07 18:57:58 +0000469}
470
Craig Topperb45eabc2017-04-26 16:39:58 +0000471static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known,
472 unsigned Depth, const Query &Q) {
Hal Finkel60db0582014-09-07 18:57:58 +0000473 // Use of assumptions is context-sensitive. If we don't have a context, we
474 // cannot use them!
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000475 if (!Q.AC || !Q.CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000476 return;
477
Craig Topperb45eabc2017-04-26 16:39:58 +0000478 unsigned BitWidth = Known.getBitWidth();
Hal Finkel60db0582014-09-07 18:57:58 +0000479
Hal Finkel8a9a7832017-01-11 13:24:24 +0000480 // Note that the patterns below need to be kept in sync with the code
481 // in AssumptionCache::updateAffectedValues.
482
483 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000484 if (!AssumeVH)
Chandler Carruth66b31302015-01-04 12:03:27 +0000485 continue;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000486 CallInst *I = cast<CallInst>(AssumeVH);
487 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
488 "Got assumption for the wrong function!");
489 if (Q.isExcluded(I))
Hal Finkel60db0582014-09-07 18:57:58 +0000490 continue;
491
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000492 // Warning: This loop can end up being somewhat performance sensetive.
493 // We're running this loop for once for each value queried resulting in a
494 // runtime of ~O(#assumes * #values).
Philip Reames00d3b272014-11-24 23:44:28 +0000495
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000496 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
497 "must be an assume intrinsic");
498
499 Value *Arg = I->getArgOperand(0);
500
501 if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000502 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000503 Known.setAllOnes();
Hal Finkel60db0582014-09-07 18:57:58 +0000504 return;
505 }
Sanjay Patel96669962017-01-17 18:15:49 +0000506 if (match(Arg, m_Not(m_Specific(V))) &&
507 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
508 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000509 Known.setAllZero();
Sanjay Patel96669962017-01-17 18:15:49 +0000510 return;
511 }
Hal Finkel60db0582014-09-07 18:57:58 +0000512
David Majnemer9b609752014-12-12 23:59:29 +0000513 // The remaining tests are all recursive, so bail out if we hit the limit.
514 if (Depth == MaxDepth)
515 continue;
516
Hal Finkel60db0582014-09-07 18:57:58 +0000517 Value *A, *B;
518 auto m_V = m_CombineOr(m_Specific(V),
519 m_CombineOr(m_PtrToInt(m_Specific(V)),
520 m_BitCast(m_Specific(V))));
521
522 CmpInst::Predicate Pred;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000523 ConstantInt *C;
Hal Finkel60db0582014-09-07 18:57:58 +0000524 // assume(v = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000525 if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000526 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000527 KnownBits RHSKnown(BitWidth);
528 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
529 Known.Zero |= RHSKnown.Zero;
530 Known.One |= RHSKnown.One;
Hal Finkel60db0582014-09-07 18:57:58 +0000531 // assume(v & b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000532 } else if (match(Arg,
533 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000534 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000535 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000536 KnownBits RHSKnown(BitWidth);
537 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
538 KnownBits MaskKnown(BitWidth);
539 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel60db0582014-09-07 18:57:58 +0000540
541 // For those bits in the mask that are known to be one, we can propagate
542 // known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000543 Known.Zero |= RHSKnown.Zero & MaskKnown.One;
544 Known.One |= RHSKnown.One & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000545 // assume(~(v & b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000546 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
547 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000548 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000549 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000550 KnownBits RHSKnown(BitWidth);
551 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
552 KnownBits MaskKnown(BitWidth);
553 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000554
555 // For those bits in the mask that are known to be one, we can propagate
556 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000557 Known.Zero |= RHSKnown.One & MaskKnown.One;
558 Known.One |= RHSKnown.Zero & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000559 // assume(v | b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000560 } else if (match(Arg,
561 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000562 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000563 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000564 KnownBits RHSKnown(BitWidth);
565 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
566 KnownBits BKnown(BitWidth);
567 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000568
569 // For those bits in B that are known to be zero, we can propagate known
570 // bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000571 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
572 Known.One |= RHSKnown.One & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000573 // assume(~(v | b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000574 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
575 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000576 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000577 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000578 KnownBits RHSKnown(BitWidth);
579 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
580 KnownBits BKnown(BitWidth);
581 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000582
583 // For those bits in B that are known to be zero, we can propagate
584 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000585 Known.Zero |= RHSKnown.One & BKnown.Zero;
586 Known.One |= RHSKnown.Zero & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000587 // assume(v ^ b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000588 } else if (match(Arg,
589 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000590 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000591 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000592 KnownBits RHSKnown(BitWidth);
593 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
594 KnownBits BKnown(BitWidth);
595 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000596
597 // For those bits in B that are known to be zero, we can propagate known
598 // bits from the RHS to V. For those bits in B that are known to be one,
599 // we can propagate inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000600 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
601 Known.One |= RHSKnown.One & BKnown.Zero;
602 Known.Zero |= RHSKnown.One & BKnown.One;
603 Known.One |= RHSKnown.Zero & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000604 // assume(~(v ^ b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000605 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
606 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000607 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000608 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000609 KnownBits RHSKnown(BitWidth);
610 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
611 KnownBits BKnown(BitWidth);
612 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000613
614 // For those bits in B that are known to be zero, we can propagate
615 // inverted known bits from the RHS to V. For those bits in B that are
616 // known to be one, we can propagate known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000617 Known.Zero |= RHSKnown.One & BKnown.Zero;
618 Known.One |= RHSKnown.Zero & BKnown.Zero;
619 Known.Zero |= RHSKnown.Zero & BKnown.One;
620 Known.One |= RHSKnown.One & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000621 // assume(v << c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000622 } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
623 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000624 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000625 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000626 KnownBits RHSKnown(BitWidth);
627 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000628 // For those bits in RHS that are known, we can propagate them to known
629 // bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000630 RHSKnown.Zero.lshrInPlace(C->getZExtValue());
631 Known.Zero |= RHSKnown.Zero;
632 RHSKnown.One.lshrInPlace(C->getZExtValue());
633 Known.One |= RHSKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000634 // assume(~(v << c) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000635 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
636 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000637 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000638 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000639 KnownBits RHSKnown(BitWidth);
640 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000641 // For those bits in RHS that are known, we can propagate them inverted
642 // to known bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000643 RHSKnown.One.lshrInPlace(C->getZExtValue());
644 Known.Zero |= RHSKnown.One;
645 RHSKnown.Zero.lshrInPlace(C->getZExtValue());
646 Known.One |= RHSKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000647 // assume(v >> c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000648 } else if (match(Arg,
Craig Topper7b66ffe2017-06-24 06:24:04 +0000649 m_c_ICmp(Pred, m_Shr(m_V, m_ConstantInt(C)),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000650 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000651 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000652 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000653 KnownBits RHSKnown(BitWidth);
654 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000655 // For those bits in RHS that are known, we can propagate them to known
656 // bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000657 Known.Zero |= RHSKnown.Zero << C->getZExtValue();
658 Known.One |= RHSKnown.One << C->getZExtValue();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000659 // assume(~(v >> c) = a)
Craig Topper7b66ffe2017-06-24 06:24:04 +0000660 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shr(m_V, m_ConstantInt(C))),
Philip Reames00d3b272014-11-24 23:44:28 +0000661 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000662 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000663 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000664 KnownBits RHSKnown(BitWidth);
665 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000666 // For those bits in RHS that are known, we can propagate them inverted
667 // to known bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000668 Known.Zero |= RHSKnown.One << C->getZExtValue();
669 Known.One |= RHSKnown.Zero << C->getZExtValue();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000670 // assume(v >=_s c) where c is non-negative
Philip Reames00d3b272014-11-24 23:44:28 +0000671 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000672 Pred == ICmpInst::ICMP_SGE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000673 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000674 KnownBits RHSKnown(BitWidth);
675 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000676
Craig Topperca48af32017-04-29 16:43:11 +0000677 if (RHSKnown.isNonNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000678 // We know that the sign bit is zero.
Craig Topperca48af32017-04-29 16:43:11 +0000679 Known.makeNonNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000680 }
681 // assume(v >_s c) where c is at least -1.
Philip Reames00d3b272014-11-24 23:44:28 +0000682 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000683 Pred == ICmpInst::ICMP_SGT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000684 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000685 KnownBits RHSKnown(BitWidth);
686 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000687
Craig Topperf0aeee02017-05-05 17:36:09 +0000688 if (RHSKnown.isAllOnes() || RHSKnown.isNonNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000689 // We know that the sign bit is zero.
Craig Topperca48af32017-04-29 16:43:11 +0000690 Known.makeNonNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000691 }
692 // assume(v <=_s c) where c is negative
Philip Reames00d3b272014-11-24 23:44:28 +0000693 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000694 Pred == ICmpInst::ICMP_SLE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000695 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000696 KnownBits RHSKnown(BitWidth);
697 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000698
Craig Topperca48af32017-04-29 16:43:11 +0000699 if (RHSKnown.isNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000700 // We know that the sign bit is one.
Craig Topperca48af32017-04-29 16:43:11 +0000701 Known.makeNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000702 }
703 // assume(v <_s c) where c is non-positive
Philip Reames00d3b272014-11-24 23:44:28 +0000704 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000705 Pred == ICmpInst::ICMP_SLT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000706 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000707 KnownBits RHSKnown(BitWidth);
708 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000709
Craig Topperf0aeee02017-05-05 17:36:09 +0000710 if (RHSKnown.isZero() || RHSKnown.isNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000711 // We know that the sign bit is one.
Craig Topperca48af32017-04-29 16:43:11 +0000712 Known.makeNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000713 }
714 // assume(v <=_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000715 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000716 Pred == ICmpInst::ICMP_ULE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000717 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000718 KnownBits RHSKnown(BitWidth);
719 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000720
721 // Whatever high bits in c are zero are known to be zero.
Craig Topper8df66c62017-05-12 17:20:30 +0000722 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
723 // assume(v <_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000724 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000725 Pred == ICmpInst::ICMP_ULT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000726 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000727 KnownBits RHSKnown(BitWidth);
728 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000729
730 // Whatever high bits in c are zero are known to be zero (if c is a power
731 // of 2, then one more).
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000732 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I)))
Craig Topper8df66c62017-05-12 17:20:30 +0000733 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros() + 1);
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000734 else
Craig Topper8df66c62017-05-12 17:20:30 +0000735 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
Hal Finkel60db0582014-09-07 18:57:58 +0000736 }
737 }
Sanjay Patel25f6d712017-02-01 15:41:32 +0000738
739 // If assumptions conflict with each other or previous known bits, then we
Sanjay Patel54656ca2017-02-06 18:26:06 +0000740 // have a logical fallacy. It's possible that the assumption is not reachable,
741 // so this isn't a real bug. On the other hand, the program may have undefined
742 // behavior, or we might have a bug in the compiler. We can't assert/crash, so
743 // clear out the known bits, try to warn the user, and hope for the best.
Craig Topperb45eabc2017-04-26 16:39:58 +0000744 if (Known.Zero.intersects(Known.One)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000745 Known.resetAll();
Sanjay Patel54656ca2017-02-06 18:26:06 +0000746
747 if (Q.ORE) {
748 auto *CxtI = const_cast<Instruction *>(Q.CxtI);
749 OptimizationRemarkAnalysis ORA("value-tracking", "BadAssumption", CxtI);
750 Q.ORE->emit(ORA << "Detected conflicting code assumptions. Program may "
751 "have undefined behavior, or compiler may have "
752 "internal error.");
753 }
Sanjay Patel25f6d712017-02-01 15:41:32 +0000754 }
Hal Finkel60db0582014-09-07 18:57:58 +0000755}
756
Hal Finkelf2199b22015-10-23 20:37:08 +0000757// Compute known bits from a shift operator, including those with a
Craig Topperb45eabc2017-04-26 16:39:58 +0000758// non-constant shift amount. Known is the outputs of this function. Known2 is a
759// pre-allocated temporary with the/ same bit width as Known. KZF and KOF are
760// operator-specific functors that, given the known-zero or known-one bits
761// respectively, and a shift amount, compute the implied known-zero or known-one
762// bits of the shift operator's result respectively for that shift amount. The
763// results from calling KZF and KOF are conservatively combined for all
764// permitted shift amounts.
David Majnemer54690dc2016-08-23 20:52:00 +0000765static void computeKnownBitsFromShiftOperator(
Craig Topperb45eabc2017-04-26 16:39:58 +0000766 const Operator *I, KnownBits &Known, KnownBits &Known2,
767 unsigned Depth, const Query &Q,
David Majnemer54690dc2016-08-23 20:52:00 +0000768 function_ref<APInt(const APInt &, unsigned)> KZF,
769 function_ref<APInt(const APInt &, unsigned)> KOF) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000770 unsigned BitWidth = Known.getBitWidth();
Hal Finkelf2199b22015-10-23 20:37:08 +0000771
772 if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
773 unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1);
774
Craig Topperb45eabc2017-04-26 16:39:58 +0000775 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
776 Known.Zero = KZF(Known.Zero, ShiftAmt);
777 Known.One = KOF(Known.One, ShiftAmt);
778 // If there is conflict between Known.Zero and Known.One, this must be an
779 // overflowing left shift, so the shift result is undefined. Clear Known
780 // bits so that other code could propagate this undef.
Craig Topperf0aeee02017-05-05 17:36:09 +0000781 if ((Known.Zero & Known.One) != 0)
782 Known.resetAll();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +0000783
Hal Finkelf2199b22015-10-23 20:37:08 +0000784 return;
785 }
786
Craig Topperb45eabc2017-04-26 16:39:58 +0000787 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000788
Oliver Stannard06204112017-03-14 10:13:17 +0000789 // If the shift amount could be greater than or equal to the bit-width of the LHS, the
790 // value could be undef, so we don't know anything about it.
Craig Topperb45eabc2017-04-26 16:39:58 +0000791 if ((~Known.Zero).uge(BitWidth)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000792 Known.resetAll();
Oliver Stannard06204112017-03-14 10:13:17 +0000793 return;
794 }
795
Craig Topperb45eabc2017-04-26 16:39:58 +0000796 // Note: We cannot use Known.Zero.getLimitedValue() here, because if
Hal Finkelf2199b22015-10-23 20:37:08 +0000797 // BitWidth > 64 and any upper bits are known, we'll end up returning the
798 // limit value (which implies all bits are known).
Craig Topperb45eabc2017-04-26 16:39:58 +0000799 uint64_t ShiftAmtKZ = Known.Zero.zextOrTrunc(64).getZExtValue();
800 uint64_t ShiftAmtKO = Known.One.zextOrTrunc(64).getZExtValue();
Hal Finkelf2199b22015-10-23 20:37:08 +0000801
802 // It would be more-clearly correct to use the two temporaries for this
803 // calculation. Reusing the APInts here to prevent unnecessary allocations.
Craig Topperf0aeee02017-05-05 17:36:09 +0000804 Known.resetAll();
Hal Finkelf2199b22015-10-23 20:37:08 +0000805
James Molloy493e57d2015-10-26 14:10:46 +0000806 // If we know the shifter operand is nonzero, we can sometimes infer more
807 // known bits. However this is expensive to compute, so be lazy about it and
808 // only compute it when absolutely necessary.
809 Optional<bool> ShifterOperandIsNonZero;
810
Hal Finkelf2199b22015-10-23 20:37:08 +0000811 // Early exit if we can't constrain any well-defined shift amount.
Craig Topperf93b7b12017-06-14 17:04:59 +0000812 if (!(ShiftAmtKZ & (PowerOf2Ceil(BitWidth) - 1)) &&
813 !(ShiftAmtKO & (PowerOf2Ceil(BitWidth) - 1))) {
James Molloy493e57d2015-10-26 14:10:46 +0000814 ShifterOperandIsNonZero =
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000815 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000816 if (!*ShifterOperandIsNonZero)
817 return;
818 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000819
Craig Topperb45eabc2017-04-26 16:39:58 +0000820 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000821
Craig Topperb45eabc2017-04-26 16:39:58 +0000822 Known.Zero.setAllBits();
823 Known.One.setAllBits();
Hal Finkelf2199b22015-10-23 20:37:08 +0000824 for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
825 // Combine the shifted known input bits only for those shift amounts
826 // compatible with its known constraints.
827 if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
828 continue;
829 if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
830 continue;
James Molloy493e57d2015-10-26 14:10:46 +0000831 // If we know the shifter is nonzero, we may be able to infer more known
832 // bits. This check is sunk down as far as possible to avoid the expensive
833 // call to isKnownNonZero if the cheaper checks above fail.
834 if (ShiftAmt == 0) {
835 if (!ShifterOperandIsNonZero.hasValue())
836 ShifterOperandIsNonZero =
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000837 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000838 if (*ShifterOperandIsNonZero)
839 continue;
840 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000841
Craig Topperb45eabc2017-04-26 16:39:58 +0000842 Known.Zero &= KZF(Known2.Zero, ShiftAmt);
843 Known.One &= KOF(Known2.One, ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +0000844 }
845
846 // If there are no compatible shift amounts, then we've proven that the shift
847 // amount must be >= the BitWidth, and the result is undefined. We could
848 // return anything we'd like, but we need to make sure the sets of known bits
849 // stay disjoint (it should be better for some other code to actually
850 // propagate the undef than to pick a value here using known bits).
Craig Topperf0aeee02017-05-05 17:36:09 +0000851 if (Known.Zero.intersects(Known.One))
852 Known.resetAll();
Hal Finkelf2199b22015-10-23 20:37:08 +0000853}
854
Craig Topperb45eabc2017-04-26 16:39:58 +0000855static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known,
856 unsigned Depth, const Query &Q) {
857 unsigned BitWidth = Known.getBitWidth();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000858
Craig Topperb45eabc2017-04-26 16:39:58 +0000859 KnownBits Known2(Known);
Dan Gohman80ca01c2009-07-17 20:47:02 +0000860 switch (I->getOpcode()) {
Chris Lattner965c7692008-06-02 01:18:21 +0000861 default: break;
Rafael Espindola53190532012-03-30 15:52:11 +0000862 case Instruction::Load:
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000863 if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +0000864 computeKnownBitsFromRangeMetadata(*MD, Known);
Jay Foad5a29c362014-05-15 12:12:55 +0000865 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000866 case Instruction::And: {
867 // If either the LHS or the RHS are Zero, the result is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +0000868 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
869 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000870
Chris Lattner965c7692008-06-02 01:18:21 +0000871 // Output known-1 bits are only known if set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000872 Known.One &= Known2.One;
Chris Lattner965c7692008-06-02 01:18:21 +0000873 // Output known-0 are known to be clear if zero in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000874 Known.Zero |= Known2.Zero;
Philip Reames2d858742015-11-10 18:46:14 +0000875
876 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
877 // here we handle the more general case of adding any odd number by
878 // matching the form add(x, add(x, y)) where y is odd.
879 // TODO: This could be generalized to clearing any bit set in y where the
880 // following bit is known to be unset in y.
881 Value *Y = nullptr;
Craig Topperb45eabc2017-04-26 16:39:58 +0000882 if (!Known.Zero[0] && !Known.One[0] &&
Craig Toppera80f2042017-04-13 19:04:45 +0000883 (match(I->getOperand(0), m_Add(m_Specific(I->getOperand(1)),
884 m_Value(Y))) ||
885 match(I->getOperand(1), m_Add(m_Specific(I->getOperand(0)),
886 m_Value(Y))))) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000887 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000888 computeKnownBits(Y, Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +0000889 if (Known2.countMinTrailingOnes() > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +0000890 Known.Zero.setBit(0);
Philip Reames2d858742015-11-10 18:46:14 +0000891 }
Jay Foad5a29c362014-05-15 12:12:55 +0000892 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000893 }
894 case Instruction::Or: {
Craig Topperb45eabc2017-04-26 16:39:58 +0000895 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
896 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000897
Chris Lattner965c7692008-06-02 01:18:21 +0000898 // Output known-0 bits are only known if clear in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000899 Known.Zero &= Known2.Zero;
Chris Lattner965c7692008-06-02 01:18:21 +0000900 // Output known-1 are known to be set if set in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000901 Known.One |= Known2.One;
Jay Foad5a29c362014-05-15 12:12:55 +0000902 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000903 }
904 case Instruction::Xor: {
Craig Topperb45eabc2017-04-26 16:39:58 +0000905 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
906 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000907
Chris Lattner965c7692008-06-02 01:18:21 +0000908 // Output known-0 bits are known if clear or set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000909 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
Chris Lattner965c7692008-06-02 01:18:21 +0000910 // Output known-1 are known to be set if set in only one of the LHS, RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000911 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
912 Known.Zero = std::move(KnownZeroOut);
Jay Foad5a29c362014-05-15 12:12:55 +0000913 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000914 }
915 case Instruction::Mul: {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000916 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Craig Topperb45eabc2017-04-26 16:39:58 +0000917 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, Known,
918 Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000919 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000920 }
921 case Instruction::UDiv: {
922 // For the purposes of computing leading zeros we can conservatively
923 // treat a udiv as a logical right shift by the power of 2 known to
924 // be less than the denominator.
Craig Topperb45eabc2017-04-26 16:39:58 +0000925 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +0000926 unsigned LeadZ = Known2.countMinLeadingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +0000927
Craig Topperf0aeee02017-05-05 17:36:09 +0000928 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000929 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +0000930 unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
931 if (RHSMaxLeadingZeros != BitWidth)
932 LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
Chris Lattner965c7692008-06-02 01:18:21 +0000933
Craig Topperb45eabc2017-04-26 16:39:58 +0000934 Known.Zero.setHighBits(LeadZ);
Jay Foad5a29c362014-05-15 12:12:55 +0000935 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000936 }
David Majnemera19d0f22016-08-06 08:16:00 +0000937 case Instruction::Select: {
Craig Toppere953dec2017-04-13 20:39:37 +0000938 const Value *LHS, *RHS;
David Majnemera19d0f22016-08-06 08:16:00 +0000939 SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
940 if (SelectPatternResult::isMinOrMax(SPF)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000941 computeKnownBits(RHS, Known, Depth + 1, Q);
942 computeKnownBits(LHS, Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +0000943 } else {
Craig Topperb45eabc2017-04-26 16:39:58 +0000944 computeKnownBits(I->getOperand(2), Known, Depth + 1, Q);
945 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +0000946 }
947
948 unsigned MaxHighOnes = 0;
949 unsigned MaxHighZeros = 0;
950 if (SPF == SPF_SMAX) {
951 // If both sides are negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +0000952 if (Known.isNegative() && Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +0000953 // We can derive a lower bound on the result by taking the max of the
954 // leading one bits.
Craig Topper8df66c62017-05-12 17:20:30 +0000955 MaxHighOnes =
956 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +0000957 // If either side is non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +0000958 else if (Known.isNonNegative() || Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +0000959 MaxHighZeros = 1;
960 } else if (SPF == SPF_SMIN) {
961 // If both sides are non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +0000962 if (Known.isNonNegative() && Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +0000963 // We can derive an upper bound on the result by taking the max of the
964 // leading zero bits.
Craig Topper8df66c62017-05-12 17:20:30 +0000965 MaxHighZeros = std::max(Known.countMinLeadingZeros(),
966 Known2.countMinLeadingZeros());
David Majnemera19d0f22016-08-06 08:16:00 +0000967 // If either side is negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +0000968 else if (Known.isNegative() || Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +0000969 MaxHighOnes = 1;
970 } else if (SPF == SPF_UMAX) {
971 // We can derive a lower bound on the result by taking the max of the
972 // leading one bits.
973 MaxHighOnes =
Craig Topper8df66c62017-05-12 17:20:30 +0000974 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +0000975 } else if (SPF == SPF_UMIN) {
976 // We can derive an upper bound on the result by taking the max of the
977 // leading zero bits.
978 MaxHighZeros =
Craig Topper8df66c62017-05-12 17:20:30 +0000979 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
David Majnemera19d0f22016-08-06 08:16:00 +0000980 }
981
Chris Lattner965c7692008-06-02 01:18:21 +0000982 // Only known if known in both the LHS and RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000983 Known.One &= Known2.One;
984 Known.Zero &= Known2.Zero;
David Majnemera19d0f22016-08-06 08:16:00 +0000985 if (MaxHighOnes > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +0000986 Known.One.setHighBits(MaxHighOnes);
David Majnemera19d0f22016-08-06 08:16:00 +0000987 if (MaxHighZeros > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +0000988 Known.Zero.setHighBits(MaxHighZeros);
Jay Foad5a29c362014-05-15 12:12:55 +0000989 break;
David Majnemera19d0f22016-08-06 08:16:00 +0000990 }
Chris Lattner965c7692008-06-02 01:18:21 +0000991 case Instruction::FPTrunc:
992 case Instruction::FPExt:
993 case Instruction::FPToUI:
994 case Instruction::FPToSI:
995 case Instruction::SIToFP:
996 case Instruction::UIToFP:
Jay Foad5a29c362014-05-15 12:12:55 +0000997 break; // Can't work with floating point.
Chris Lattner965c7692008-06-02 01:18:21 +0000998 case Instruction::PtrToInt:
999 case Instruction::IntToPtr:
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001000 // Fall through and handle them the same as zext/trunc.
1001 LLVM_FALLTHROUGH;
Chris Lattner965c7692008-06-02 01:18:21 +00001002 case Instruction::ZExt:
1003 case Instruction::Trunc: {
Chris Lattner229907c2011-07-18 04:54:35 +00001004 Type *SrcTy = I->getOperand(0)->getType();
Nadav Rotem15198e92012-10-26 17:17:05 +00001005
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001006 unsigned SrcBitWidth;
Chris Lattner965c7692008-06-02 01:18:21 +00001007 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1008 // which fall through here.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001009 SrcBitWidth = Q.DL.getTypeSizeInBits(SrcTy->getScalarType());
Nadav Rotem15198e92012-10-26 17:17:05 +00001010
1011 assert(SrcBitWidth && "SrcBitWidth can't be zero");
Craig Topperd938fd12017-05-03 22:07:25 +00001012 Known = Known.zextOrTrunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001013 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Craig Topperd938fd12017-05-03 22:07:25 +00001014 Known = Known.zextOrTrunc(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +00001015 // Any top bits are known to be zero.
1016 if (BitWidth > SrcBitWidth)
Craig Topperb45eabc2017-04-26 16:39:58 +00001017 Known.Zero.setBitsFrom(SrcBitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001018 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001019 }
1020 case Instruction::BitCast: {
Chris Lattner229907c2011-07-18 04:54:35 +00001021 Type *SrcTy = I->getOperand(0)->getType();
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001022 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattneredb84072009-07-02 16:04:08 +00001023 // TODO: For now, not handling conversions like:
1024 // (bitcast i64 %x to <2 x i32>)
Duncan Sands19d0b472010-02-16 11:11:14 +00001025 !I->getType()->isVectorTy()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001026 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Jay Foad5a29c362014-05-15 12:12:55 +00001027 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001028 }
1029 break;
1030 }
1031 case Instruction::SExt: {
1032 // Compute the bits in the result that are not present in the input.
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001033 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Craig Topper1bef2c82012-12-22 19:15:35 +00001034
Craig Topperd938fd12017-05-03 22:07:25 +00001035 Known = Known.trunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001036 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001037 // If the sign bit of the input is known set or clear, then we know the
1038 // top bits of the result.
Craig Topperd938fd12017-05-03 22:07:25 +00001039 Known = Known.sext(BitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001040 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001041 }
Hal Finkelf2199b22015-10-23 20:37:08 +00001042 case Instruction::Shl: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001043 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001044 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Craig Topperd73c6b42017-03-23 07:06:39 +00001045 auto KZF = [NSW](const APInt &KnownZero, unsigned ShiftAmt) {
1046 APInt KZResult = KnownZero << ShiftAmt;
1047 KZResult.setLowBits(ShiftAmt); // Low bits known 0.
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001048 // If this shift has "nsw" keyword, then the result is either a poison
1049 // value or has the same sign bit as the first operand.
Craig Topperd23004c2017-04-17 16:38:20 +00001050 if (NSW && KnownZero.isSignBitSet())
Craig Topperd73c6b42017-03-23 07:06:39 +00001051 KZResult.setSignBit();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001052 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001053 };
1054
Craig Topperd73c6b42017-03-23 07:06:39 +00001055 auto KOF = [NSW](const APInt &KnownOne, unsigned ShiftAmt) {
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001056 APInt KOResult = KnownOne << ShiftAmt;
Craig Topperd23004c2017-04-17 16:38:20 +00001057 if (NSW && KnownOne.isSignBitSet())
Craig Topperd73c6b42017-03-23 07:06:39 +00001058 KOResult.setSignBit();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001059 return KOResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001060 };
1061
Craig Topperb45eabc2017-04-26 16:39:58 +00001062 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001063 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001064 }
1065 case Instruction::LShr: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001066 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Craig Topperfc947bc2017-04-18 17:14:21 +00001067 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1068 APInt KZResult = KnownZero.lshr(ShiftAmt);
1069 // High bits known zero.
1070 KZResult.setHighBits(ShiftAmt);
1071 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001072 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001073
Malcolm Parsons17d266b2017-01-13 17:12:16 +00001074 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
Craig Topper885fa122017-03-31 20:01:16 +00001075 return KnownOne.lshr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001076 };
1077
Craig Topperb45eabc2017-04-26 16:39:58 +00001078 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001079 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001080 }
1081 case Instruction::AShr: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001082 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Malcolm Parsons17d266b2017-01-13 17:12:16 +00001083 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
Craig Topper885fa122017-03-31 20:01:16 +00001084 return KnownZero.ashr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001085 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001086
Malcolm Parsons17d266b2017-01-13 17:12:16 +00001087 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
Craig Topper885fa122017-03-31 20:01:16 +00001088 return KnownOne.ashr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001089 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001090
Craig Topperb45eabc2017-04-26 16:39:58 +00001091 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001092 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001093 }
Chris Lattner965c7692008-06-02 01:18:21 +00001094 case Instruction::Sub: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001095 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001096 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001097 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001098 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001099 }
Chris Lattner965c7692008-06-02 01:18:21 +00001100 case Instruction::Add: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001101 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001102 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001103 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001104 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001105 }
1106 case Instruction::SRem:
1107 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001108 APInt RA = Rem->getValue().abs();
1109 if (RA.isPowerOf2()) {
1110 APInt LowBits = RA - 1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001111 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001112
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001113 // The low bits of the first operand are unchanged by the srem.
Craig Topperb45eabc2017-04-26 16:39:58 +00001114 Known.Zero = Known2.Zero & LowBits;
1115 Known.One = Known2.One & LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001116
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001117 // If the first operand is non-negative or has all low bits zero, then
1118 // the upper bits are all zero.
Craig Topperca48af32017-04-29 16:43:11 +00001119 if (Known2.isNonNegative() || LowBits.isSubsetOf(Known2.Zero))
Craig Topperb45eabc2017-04-26 16:39:58 +00001120 Known.Zero |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001121
1122 // If the first operand is negative and not all low bits are zero, then
1123 // the upper bits are all one.
Craig Topperca48af32017-04-29 16:43:11 +00001124 if (Known2.isNegative() && LowBits.intersects(Known2.One))
Craig Topperb45eabc2017-04-26 16:39:58 +00001125 Known.One |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001126
Craig Topperb45eabc2017-04-26 16:39:58 +00001127 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Craig Topperda886c62017-04-16 21:46:12 +00001128 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001129 }
1130 }
Nick Lewyckye4679792011-03-07 01:50:10 +00001131
1132 // The sign bit is the LHS's sign bit, except when the result of the
1133 // remainder is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +00001134 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topperda886c62017-04-16 21:46:12 +00001135 // If it's known zero, our sign bit is also zero.
Craig Topperca48af32017-04-29 16:43:11 +00001136 if (Known2.isNonNegative())
1137 Known.makeNonNegative();
Nick Lewyckye4679792011-03-07 01:50:10 +00001138
Chris Lattner965c7692008-06-02 01:18:21 +00001139 break;
1140 case Instruction::URem: {
1141 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001142 const APInt &RA = Rem->getValue();
Chris Lattner965c7692008-06-02 01:18:21 +00001143 if (RA.isPowerOf2()) {
1144 APInt LowBits = (RA - 1);
Craig Topperb45eabc2017-04-26 16:39:58 +00001145 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1146 Known.Zero |= ~LowBits;
1147 Known.One &= LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001148 break;
1149 }
1150 }
1151
1152 // Since the result is less than or equal to either operand, any leading
1153 // zero bits in either operand must also exist in the result.
Craig Topperb45eabc2017-04-26 16:39:58 +00001154 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1155 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001156
Craig Topper8df66c62017-05-12 17:20:30 +00001157 unsigned Leaders =
1158 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
Craig Topperf0aeee02017-05-05 17:36:09 +00001159 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001160 Known.Zero.setHighBits(Leaders);
Chris Lattner965c7692008-06-02 01:18:21 +00001161 break;
1162 }
1163
Victor Hernandeza3aaf852009-10-17 01:18:07 +00001164 case Instruction::Alloca: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001165 const AllocaInst *AI = cast<AllocaInst>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001166 unsigned Align = AI->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001167 if (Align == 0)
Eduard Burtescu90c44492016-01-18 00:10:01 +00001168 Align = Q.DL.getABITypeAlignment(AI->getAllocatedType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001169
Chris Lattner965c7692008-06-02 01:18:21 +00001170 if (Align > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001171 Known.Zero.setLowBits(countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +00001172 break;
1173 }
1174 case Instruction::GetElementPtr: {
1175 // Analyze all of the subscripts of this getelementptr instruction
1176 // to determine if we can prove known low zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001177 KnownBits LocalKnown(BitWidth);
1178 computeKnownBits(I->getOperand(0), LocalKnown, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001179 unsigned TrailZ = LocalKnown.countMinTrailingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +00001180
1181 gep_type_iterator GTI = gep_type_begin(I);
1182 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1183 Value *Index = I->getOperand(i);
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001184 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chris Lattner965c7692008-06-02 01:18:21 +00001185 // Handle struct member offset arithmetic.
Matt Arsenault74742a12013-08-19 21:43:16 +00001186
1187 // Handle case when index is vector zeroinitializer
1188 Constant *CIndex = cast<Constant>(Index);
1189 if (CIndex->isZeroValue())
1190 continue;
1191
1192 if (CIndex->getType()->isVectorTy())
1193 Index = CIndex->getSplatValue();
1194
Chris Lattner965c7692008-06-02 01:18:21 +00001195 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001196 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chris Lattner965c7692008-06-02 01:18:21 +00001197 uint64_t Offset = SL->getElementOffset(Idx);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001198 TrailZ = std::min<unsigned>(TrailZ,
1199 countTrailingZeros(Offset));
Chris Lattner965c7692008-06-02 01:18:21 +00001200 } else {
1201 // Handle array index arithmetic.
Chris Lattner229907c2011-07-18 04:54:35 +00001202 Type *IndexedTy = GTI.getIndexedType();
Jay Foad5a29c362014-05-15 12:12:55 +00001203 if (!IndexedTy->isSized()) {
1204 TrailZ = 0;
1205 break;
1206 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001207 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001208 uint64_t TypeSize = Q.DL.getTypeAllocSize(IndexedTy);
Craig Topperb45eabc2017-04-26 16:39:58 +00001209 LocalKnown.Zero = LocalKnown.One = APInt(GEPOpiBits, 0);
1210 computeKnownBits(Index, LocalKnown, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001211 TrailZ = std::min(TrailZ,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001212 unsigned(countTrailingZeros(TypeSize) +
Craig Topper8df66c62017-05-12 17:20:30 +00001213 LocalKnown.countMinTrailingZeros()));
Chris Lattner965c7692008-06-02 01:18:21 +00001214 }
1215 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001216
Craig Topperb45eabc2017-04-26 16:39:58 +00001217 Known.Zero.setLowBits(TrailZ);
Chris Lattner965c7692008-06-02 01:18:21 +00001218 break;
1219 }
1220 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001221 const PHINode *P = cast<PHINode>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001222 // Handle the case of a simple two-predecessor recurrence PHI.
1223 // There's a lot more that could theoretically be done here, but
1224 // this is sufficient to catch some interesting cases.
1225 if (P->getNumIncomingValues() == 2) {
1226 for (unsigned i = 0; i != 2; ++i) {
1227 Value *L = P->getIncomingValue(i);
1228 Value *R = P->getIncomingValue(!i);
Dan Gohman80ca01c2009-07-17 20:47:02 +00001229 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner965c7692008-06-02 01:18:21 +00001230 if (!LU)
1231 continue;
Dan Gohman80ca01c2009-07-17 20:47:02 +00001232 unsigned Opcode = LU->getOpcode();
Chris Lattner965c7692008-06-02 01:18:21 +00001233 // Check for operations that have the property that if
1234 // both their operands have low zero bits, the result
Artur Pilipenkobc76eca2016-08-22 13:14:07 +00001235 // will have low zero bits.
Chris Lattner965c7692008-06-02 01:18:21 +00001236 if (Opcode == Instruction::Add ||
1237 Opcode == Instruction::Sub ||
1238 Opcode == Instruction::And ||
1239 Opcode == Instruction::Or ||
1240 Opcode == Instruction::Mul) {
1241 Value *LL = LU->getOperand(0);
1242 Value *LR = LU->getOperand(1);
1243 // Find a recurrence.
1244 if (LL == I)
1245 L = LR;
1246 else if (LR == I)
1247 L = LL;
1248 else
1249 break;
1250 // Ok, we have a PHI of the form L op= R. Check for low
1251 // zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001252 computeKnownBits(R, Known2, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001253
1254 // We need to take the minimum number of known bits
Craig Topperb45eabc2017-04-26 16:39:58 +00001255 KnownBits Known3(Known);
1256 computeKnownBits(L, Known3, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001257
Craig Topper8df66c62017-05-12 17:20:30 +00001258 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1259 Known3.countMinTrailingZeros()));
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001260
Chandler Carruth37c7b082017-08-14 07:03:24 +00001261 if (DontImproveNonNegativePhiBits)
1262 break;
1263
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001264 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(LU);
1265 if (OverflowOp && OverflowOp->hasNoSignedWrap()) {
1266 // If initial value of recurrence is nonnegative, and we are adding
1267 // a nonnegative number with nsw, the result can only be nonnegative
1268 // or poison value regardless of the number of times we execute the
1269 // add in phi recurrence. If initial value is negative and we are
1270 // adding a negative number with nsw, the result can only be
1271 // negative or poison value. Similar arguments apply to sub and mul.
1272 //
1273 // (add non-negative, non-negative) --> non-negative
1274 // (add negative, negative) --> negative
1275 if (Opcode == Instruction::Add) {
Craig Topperca48af32017-04-29 16:43:11 +00001276 if (Known2.isNonNegative() && Known3.isNonNegative())
1277 Known.makeNonNegative();
1278 else if (Known2.isNegative() && Known3.isNegative())
1279 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001280 }
1281
1282 // (sub nsw non-negative, negative) --> non-negative
1283 // (sub nsw negative, non-negative) --> negative
1284 else if (Opcode == Instruction::Sub && LL == I) {
Craig Topperca48af32017-04-29 16:43:11 +00001285 if (Known2.isNonNegative() && Known3.isNegative())
1286 Known.makeNonNegative();
1287 else if (Known2.isNegative() && Known3.isNonNegative())
1288 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001289 }
1290
1291 // (mul nsw non-negative, non-negative) --> non-negative
Craig Topperca48af32017-04-29 16:43:11 +00001292 else if (Opcode == Instruction::Mul && Known2.isNonNegative() &&
1293 Known3.isNonNegative())
1294 Known.makeNonNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001295 }
1296
Chris Lattner965c7692008-06-02 01:18:21 +00001297 break;
1298 }
1299 }
1300 }
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001301
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001302 // Unreachable blocks may have zero-operand PHI nodes.
1303 if (P->getNumIncomingValues() == 0)
Jay Foad5a29c362014-05-15 12:12:55 +00001304 break;
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001305
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001306 // Otherwise take the unions of the known bit sets of the operands,
1307 // taking conservative care to avoid excessive recursion.
Craig Topperb45eabc2017-04-26 16:39:58 +00001308 if (Depth < MaxDepth - 1 && !Known.Zero && !Known.One) {
Duncan Sands7dc3d472011-03-08 12:39:03 +00001309 // Skip if every incoming value references to ourself.
Nuno Lopes0d44a502012-07-03 21:15:40 +00001310 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
Duncan Sands7dc3d472011-03-08 12:39:03 +00001311 break;
1312
Craig Topperb45eabc2017-04-26 16:39:58 +00001313 Known.Zero.setAllBits();
1314 Known.One.setAllBits();
Pete Cooper833f34d2015-05-12 20:05:31 +00001315 for (Value *IncValue : P->incoming_values()) {
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001316 // Skip direct self references.
Pete Cooper833f34d2015-05-12 20:05:31 +00001317 if (IncValue == P) continue;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001318
Craig Topperb45eabc2017-04-26 16:39:58 +00001319 Known2 = KnownBits(BitWidth);
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001320 // Recurse, but cap the recursion to one level, because we don't
1321 // want to waste time spinning around in loops.
Craig Topperb45eabc2017-04-26 16:39:58 +00001322 computeKnownBits(IncValue, Known2, MaxDepth - 1, Q);
1323 Known.Zero &= Known2.Zero;
1324 Known.One &= Known2.One;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001325 // If all bits have been ruled out, there's no need to check
1326 // more operands.
Craig Topperb45eabc2017-04-26 16:39:58 +00001327 if (!Known.Zero && !Known.One)
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001328 break;
1329 }
1330 }
Chris Lattner965c7692008-06-02 01:18:21 +00001331 break;
1332 }
1333 case Instruction::Call:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001334 case Instruction::Invoke:
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001335 // If range metadata is attached to this call, set known bits from that,
1336 // and then intersect with known bits based on other properties of the
1337 // function.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001338 if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +00001339 computeKnownBitsFromRangeMetadata(*MD, Known);
Pete Cooper35b00d52016-08-13 01:05:32 +00001340 if (const Value *RV = ImmutableCallSite(I).getReturnedArgOperand()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001341 computeKnownBits(RV, Known2, Depth + 1, Q);
1342 Known.Zero |= Known2.Zero;
1343 Known.One |= Known2.One;
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001344 }
Pete Cooper35b00d52016-08-13 01:05:32 +00001345 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001346 switch (II->getIntrinsicID()) {
1347 default: break;
Chad Rosier85204292017-01-17 17:23:51 +00001348 case Intrinsic::bitreverse:
Craig Topperb45eabc2017-04-26 16:39:58 +00001349 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1350 Known.Zero |= Known2.Zero.reverseBits();
1351 Known.One |= Known2.One.reverseBits();
Chad Rosier85204292017-01-17 17:23:51 +00001352 break;
Philip Reames675418e2015-10-06 20:20:45 +00001353 case Intrinsic::bswap:
Craig Topperb45eabc2017-04-26 16:39:58 +00001354 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1355 Known.Zero |= Known2.Zero.byteSwap();
1356 Known.One |= Known2.One.byteSwap();
Philip Reames675418e2015-10-06 20:20:45 +00001357 break;
Craig Topper868813f2017-05-08 17:22:34 +00001358 case Intrinsic::ctlz: {
1359 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1360 // If we have a known 1, its position is our upper bound.
1361 unsigned PossibleLZ = Known2.One.countLeadingZeros();
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001362 // If this call is undefined for 0, the result will be less than 2^n.
1363 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
Craig Topper868813f2017-05-08 17:22:34 +00001364 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
1365 unsigned LowBits = Log2_32(PossibleLZ)+1;
1366 Known.Zero.setBitsFrom(LowBits);
1367 break;
1368 }
1369 case Intrinsic::cttz: {
1370 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1371 // If we have a known 1, its position is our upper bound.
1372 unsigned PossibleTZ = Known2.One.countTrailingZeros();
1373 // If this call is undefined for 0, the result will be less than 2^n.
1374 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1375 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
1376 unsigned LowBits = Log2_32(PossibleTZ)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001377 Known.Zero.setBitsFrom(LowBits);
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001378 break;
1379 }
1380 case Intrinsic::ctpop: {
Craig Topperb45eabc2017-04-26 16:39:58 +00001381 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001382 // We can bound the space the count needs. Also, bits known to be zero
1383 // can't contribute to the population.
Craig Topper8df66c62017-05-12 17:20:30 +00001384 unsigned BitsPossiblySet = Known2.countMaxPopulation();
Craig Topper66df10f2017-04-14 06:43:34 +00001385 unsigned LowBits = Log2_32(BitsPossiblySet)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001386 Known.Zero.setBitsFrom(LowBits);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001387 // TODO: we could bound KnownOne using the lower bound on the number
1388 // of bits which might be set provided by popcnt KnownOne2.
Chris Lattner965c7692008-06-02 01:18:21 +00001389 break;
1390 }
Chad Rosierb3628842011-05-26 23:13:19 +00001391 case Intrinsic::x86_sse42_crc32_64_64:
Craig Topperb45eabc2017-04-26 16:39:58 +00001392 Known.Zero.setBitsFrom(32);
Evan Cheng2a746bf2011-05-22 18:25:30 +00001393 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001394 }
1395 }
1396 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00001397 case Instruction::ExtractElement:
1398 // Look through extract element. At the moment we keep this simple and skip
1399 // tracking the specific element. But at least we might find information
1400 // valid for all elements of the vector (for example if vector is sign
1401 // extended, shifted, etc).
Craig Topperb45eabc2017-04-26 16:39:58 +00001402 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Bjorn Pettersson39616032016-10-06 09:56:21 +00001403 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001404 case Instruction::ExtractValue:
1405 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001406 const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001407 if (EVI->getNumIndices() != 1) break;
1408 if (EVI->getIndices()[0] == 0) {
1409 switch (II->getIntrinsicID()) {
1410 default: break;
1411 case Intrinsic::uadd_with_overflow:
1412 case Intrinsic::sadd_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001413 computeKnownBitsAddSub(true, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001414 II->getArgOperand(1), false, Known, Known2,
1415 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001416 break;
1417 case Intrinsic::usub_with_overflow:
1418 case Intrinsic::ssub_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001419 computeKnownBitsAddSub(false, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001420 II->getArgOperand(1), false, Known, Known2,
1421 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001422 break;
Nick Lewyckyfa306072012-03-18 23:28:48 +00001423 case Intrinsic::umul_with_overflow:
1424 case Intrinsic::smul_with_overflow:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001425 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
Craig Topperb45eabc2017-04-26 16:39:58 +00001426 Known, Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001427 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001428 }
1429 }
1430 }
Chris Lattner965c7692008-06-02 01:18:21 +00001431 }
Jingyue Wu12b0c282015-06-15 05:46:29 +00001432}
1433
1434/// Determine which bits of V are known to be either zero or one and return
Craig Topper6e11a052017-05-08 16:22:48 +00001435/// them.
1436KnownBits computeKnownBits(const Value *V, unsigned Depth, const Query &Q) {
1437 KnownBits Known(getBitWidth(V->getType(), Q.DL));
1438 computeKnownBits(V, Known, Depth, Q);
1439 return Known;
1440}
1441
1442/// Determine which bits of V are known to be either zero or one and return
Craig Topperb45eabc2017-04-26 16:39:58 +00001443/// them in the Known bit set.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001444///
1445/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
1446/// we cannot optimize based on the assumption that it is zero without changing
1447/// it to be an explicit zero. If we don't change it to zero, other code could
1448/// optimized based on the contradictory assumption that it is non-zero.
1449/// Because instcombine aggressively folds operations with undef args anyway,
1450/// this won't lose us code quality.
1451///
1452/// This function is defined on values with integer type, values with pointer
1453/// type, and vectors of integers. In the case
1454/// where V is a vector, known zero, and known one values are the
1455/// same width as the vector element, and the bit is set only if it is true
1456/// for all of the elements in the vector.
Craig Topperb45eabc2017-04-26 16:39:58 +00001457void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
1458 const Query &Q) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001459 assert(V && "No Value?");
1460 assert(Depth <= MaxDepth && "Limit Search Depth");
Craig Topperb45eabc2017-04-26 16:39:58 +00001461 unsigned BitWidth = Known.getBitWidth();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001462
Craig Topperfde47232017-07-09 07:04:03 +00001463 assert((V->getType()->isIntOrIntVectorTy(BitWidth) ||
Craig Topper95d23472017-07-09 07:04:00 +00001464 V->getType()->isPtrOrPtrVectorTy()) &&
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001465 "Not integer or pointer type!");
Craig Topperfde47232017-07-09 07:04:03 +00001466 assert(Q.DL.getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth &&
Craig Topperb45eabc2017-04-26 16:39:58 +00001467 "V and Known should have same BitWidth");
Craig Topperd73c6b42017-03-23 07:06:39 +00001468 (void)BitWidth;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001469
Sanjay Patelc96f6db2016-09-16 21:20:36 +00001470 const APInt *C;
1471 if (match(V, m_APInt(C))) {
1472 // We know all of the bits for a scalar constant or a splat vector constant!
Craig Topperb45eabc2017-04-26 16:39:58 +00001473 Known.One = *C;
1474 Known.Zero = ~Known.One;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001475 return;
1476 }
1477 // Null and aggregate-zero are all-zeros.
Sanjay Patele8dc0902016-05-23 17:57:54 +00001478 if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001479 Known.setAllZero();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001480 return;
1481 }
1482 // Handle a constant vector by taking the intersection of the known bits of
David Majnemer3918cdd2016-05-04 06:13:33 +00001483 // each element.
Pete Cooper35b00d52016-08-13 01:05:32 +00001484 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001485 // We know that CDS must be a vector of integers. Take the intersection of
1486 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001487 Known.Zero.setAllBits(); Known.One.setAllBits();
Craig Topper9c932d32017-04-25 16:48:03 +00001488 APInt Elt(BitWidth, 0);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001489 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1490 Elt = CDS->getElementAsInteger(i);
Craig Topperb45eabc2017-04-26 16:39:58 +00001491 Known.Zero &= ~Elt;
1492 Known.One &= Elt;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001493 }
1494 return;
1495 }
1496
Pete Cooper35b00d52016-08-13 01:05:32 +00001497 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
David Majnemer3918cdd2016-05-04 06:13:33 +00001498 // We know that CV must be a vector of integers. Take the intersection of
1499 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001500 Known.Zero.setAllBits(); Known.One.setAllBits();
1501 APInt Elt(BitWidth, 0);
David Majnemer3918cdd2016-05-04 06:13:33 +00001502 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1503 Constant *Element = CV->getAggregateElement(i);
1504 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
1505 if (!ElementCI) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001506 Known.resetAll();
David Majnemer3918cdd2016-05-04 06:13:33 +00001507 return;
1508 }
1509 Elt = ElementCI->getValue();
Craig Topperb45eabc2017-04-26 16:39:58 +00001510 Known.Zero &= ~Elt;
1511 Known.One &= Elt;
David Majnemer3918cdd2016-05-04 06:13:33 +00001512 }
1513 return;
1514 }
1515
Jingyue Wu12b0c282015-06-15 05:46:29 +00001516 // Start out not knowing anything.
Craig Topperf0aeee02017-05-05 17:36:09 +00001517 Known.resetAll();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001518
Duncan P. N. Exon Smithb1b208a2016-09-24 20:42:02 +00001519 // We can't imply anything about undefs.
1520 if (isa<UndefValue>(V))
1521 return;
1522
1523 // There's no point in looking through other users of ConstantData for
1524 // assumptions. Confirm that we've handled them all.
1525 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
1526
Jingyue Wu12b0c282015-06-15 05:46:29 +00001527 // Limit search depth.
1528 // All recursive calls that increase depth must come after this.
1529 if (Depth == MaxDepth)
1530 return;
1531
1532 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1533 // the bits of its aliasee.
Pete Cooper35b00d52016-08-13 01:05:32 +00001534 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001535 if (!GA->isInterposable())
Craig Topperb45eabc2017-04-26 16:39:58 +00001536 computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001537 return;
1538 }
1539
Pete Cooper35b00d52016-08-13 01:05:32 +00001540 if (const Operator *I = dyn_cast<Operator>(V))
Craig Topperb45eabc2017-04-26 16:39:58 +00001541 computeKnownBitsFromOperator(I, Known, Depth, Q);
Sanjay Patela67559c2015-09-25 20:12:43 +00001542
Craig Topperb45eabc2017-04-26 16:39:58 +00001543 // Aligned pointers have trailing zeros - refine Known.Zero set
Artur Pilipenko029d8532015-09-30 11:55:45 +00001544 if (V->getType()->isPointerTy()) {
Artur Pilipenkoae51afc2016-02-24 12:25:10 +00001545 unsigned Align = V->getPointerAlignment(Q.DL);
Artur Pilipenko029d8532015-09-30 11:55:45 +00001546 if (Align)
Craig Topperb45eabc2017-04-26 16:39:58 +00001547 Known.Zero.setLowBits(countTrailingZeros(Align));
Artur Pilipenko029d8532015-09-30 11:55:45 +00001548 }
1549
Craig Topperb45eabc2017-04-26 16:39:58 +00001550 // computeKnownBitsFromAssume strictly refines Known.
1551 // Therefore, we run them after computeKnownBitsFromOperator.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001552
1553 // Check whether a nearby assume intrinsic can determine some known bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001554 computeKnownBitsFromAssume(V, Known, Depth, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001555
Craig Topperb45eabc2017-04-26 16:39:58 +00001556 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001557}
1558
Sanjay Patelaee84212014-11-04 16:27:42 +00001559/// Return true if the given value is known to have exactly one
Duncan Sandsd3951082011-01-25 09:38:29 +00001560/// bit set when defined. For vectors return true if every element is known to
Sanjay Patelaee84212014-11-04 16:27:42 +00001561/// be a power of two when defined. Supports values with integer or pointer
Duncan Sandsd3951082011-01-25 09:38:29 +00001562/// types and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001563bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001564 const Query &Q) {
Craig Topper7227eba2017-08-21 22:56:12 +00001565 assert(Depth <= MaxDepth && "Limit Search Depth");
1566
Pete Cooper35b00d52016-08-13 01:05:32 +00001567 if (const Constant *C = dyn_cast<Constant>(V)) {
Duncan Sandsba286d72011-10-26 20:55:21 +00001568 if (C->isNullValue())
1569 return OrZero;
Sanjay Patele2e89ef2016-05-22 15:41:53 +00001570
1571 const APInt *ConstIntOrConstSplatInt;
1572 if (match(C, m_APInt(ConstIntOrConstSplatInt)))
1573 return ConstIntOrConstSplatInt->isPowerOf2();
Duncan Sandsba286d72011-10-26 20:55:21 +00001574 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001575
1576 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1577 // it is shifted off the end then the result is undefined.
1578 if (match(V, m_Shl(m_One(), m_Value())))
1579 return true;
1580
Craig Topperbcfd2d12017-04-20 16:56:25 +00001581 // (signmask) >>l X is clearly a power of two if the one is not shifted off
1582 // the bottom. If it is shifted off the bottom then the result is undefined.
1583 if (match(V, m_LShr(m_SignMask(), m_Value())))
Duncan Sandsd3951082011-01-25 09:38:29 +00001584 return true;
1585
1586 // The remaining tests are all recursive, so bail out if we hit the limit.
1587 if (Depth++ == MaxDepth)
1588 return false;
1589
Craig Topper9f008862014-04-15 04:59:12 +00001590 Value *X = nullptr, *Y = nullptr;
Sanjay Patel41160c22015-12-30 22:40:52 +00001591 // A shift left or a logical shift right of a power of two is a power of two
1592 // or zero.
Duncan Sands985ba632011-10-28 18:30:05 +00001593 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
Sanjay Patel41160c22015-12-30 22:40:52 +00001594 match(V, m_LShr(m_Value(X), m_Value()))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001595 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
Duncan Sands985ba632011-10-28 18:30:05 +00001596
Pete Cooper35b00d52016-08-13 01:05:32 +00001597 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001598 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001599
Pete Cooper35b00d52016-08-13 01:05:32 +00001600 if (const SelectInst *SI = dyn_cast<SelectInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001601 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1602 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
Duncan Sandsba286d72011-10-26 20:55:21 +00001603
Duncan Sandsba286d72011-10-26 20:55:21 +00001604 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1605 // A power of two and'd with anything is a power of two or zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001606 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
1607 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
Duncan Sandsba286d72011-10-26 20:55:21 +00001608 return true;
1609 // X & (-X) is always a power of two or zero.
1610 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1611 return true;
1612 return false;
1613 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001614
David Majnemerb7d54092013-07-30 21:01:36 +00001615 // Adding a power-of-two or zero to the same power-of-two or zero yields
1616 // either the original power-of-two, a larger power-of-two or zero.
1617 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001618 const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
David Majnemerb7d54092013-07-30 21:01:36 +00001619 if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1620 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1621 match(X, m_And(m_Value(), m_Specific(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001622 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001623 return true;
1624 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1625 match(Y, m_And(m_Value(), m_Specific(X))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001626 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001627 return true;
1628
1629 unsigned BitWidth = V->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00001630 KnownBits LHSBits(BitWidth);
1631 computeKnownBits(X, LHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001632
Craig Topperb45eabc2017-04-26 16:39:58 +00001633 KnownBits RHSBits(BitWidth);
1634 computeKnownBits(Y, RHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001635 // If i8 V is a power of two or zero:
1636 // ZeroBits: 1 1 1 0 1 1 1 1
1637 // ~ZeroBits: 0 0 0 1 0 0 0 0
Craig Topperb45eabc2017-04-26 16:39:58 +00001638 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
David Majnemerb7d54092013-07-30 21:01:36 +00001639 // If OrZero isn't set, we cannot give back a zero result.
1640 // Make sure either the LHS or RHS has a bit set.
Craig Topperb45eabc2017-04-26 16:39:58 +00001641 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
David Majnemerb7d54092013-07-30 21:01:36 +00001642 return true;
1643 }
1644 }
David Majnemerbeab5672013-05-18 19:30:37 +00001645
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001646 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewyckyf0469af2011-03-21 21:40:32 +00001647 // is a power of two only if the first operand is a power of two and not
1648 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001649 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1650 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
Hal Finkel60db0582014-09-07 18:57:58 +00001651 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001652 Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001653 }
1654
Duncan Sandsd3951082011-01-25 09:38:29 +00001655 return false;
1656}
1657
Chandler Carruth80d3e562012-12-07 02:08:58 +00001658/// \brief Test whether a GEP's result is known to be non-null.
1659///
1660/// Uses properties inherent in a GEP to try to determine whether it is known
1661/// to be non-null.
1662///
1663/// Currently this routine does not support vector GEPs.
Pete Cooper35b00d52016-08-13 01:05:32 +00001664static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001665 const Query &Q) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001666 if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1667 return false;
1668
1669 // FIXME: Support vector-GEPs.
1670 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1671
1672 // If the base pointer is non-null, we cannot walk to a null address with an
1673 // inbounds GEP in address space zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001674 if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001675 return true;
1676
Chandler Carruth80d3e562012-12-07 02:08:58 +00001677 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1678 // If so, then the GEP cannot produce a null pointer, as doing so would
1679 // inherently violate the inbounds contract within address space zero.
1680 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1681 GTI != GTE; ++GTI) {
1682 // Struct types are easy -- they must always be indexed by a constant.
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001683 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001684 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1685 unsigned ElementIdx = OpC->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001686 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chandler Carruth80d3e562012-12-07 02:08:58 +00001687 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1688 if (ElementOffset > 0)
1689 return true;
1690 continue;
1691 }
1692
1693 // If we have a zero-sized type, the index doesn't matter. Keep looping.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001694 if (Q.DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
Chandler Carruth80d3e562012-12-07 02:08:58 +00001695 continue;
1696
1697 // Fast path the constant operand case both for efficiency and so we don't
1698 // increment Depth when just zipping down an all-constant GEP.
1699 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1700 if (!OpC->isZero())
1701 return true;
1702 continue;
1703 }
1704
1705 // We post-increment Depth here because while isKnownNonZero increments it
1706 // as well, when we pop back up that increment won't persist. We don't want
1707 // to recurse 10k times just because we have 10k GEP operands. We don't
1708 // bail completely out because we want to handle constant GEPs regardless
1709 // of depth.
1710 if (Depth++ >= MaxDepth)
1711 continue;
1712
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001713 if (isKnownNonZero(GTI.getOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001714 return true;
1715 }
1716
1717 return false;
1718}
1719
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001720/// Does the 'Range' metadata (which must be a valid MD_range operand list)
1721/// ensure that the value it's attached to is never Value? 'RangeType' is
1722/// is the type of the value described by the range.
Pete Cooper35b00d52016-08-13 01:05:32 +00001723static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001724 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1725 assert(NumRanges >= 1);
1726 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001727 ConstantInt *Lower =
1728 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1729 ConstantInt *Upper =
1730 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001731 ConstantRange Range(Lower->getValue(), Upper->getValue());
1732 if (Range.contains(Value))
1733 return false;
1734 }
1735 return true;
1736}
1737
Sanjay Patel97e4b9872017-02-12 15:35:34 +00001738/// Return true if the given value is known to be non-zero when defined. For
1739/// vectors, return true if every element is known to be non-zero when
1740/// defined. For pointers, if the context instruction and dominator tree are
1741/// specified, perform context-sensitive analysis and return true if the
1742/// pointer couldn't possibly be null at the specified instruction.
1743/// Supports values with integer or pointer type and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001744bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q) {
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001745 if (auto *C = dyn_cast<Constant>(V)) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001746 if (C->isNullValue())
1747 return false;
1748 if (isa<ConstantInt>(C))
1749 // Must be non-zero due to null test above.
1750 return true;
Sanjay Patel23019d12016-05-24 14:18:49 +00001751
1752 // For constant vectors, check that all elements are undefined or known
1753 // non-zero to determine that the whole vector is known non-zero.
1754 if (auto *VecTy = dyn_cast<VectorType>(C->getType())) {
1755 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
1756 Constant *Elt = C->getAggregateElement(i);
1757 if (!Elt || Elt->isNullValue())
1758 return false;
1759 if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
1760 return false;
1761 }
1762 return true;
1763 }
1764
Duncan Sandsd3951082011-01-25 09:38:29 +00001765 return false;
1766 }
1767
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001768 if (auto *I = dyn_cast<Instruction>(V)) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001769 if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001770 // If the possible ranges don't contain zero, then the value is
1771 // definitely non-zero.
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001772 if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001773 const APInt ZeroValue(Ty->getBitWidth(), 0);
1774 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
1775 return true;
1776 }
1777 }
1778 }
1779
Duncan Sandsd3951082011-01-25 09:38:29 +00001780 // The remaining tests are all recursive, so bail out if we hit the limit.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001781 if (Depth++ >= MaxDepth)
Duncan Sandsd3951082011-01-25 09:38:29 +00001782 return false;
1783
Chandler Carruth80d3e562012-12-07 02:08:58 +00001784 // Check for pointer simplifications.
1785 if (V->getType()->isPointerTy()) {
Sanjay Patel97e4b9872017-02-12 15:35:34 +00001786 if (isKnownNonNullAt(V, Q.CxtI, Q.DT))
Sanjoy Das6082c1a2016-05-07 02:08:15 +00001787 return true;
Pete Cooper35b00d52016-08-13 01:05:32 +00001788 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001789 if (isGEPKnownNonNull(GEP, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001790 return true;
1791 }
1792
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001793 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001794
1795 // X | Y != 0 if X != 0 or Y != 0.
Craig Topper9f008862014-04-15 04:59:12 +00001796 Value *X = nullptr, *Y = nullptr;
Duncan Sandsd3951082011-01-25 09:38:29 +00001797 if (match(V, m_Or(m_Value(X), m_Value(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001798 return isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001799
1800 // ext X != 0 if X != 0.
1801 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001802 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001803
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001804 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd3951082011-01-25 09:38:29 +00001805 // if the lowest bit is shifted off the end.
Craig Topper6b3940a2017-05-03 22:25:19 +00001806 if (match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001807 // shl nuw can't remove any non-zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00001808 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001809 if (BO->hasNoUnsignedWrap())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001810 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001811
Craig Topperb45eabc2017-04-26 16:39:58 +00001812 KnownBits Known(BitWidth);
1813 computeKnownBits(X, Known, Depth, Q);
1814 if (Known.One[0])
Duncan Sandsd3951082011-01-25 09:38:29 +00001815 return true;
1816 }
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001817 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd3951082011-01-25 09:38:29 +00001818 // defined if the sign bit is shifted off the end.
1819 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001820 // shr exact can only shift out zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00001821 const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001822 if (BO->isExact())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001823 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001824
Craig Topper6e11a052017-05-08 16:22:48 +00001825 KnownBits Known = computeKnownBits(X, Depth, Q);
1826 if (Known.isNegative())
Duncan Sandsd3951082011-01-25 09:38:29 +00001827 return true;
James Molloyb6be1eb2015-09-24 16:06:32 +00001828
1829 // If the shifter operand is a constant, and all of the bits shifted
1830 // out are known to be zero, and X is known non-zero then at least one
1831 // non-zero bit must remain.
1832 if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
James Molloyb6be1eb2015-09-24 16:06:32 +00001833 auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
1834 // Is there a known one in the portion not shifted out?
Craig Topper8df66c62017-05-12 17:20:30 +00001835 if (Known.countMaxLeadingZeros() < BitWidth - ShiftVal)
James Molloyb6be1eb2015-09-24 16:06:32 +00001836 return true;
1837 // Are all the bits to be shifted out known zero?
NAKAMURA Takumi76bab1f2017-07-11 02:31:51 +00001838 if (Known.countMinTrailingZeros() >= ShiftVal)
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001839 return isKnownNonZero(X, Depth, Q);
James Molloyb6be1eb2015-09-24 16:06:32 +00001840 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001841 }
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001842 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001843 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001844 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001845 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001846 // X + Y.
1847 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Craig Topper6e11a052017-05-08 16:22:48 +00001848 KnownBits XKnown = computeKnownBits(X, Depth, Q);
1849 KnownBits YKnown = computeKnownBits(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001850
1851 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001852 // zero unless both X and Y are zero.
Craig Topper6e11a052017-05-08 16:22:48 +00001853 if (XKnown.isNonNegative() && YKnown.isNonNegative())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001854 if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q))
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001855 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00001856
1857 // If X and Y are both negative (as signed values) then their sum is not
1858 // zero unless both X and Y equal INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00001859 if (XKnown.isNegative() && YKnown.isNegative()) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001860 APInt Mask = APInt::getSignedMaxValue(BitWidth);
1861 // The sign bit of X is set. If some other bit is set then X is not equal
1862 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00001863 if (XKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00001864 return true;
1865 // The sign bit of Y is set. If some other bit is set then Y is not equal
1866 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00001867 if (YKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00001868 return true;
1869 }
1870
1871 // The sum of a non-negative number and a power of two is not zero.
Craig Topper6e11a052017-05-08 16:22:48 +00001872 if (XKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001873 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001874 return true;
Craig Topper6e11a052017-05-08 16:22:48 +00001875 if (YKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001876 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001877 return true;
1878 }
Duncan Sands7cb61e52011-10-27 19:16:21 +00001879 // X * Y.
1880 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001881 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Duncan Sands7cb61e52011-10-27 19:16:21 +00001882 // If X and Y are non-zero then so is X * Y as long as the multiplication
1883 // does not overflow.
1884 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001885 isKnownNonZero(X, Depth, Q) && isKnownNonZero(Y, Depth, Q))
Duncan Sands7cb61e52011-10-27 19:16:21 +00001886 return true;
1887 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001888 // (C ? X : Y) != 0 if X != 0 and Y != 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00001889 else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001890 if (isKnownNonZero(SI->getTrueValue(), Depth, Q) &&
1891 isKnownNonZero(SI->getFalseValue(), Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001892 return true;
1893 }
James Molloy897048b2015-09-29 14:08:45 +00001894 // PHI
Pete Cooper35b00d52016-08-13 01:05:32 +00001895 else if (const PHINode *PN = dyn_cast<PHINode>(V)) {
James Molloy897048b2015-09-29 14:08:45 +00001896 // Try and detect a recurrence that monotonically increases from a
1897 // starting value, as these are common as induction variables.
1898 if (PN->getNumIncomingValues() == 2) {
1899 Value *Start = PN->getIncomingValue(0);
1900 Value *Induction = PN->getIncomingValue(1);
1901 if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start))
1902 std::swap(Start, Induction);
1903 if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) {
1904 if (!C->isZero() && !C->isNegative()) {
1905 ConstantInt *X;
1906 if ((match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) ||
1907 match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) &&
1908 !X->isNegative())
1909 return true;
1910 }
1911 }
1912 }
Jun Bum Limca832662016-02-01 17:03:07 +00001913 // Check if all incoming values are non-zero constant.
1914 bool AllNonZeroConstants = all_of(PN->operands(), [](Value *V) {
Craig Topper79ab6432017-07-06 18:39:47 +00001915 return isa<ConstantInt>(V) && !cast<ConstantInt>(V)->isZero();
Jun Bum Limca832662016-02-01 17:03:07 +00001916 });
1917 if (AllNonZeroConstants)
1918 return true;
James Molloy897048b2015-09-29 14:08:45 +00001919 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001920
Craig Topperb45eabc2017-04-26 16:39:58 +00001921 KnownBits Known(BitWidth);
1922 computeKnownBits(V, Known, Depth, Q);
1923 return Known.One != 0;
Duncan Sandsd3951082011-01-25 09:38:29 +00001924}
1925
James Molloy1d88d6f2015-10-22 13:18:42 +00001926/// Return true if V2 == V1 + X, where X is known non-zero.
Pete Cooper35b00d52016-08-13 01:05:32 +00001927static bool isAddOfNonZero(const Value *V1, const Value *V2, const Query &Q) {
1928 const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
James Molloy1d88d6f2015-10-22 13:18:42 +00001929 if (!BO || BO->getOpcode() != Instruction::Add)
1930 return false;
1931 Value *Op = nullptr;
1932 if (V2 == BO->getOperand(0))
1933 Op = BO->getOperand(1);
1934 else if (V2 == BO->getOperand(1))
1935 Op = BO->getOperand(0);
1936 else
1937 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001938 return isKnownNonZero(Op, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00001939}
1940
1941/// Return true if it is known that V1 != V2.
Pete Cooper35b00d52016-08-13 01:05:32 +00001942static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q) {
Craig Topper3002d5b2017-06-06 07:13:15 +00001943 if (V1 == V2)
James Molloy1d88d6f2015-10-22 13:18:42 +00001944 return false;
1945 if (V1->getType() != V2->getType())
1946 // We can't look through casts yet.
1947 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001948 if (isAddOfNonZero(V1, V2, Q) || isAddOfNonZero(V2, V1, Q))
James Molloy1d88d6f2015-10-22 13:18:42 +00001949 return true;
1950
Craig Topper3002d5b2017-06-06 07:13:15 +00001951 if (V1->getType()->isIntOrIntVectorTy()) {
James Molloy1d88d6f2015-10-22 13:18:42 +00001952 // Are any known bits in V1 contradictory to known bits in V2? If V1
1953 // has a known zero where V2 has a known one, they must not be equal.
Craig Topper8e662f72017-06-06 07:13:11 +00001954 KnownBits Known1 = computeKnownBits(V1, 0, Q);
1955 KnownBits Known2 = computeKnownBits(V2, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00001956
Craig Topper8365df82017-06-06 07:13:09 +00001957 if (Known1.Zero.intersects(Known2.One) ||
1958 Known2.Zero.intersects(Known1.One))
James Molloy1d88d6f2015-10-22 13:18:42 +00001959 return true;
1960 }
1961 return false;
1962}
1963
Sanjay Patelaee84212014-11-04 16:27:42 +00001964/// Return true if 'V & Mask' is known to be zero. We use this predicate to
1965/// simplify operations downstream. Mask is known to be zero for bits that V
1966/// cannot have.
Chris Lattner4bc28252009-09-08 00:06:16 +00001967///
1968/// This function is defined on values with integer type, values with pointer
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001969/// type, and vectors of integers. In the case
Chris Lattner4bc28252009-09-08 00:06:16 +00001970/// where V is a vector, the mask, known zero, and known one values are the
1971/// same width as the vector element, and the bit is set only if it is true
1972/// for all of the elements in the vector.
Pete Cooper35b00d52016-08-13 01:05:32 +00001973bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001974 const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001975 KnownBits Known(Mask.getBitWidth());
1976 computeKnownBits(V, Known, Depth, Q);
1977 return Mask.isSubsetOf(Known.Zero);
Chris Lattner965c7692008-06-02 01:18:21 +00001978}
1979
Sanjay Patela06d9892016-06-22 19:20:59 +00001980/// For vector constants, loop over the elements and find the constant with the
1981/// minimum number of sign bits. Return 0 if the value is not a vector constant
1982/// or if any element was not analyzed; otherwise, return the count for the
1983/// element with the minimum number of sign bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00001984static unsigned computeNumSignBitsVectorConstant(const Value *V,
1985 unsigned TyBits) {
1986 const auto *CV = dyn_cast<Constant>(V);
Sanjay Patela06d9892016-06-22 19:20:59 +00001987 if (!CV || !CV->getType()->isVectorTy())
1988 return 0;
Chris Lattner965c7692008-06-02 01:18:21 +00001989
Sanjay Patela06d9892016-06-22 19:20:59 +00001990 unsigned MinSignBits = TyBits;
1991 unsigned NumElts = CV->getType()->getVectorNumElements();
1992 for (unsigned i = 0; i != NumElts; ++i) {
1993 // If we find a non-ConstantInt, bail out.
1994 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
1995 if (!Elt)
1996 return 0;
1997
1998 // If the sign bit is 1, flip the bits, so we always count leading zeros.
1999 APInt EltVal = Elt->getValue();
2000 if (EltVal.isNegative())
2001 EltVal = ~EltVal;
2002 MinSignBits = std::min(MinSignBits, EltVal.countLeadingZeros());
2003 }
2004
2005 return MinSignBits;
2006}
Chris Lattner965c7692008-06-02 01:18:21 +00002007
Sanjoy Das39a684d2017-02-25 20:30:45 +00002008static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2009 const Query &Q);
2010
2011static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
2012 const Query &Q) {
2013 unsigned Result = ComputeNumSignBitsImpl(V, Depth, Q);
2014 assert(Result > 0 && "At least one sign bit needs to be present!");
2015 return Result;
2016}
2017
Sanjay Patelaee84212014-11-04 16:27:42 +00002018/// Return the number of times the sign bit of the register is replicated into
2019/// the other bits. We know that at least 1 bit is always equal to the sign bit
2020/// (itself), but other cases can give us information. For example, immediately
2021/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
Sanjay Patela06d9892016-06-22 19:20:59 +00002022/// other, so we return 3. For vectors, return the number of sign bits for the
2023/// vector element with the mininum number of known sign bits.
Sanjoy Das39a684d2017-02-25 20:30:45 +00002024static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2025 const Query &Q) {
Craig Topper7227eba2017-08-21 22:56:12 +00002026 assert(Depth <= MaxDepth && "Limit Search Depth");
Sanjoy Das39a684d2017-02-25 20:30:45 +00002027
2028 // We return the minimum number of sign bits that are guaranteed to be present
2029 // in V, so for undef we have to conservatively return 1. We don't have the
2030 // same behavior for poison though -- that's a FIXME today.
2031
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002032 unsigned TyBits = Q.DL.getTypeSizeInBits(V->getType()->getScalarType());
Chris Lattner965c7692008-06-02 01:18:21 +00002033 unsigned Tmp, Tmp2;
2034 unsigned FirstAnswer = 1;
2035
Jay Foada0653a32014-05-14 21:14:37 +00002036 // Note that ConstantInt is handled by the general computeKnownBits case
Chris Lattner2e01a692008-06-02 18:39:07 +00002037 // below.
2038
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002039 if (Depth == MaxDepth)
Chris Lattner965c7692008-06-02 01:18:21 +00002040 return 1; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002041
Pete Cooper35b00d52016-08-13 01:05:32 +00002042 const Operator *U = dyn_cast<Operator>(V);
Dan Gohman80ca01c2009-07-17 20:47:02 +00002043 switch (Operator::getOpcode(V)) {
Chris Lattner965c7692008-06-02 01:18:21 +00002044 default: break;
2045 case Instruction::SExt:
Mon P Wangbb3eac92009-12-02 04:59:58 +00002046 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002047 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
Craig Topper1bef2c82012-12-22 19:15:35 +00002048
Nadav Rotemc99a3872015-03-06 00:23:58 +00002049 case Instruction::SDiv: {
Nadav Rotem029c5c72015-03-03 21:39:02 +00002050 const APInt *Denominator;
2051 // sdiv X, C -> adds log(C) sign bits.
2052 if (match(U->getOperand(1), m_APInt(Denominator))) {
2053
2054 // Ignore non-positive denominator.
2055 if (!Denominator->isStrictlyPositive())
2056 break;
2057
2058 // Calculate the incoming numerator bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002059 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotem029c5c72015-03-03 21:39:02 +00002060
2061 // Add floor(log(C)) bits to the numerator bits.
2062 return std::min(TyBits, NumBits + Denominator->logBase2());
2063 }
2064 break;
Nadav Rotemc99a3872015-03-06 00:23:58 +00002065 }
2066
2067 case Instruction::SRem: {
2068 const APInt *Denominator;
Sanjoy Dase561fee2015-03-25 22:33:53 +00002069 // srem X, C -> we know that the result is within [-C+1,C) when C is a
2070 // positive constant. This let us put a lower bound on the number of sign
2071 // bits.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002072 if (match(U->getOperand(1), m_APInt(Denominator))) {
2073
2074 // Ignore non-positive denominator.
2075 if (!Denominator->isStrictlyPositive())
2076 break;
2077
2078 // Calculate the incoming numerator bits. SRem by a positive constant
2079 // can't lower the number of sign bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002080 unsigned NumrBits =
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002081 ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotemc99a3872015-03-06 00:23:58 +00002082
2083 // Calculate the leading sign bit constraints by examining the
Sanjoy Dase561fee2015-03-25 22:33:53 +00002084 // denominator. Given that the denominator is positive, there are two
2085 // cases:
2086 //
2087 // 1. the numerator is positive. The result range is [0,C) and [0,C) u<
2088 // (1 << ceilLogBase2(C)).
2089 //
2090 // 2. the numerator is negative. Then the result range is (-C,0] and
2091 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2092 //
2093 // Thus a lower bound on the number of sign bits is `TyBits -
2094 // ceilLogBase2(C)`.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002095
Sanjoy Dase561fee2015-03-25 22:33:53 +00002096 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
Nadav Rotemc99a3872015-03-06 00:23:58 +00002097 return std::max(NumrBits, ResBits);
2098 }
2099 break;
2100 }
Nadav Rotem029c5c72015-03-03 21:39:02 +00002101
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002102 case Instruction::AShr: {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002103 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002104 // ashr X, C -> adds C sign bits. Vectors too.
2105 const APInt *ShAmt;
2106 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Sanjoy Das39a684d2017-02-25 20:30:45 +00002107 unsigned ShAmtLimited = ShAmt->getZExtValue();
2108 if (ShAmtLimited >= TyBits)
2109 break; // Bad shift.
2110 Tmp += ShAmtLimited;
Chris Lattner965c7692008-06-02 01:18:21 +00002111 if (Tmp > TyBits) Tmp = TyBits;
2112 }
2113 return Tmp;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002114 }
2115 case Instruction::Shl: {
2116 const APInt *ShAmt;
2117 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner965c7692008-06-02 01:18:21 +00002118 // shl destroys sign bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002119 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002120 Tmp2 = ShAmt->getZExtValue();
2121 if (Tmp2 >= TyBits || // Bad shift.
2122 Tmp2 >= Tmp) break; // Shifted all sign bits out.
2123 return Tmp - Tmp2;
Chris Lattner965c7692008-06-02 01:18:21 +00002124 }
2125 break;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002126 }
Chris Lattner965c7692008-06-02 01:18:21 +00002127 case Instruction::And:
2128 case Instruction::Or:
2129 case Instruction::Xor: // NOT is handled here.
2130 // Logical binary ops preserve the number of sign bits at the worst.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002131 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002132 if (Tmp != 1) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002133 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002134 FirstAnswer = std::min(Tmp, Tmp2);
2135 // We computed what we know about the sign bits as our first
2136 // answer. Now proceed to the generic code that uses
Jay Foada0653a32014-05-14 21:14:37 +00002137 // computeKnownBits, and pick whichever answer is better.
Chris Lattner965c7692008-06-02 01:18:21 +00002138 }
2139 break;
2140
2141 case Instruction::Select:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002142 Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002143 if (Tmp == 1) return 1; // Early out.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002144 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002145 return std::min(Tmp, Tmp2);
Craig Topper1bef2c82012-12-22 19:15:35 +00002146
Chris Lattner965c7692008-06-02 01:18:21 +00002147 case Instruction::Add:
2148 // Add can have at most one carry bit. Thus we know that the output
2149 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002150 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002151 if (Tmp == 1) return 1; // Early out.
Craig Topper1bef2c82012-12-22 19:15:35 +00002152
Chris Lattner965c7692008-06-02 01:18:21 +00002153 // Special case decrementing a value (ADD X, -1):
David Majnemera55027f2014-12-26 09:20:17 +00002154 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
Chris Lattner965c7692008-06-02 01:18:21 +00002155 if (CRHS->isAllOnesValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002156 KnownBits Known(TyBits);
2157 computeKnownBits(U->getOperand(0), Known, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002158
Chris Lattner965c7692008-06-02 01:18:21 +00002159 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2160 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002161 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002162 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002163
Chris Lattner965c7692008-06-02 01:18:21 +00002164 // If we are subtracting one from a positive number, there is no carry
2165 // out of the result.
Craig Topperca48af32017-04-29 16:43:11 +00002166 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002167 return Tmp;
2168 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002169
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002170 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002171 if (Tmp2 == 1) return 1;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002172 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002173
Chris Lattner965c7692008-06-02 01:18:21 +00002174 case Instruction::Sub:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002175 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002176 if (Tmp2 == 1) return 1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002177
Chris Lattner965c7692008-06-02 01:18:21 +00002178 // Handle NEG.
David Majnemera55027f2014-12-26 09:20:17 +00002179 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
Chris Lattner965c7692008-06-02 01:18:21 +00002180 if (CLHS->isNullValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002181 KnownBits Known(TyBits);
2182 computeKnownBits(U->getOperand(1), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002183 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2184 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002185 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002186 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002187
Chris Lattner965c7692008-06-02 01:18:21 +00002188 // If the input is known to be positive (the sign bit is known clear),
2189 // the output of the NEG has the same number of sign bits as the input.
Craig Topperca48af32017-04-29 16:43:11 +00002190 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002191 return Tmp2;
Craig Topper1bef2c82012-12-22 19:15:35 +00002192
Chris Lattner965c7692008-06-02 01:18:21 +00002193 // Otherwise, we treat this like a SUB.
2194 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002195
Chris Lattner965c7692008-06-02 01:18:21 +00002196 // Sub can have at most one carry bit. Thus we know that the output
2197 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002198 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002199 if (Tmp == 1) return 1; // Early out.
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002200 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002201
Amjad Aboud88ffa3a2017-08-18 22:56:55 +00002202 case Instruction::Mul: {
2203 // The output of the Mul can be at most twice the valid bits in the inputs.
2204 unsigned SignBitsOp0 = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2205 if (SignBitsOp0 == 1) return 1; // Early out.
2206 unsigned SignBitsOp1 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2207 if (SignBitsOp1 == 1) return 1;
2208 unsigned OutValidBits =
2209 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
2210 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
2211 }
2212
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002213 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00002214 const PHINode *PN = cast<PHINode>(U);
David Majnemer6ee8d172015-01-04 07:06:53 +00002215 unsigned NumIncomingValues = PN->getNumIncomingValues();
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002216 // Don't analyze large in-degree PHIs.
David Majnemer6ee8d172015-01-04 07:06:53 +00002217 if (NumIncomingValues > 4) break;
2218 // Unreachable blocks may have zero-operand PHI nodes.
2219 if (NumIncomingValues == 0) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002220
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002221 // Take the minimum of all incoming values. This can't infinitely loop
2222 // because of our depth threshold.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002223 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), Depth + 1, Q);
David Majnemer6ee8d172015-01-04 07:06:53 +00002224 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002225 if (Tmp == 1) return Tmp;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002226 Tmp = std::min(
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002227 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, Q));
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002228 }
2229 return Tmp;
2230 }
2231
Chris Lattner965c7692008-06-02 01:18:21 +00002232 case Instruction::Trunc:
2233 // FIXME: it's tricky to do anything useful for this, but it is an important
2234 // case for targets like X86.
2235 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00002236
2237 case Instruction::ExtractElement:
2238 // Look through extract element. At the moment we keep this simple and skip
2239 // tracking the specific element. But at least we might find information
2240 // valid for all elements of the vector (for example if vector is sign
2241 // extended, shifted, etc).
2242 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002243 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002244
Chris Lattner965c7692008-06-02 01:18:21 +00002245 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2246 // use this information.
Sanjay Patela06d9892016-06-22 19:20:59 +00002247
2248 // If we can examine all elements of a vector constant successfully, we're
2249 // done (we can't do any better than that). If not, keep trying.
2250 if (unsigned VecSignBits = computeNumSignBitsVectorConstant(V, TyBits))
2251 return VecSignBits;
2252
Craig Topperb45eabc2017-04-26 16:39:58 +00002253 KnownBits Known(TyBits);
2254 computeKnownBits(V, Known, Depth, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002255
Sanjay Patele0536212016-06-23 17:41:59 +00002256 // If we know that the sign bit is either zero or one, determine the number of
2257 // identical bits in the top of the input value.
Craig Topper8df66c62017-05-12 17:20:30 +00002258 return std::max(FirstAnswer, Known.countMinSignBits());
Chris Lattner965c7692008-06-02 01:18:21 +00002259}
Chris Lattnera12a6de2008-06-02 01:29:46 +00002260
Sanjay Patelaee84212014-11-04 16:27:42 +00002261/// This function computes the integer multiple of Base that equals V.
2262/// If successful, it returns true and returns the multiple in
2263/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez47444882009-11-10 08:28:35 +00002264/// through SExt instructions only if LookThroughSExt is true.
2265bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman6a976bb2009-11-18 00:58:27 +00002266 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez47444882009-11-10 08:28:35 +00002267 const unsigned MaxDepth = 6;
2268
Dan Gohman6a976bb2009-11-18 00:58:27 +00002269 assert(V && "No Value?");
Victor Hernandez47444882009-11-10 08:28:35 +00002270 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002271 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez47444882009-11-10 08:28:35 +00002272
Chris Lattner229907c2011-07-18 04:54:35 +00002273 Type *T = V->getType();
Victor Hernandez47444882009-11-10 08:28:35 +00002274
Dan Gohman6a976bb2009-11-18 00:58:27 +00002275 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez47444882009-11-10 08:28:35 +00002276
2277 if (Base == 0)
2278 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002279
Victor Hernandez47444882009-11-10 08:28:35 +00002280 if (Base == 1) {
2281 Multiple = V;
2282 return true;
2283 }
2284
2285 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2286 Constant *BaseVal = ConstantInt::get(T, Base);
2287 if (CO && CO == BaseVal) {
2288 // Multiple is 1.
2289 Multiple = ConstantInt::get(T, 1);
2290 return true;
2291 }
2292
2293 if (CI && CI->getZExtValue() % Base == 0) {
2294 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
Craig Topper1bef2c82012-12-22 19:15:35 +00002295 return true;
Victor Hernandez47444882009-11-10 08:28:35 +00002296 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002297
Victor Hernandez47444882009-11-10 08:28:35 +00002298 if (Depth == MaxDepth) return false; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002299
Victor Hernandez47444882009-11-10 08:28:35 +00002300 Operator *I = dyn_cast<Operator>(V);
2301 if (!I) return false;
2302
2303 switch (I->getOpcode()) {
2304 default: break;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002305 case Instruction::SExt:
Victor Hernandez47444882009-11-10 08:28:35 +00002306 if (!LookThroughSExt) return false;
2307 // otherwise fall through to ZExt
Galina Kistanova244621f2017-05-31 22:16:24 +00002308 LLVM_FALLTHROUGH;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002309 case Instruction::ZExt:
Dan Gohman6a976bb2009-11-18 00:58:27 +00002310 return ComputeMultiple(I->getOperand(0), Base, Multiple,
2311 LookThroughSExt, Depth+1);
Victor Hernandez47444882009-11-10 08:28:35 +00002312 case Instruction::Shl:
2313 case Instruction::Mul: {
2314 Value *Op0 = I->getOperand(0);
2315 Value *Op1 = I->getOperand(1);
2316
2317 if (I->getOpcode() == Instruction::Shl) {
2318 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2319 if (!Op1CI) return false;
2320 // Turn Op0 << Op1 into Op0 * 2^Op1
2321 APInt Op1Int = Op1CI->getValue();
2322 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foad15084f02010-11-30 09:02:01 +00002323 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002324 API.setBit(BitToSet);
Jay Foad15084f02010-11-30 09:02:01 +00002325 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez47444882009-11-10 08:28:35 +00002326 }
2327
Craig Topper9f008862014-04-15 04:59:12 +00002328 Value *Mul0 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002329 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2330 if (Constant *Op1C = dyn_cast<Constant>(Op1))
2331 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002332 if (Op1C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002333 MulC->getType()->getPrimitiveSizeInBits())
2334 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002335 if (Op1C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002336 MulC->getType()->getPrimitiveSizeInBits())
2337 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002338
Chris Lattner72d283c2010-09-05 17:20:46 +00002339 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2340 Multiple = ConstantExpr::getMul(MulC, Op1C);
2341 return true;
2342 }
Victor Hernandez47444882009-11-10 08:28:35 +00002343
2344 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2345 if (Mul0CI->getValue() == 1) {
2346 // V == Base * Op1, so return Op1
2347 Multiple = Op1;
2348 return true;
2349 }
2350 }
2351
Craig Topper9f008862014-04-15 04:59:12 +00002352 Value *Mul1 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002353 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2354 if (Constant *Op0C = dyn_cast<Constant>(Op0))
2355 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002356 if (Op0C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002357 MulC->getType()->getPrimitiveSizeInBits())
2358 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002359 if (Op0C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002360 MulC->getType()->getPrimitiveSizeInBits())
2361 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002362
Chris Lattner72d283c2010-09-05 17:20:46 +00002363 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2364 Multiple = ConstantExpr::getMul(MulC, Op0C);
2365 return true;
2366 }
Victor Hernandez47444882009-11-10 08:28:35 +00002367
2368 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2369 if (Mul1CI->getValue() == 1) {
2370 // V == Base * Op0, so return Op0
2371 Multiple = Op0;
2372 return true;
2373 }
2374 }
Victor Hernandez47444882009-11-10 08:28:35 +00002375 }
2376 }
2377
2378 // We could not determine if V is a multiple of Base.
2379 return false;
2380}
2381
David Majnemerb4b27232016-04-19 19:10:21 +00002382Intrinsic::ID llvm::getIntrinsicForCallSite(ImmutableCallSite ICS,
2383 const TargetLibraryInfo *TLI) {
2384 const Function *F = ICS.getCalledFunction();
2385 if (!F)
2386 return Intrinsic::not_intrinsic;
2387
2388 if (F->isIntrinsic())
2389 return F->getIntrinsicID();
2390
2391 if (!TLI)
2392 return Intrinsic::not_intrinsic;
2393
David L. Jonesd21529f2017-01-23 23:16:46 +00002394 LibFunc Func;
David Majnemerb4b27232016-04-19 19:10:21 +00002395 // We're going to make assumptions on the semantics of the functions, check
2396 // that the target knows that it's available in this environment and it does
2397 // not have local linkage.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002398 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(*F, Func))
2399 return Intrinsic::not_intrinsic;
2400
2401 if (!ICS.onlyReadsMemory())
David Majnemerb4b27232016-04-19 19:10:21 +00002402 return Intrinsic::not_intrinsic;
2403
2404 // Otherwise check if we have a call to a function that can be turned into a
2405 // vector intrinsic.
2406 switch (Func) {
2407 default:
2408 break;
David L. Jonesd21529f2017-01-23 23:16:46 +00002409 case LibFunc_sin:
2410 case LibFunc_sinf:
2411 case LibFunc_sinl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002412 return Intrinsic::sin;
David L. Jonesd21529f2017-01-23 23:16:46 +00002413 case LibFunc_cos:
2414 case LibFunc_cosf:
2415 case LibFunc_cosl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002416 return Intrinsic::cos;
David L. Jonesd21529f2017-01-23 23:16:46 +00002417 case LibFunc_exp:
2418 case LibFunc_expf:
2419 case LibFunc_expl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002420 return Intrinsic::exp;
David L. Jonesd21529f2017-01-23 23:16:46 +00002421 case LibFunc_exp2:
2422 case LibFunc_exp2f:
2423 case LibFunc_exp2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002424 return Intrinsic::exp2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002425 case LibFunc_log:
2426 case LibFunc_logf:
2427 case LibFunc_logl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002428 return Intrinsic::log;
David L. Jonesd21529f2017-01-23 23:16:46 +00002429 case LibFunc_log10:
2430 case LibFunc_log10f:
2431 case LibFunc_log10l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002432 return Intrinsic::log10;
David L. Jonesd21529f2017-01-23 23:16:46 +00002433 case LibFunc_log2:
2434 case LibFunc_log2f:
2435 case LibFunc_log2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002436 return Intrinsic::log2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002437 case LibFunc_fabs:
2438 case LibFunc_fabsf:
2439 case LibFunc_fabsl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002440 return Intrinsic::fabs;
David L. Jonesd21529f2017-01-23 23:16:46 +00002441 case LibFunc_fmin:
2442 case LibFunc_fminf:
2443 case LibFunc_fminl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002444 return Intrinsic::minnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002445 case LibFunc_fmax:
2446 case LibFunc_fmaxf:
2447 case LibFunc_fmaxl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002448 return Intrinsic::maxnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002449 case LibFunc_copysign:
2450 case LibFunc_copysignf:
2451 case LibFunc_copysignl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002452 return Intrinsic::copysign;
David L. Jonesd21529f2017-01-23 23:16:46 +00002453 case LibFunc_floor:
2454 case LibFunc_floorf:
2455 case LibFunc_floorl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002456 return Intrinsic::floor;
David L. Jonesd21529f2017-01-23 23:16:46 +00002457 case LibFunc_ceil:
2458 case LibFunc_ceilf:
2459 case LibFunc_ceill:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002460 return Intrinsic::ceil;
David L. Jonesd21529f2017-01-23 23:16:46 +00002461 case LibFunc_trunc:
2462 case LibFunc_truncf:
2463 case LibFunc_truncl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002464 return Intrinsic::trunc;
David L. Jonesd21529f2017-01-23 23:16:46 +00002465 case LibFunc_rint:
2466 case LibFunc_rintf:
2467 case LibFunc_rintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002468 return Intrinsic::rint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002469 case LibFunc_nearbyint:
2470 case LibFunc_nearbyintf:
2471 case LibFunc_nearbyintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002472 return Intrinsic::nearbyint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002473 case LibFunc_round:
2474 case LibFunc_roundf:
2475 case LibFunc_roundl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002476 return Intrinsic::round;
David L. Jonesd21529f2017-01-23 23:16:46 +00002477 case LibFunc_pow:
2478 case LibFunc_powf:
2479 case LibFunc_powl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002480 return Intrinsic::pow;
David L. Jonesd21529f2017-01-23 23:16:46 +00002481 case LibFunc_sqrt:
2482 case LibFunc_sqrtf:
2483 case LibFunc_sqrtl:
David Majnemerb4b27232016-04-19 19:10:21 +00002484 if (ICS->hasNoNaNs())
Ahmed Bougachad765a822016-04-27 19:04:35 +00002485 return Intrinsic::sqrt;
David Majnemerb4b27232016-04-19 19:10:21 +00002486 return Intrinsic::not_intrinsic;
2487 }
2488
2489 return Intrinsic::not_intrinsic;
2490}
2491
Sanjay Patelaee84212014-11-04 16:27:42 +00002492/// Return true if we can prove that the specified FP value is never equal to
2493/// -0.0.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002494///
2495/// NOTE: this function will need to be revisited when we support non-default
2496/// rounding modes!
2497///
David Majnemer3ee5f342016-04-13 06:55:52 +00002498bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
2499 unsigned Depth) {
Chris Lattnera12a6de2008-06-02 01:29:46 +00002500 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2501 return !CFP->getValueAPF().isNegZero();
Craig Topper1bef2c82012-12-22 19:15:35 +00002502
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002503 if (Depth == MaxDepth)
Sanjay Patel40eaa8d2015-02-25 18:00:15 +00002504 return false; // Limit search depth.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002505
Dan Gohman80ca01c2009-07-17 20:47:02 +00002506 const Operator *I = dyn_cast<Operator>(V);
Craig Topper9f008862014-04-15 04:59:12 +00002507 if (!I) return false;
Michael Ilseman0f128372012-12-06 00:07:09 +00002508
2509 // Check if the nsz fast-math flag is set
2510 if (const FPMathOperator *FPO = dyn_cast<FPMathOperator>(I))
2511 if (FPO->hasNoSignedZeros())
2512 return true;
2513
Chris Lattnera12a6de2008-06-02 01:29:46 +00002514 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Jakub Staszakb7129f22013-03-06 00:16:16 +00002515 if (I->getOpcode() == Instruction::FAdd)
2516 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(1)))
2517 if (CFP->isNullValue())
2518 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002519
Chris Lattnera12a6de2008-06-02 01:29:46 +00002520 // sitofp and uitofp turn into +0.0 for zero.
2521 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2522 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002523
David Majnemer3ee5f342016-04-13 06:55:52 +00002524 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
David Majnemerb4b27232016-04-19 19:10:21 +00002525 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002526 switch (IID) {
2527 default:
2528 break;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002529 // sqrt(-0.0) = -0.0, no other negative results are possible.
David Majnemer3ee5f342016-04-13 06:55:52 +00002530 case Intrinsic::sqrt:
2531 return CannotBeNegativeZero(CI->getArgOperand(0), TLI, Depth + 1);
2532 // fabs(x) != -0.0
2533 case Intrinsic::fabs:
2534 return true;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002535 }
David Majnemer3ee5f342016-04-13 06:55:52 +00002536 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002537
Chris Lattnera12a6de2008-06-02 01:29:46 +00002538 return false;
2539}
2540
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002541/// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
2542/// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
2543/// bit despite comparing equal.
2544static bool cannotBeOrderedLessThanZeroImpl(const Value *V,
2545 const TargetLibraryInfo *TLI,
2546 bool SignBitOnly,
2547 unsigned Depth) {
Justin Lebar322c1272017-01-27 00:58:34 +00002548 // TODO: This function does not do the right thing when SignBitOnly is true
2549 // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform
2550 // which flips the sign bits of NaNs. See
2551 // https://llvm.org/bugs/show_bug.cgi?id=31702.
2552
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002553 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2554 return !CFP->getValueAPF().isNegative() ||
2555 (!SignBitOnly && CFP->getValueAPF().isZero());
2556 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002557
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002558 if (Depth == MaxDepth)
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002559 return false; // Limit search depth.
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002560
2561 const Operator *I = dyn_cast<Operator>(V);
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002562 if (!I)
2563 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002564
2565 switch (I->getOpcode()) {
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002566 default:
2567 break;
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002568 // Unsigned integers are always nonnegative.
2569 case Instruction::UIToFP:
2570 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002571 case Instruction::FMul:
2572 // x*x is always non-negative or a NaN.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002573 if (I->getOperand(0) == I->getOperand(1) &&
2574 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002575 return true;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002576
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002577 LLVM_FALLTHROUGH;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002578 case Instruction::FAdd:
2579 case Instruction::FDiv:
2580 case Instruction::FRem:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002581 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2582 Depth + 1) &&
2583 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2584 Depth + 1);
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002585 case Instruction::Select:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002586 return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2587 Depth + 1) &&
2588 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2589 Depth + 1);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002590 case Instruction::FPExt:
2591 case Instruction::FPTrunc:
2592 // Widening/narrowing never change sign.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002593 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2594 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002595 case Instruction::Call:
Justin Lebar7e3184c2017-01-26 00:10:26 +00002596 const auto *CI = cast<CallInst>(I);
2597 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002598 switch (IID) {
2599 default:
2600 break;
2601 case Intrinsic::maxnum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002602 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2603 Depth + 1) ||
2604 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2605 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002606 case Intrinsic::minnum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002607 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2608 Depth + 1) &&
2609 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2610 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002611 case Intrinsic::exp:
2612 case Intrinsic::exp2:
2613 case Intrinsic::fabs:
David Majnemer3ee5f342016-04-13 06:55:52 +00002614 return true;
Justin Lebar7e3184c2017-01-26 00:10:26 +00002615
2616 case Intrinsic::sqrt:
2617 // sqrt(x) is always >= -0 or NaN. Moreover, sqrt(x) == -0 iff x == -0.
2618 if (!SignBitOnly)
2619 return true;
2620 return CI->hasNoNaNs() && (CI->hasNoSignedZeros() ||
2621 CannotBeNegativeZero(CI->getOperand(0), TLI));
2622
David Majnemer3ee5f342016-04-13 06:55:52 +00002623 case Intrinsic::powi:
Justin Lebar7e3184c2017-01-26 00:10:26 +00002624 if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) {
David Majnemer3ee5f342016-04-13 06:55:52 +00002625 // powi(x,n) is non-negative if n is even.
Justin Lebar7e3184c2017-01-26 00:10:26 +00002626 if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0)
David Majnemer3ee5f342016-04-13 06:55:52 +00002627 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002628 }
Justin Lebar322c1272017-01-27 00:58:34 +00002629 // TODO: This is not correct. Given that exp is an integer, here are the
2630 // ways that pow can return a negative value:
2631 //
2632 // pow(x, exp) --> negative if exp is odd and x is negative.
2633 // pow(-0, exp) --> -inf if exp is negative odd.
2634 // pow(-0, exp) --> -0 if exp is positive odd.
2635 // pow(-inf, exp) --> -0 if exp is negative odd.
2636 // pow(-inf, exp) --> -inf if exp is positive odd.
2637 //
2638 // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN,
2639 // but we must return false if x == -0. Unfortunately we do not currently
2640 // have a way of expressing this constraint. See details in
2641 // https://llvm.org/bugs/show_bug.cgi?id=31702.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002642 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2643 Depth + 1);
Justin Lebar322c1272017-01-27 00:58:34 +00002644
David Majnemer3ee5f342016-04-13 06:55:52 +00002645 case Intrinsic::fma:
2646 case Intrinsic::fmuladd:
2647 // x*x+y is non-negative if y is non-negative.
2648 return I->getOperand(0) == I->getOperand(1) &&
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002649 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
2650 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2651 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002652 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002653 break;
2654 }
Sanjoy Das6082c1a2016-05-07 02:08:15 +00002655 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002656}
2657
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002658bool llvm::CannotBeOrderedLessThanZero(const Value *V,
2659 const TargetLibraryInfo *TLI) {
2660 return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0);
2661}
2662
2663bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) {
2664 return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0);
2665}
2666
Sanjay Patelaee84212014-11-04 16:27:42 +00002667/// If the specified value can be set by repeating the same byte in memory,
2668/// return the i8 value that it is represented with. This is
Chris Lattner9cb10352010-12-26 20:15:01 +00002669/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2670/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
2671/// byte store (e.g. i16 0x1234), return null.
2672Value *llvm::isBytewiseValue(Value *V) {
2673 // All byte-wide stores are splatable, even of arbitrary variables.
2674 if (V->getType()->isIntegerTy(8)) return V;
Chris Lattneracf6b072011-02-19 19:35:49 +00002675
2676 // Handle 'null' ConstantArrayZero etc.
2677 if (Constant *C = dyn_cast<Constant>(V))
2678 if (C->isNullValue())
2679 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
Craig Topper1bef2c82012-12-22 19:15:35 +00002680
Chris Lattner9cb10352010-12-26 20:15:01 +00002681 // Constant float and double values can be handled as integer values if the
Craig Topper1bef2c82012-12-22 19:15:35 +00002682 // corresponding integer value is "byteable". An important case is 0.0.
Chris Lattner9cb10352010-12-26 20:15:01 +00002683 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2684 if (CFP->getType()->isFloatTy())
2685 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2686 if (CFP->getType()->isDoubleTy())
2687 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2688 // Don't handle long double formats, which have strange constraints.
2689 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002690
Benjamin Kramer17d90152015-02-07 19:29:02 +00002691 // We can handle constant integers that are multiple of 8 bits.
Chris Lattner9cb10352010-12-26 20:15:01 +00002692 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Benjamin Kramer17d90152015-02-07 19:29:02 +00002693 if (CI->getBitWidth() % 8 == 0) {
2694 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
Craig Topper1bef2c82012-12-22 19:15:35 +00002695
Benjamin Kramerb4b51502015-03-25 16:49:59 +00002696 if (!CI->getValue().isSplat(8))
Benjamin Kramer17d90152015-02-07 19:29:02 +00002697 return nullptr;
2698 return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
Chris Lattner9cb10352010-12-26 20:15:01 +00002699 }
2700 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002701
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002702 // A ConstantDataArray/Vector is splatable if all its members are equal and
2703 // also splatable.
2704 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2705 Value *Elt = CA->getElementAsConstant(0);
2706 Value *Val = isBytewiseValue(Elt);
Chris Lattner9cb10352010-12-26 20:15:01 +00002707 if (!Val)
Craig Topper9f008862014-04-15 04:59:12 +00002708 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002709
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002710 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2711 if (CA->getElementAsConstant(I) != Elt)
Craig Topper9f008862014-04-15 04:59:12 +00002712 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002713
Chris Lattner9cb10352010-12-26 20:15:01 +00002714 return Val;
2715 }
Chad Rosier8abf65a2011-12-06 00:19:08 +00002716
Chris Lattner9cb10352010-12-26 20:15:01 +00002717 // Conceptually, we could handle things like:
2718 // %a = zext i8 %X to i16
2719 // %b = shl i16 %a, 8
2720 // %c = or i16 %a, %b
2721 // but until there is an example that actually needs this, it doesn't seem
2722 // worth worrying about.
Craig Topper9f008862014-04-15 04:59:12 +00002723 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00002724}
2725
2726
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002727// This is the recursive version of BuildSubAggregate. It takes a few different
2728// arguments. Idxs is the index within the nested struct From that we are
2729// looking at now (which is of type IndexedType). IdxSkip is the number of
2730// indices from Idxs that should be left out when inserting into the resulting
2731// struct. To is the result struct built so far, new insertvalue instructions
2732// build on that.
Chris Lattner229907c2011-07-18 04:54:35 +00002733static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Craig Topper2cd5ff82013-07-11 16:22:38 +00002734 SmallVectorImpl<unsigned> &Idxs,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002735 unsigned IdxSkip,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002736 Instruction *InsertBefore) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +00002737 llvm::StructType *STy = dyn_cast<llvm::StructType>(IndexedType);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002738 if (STy) {
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002739 // Save the original To argument so we can modify it
2740 Value *OrigTo = To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002741 // General case, the type indexed by Idxs is a struct
2742 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2743 // Process each struct element recursively
2744 Idxs.push_back(i);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002745 Value *PrevTo = To;
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002746 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002747 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002748 Idxs.pop_back();
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002749 if (!To) {
2750 // Couldn't find any inserted value for this index? Cleanup
2751 while (PrevTo != OrigTo) {
2752 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
2753 PrevTo = Del->getAggregateOperand();
2754 Del->eraseFromParent();
2755 }
2756 // Stop processing elements
2757 break;
2758 }
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002759 }
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002760 // If we successfully found a value for each of our subaggregates
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002761 if (To)
2762 return To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002763 }
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002764 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
2765 // the struct's elements had a value that was inserted directly. In the latter
2766 // case, perhaps we can't determine each of the subelements individually, but
2767 // we might be able to find the complete struct somewhere.
Craig Topper1bef2c82012-12-22 19:15:35 +00002768
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002769 // Find the value that is at that particular spot
Jay Foad57aa6362011-07-13 10:26:04 +00002770 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002771
2772 if (!V)
Craig Topper9f008862014-04-15 04:59:12 +00002773 return nullptr;
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002774
2775 // Insert the value in the new (sub) aggregrate
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002776 return llvm::InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
Jay Foad57aa6362011-07-13 10:26:04 +00002777 "tmp", InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002778}
2779
2780// This helper takes a nested struct and extracts a part of it (which is again a
2781// struct) into a new value. For example, given the struct:
2782// { a, { b, { c, d }, e } }
2783// and the indices "1, 1" this returns
2784// { c, d }.
2785//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002786// It does this by inserting an insertvalue for each element in the resulting
2787// struct, as opposed to just inserting a single struct. This will only work if
2788// each of the elements of the substruct are known (ie, inserted into From by an
2789// insertvalue instruction somewhere).
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002790//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002791// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foad57aa6362011-07-13 10:26:04 +00002792static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002793 Instruction *InsertBefore) {
Matthijs Kooijman69801d42008-06-16 13:28:31 +00002794 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattner229907c2011-07-18 04:54:35 +00002795 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foad57aa6362011-07-13 10:26:04 +00002796 idx_range);
Owen Andersonb292b8c2009-07-30 23:03:37 +00002797 Value *To = UndefValue::get(IndexedType);
Jay Foad57aa6362011-07-13 10:26:04 +00002798 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002799 unsigned IdxSkip = Idxs.size();
2800
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002801 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002802}
2803
Sanjay Patelaee84212014-11-04 16:27:42 +00002804/// Given an aggregrate and an sequence of indices, see if
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002805/// the scalar value indexed is already around as a register, for example if it
2806/// were inserted directly into the aggregrate.
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002807///
2808/// If InsertBefore is not null, this function will duplicate (modified)
2809/// insertvalues when a part of a nested struct is extracted.
Jay Foad57aa6362011-07-13 10:26:04 +00002810Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
2811 Instruction *InsertBefore) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002812 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002813 // recursion).
Jay Foad57aa6362011-07-13 10:26:04 +00002814 if (idx_range.empty())
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002815 return V;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002816 // We have indices, so V should have an indexable type.
2817 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
2818 "Not looking at a struct or array?");
2819 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
2820 "Invalid indices for type?");
Owen Andersonf1f17432009-07-06 22:37:39 +00002821
Chris Lattner67058832012-01-25 06:48:06 +00002822 if (Constant *C = dyn_cast<Constant>(V)) {
2823 C = C->getAggregateElement(idx_range[0]);
Craig Topper9f008862014-04-15 04:59:12 +00002824 if (!C) return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00002825 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
2826 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002827
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002828 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002829 // Loop the indices for the insertvalue instruction in parallel with the
2830 // requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00002831 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002832 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
2833 i != e; ++i, ++req_idx) {
Jay Foad57aa6362011-07-13 10:26:04 +00002834 if (req_idx == idx_range.end()) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002835 // We can't handle this without inserting insertvalues
2836 if (!InsertBefore)
Craig Topper9f008862014-04-15 04:59:12 +00002837 return nullptr;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002838
2839 // The requested index identifies a part of a nested aggregate. Handle
2840 // this specially. For example,
2841 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
2842 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
2843 // %C = extractvalue {i32, { i32, i32 } } %B, 1
2844 // This can be changed into
2845 // %A = insertvalue {i32, i32 } undef, i32 10, 0
2846 // %C = insertvalue {i32, i32 } %A, i32 11, 1
2847 // which allows the unused 0,0 element from the nested struct to be
2848 // removed.
2849 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
2850 InsertBefore);
Duncan Sandsdb356ee2008-06-19 08:47:31 +00002851 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002852
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002853 // This insert value inserts something else than what we are looking for.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002854 // See if the (aggregate) value inserted into has the value we are
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002855 // looking for, then.
2856 if (*req_idx != *i)
Jay Foad57aa6362011-07-13 10:26:04 +00002857 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002858 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002859 }
2860 // If we end up here, the indices of the insertvalue match with those
2861 // requested (though possibly only partially). Now we recursively look at
2862 // the inserted value, passing any remaining indices.
Jay Foad57aa6362011-07-13 10:26:04 +00002863 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002864 makeArrayRef(req_idx, idx_range.end()),
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002865 InsertBefore);
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002866 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002867
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002868 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002869 // If we're extracting a value from an aggregate that was extracted from
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002870 // something else, we can extract from that something else directly instead.
2871 // However, we will need to chain I's indices with the requested indices.
Craig Topper1bef2c82012-12-22 19:15:35 +00002872
2873 // Calculate the number of indices required
Jay Foad57aa6362011-07-13 10:26:04 +00002874 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002875 // Allocate some space to put the new indices in
Matthijs Kooijman8369c672008-06-17 08:24:37 +00002876 SmallVector<unsigned, 5> Idxs;
2877 Idxs.reserve(size);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002878 // Add indices from the extract value instruction
Jay Foad57aa6362011-07-13 10:26:04 +00002879 Idxs.append(I->idx_begin(), I->idx_end());
Craig Topper1bef2c82012-12-22 19:15:35 +00002880
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002881 // Add requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00002882 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002883
Craig Topper1bef2c82012-12-22 19:15:35 +00002884 assert(Idxs.size() == size
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002885 && "Number of indices added not correct?");
Craig Topper1bef2c82012-12-22 19:15:35 +00002886
Jay Foad57aa6362011-07-13 10:26:04 +00002887 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002888 }
2889 // Otherwise, we don't know (such as, extracting from a function return value
2890 // or load instruction)
Craig Topper9f008862014-04-15 04:59:12 +00002891 return nullptr;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002892}
Evan Chengda3db112008-06-30 07:31:25 +00002893
Sanjay Patelaee84212014-11-04 16:27:42 +00002894/// Analyze the specified pointer to see if it can be expressed as a base
2895/// pointer plus a constant offset. Return the base and offset to the caller.
Chris Lattnere28618d2010-11-30 22:25:26 +00002896Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002897 const DataLayout &DL) {
2898 unsigned BitWidth = DL.getPointerTypeSizeInBits(Ptr->getType());
Nuno Lopes368c4d02012-12-31 20:48:35 +00002899 APInt ByteOffset(BitWidth, 0);
Chandler Carruth76641272016-01-04 07:23:12 +00002900
2901 // We walk up the defs but use a visited set to handle unreachable code. In
2902 // that case, we stop after accumulating the cycle once (not that it
2903 // matters).
2904 SmallPtrSet<Value *, 16> Visited;
2905 while (Visited.insert(Ptr).second) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002906 if (Ptr->getType()->isVectorTy())
2907 break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002908
Nuno Lopes368c4d02012-12-31 20:48:35 +00002909 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
Tom Stellard17eb3412016-10-07 14:23:29 +00002910 // If one of the values we have visited is an addrspacecast, then
2911 // the pointer type of this GEP may be different from the type
2912 // of the Ptr parameter which was passed to this function. This
2913 // means when we construct GEPOffset, we need to use the size
2914 // of GEP's pointer type rather than the size of the original
2915 // pointer type.
2916 APInt GEPOffset(DL.getPointerTypeSizeInBits(Ptr->getType()), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002917 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
2918 break;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00002919
Tom Stellard17eb3412016-10-07 14:23:29 +00002920 ByteOffset += GEPOffset.getSExtValue();
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00002921
Nuno Lopes368c4d02012-12-31 20:48:35 +00002922 Ptr = GEP->getPointerOperand();
Tom Stellard17eb3412016-10-07 14:23:29 +00002923 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
2924 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002925 Ptr = cast<Operator>(Ptr)->getOperand(0);
2926 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00002927 if (GA->isInterposable())
Nuno Lopes368c4d02012-12-31 20:48:35 +00002928 break;
2929 Ptr = GA->getAliasee();
Chris Lattnere28618d2010-11-30 22:25:26 +00002930 } else {
Nuno Lopes368c4d02012-12-31 20:48:35 +00002931 break;
Chris Lattnere28618d2010-11-30 22:25:26 +00002932 }
2933 }
Nuno Lopes368c4d02012-12-31 20:48:35 +00002934 Offset = ByteOffset.getSExtValue();
2935 return Ptr;
Chris Lattnere28618d2010-11-30 22:25:26 +00002936}
2937
Matthias Braun50ec0b52017-05-19 22:37:09 +00002938bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP,
2939 unsigned CharSize) {
David L Kreitzer752c1442016-04-13 14:31:06 +00002940 // Make sure the GEP has exactly three arguments.
2941 if (GEP->getNumOperands() != 3)
2942 return false;
2943
Matthias Braun50ec0b52017-05-19 22:37:09 +00002944 // Make sure the index-ee is a pointer to array of \p CharSize integers.
2945 // CharSize.
David L Kreitzer752c1442016-04-13 14:31:06 +00002946 ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
Matthias Braun50ec0b52017-05-19 22:37:09 +00002947 if (!AT || !AT->getElementType()->isIntegerTy(CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +00002948 return false;
2949
2950 // Check to make sure that the first operand of the GEP is an integer and
2951 // has value 0 so that we are sure we're indexing into the initializer.
2952 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
2953 if (!FirstIdx || !FirstIdx->isZero())
2954 return false;
2955
2956 return true;
Sanjoy Das6082c1a2016-05-07 02:08:15 +00002957}
Chris Lattnere28618d2010-11-30 22:25:26 +00002958
Matthias Braun50ec0b52017-05-19 22:37:09 +00002959bool llvm::getConstantDataArrayInfo(const Value *V,
2960 ConstantDataArraySlice &Slice,
2961 unsigned ElementSize, uint64_t Offset) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002962 assert(V);
Evan Chengda3db112008-06-30 07:31:25 +00002963
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002964 // Look through bitcast instructions and geps.
2965 V = V->stripPointerCasts();
Craig Topper1bef2c82012-12-22 19:15:35 +00002966
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00002967 // If the value is a GEP instruction or constant expression, treat it as an
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002968 // offset.
2969 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
David L Kreitzer752c1442016-04-13 14:31:06 +00002970 // The GEP operator should be based on a pointer to string constant, and is
2971 // indexing into the string constant.
Matthias Braun50ec0b52017-05-19 22:37:09 +00002972 if (!isGEPBasedOnPointerToString(GEP, ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002973 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002974
Evan Chengda3db112008-06-30 07:31:25 +00002975 // If the second index isn't a ConstantInt, then this is a variable index
2976 // into the array. If this occurs, we can't say anything meaningful about
2977 // the string.
2978 uint64_t StartIdx = 0;
Dan Gohman0b4df042010-04-14 22:20:45 +00002979 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Chengda3db112008-06-30 07:31:25 +00002980 StartIdx = CI->getZExtValue();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002981 else
2982 return false;
Matthias Braun50ec0b52017-05-19 22:37:09 +00002983 return getConstantDataArrayInfo(GEP->getOperand(0), Slice, ElementSize,
2984 StartIdx + Offset);
Evan Chengda3db112008-06-30 07:31:25 +00002985 }
Nick Lewycky46209882011-10-20 00:34:35 +00002986
Evan Chengda3db112008-06-30 07:31:25 +00002987 // The GEP instruction, constant or instruction, must reference a global
2988 // variable that is a constant and is initialized. The referenced constant
2989 // initializer is the array that we'll use for optimization.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002990 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00002991 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00002992 return false;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002993
Matthias Braun50ec0b52017-05-19 22:37:09 +00002994 const ConstantDataArray *Array;
2995 ArrayType *ArrayTy;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002996 if (GV->getInitializer()->isNullValue()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00002997 Type *GVTy = GV->getValueType();
2998 if ( (ArrayTy = dyn_cast<ArrayType>(GVTy)) ) {
Sanjay Patel2ad88f82017-06-12 22:34:37 +00002999 // A zeroinitializer for the array; there is no ConstantDataArray.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003000 Array = nullptr;
3001 } else {
3002 const DataLayout &DL = GV->getParent()->getDataLayout();
3003 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy);
3004 uint64_t Length = SizeInBytes / (ElementSize / 8);
3005 if (Length <= Offset)
3006 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003007
Matthias Braun50ec0b52017-05-19 22:37:09 +00003008 Slice.Array = nullptr;
3009 Slice.Offset = 0;
3010 Slice.Length = Length - Offset;
3011 return true;
3012 }
3013 } else {
3014 // This must be a ConstantDataArray.
3015 Array = dyn_cast<ConstantDataArray>(GV->getInitializer());
3016 if (!Array)
3017 return false;
3018 ArrayTy = Array->getType();
3019 }
3020 if (!ArrayTy->getElementType()->isIntegerTy(ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003021 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003022
Matthias Braun50ec0b52017-05-19 22:37:09 +00003023 uint64_t NumElts = ArrayTy->getArrayNumElements();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003024 if (Offset > NumElts)
3025 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003026
Matthias Braun50ec0b52017-05-19 22:37:09 +00003027 Slice.Array = Array;
3028 Slice.Offset = Offset;
3029 Slice.Length = NumElts - Offset;
3030 return true;
3031}
3032
3033/// This function computes the length of a null-terminated C string pointed to
3034/// by V. If successful, it returns true and returns the string in Str.
3035/// If unsuccessful, it returns false.
3036bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
3037 uint64_t Offset, bool TrimAtNul) {
3038 ConstantDataArraySlice Slice;
3039 if (!getConstantDataArrayInfo(V, Slice, 8, Offset))
3040 return false;
3041
3042 if (Slice.Array == nullptr) {
3043 if (TrimAtNul) {
3044 Str = StringRef();
3045 return true;
3046 }
3047 if (Slice.Length == 1) {
3048 Str = StringRef("", 1);
3049 return true;
3050 }
Sanjay Patelfef83e82017-06-09 14:21:18 +00003051 // We cannot instantiate a StringRef as we do not have an appropriate string
Matthias Braun50ec0b52017-05-19 22:37:09 +00003052 // of 0s at hand.
3053 return false;
3054 }
3055
3056 // Start out with the entire array in the StringRef.
3057 Str = Slice.Array->getAsString();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003058 // Skip over 'offset' bytes.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003059 Str = Str.substr(Slice.Offset);
Craig Topper1bef2c82012-12-22 19:15:35 +00003060
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003061 if (TrimAtNul) {
3062 // Trim off the \0 and anything after it. If the array is not nul
3063 // terminated, we just return the whole end of string. The client may know
3064 // some other way that the string is length-bound.
3065 Str = Str.substr(0, Str.find('\0'));
3066 }
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003067 return true;
Evan Chengda3db112008-06-30 07:31:25 +00003068}
Eric Christopher4899cbc2010-03-05 06:58:57 +00003069
3070// These next two are very similar to the above, but also look through PHI
3071// nodes.
3072// TODO: See if we can integrate these two together.
3073
Sanjay Patelaee84212014-11-04 16:27:42 +00003074/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003075/// the specified pointer, return 'len+1'. If we can't, return 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00003076static uint64_t GetStringLengthH(const Value *V,
Matthias Braun50ec0b52017-05-19 22:37:09 +00003077 SmallPtrSetImpl<const PHINode*> &PHIs,
3078 unsigned CharSize) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003079 // Look through noop bitcast instructions.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003080 V = V->stripPointerCasts();
Eric Christopher4899cbc2010-03-05 06:58:57 +00003081
3082 // If this is a PHI node, there are two cases: either we have already seen it
3083 // or we haven't.
Pete Cooper35b00d52016-08-13 01:05:32 +00003084 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
David Blaikie70573dc2014-11-19 07:49:26 +00003085 if (!PHIs.insert(PN).second)
Eric Christopher4899cbc2010-03-05 06:58:57 +00003086 return ~0ULL; // already in the set.
3087
3088 // If it was new, see if all the input strings are the same length.
3089 uint64_t LenSoFar = ~0ULL;
Pete Cooper833f34d2015-05-12 20:05:31 +00003090 for (Value *IncValue : PN->incoming_values()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003091 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003092 if (Len == 0) return 0; // Unknown length -> unknown.
3093
3094 if (Len == ~0ULL) continue;
3095
3096 if (Len != LenSoFar && LenSoFar != ~0ULL)
3097 return 0; // Disagree -> unknown.
3098 LenSoFar = Len;
3099 }
3100
3101 // Success, all agree.
3102 return LenSoFar;
3103 }
3104
3105 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
Pete Cooper35b00d52016-08-13 01:05:32 +00003106 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003107 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003108 if (Len1 == 0) return 0;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003109 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003110 if (Len2 == 0) return 0;
3111 if (Len1 == ~0ULL) return Len2;
3112 if (Len2 == ~0ULL) return Len1;
3113 if (Len1 != Len2) return 0;
3114 return Len1;
3115 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003116
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003117 // Otherwise, see if we can read the string.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003118 ConstantDataArraySlice Slice;
3119 if (!getConstantDataArrayInfo(V, Slice, CharSize))
Eric Christopher4899cbc2010-03-05 06:58:57 +00003120 return 0;
3121
Matthias Braun50ec0b52017-05-19 22:37:09 +00003122 if (Slice.Array == nullptr)
3123 return 1;
3124
3125 // Search for nul characters
3126 unsigned NullIndex = 0;
3127 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
3128 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
3129 break;
3130 }
3131
3132 return NullIndex + 1;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003133}
3134
Sanjay Patelaee84212014-11-04 16:27:42 +00003135/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003136/// the specified pointer, return 'len+1'. If we can't, return 0.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003137uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003138 if (!V->getType()->isPointerTy()) return 0;
3139
Pete Cooper35b00d52016-08-13 01:05:32 +00003140 SmallPtrSet<const PHINode*, 32> PHIs;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003141 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003142 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
3143 // an empty string as a length.
3144 return Len == ~0ULL ? 1 : Len;
3145}
Dan Gohmana4fcd242010-12-15 20:02:24 +00003146
Adam Nemete2b885c2015-04-23 20:09:20 +00003147/// \brief \p PN defines a loop-variant pointer to an object. Check if the
3148/// previous iteration of the loop was referring to the same object as \p PN.
Pete Cooper35b00d52016-08-13 01:05:32 +00003149static bool isSameUnderlyingObjectInLoop(const PHINode *PN,
3150 const LoopInfo *LI) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003151 // Find the loop-defined value.
3152 Loop *L = LI->getLoopFor(PN->getParent());
3153 if (PN->getNumIncomingValues() != 2)
3154 return true;
3155
3156 // Find the value from previous iteration.
3157 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
3158 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3159 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
3160 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3161 return true;
3162
3163 // If a new pointer is loaded in the loop, the pointer references a different
3164 // object in every iteration. E.g.:
3165 // for (i)
3166 // int *p = a[i];
3167 // ...
3168 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
3169 if (!L->isLoopInvariant(Load->getPointerOperand()))
3170 return false;
3171 return true;
3172}
3173
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003174Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
3175 unsigned MaxLookup) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003176 if (!V->getType()->isPointerTy())
3177 return V;
3178 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
3179 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3180 V = GEP->getPointerOperand();
Matt Arsenault70f4db882014-07-15 00:56:40 +00003181 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
3182 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003183 V = cast<Operator>(V)->getOperand(0);
3184 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00003185 if (GA->isInterposable())
Dan Gohmana4fcd242010-12-15 20:02:24 +00003186 return V;
3187 V = GA->getAliasee();
Craig Topper85482412017-04-12 22:29:23 +00003188 } else if (isa<AllocaInst>(V)) {
3189 // An alloca can't be further simplified.
3190 return V;
Dan Gohmana4fcd242010-12-15 20:02:24 +00003191 } else {
Hal Finkel5c12d8f2016-07-11 01:32:20 +00003192 if (auto CS = CallSite(V))
3193 if (Value *RV = CS.getReturnedArgOperand()) {
3194 V = RV;
3195 continue;
3196 }
3197
Dan Gohman05b18f12010-12-15 20:49:55 +00003198 // See if InstructionSimplify knows any relevant tricks.
3199 if (Instruction *I = dyn_cast<Instruction>(V))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003200 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00003201 if (Value *Simplified = SimplifyInstruction(I, {DL, I})) {
Dan Gohman05b18f12010-12-15 20:49:55 +00003202 V = Simplified;
3203 continue;
3204 }
3205
Dan Gohmana4fcd242010-12-15 20:02:24 +00003206 return V;
3207 }
3208 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
3209 }
3210 return V;
3211}
Nick Lewycky3e334a42011-06-27 04:20:45 +00003212
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003213void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
Adam Nemete2b885c2015-04-23 20:09:20 +00003214 const DataLayout &DL, LoopInfo *LI,
3215 unsigned MaxLookup) {
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003216 SmallPtrSet<Value *, 4> Visited;
3217 SmallVector<Value *, 4> Worklist;
3218 Worklist.push_back(V);
3219 do {
3220 Value *P = Worklist.pop_back_val();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003221 P = GetUnderlyingObject(P, DL, MaxLookup);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003222
David Blaikie70573dc2014-11-19 07:49:26 +00003223 if (!Visited.insert(P).second)
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003224 continue;
3225
3226 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
3227 Worklist.push_back(SI->getTrueValue());
3228 Worklist.push_back(SI->getFalseValue());
3229 continue;
3230 }
3231
3232 if (PHINode *PN = dyn_cast<PHINode>(P)) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003233 // If this PHI changes the underlying object in every iteration of the
3234 // loop, don't look through it. Consider:
3235 // int **A;
3236 // for (i) {
3237 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
3238 // Curr = A[i];
3239 // *Prev, *Curr;
3240 //
3241 // Prev is tracking Curr one iteration behind so they refer to different
3242 // underlying objects.
3243 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
3244 isSameUnderlyingObjectInLoop(PN, LI))
Pete Cooper833f34d2015-05-12 20:05:31 +00003245 for (Value *IncValue : PN->incoming_values())
3246 Worklist.push_back(IncValue);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003247 continue;
3248 }
3249
3250 Objects.push_back(P);
3251 } while (!Worklist.empty());
3252}
3253
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003254/// This is the function that does the work of looking through basic
3255/// ptrtoint+arithmetic+inttoptr sequences.
3256static const Value *getUnderlyingObjectFromInt(const Value *V) {
3257 do {
3258 if (const Operator *U = dyn_cast<Operator>(V)) {
3259 // If we find a ptrtoint, we can transfer control back to the
3260 // regular getUnderlyingObjectFromInt.
3261 if (U->getOpcode() == Instruction::PtrToInt)
3262 return U->getOperand(0);
3263 // If we find an add of a constant, a multiplied value, or a phi, it's
3264 // likely that the other operand will lead us to the base
3265 // object. We don't have to worry about the case where the
3266 // object address is somehow being computed by the multiply,
3267 // because our callers only care when the result is an
3268 // identifiable object.
3269 if (U->getOpcode() != Instruction::Add ||
3270 (!isa<ConstantInt>(U->getOperand(1)) &&
3271 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
3272 !isa<PHINode>(U->getOperand(1))))
3273 return V;
3274 V = U->getOperand(0);
3275 } else {
3276 return V;
3277 }
3278 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
3279 } while (true);
3280}
3281
3282/// This is a wrapper around GetUnderlyingObjects and adds support for basic
3283/// ptrtoint+arithmetic+inttoptr sequences.
3284void llvm::getUnderlyingObjectsForCodeGen(const Value *V,
3285 SmallVectorImpl<Value *> &Objects,
3286 const DataLayout &DL) {
3287 SmallPtrSet<const Value *, 16> Visited;
3288 SmallVector<const Value *, 4> Working(1, V);
3289 do {
3290 V = Working.pop_back_val();
3291
3292 SmallVector<Value *, 4> Objs;
3293 GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
3294
3295 for (Value *V : Objs) {
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003296 if (!Visited.insert(V).second)
3297 continue;
3298 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
3299 const Value *O =
3300 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
3301 if (O->getType()->isPointerTy()) {
3302 Working.push_back(O);
3303 continue;
3304 }
3305 }
Hiroshi Inoue0bd906e2017-08-02 18:16:32 +00003306 // If GetUnderlyingObjects fails to find an identifiable object,
3307 // getUnderlyingObjectsForCodeGen also fails for safety.
3308 if (!isIdentifiedObject(V)) {
3309 Objects.clear();
3310 return;
3311 }
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003312 Objects.push_back(const_cast<Value *>(V));
3313 }
3314 } while (!Working.empty());
3315}
3316
Sanjay Patelaee84212014-11-04 16:27:42 +00003317/// Return true if the only users of this pointer are lifetime markers.
Nick Lewycky3e334a42011-06-27 04:20:45 +00003318bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003319 for (const User *U : V->users()) {
3320 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Nick Lewycky3e334a42011-06-27 04:20:45 +00003321 if (!II) return false;
3322
3323 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
3324 II->getIntrinsicID() != Intrinsic::lifetime_end)
3325 return false;
3326 }
3327 return true;
3328}
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003329
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003330bool llvm::isSafeToSpeculativelyExecute(const Value *V,
3331 const Instruction *CtxI,
Sean Silva45835e72016-07-02 23:47:27 +00003332 const DominatorTree *DT) {
Dan Gohman7ac046a2012-01-04 23:01:09 +00003333 const Operator *Inst = dyn_cast<Operator>(V);
3334 if (!Inst)
3335 return false;
3336
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003337 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3338 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3339 if (C->canTrap())
3340 return false;
3341
3342 switch (Inst->getOpcode()) {
3343 default:
3344 return true;
3345 case Instruction::UDiv:
David Majnemerf20d7c42014-11-04 23:49:08 +00003346 case Instruction::URem: {
3347 // x / y is undefined if y == 0.
3348 const APInt *V;
3349 if (match(Inst->getOperand(1), m_APInt(V)))
3350 return *V != 0;
3351 return false;
3352 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003353 case Instruction::SDiv:
3354 case Instruction::SRem: {
David Majnemerf20d7c42014-11-04 23:49:08 +00003355 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
David Majnemer8a6578a2015-02-01 19:10:19 +00003356 const APInt *Numerator, *Denominator;
3357 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3358 return false;
3359 // We cannot hoist this division if the denominator is 0.
3360 if (*Denominator == 0)
3361 return false;
3362 // It's safe to hoist if the denominator is not 0 or -1.
3363 if (*Denominator != -1)
3364 return true;
3365 // At this point we know that the denominator is -1. It is safe to hoist as
3366 // long we know that the numerator is not INT_MIN.
3367 if (match(Inst->getOperand(0), m_APInt(Numerator)))
3368 return !Numerator->isMinSignedValue();
3369 // The numerator *might* be MinSignedValue.
David Majnemerf20d7c42014-11-04 23:49:08 +00003370 return false;
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003371 }
3372 case Instruction::Load: {
3373 const LoadInst *LI = cast<LoadInst>(Inst);
Kostya Serebryany0b458282013-11-21 07:29:28 +00003374 if (!LI->isUnordered() ||
3375 // Speculative load may create a race that did not exist in the source.
Sanjoy Dasb66374c2016-07-14 20:19:01 +00003376 LI->getFunction()->hasFnAttribute(Attribute::SanitizeThread) ||
Kostya Serebryany5cb86d52015-10-14 00:21:05 +00003377 // Speculative load may load data from dirty regions.
Sanjoy Dasb66374c2016-07-14 20:19:01 +00003378 LI->getFunction()->hasFnAttribute(Attribute::SanitizeAddress))
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003379 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003380 const DataLayout &DL = LI->getModule()->getDataLayout();
Sean Silva45835e72016-07-02 23:47:27 +00003381 return isDereferenceableAndAlignedPointer(LI->getPointerOperand(),
3382 LI->getAlignment(), DL, CtxI, DT);
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003383 }
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003384 case Instruction::Call: {
Matt Arsenaultcf5e7fe2017-04-28 21:13:09 +00003385 auto *CI = cast<const CallInst>(Inst);
3386 const Function *Callee = CI->getCalledFunction();
David Majnemer0a92f862015-08-28 21:13:39 +00003387
Matt Arsenault6a288c12017-05-03 02:26:10 +00003388 // The called function could have undefined behavior or side-effects, even
3389 // if marked readnone nounwind.
3390 return Callee && Callee->isSpeculatable();
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003391 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003392 case Instruction::VAArg:
3393 case Instruction::Alloca:
3394 case Instruction::Invoke:
3395 case Instruction::PHI:
3396 case Instruction::Store:
3397 case Instruction::Ret:
3398 case Instruction::Br:
3399 case Instruction::IndirectBr:
3400 case Instruction::Switch:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003401 case Instruction::Unreachable:
3402 case Instruction::Fence:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003403 case Instruction::AtomicRMW:
3404 case Instruction::AtomicCmpXchg:
David Majnemer654e1302015-07-31 17:58:14 +00003405 case Instruction::LandingPad:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003406 case Instruction::Resume:
David Majnemer8a1c45d2015-12-12 05:38:55 +00003407 case Instruction::CatchSwitch:
David Majnemer654e1302015-07-31 17:58:14 +00003408 case Instruction::CatchPad:
David Majnemer654e1302015-07-31 17:58:14 +00003409 case Instruction::CatchRet:
3410 case Instruction::CleanupPad:
3411 case Instruction::CleanupRet:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003412 return false; // Misc instructions which have effects
3413 }
3414}
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003415
Quentin Colombet6443cce2015-08-06 18:44:34 +00003416bool llvm::mayBeMemoryDependent(const Instruction &I) {
3417 return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
3418}
3419
Sanjay Patelaee84212014-11-04 16:27:42 +00003420/// Return true if we know that the specified value is never null.
Sean Silva45835e72016-07-02 23:47:27 +00003421bool llvm::isKnownNonNull(const Value *V) {
Chen Li0d043b52015-09-14 18:10:43 +00003422 assert(V->getType()->isPointerTy() && "V must be pointer type");
3423
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003424 // Alloca never returns null, malloc might.
3425 if (isa<AllocaInst>(V)) return true;
3426
Nick Lewyckyd52b1522014-05-20 01:23:40 +00003427 // A byval, inalloca, or nonnull argument is never null.
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003428 if (const Argument *A = dyn_cast<Argument>(V))
Nick Lewyckyd52b1522014-05-20 01:23:40 +00003429 return A->hasByValOrInAllocaAttr() || A->hasNonNullAttr();
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003430
Peter Collingbourne235c2752016-12-08 19:01:00 +00003431 // A global variable in address space 0 is non null unless extern weak
3432 // or an absolute symbol reference. Other address spaces may have null as a
3433 // valid address for a global, so we can't assume anything.
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003434 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
Peter Collingbourne235c2752016-12-08 19:01:00 +00003435 return !GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
Pete Cooper6b716212015-08-27 03:16:29 +00003436 GV->getType()->getAddressSpace() == 0;
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00003437
Sanjoy Das5056e192016-05-07 02:08:22 +00003438 // A Load tagged with nonnull metadata is never null.
Philip Reamescdb72f32014-10-20 22:40:55 +00003439 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
Philip Reames5a3f5f72014-10-21 00:13:20 +00003440 return LI->getMetadata(LLVMContext::MD_nonnull);
Philip Reamescdb72f32014-10-20 22:40:55 +00003441
Benjamin Kramer3a09ef62015-04-10 14:50:08 +00003442 if (auto CS = ImmutableCallSite(V))
Hal Finkelb0407ba2014-07-18 15:51:28 +00003443 if (CS.isReturnNonNull())
Nick Lewyckyec373542014-05-20 05:13:21 +00003444 return true;
3445
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003446 return false;
3447}
David Majnemer491331a2015-01-02 07:29:43 +00003448
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003449static bool isKnownNonNullFromDominatingCondition(const Value *V,
3450 const Instruction *CtxI,
3451 const DominatorTree *DT) {
Chen Li0d043b52015-09-14 18:10:43 +00003452 assert(V->getType()->isPointerTy() && "V must be pointer type");
Duncan P. N. Exon Smithb4798732016-09-24 19:39:47 +00003453 assert(!isa<ConstantData>(V) && "Did not expect ConstantPointerNull");
Sanjay Patel7fd779f2016-12-31 17:37:01 +00003454 assert(CtxI && "Context instruction required for analysis");
3455 assert(DT && "Dominator tree required for analysis");
Chen Li0d043b52015-09-14 18:10:43 +00003456
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003457 unsigned NumUsesExplored = 0;
Sanjoy Das987aaa12016-05-07 02:08:24 +00003458 for (auto *U : V->users()) {
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003459 // Avoid massive lists
3460 if (NumUsesExplored >= DomConditionsMaxUses)
3461 break;
3462 NumUsesExplored++;
Sanjay Patel97e4b9872017-02-12 15:35:34 +00003463
3464 // If the value is used as an argument to a call or invoke, then argument
3465 // attributes may provide an answer about null-ness.
3466 if (auto CS = ImmutableCallSite(U))
3467 if (auto *CalledFunc = CS.getCalledFunction())
3468 for (const Argument &Arg : CalledFunc->args())
3469 if (CS.getArgOperand(Arg.getArgNo()) == V &&
3470 Arg.hasNonNullAttr() && DT->dominates(CS.getInstruction(), CtxI))
3471 return true;
3472
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003473 // Consider only compare instructions uniquely controlling a branch
Sanjoy Das987aaa12016-05-07 02:08:24 +00003474 CmpInst::Predicate Pred;
3475 if (!match(const_cast<User *>(U),
3476 m_c_ICmp(Pred, m_Specific(V), m_Zero())) ||
3477 (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE))
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003478 continue;
3479
Sanjoy Das987aaa12016-05-07 02:08:24 +00003480 for (auto *CmpU : U->users()) {
Sanjoy Das12c91dc2016-05-10 02:35:44 +00003481 if (const BranchInst *BI = dyn_cast<BranchInst>(CmpU)) {
3482 assert(BI->isConditional() && "uses a comparison!");
Sanjoy Das6082c1a2016-05-07 02:08:15 +00003483
Sanjoy Das12c91dc2016-05-10 02:35:44 +00003484 BasicBlock *NonNullSuccessor =
3485 BI->getSuccessor(Pred == ICmpInst::ICMP_EQ ? 1 : 0);
3486 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3487 if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
3488 return true;
3489 } else if (Pred == ICmpInst::ICMP_NE &&
3490 match(CmpU, m_Intrinsic<Intrinsic::experimental_guard>()) &&
3491 DT->dominates(cast<Instruction>(CmpU), CtxI)) {
Sanjoy Das987aaa12016-05-07 02:08:24 +00003492 return true;
Sanjoy Das12c91dc2016-05-10 02:35:44 +00003493 }
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003494 }
3495 }
3496
3497 return false;
3498}
3499
3500bool llvm::isKnownNonNullAt(const Value *V, const Instruction *CtxI,
Sean Silva45835e72016-07-02 23:47:27 +00003501 const DominatorTree *DT) {
Duncan P. N. Exon Smithb4798732016-09-24 19:39:47 +00003502 if (isa<ConstantPointerNull>(V) || isa<UndefValue>(V))
3503 return false;
3504
Sean Silva45835e72016-07-02 23:47:27 +00003505 if (isKnownNonNull(V))
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003506 return true;
3507
Sanjay Patel7fd779f2016-12-31 17:37:01 +00003508 if (!CtxI || !DT)
3509 return false;
3510
3511 return ::isKnownNonNullFromDominatingCondition(V, CtxI, DT);
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003512}
3513
Pete Cooper35b00d52016-08-13 01:05:32 +00003514OverflowResult llvm::computeOverflowForUnsignedMul(const Value *LHS,
3515 const Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003516 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003517 AssumptionCache *AC,
David Majnemer491331a2015-01-02 07:29:43 +00003518 const Instruction *CxtI,
3519 const DominatorTree *DT) {
3520 // Multiplying n * m significant bits yields a result of n + m significant
3521 // bits. If the total number of significant bits does not exceed the
3522 // result bit width (minus 1), there is no overflow.
3523 // This means if we have enough leading zero bits in the operands
3524 // we can guarantee that the result does not overflow.
3525 // Ref: "Hacker's Delight" by Henry Warren
3526 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00003527 KnownBits LHSKnown(BitWidth);
3528 KnownBits RHSKnown(BitWidth);
3529 computeKnownBits(LHS, LHSKnown, DL, /*Depth=*/0, AC, CxtI, DT);
3530 computeKnownBits(RHS, RHSKnown, DL, /*Depth=*/0, AC, CxtI, DT);
David Majnemer491331a2015-01-02 07:29:43 +00003531 // Note that underestimating the number of zero bits gives a more
3532 // conservative answer.
Craig Topper8df66c62017-05-12 17:20:30 +00003533 unsigned ZeroBits = LHSKnown.countMinLeadingZeros() +
3534 RHSKnown.countMinLeadingZeros();
David Majnemer491331a2015-01-02 07:29:43 +00003535 // First handle the easy case: if we have enough zero bits there's
3536 // definitely no overflow.
3537 if (ZeroBits >= BitWidth)
3538 return OverflowResult::NeverOverflows;
3539
3540 // Get the largest possible values for each operand.
Craig Topperb45eabc2017-04-26 16:39:58 +00003541 APInt LHSMax = ~LHSKnown.Zero;
3542 APInt RHSMax = ~RHSKnown.Zero;
David Majnemer491331a2015-01-02 07:29:43 +00003543
3544 // We know the multiply operation doesn't overflow if the maximum values for
3545 // each operand will not overflow after we multiply them together.
David Majnemerc8a576b2015-01-02 07:29:47 +00003546 bool MaxOverflow;
Craig Topper9b71a402017-04-19 21:09:45 +00003547 (void)LHSMax.umul_ov(RHSMax, MaxOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00003548 if (!MaxOverflow)
3549 return OverflowResult::NeverOverflows;
David Majnemer491331a2015-01-02 07:29:43 +00003550
David Majnemerc8a576b2015-01-02 07:29:47 +00003551 // We know it always overflows if multiplying the smallest possible values for
3552 // the operands also results in overflow.
3553 bool MinOverflow;
Craig Topperb45eabc2017-04-26 16:39:58 +00003554 (void)LHSKnown.One.umul_ov(RHSKnown.One, MinOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00003555 if (MinOverflow)
3556 return OverflowResult::AlwaysOverflows;
3557
3558 return OverflowResult::MayOverflow;
David Majnemer491331a2015-01-02 07:29:43 +00003559}
David Majnemer5310c1e2015-01-07 00:39:50 +00003560
Pete Cooper35b00d52016-08-13 01:05:32 +00003561OverflowResult llvm::computeOverflowForUnsignedAdd(const Value *LHS,
3562 const Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003563 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003564 AssumptionCache *AC,
David Majnemer5310c1e2015-01-07 00:39:50 +00003565 const Instruction *CxtI,
3566 const DominatorTree *DT) {
Craig Topper6e11a052017-05-08 16:22:48 +00003567 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
3568 if (LHSKnown.isNonNegative() || LHSKnown.isNegative()) {
3569 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
David Majnemer5310c1e2015-01-07 00:39:50 +00003570
Craig Topper6e11a052017-05-08 16:22:48 +00003571 if (LHSKnown.isNegative() && RHSKnown.isNegative()) {
David Majnemer5310c1e2015-01-07 00:39:50 +00003572 // The sign bit is set in both cases: this MUST overflow.
3573 // Create a simple add instruction, and insert it into the struct.
3574 return OverflowResult::AlwaysOverflows;
3575 }
3576
Craig Topper6e11a052017-05-08 16:22:48 +00003577 if (LHSKnown.isNonNegative() && RHSKnown.isNonNegative()) {
David Majnemer5310c1e2015-01-07 00:39:50 +00003578 // The sign bit is clear in both cases: this CANNOT overflow.
3579 // Create a simple add instruction, and insert it into the struct.
3580 return OverflowResult::NeverOverflows;
3581 }
3582 }
3583
3584 return OverflowResult::MayOverflow;
3585}
James Molloy71b91c22015-05-11 14:42:20 +00003586
Craig Topperbb973722017-05-15 02:44:08 +00003587/// \brief Return true if we can prove that adding the two values of the
3588/// knownbits will not overflow.
3589/// Otherwise return false.
3590static bool checkRippleForSignedAdd(const KnownBits &LHSKnown,
3591 const KnownBits &RHSKnown) {
3592 // Addition of two 2's complement numbers having opposite signs will never
3593 // overflow.
3594 if ((LHSKnown.isNegative() && RHSKnown.isNonNegative()) ||
3595 (LHSKnown.isNonNegative() && RHSKnown.isNegative()))
3596 return true;
3597
3598 // If either of the values is known to be non-negative, adding them can only
3599 // overflow if the second is also non-negative, so we can assume that.
3600 // Two non-negative numbers will only overflow if there is a carry to the
3601 // sign bit, so we can check if even when the values are as big as possible
3602 // there is no overflow to the sign bit.
3603 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative()) {
3604 APInt MaxLHS = ~LHSKnown.Zero;
3605 MaxLHS.clearSignBit();
3606 APInt MaxRHS = ~RHSKnown.Zero;
3607 MaxRHS.clearSignBit();
3608 APInt Result = std::move(MaxLHS) + std::move(MaxRHS);
3609 return Result.isSignBitClear();
3610 }
3611
3612 // If either of the values is known to be negative, adding them can only
3613 // overflow if the second is also negative, so we can assume that.
3614 // Two negative number will only overflow if there is no carry to the sign
3615 // bit, so we can check if even when the values are as small as possible
3616 // there is overflow to the sign bit.
3617 if (LHSKnown.isNegative() || RHSKnown.isNegative()) {
3618 APInt MinLHS = LHSKnown.One;
3619 MinLHS.clearSignBit();
3620 APInt MinRHS = RHSKnown.One;
3621 MinRHS.clearSignBit();
3622 APInt Result = std::move(MinLHS) + std::move(MinRHS);
3623 return Result.isSignBitSet();
3624 }
3625
3626 // If we reached here it means that we know nothing about the sign bits.
3627 // In this case we can't know if there will be an overflow, since by
3628 // changing the sign bits any two values can be made to overflow.
3629 return false;
3630}
3631
Pete Cooper35b00d52016-08-13 01:05:32 +00003632static OverflowResult computeOverflowForSignedAdd(const Value *LHS,
3633 const Value *RHS,
3634 const AddOperator *Add,
3635 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003636 AssumptionCache *AC,
Pete Cooper35b00d52016-08-13 01:05:32 +00003637 const Instruction *CxtI,
3638 const DominatorTree *DT) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00003639 if (Add && Add->hasNoSignedWrap()) {
3640 return OverflowResult::NeverOverflows;
3641 }
3642
Craig Topperbb973722017-05-15 02:44:08 +00003643 // If LHS and RHS each have at least two sign bits, the addition will look
3644 // like
3645 //
3646 // XX..... +
3647 // YY.....
3648 //
3649 // If the carry into the most significant position is 0, X and Y can't both
3650 // be 1 and therefore the carry out of the addition is also 0.
3651 //
3652 // If the carry into the most significant position is 1, X and Y can't both
3653 // be 0 and therefore the carry out of the addition is also 1.
3654 //
3655 // Since the carry into the most significant position is always equal to
3656 // the carry out of the addition, there is no signed overflow.
3657 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
3658 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
3659 return OverflowResult::NeverOverflows;
3660
Craig Topper6e11a052017-05-08 16:22:48 +00003661 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
3662 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003663
Craig Topperbb973722017-05-15 02:44:08 +00003664 if (checkRippleForSignedAdd(LHSKnown, RHSKnown))
Jingyue Wu10fcea52015-08-20 18:27:04 +00003665 return OverflowResult::NeverOverflows;
Jingyue Wu10fcea52015-08-20 18:27:04 +00003666
3667 // The remaining code needs Add to be available. Early returns if not so.
3668 if (!Add)
3669 return OverflowResult::MayOverflow;
3670
3671 // If the sign of Add is the same as at least one of the operands, this add
3672 // CANNOT overflow. This is particularly useful when the sum is
3673 // @llvm.assume'ed non-negative rather than proved so from analyzing its
3674 // operands.
3675 bool LHSOrRHSKnownNonNegative =
Craig Topper6e11a052017-05-08 16:22:48 +00003676 (LHSKnown.isNonNegative() || RHSKnown.isNonNegative());
Craig Topperbb973722017-05-15 02:44:08 +00003677 bool LHSOrRHSKnownNegative =
3678 (LHSKnown.isNegative() || RHSKnown.isNegative());
Jingyue Wu10fcea52015-08-20 18:27:04 +00003679 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
Craig Topper6e11a052017-05-08 16:22:48 +00003680 KnownBits AddKnown = computeKnownBits(Add, DL, /*Depth=*/0, AC, CxtI, DT);
3681 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
3682 (AddKnown.isNegative() && LHSOrRHSKnownNegative)) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00003683 return OverflowResult::NeverOverflows;
3684 }
3685 }
3686
3687 return OverflowResult::MayOverflow;
3688}
3689
Pete Cooper35b00d52016-08-13 01:05:32 +00003690bool llvm::isOverflowIntrinsicNoWrap(const IntrinsicInst *II,
3691 const DominatorTree &DT) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003692#ifndef NDEBUG
3693 auto IID = II->getIntrinsicID();
3694 assert((IID == Intrinsic::sadd_with_overflow ||
3695 IID == Intrinsic::uadd_with_overflow ||
3696 IID == Intrinsic::ssub_with_overflow ||
3697 IID == Intrinsic::usub_with_overflow ||
3698 IID == Intrinsic::smul_with_overflow ||
3699 IID == Intrinsic::umul_with_overflow) &&
3700 "Not an overflow intrinsic!");
3701#endif
3702
Pete Cooper35b00d52016-08-13 01:05:32 +00003703 SmallVector<const BranchInst *, 2> GuardingBranches;
3704 SmallVector<const ExtractValueInst *, 2> Results;
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003705
Pete Cooper35b00d52016-08-13 01:05:32 +00003706 for (const User *U : II->users()) {
3707 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003708 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
3709
3710 if (EVI->getIndices()[0] == 0)
3711 Results.push_back(EVI);
3712 else {
3713 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
3714
Pete Cooper35b00d52016-08-13 01:05:32 +00003715 for (const auto *U : EVI->users())
3716 if (const auto *B = dyn_cast<BranchInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003717 assert(B->isConditional() && "How else is it using an i1?");
3718 GuardingBranches.push_back(B);
3719 }
3720 }
3721 } else {
3722 // We are using the aggregate directly in a way we don't want to analyze
3723 // here (storing it to a global, say).
3724 return false;
3725 }
3726 }
3727
Pete Cooper35b00d52016-08-13 01:05:32 +00003728 auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003729 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
3730 if (!NoWrapEdge.isSingleEdge())
3731 return false;
3732
3733 // Check if all users of the add are provably no-wrap.
Pete Cooper35b00d52016-08-13 01:05:32 +00003734 for (const auto *Result : Results) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003735 // If the extractvalue itself is not executed on overflow, the we don't
3736 // need to check each use separately, since domination is transitive.
3737 if (DT.dominates(NoWrapEdge, Result->getParent()))
3738 continue;
3739
3740 for (auto &RU : Result->uses())
3741 if (!DT.dominates(NoWrapEdge, RU))
3742 return false;
3743 }
3744
3745 return true;
3746 };
3747
3748 return any_of(GuardingBranches, AllUsesGuardedByBranch);
3749}
3750
3751
Pete Cooper35b00d52016-08-13 01:05:32 +00003752OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003753 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003754 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003755 const Instruction *CxtI,
3756 const DominatorTree *DT) {
3757 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003758 Add, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003759}
3760
Pete Cooper35b00d52016-08-13 01:05:32 +00003761OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS,
3762 const Value *RHS,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003763 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003764 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003765 const Instruction *CxtI,
3766 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003767 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003768}
3769
Jingyue Wu42f1d672015-07-28 18:22:40 +00003770bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003771 // A memory operation returns normally if it isn't volatile. A volatile
3772 // operation is allowed to trap.
3773 //
3774 // An atomic operation isn't guaranteed to return in a reasonable amount of
3775 // time because it's possible for another thread to interfere with it for an
3776 // arbitrary length of time, but programs aren't allowed to rely on that.
3777 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
3778 return !LI->isVolatile();
3779 if (const StoreInst *SI = dyn_cast<StoreInst>(I))
3780 return !SI->isVolatile();
3781 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
3782 return !CXI->isVolatile();
3783 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
3784 return !RMWI->isVolatile();
3785 if (const MemIntrinsic *MII = dyn_cast<MemIntrinsic>(I))
3786 return !MII->isVolatile();
Jingyue Wu42f1d672015-07-28 18:22:40 +00003787
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003788 // If there is no successor, then execution can't transfer to it.
3789 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I))
3790 return !CRI->unwindsToCaller();
3791 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I))
3792 return !CatchSwitch->unwindsToCaller();
3793 if (isa<ResumeInst>(I))
3794 return false;
3795 if (isa<ReturnInst>(I))
3796 return false;
Sebastian Pop4a4d2452017-03-08 01:54:50 +00003797 if (isa<UnreachableInst>(I))
3798 return false;
Sanjoy Das9a65cd22016-06-08 17:48:36 +00003799
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003800 // Calls can throw, or contain an infinite loop, or kill the process.
Sanjoy Das09455302016-12-31 22:12:31 +00003801 if (auto CS = ImmutableCallSite(I)) {
Sanjoy Das3bb2dbd2016-12-31 22:12:34 +00003802 // Call sites that throw have implicit non-local control flow.
3803 if (!CS.doesNotThrow())
3804 return false;
3805
3806 // Non-throwing call sites can loop infinitely, call exit/pthread_exit
3807 // etc. and thus not return. However, LLVM already assumes that
3808 //
3809 // - Thread exiting actions are modeled as writes to memory invisible to
3810 // the program.
3811 //
3812 // - Loops that don't have side effects (side effects are volatile/atomic
3813 // stores and IO) always terminate (see http://llvm.org/PR965).
3814 // Furthermore IO itself is also modeled as writes to memory invisible to
3815 // the program.
3816 //
3817 // We rely on those assumptions here, and use the memory effects of the call
3818 // target as a proxy for checking that it always returns.
3819
3820 // FIXME: This isn't aggressive enough; a call which only writes to a global
3821 // is guaranteed to return.
Sanjoy Dasd7e82062016-06-14 20:23:16 +00003822 return CS.onlyReadsMemory() || CS.onlyAccessesArgMemory() ||
3823 match(I, m_Intrinsic<Intrinsic::assume>());
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003824 }
3825
3826 // Other instructions return normally.
3827 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003828}
3829
3830bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
3831 const Loop *L) {
3832 // The loop header is guaranteed to be executed for every iteration.
3833 //
3834 // FIXME: Relax this constraint to cover all basic blocks that are
3835 // guaranteed to be executed at every iteration.
3836 if (I->getParent() != L->getHeader()) return false;
3837
3838 for (const Instruction &LI : *L->getHeader()) {
3839 if (&LI == I) return true;
3840 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
3841 }
3842 llvm_unreachable("Instruction not contained in its own parent basic block.");
3843}
3844
3845bool llvm::propagatesFullPoison(const Instruction *I) {
3846 switch (I->getOpcode()) {
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003847 case Instruction::Add:
3848 case Instruction::Sub:
3849 case Instruction::Xor:
3850 case Instruction::Trunc:
3851 case Instruction::BitCast:
3852 case Instruction::AddrSpaceCast:
Sanjoy Das5cd6c5ca2017-02-22 06:52:32 +00003853 case Instruction::Mul:
3854 case Instruction::Shl:
3855 case Instruction::GetElementPtr:
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003856 // These operations all propagate poison unconditionally. Note that poison
3857 // is not any particular value, so xor or subtraction of poison with
3858 // itself still yields poison, not zero.
3859 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003860
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003861 case Instruction::AShr:
3862 case Instruction::SExt:
3863 // For these operations, one bit of the input is replicated across
3864 // multiple output bits. A replicated poison bit is still poison.
3865 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003866
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003867 case Instruction::ICmp:
3868 // Comparing poison with any value yields poison. This is why, for
3869 // instance, x s< (x +nsw 1) can be folded to true.
3870 return true;
Sanjoy Das70c2bbd2016-05-29 00:31:18 +00003871
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003872 default:
3873 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003874 }
3875}
3876
3877const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
3878 switch (I->getOpcode()) {
3879 case Instruction::Store:
3880 return cast<StoreInst>(I)->getPointerOperand();
3881
3882 case Instruction::Load:
3883 return cast<LoadInst>(I)->getPointerOperand();
3884
3885 case Instruction::AtomicCmpXchg:
3886 return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
3887
3888 case Instruction::AtomicRMW:
3889 return cast<AtomicRMWInst>(I)->getPointerOperand();
3890
3891 case Instruction::UDiv:
3892 case Instruction::SDiv:
3893 case Instruction::URem:
3894 case Instruction::SRem:
3895 return I->getOperand(1);
3896
3897 default:
3898 return nullptr;
3899 }
3900}
3901
Sanjoy Das08989c72017-04-30 19:41:19 +00003902bool llvm::programUndefinedIfFullPoison(const Instruction *PoisonI) {
Jingyue Wu42f1d672015-07-28 18:22:40 +00003903 // We currently only look for uses of poison values within the same basic
3904 // block, as that makes it easier to guarantee that the uses will be
3905 // executed given that PoisonI is executed.
3906 //
3907 // FIXME: Expand this to consider uses beyond the same basic block. To do
3908 // this, look out for the distinction between post-dominance and strong
3909 // post-dominance.
3910 const BasicBlock *BB = PoisonI->getParent();
3911
3912 // Set of instructions that we have proved will yield poison if PoisonI
3913 // does.
3914 SmallSet<const Value *, 16> YieldsPoison;
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003915 SmallSet<const BasicBlock *, 4> Visited;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003916 YieldsPoison.insert(PoisonI);
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003917 Visited.insert(PoisonI->getParent());
Jingyue Wu42f1d672015-07-28 18:22:40 +00003918
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003919 BasicBlock::const_iterator Begin = PoisonI->getIterator(), End = BB->end();
Jingyue Wu42f1d672015-07-28 18:22:40 +00003920
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003921 unsigned Iter = 0;
3922 while (Iter++ < MaxDepth) {
3923 for (auto &I : make_range(Begin, End)) {
3924 if (&I != PoisonI) {
3925 const Value *NotPoison = getGuaranteedNonFullPoisonOp(&I);
3926 if (NotPoison != nullptr && YieldsPoison.count(NotPoison))
3927 return true;
3928 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
3929 return false;
3930 }
3931
3932 // Mark poison that propagates from I through uses of I.
3933 if (YieldsPoison.count(&I)) {
3934 for (const User *User : I.users()) {
3935 const Instruction *UserI = cast<Instruction>(User);
3936 if (propagatesFullPoison(UserI))
3937 YieldsPoison.insert(User);
3938 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003939 }
3940 }
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003941
3942 if (auto *NextBB = BB->getSingleSuccessor()) {
3943 if (Visited.insert(NextBB).second) {
3944 BB = NextBB;
3945 Begin = BB->getFirstNonPHI()->getIterator();
3946 End = BB->end();
3947 continue;
3948 }
3949 }
3950
3951 break;
3952 };
Jingyue Wu42f1d672015-07-28 18:22:40 +00003953 return false;
3954}
3955
Pete Cooper35b00d52016-08-13 01:05:32 +00003956static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
James Molloy134bec22015-08-11 09:12:57 +00003957 if (FMF.noNaNs())
3958 return true;
3959
3960 if (auto *C = dyn_cast<ConstantFP>(V))
3961 return !C->isNaN();
3962 return false;
3963}
3964
Pete Cooper35b00d52016-08-13 01:05:32 +00003965static bool isKnownNonZero(const Value *V) {
James Molloy134bec22015-08-11 09:12:57 +00003966 if (auto *C = dyn_cast<ConstantFP>(V))
3967 return !C->isZero();
3968 return false;
3969}
3970
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00003971/// Match clamp pattern for float types without care about NaNs or signed zeros.
3972/// Given non-min/max outer cmp/select from the clamp pattern this
3973/// function recognizes if it can be substitued by a "canonical" min/max
3974/// pattern.
3975static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred,
3976 Value *CmpLHS, Value *CmpRHS,
3977 Value *TrueVal, Value *FalseVal,
3978 Value *&LHS, Value *&RHS) {
3979 // Try to match
3980 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
3981 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
3982 // and return description of the outer Max/Min.
3983
3984 // First, check if select has inverse order:
3985 if (CmpRHS == FalseVal) {
3986 std::swap(TrueVal, FalseVal);
3987 Pred = CmpInst::getInversePredicate(Pred);
3988 }
3989
3990 // Assume success now. If there's no match, callers should not use these anyway.
3991 LHS = TrueVal;
3992 RHS = FalseVal;
3993
3994 const APFloat *FC1;
3995 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
3996 return {SPF_UNKNOWN, SPNB_NA, false};
3997
3998 const APFloat *FC2;
3999 switch (Pred) {
4000 case CmpInst::FCMP_OLT:
4001 case CmpInst::FCMP_OLE:
4002 case CmpInst::FCMP_ULT:
4003 case CmpInst::FCMP_ULE:
4004 if (match(FalseVal,
4005 m_CombineOr(m_OrdFMin(m_Specific(CmpLHS), m_APFloat(FC2)),
4006 m_UnordFMin(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4007 FC1->compare(*FC2) == APFloat::cmpResult::cmpLessThan)
4008 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
4009 break;
4010 case CmpInst::FCMP_OGT:
4011 case CmpInst::FCMP_OGE:
4012 case CmpInst::FCMP_UGT:
4013 case CmpInst::FCMP_UGE:
4014 if (match(FalseVal,
4015 m_CombineOr(m_OrdFMax(m_Specific(CmpLHS), m_APFloat(FC2)),
4016 m_UnordFMax(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4017 FC1->compare(*FC2) == APFloat::cmpResult::cmpGreaterThan)
4018 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
4019 break;
4020 default:
4021 break;
4022 }
4023
4024 return {SPF_UNKNOWN, SPNB_NA, false};
4025}
4026
Sanjay Patel819f0962016-11-13 19:30:19 +00004027/// Match non-obvious integer minimum and maximum sequences.
4028static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
4029 Value *CmpLHS, Value *CmpRHS,
4030 Value *TrueVal, Value *FalseVal,
4031 Value *&LHS, Value *&RHS) {
Sanjay Patel24c6f882017-01-21 17:51:25 +00004032 // Assume success. If there's no match, callers should not use these anyway.
4033 LHS = TrueVal;
4034 RHS = FalseVal;
4035
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004036 // Recognize variations of:
4037 // CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
4038 const APInt *C1;
4039 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
4040 const APInt *C2;
4041
4042 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
4043 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004044 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004045 return {SPF_SMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004046
4047 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
4048 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004049 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004050 return {SPF_SMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004051
4052 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
4053 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004054 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004055 return {SPF_UMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004056
4057 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
4058 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004059 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004060 return {SPF_UMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004061 }
4062
Sanjay Patel819f0962016-11-13 19:30:19 +00004063 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
4064 return {SPF_UNKNOWN, SPNB_NA, false};
4065
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004066 // Z = X -nsw Y
4067 // (X >s Y) ? 0 : Z ==> (Z >s 0) ? 0 : Z ==> SMIN(Z, 0)
4068 // (X <s Y) ? 0 : Z ==> (Z <s 0) ? 0 : Z ==> SMAX(Z, 0)
4069 if (match(TrueVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004070 match(FalseVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004071 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004072
4073 // Z = X -nsw Y
4074 // (X >s Y) ? Z : 0 ==> (Z >s 0) ? Z : 0 ==> SMAX(Z, 0)
4075 // (X <s Y) ? Z : 0 ==> (Z <s 0) ? Z : 0 ==> SMIN(Z, 0)
4076 if (match(FalseVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004077 match(TrueVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004078 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004079
Sanjay Patel819f0962016-11-13 19:30:19 +00004080 if (!match(CmpRHS, m_APInt(C1)))
4081 return {SPF_UNKNOWN, SPNB_NA, false};
4082
4083 // An unsigned min/max can be written with a signed compare.
4084 const APInt *C2;
4085 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
4086 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
4087 // Is the sign bit set?
4088 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
4089 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
Sanjay Patel24c6f882017-01-21 17:51:25 +00004090 if (Pred == CmpInst::ICMP_SLT && *C1 == 0 && C2->isMaxSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004091 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004092
4093 // Is the sign bit clear?
4094 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
4095 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
4096 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnesValue() &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004097 C2->isMinSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004098 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004099 }
4100
4101 // Look through 'not' ops to find disguised signed min/max.
4102 // (X >s C) ? ~X : ~C ==> (~X <s ~C) ? ~X : ~C ==> SMIN(~X, ~C)
4103 // (X <s C) ? ~X : ~C ==> (~X >s ~C) ? ~X : ~C ==> SMAX(~X, ~C)
4104 if (match(TrueVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004105 match(FalseVal, m_APInt(C2)) && ~(*C1) == *C2)
Sanjay Patel819f0962016-11-13 19:30:19 +00004106 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004107
4108 // (X >s C) ? ~C : ~X ==> (~X <s ~C) ? ~C : ~X ==> SMAX(~C, ~X)
4109 // (X <s C) ? ~C : ~X ==> (~X >s ~C) ? ~C : ~X ==> SMIN(~C, ~X)
4110 if (match(FalseVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004111 match(TrueVal, m_APInt(C2)) && ~(*C1) == *C2)
Sanjay Patel819f0962016-11-13 19:30:19 +00004112 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004113
4114 return {SPF_UNKNOWN, SPNB_NA, false};
4115}
4116
James Molloy134bec22015-08-11 09:12:57 +00004117static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
4118 FastMathFlags FMF,
James Molloy270ef8c2015-05-15 16:04:50 +00004119 Value *CmpLHS, Value *CmpRHS,
4120 Value *TrueVal, Value *FalseVal,
4121 Value *&LHS, Value *&RHS) {
James Molloy71b91c22015-05-11 14:42:20 +00004122 LHS = CmpLHS;
4123 RHS = CmpRHS;
4124
James Molloy134bec22015-08-11 09:12:57 +00004125 // If the predicate is an "or-equal" (FP) predicate, then signed zeroes may
4126 // return inconsistent results between implementations.
4127 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
4128 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
4129 // Therefore we behave conservatively and only proceed if at least one of the
4130 // operands is known to not be zero, or if we don't care about signed zeroes.
4131 switch (Pred) {
4132 default: break;
4133 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
4134 case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
4135 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4136 !isKnownNonZero(CmpRHS))
4137 return {SPF_UNKNOWN, SPNB_NA, false};
4138 }
4139
4140 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
4141 bool Ordered = false;
4142
4143 // When given one NaN and one non-NaN input:
4144 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
4145 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
4146 // ordered comparison fails), which could be NaN or non-NaN.
4147 // so here we discover exactly what NaN behavior is required/accepted.
4148 if (CmpInst::isFPPredicate(Pred)) {
4149 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
4150 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
4151
4152 if (LHSSafe && RHSSafe) {
4153 // Both operands are known non-NaN.
4154 NaNBehavior = SPNB_RETURNS_ANY;
4155 } else if (CmpInst::isOrdered(Pred)) {
4156 // An ordered comparison will return false when given a NaN, so it
4157 // returns the RHS.
4158 Ordered = true;
4159 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004160 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004161 NaNBehavior = SPNB_RETURNS_NAN;
4162 else if (RHSSafe)
4163 NaNBehavior = SPNB_RETURNS_OTHER;
4164 else
4165 // Completely unsafe.
4166 return {SPF_UNKNOWN, SPNB_NA, false};
4167 } else {
4168 Ordered = false;
4169 // An unordered comparison will return true when given a NaN, so it
4170 // returns the LHS.
4171 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004172 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004173 NaNBehavior = SPNB_RETURNS_OTHER;
4174 else if (RHSSafe)
4175 NaNBehavior = SPNB_RETURNS_NAN;
4176 else
4177 // Completely unsafe.
4178 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004179 }
4180 }
4181
James Molloy71b91c22015-05-11 14:42:20 +00004182 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
James Molloy134bec22015-08-11 09:12:57 +00004183 std::swap(CmpLHS, CmpRHS);
4184 Pred = CmpInst::getSwappedPredicate(Pred);
4185 if (NaNBehavior == SPNB_RETURNS_NAN)
4186 NaNBehavior = SPNB_RETURNS_OTHER;
4187 else if (NaNBehavior == SPNB_RETURNS_OTHER)
4188 NaNBehavior = SPNB_RETURNS_NAN;
4189 Ordered = !Ordered;
4190 }
4191
4192 // ([if]cmp X, Y) ? X : Y
4193 if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
James Molloy71b91c22015-05-11 14:42:20 +00004194 switch (Pred) {
James Molloy134bec22015-08-11 09:12:57 +00004195 default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
James Molloy71b91c22015-05-11 14:42:20 +00004196 case ICmpInst::ICMP_UGT:
James Molloy134bec22015-08-11 09:12:57 +00004197 case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004198 case ICmpInst::ICMP_SGT:
James Molloy134bec22015-08-11 09:12:57 +00004199 case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004200 case ICmpInst::ICMP_ULT:
James Molloy134bec22015-08-11 09:12:57 +00004201 case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004202 case ICmpInst::ICMP_SLT:
James Molloy134bec22015-08-11 09:12:57 +00004203 case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
4204 case FCmpInst::FCMP_UGT:
4205 case FCmpInst::FCMP_UGE:
4206 case FCmpInst::FCMP_OGT:
4207 case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
4208 case FCmpInst::FCMP_ULT:
4209 case FCmpInst::FCMP_ULE:
4210 case FCmpInst::FCMP_OLT:
4211 case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
James Molloy71b91c22015-05-11 14:42:20 +00004212 }
4213 }
4214
Sanjay Patele372aec2016-10-27 15:26:10 +00004215 const APInt *C1;
4216 if (match(CmpRHS, m_APInt(C1))) {
James Molloy71b91c22015-05-11 14:42:20 +00004217 if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) ||
4218 (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) {
4219
4220 // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X
4221 // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X
Sanjay Patele372aec2016-10-27 15:26:10 +00004222 if (Pred == ICmpInst::ICMP_SGT && (*C1 == 0 || C1->isAllOnesValue())) {
James Molloy134bec22015-08-11 09:12:57 +00004223 return {(CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004224 }
4225
4226 // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X
4227 // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X
Sanjay Patele372aec2016-10-27 15:26:10 +00004228 if (Pred == ICmpInst::ICMP_SLT && (*C1 == 0 || *C1 == 1)) {
James Molloy134bec22015-08-11 09:12:57 +00004229 return {(CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004230 }
4231 }
James Molloy71b91c22015-05-11 14:42:20 +00004232 }
4233
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004234 if (CmpInst::isIntPredicate(Pred))
4235 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
4236
4237 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
4238 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
4239 // semantics than minNum. Be conservative in such case.
4240 if (NaNBehavior != SPNB_RETURNS_ANY ||
4241 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4242 !isKnownNonZero(CmpRHS)))
4243 return {SPF_UNKNOWN, SPNB_NA, false};
4244
4245 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
James Molloy71b91c22015-05-11 14:42:20 +00004246}
James Molloy270ef8c2015-05-15 16:04:50 +00004247
James Molloy569cea62015-09-02 17:25:25 +00004248static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
4249 Instruction::CastOps *CastOp) {
Sanjay Patel14a4b812017-01-29 16:34:57 +00004250 auto *Cast1 = dyn_cast<CastInst>(V1);
4251 if (!Cast1)
James Molloy270ef8c2015-05-15 16:04:50 +00004252 return nullptr;
James Molloy270ef8c2015-05-15 16:04:50 +00004253
Sanjay Patel14a4b812017-01-29 16:34:57 +00004254 *CastOp = Cast1->getOpcode();
4255 Type *SrcTy = Cast1->getSrcTy();
4256 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
4257 // If V1 and V2 are both the same cast from the same type, look through V1.
4258 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
4259 return Cast2->getOperand(0);
James Molloy569cea62015-09-02 17:25:25 +00004260 return nullptr;
4261 }
4262
Sanjay Patel14a4b812017-01-29 16:34:57 +00004263 auto *C = dyn_cast<Constant>(V2);
4264 if (!C)
4265 return nullptr;
4266
David Majnemerd2a074b2016-04-29 18:40:34 +00004267 Constant *CastedTo = nullptr;
Sanjay Patel14a4b812017-01-29 16:34:57 +00004268 switch (*CastOp) {
4269 case Instruction::ZExt:
4270 if (CmpI->isUnsigned())
4271 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
4272 break;
4273 case Instruction::SExt:
4274 if (CmpI->isSigned())
4275 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
4276 break;
4277 case Instruction::Trunc:
4278 CastedTo = ConstantExpr::getIntegerCast(C, SrcTy, CmpI->isSigned());
4279 break;
4280 case Instruction::FPTrunc:
4281 CastedTo = ConstantExpr::getFPExtend(C, SrcTy, true);
4282 break;
4283 case Instruction::FPExt:
4284 CastedTo = ConstantExpr::getFPTrunc(C, SrcTy, true);
4285 break;
4286 case Instruction::FPToUI:
4287 CastedTo = ConstantExpr::getUIToFP(C, SrcTy, true);
4288 break;
4289 case Instruction::FPToSI:
4290 CastedTo = ConstantExpr::getSIToFP(C, SrcTy, true);
4291 break;
4292 case Instruction::UIToFP:
4293 CastedTo = ConstantExpr::getFPToUI(C, SrcTy, true);
4294 break;
4295 case Instruction::SIToFP:
4296 CastedTo = ConstantExpr::getFPToSI(C, SrcTy, true);
4297 break;
4298 default:
4299 break;
4300 }
David Majnemerd2a074b2016-04-29 18:40:34 +00004301
4302 if (!CastedTo)
4303 return nullptr;
4304
David Majnemerd2a074b2016-04-29 18:40:34 +00004305 // Make sure the cast doesn't lose any information.
Sanjay Patel14a4b812017-01-29 16:34:57 +00004306 Constant *CastedBack =
4307 ConstantExpr::getCast(*CastOp, CastedTo, C->getType(), true);
David Majnemerd2a074b2016-04-29 18:40:34 +00004308 if (CastedBack != C)
4309 return nullptr;
4310
4311 return CastedTo;
James Molloy270ef8c2015-05-15 16:04:50 +00004312}
4313
Sanjay Patele8dc0902016-05-23 17:57:54 +00004314SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004315 Instruction::CastOps *CastOp) {
4316 SelectInst *SI = dyn_cast<SelectInst>(V);
James Molloy134bec22015-08-11 09:12:57 +00004317 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004318
James Molloy134bec22015-08-11 09:12:57 +00004319 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
4320 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004321
James Molloy134bec22015-08-11 09:12:57 +00004322 CmpInst::Predicate Pred = CmpI->getPredicate();
James Molloy270ef8c2015-05-15 16:04:50 +00004323 Value *CmpLHS = CmpI->getOperand(0);
4324 Value *CmpRHS = CmpI->getOperand(1);
4325 Value *TrueVal = SI->getTrueValue();
4326 Value *FalseVal = SI->getFalseValue();
James Molloy134bec22015-08-11 09:12:57 +00004327 FastMathFlags FMF;
4328 if (isa<FPMathOperator>(CmpI))
4329 FMF = CmpI->getFastMathFlags();
James Molloy270ef8c2015-05-15 16:04:50 +00004330
4331 // Bail out early.
4332 if (CmpI->isEquality())
James Molloy134bec22015-08-11 09:12:57 +00004333 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004334
4335 // Deal with type mismatches.
4336 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
James Molloy569cea62015-09-02 17:25:25 +00004337 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp))
James Molloy134bec22015-08-11 09:12:57 +00004338 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004339 cast<CastInst>(TrueVal)->getOperand(0), C,
4340 LHS, RHS);
James Molloy569cea62015-09-02 17:25:25 +00004341 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp))
James Molloy134bec22015-08-11 09:12:57 +00004342 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004343 C, cast<CastInst>(FalseVal)->getOperand(0),
4344 LHS, RHS);
4345 }
James Molloy134bec22015-08-11 09:12:57 +00004346 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
James Molloy270ef8c2015-05-15 16:04:50 +00004347 LHS, RHS);
4348}
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004349
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004350/// Return true if "icmp Pred LHS RHS" is always true.
Chad Rosiere42b44b2017-07-28 14:39:06 +00004351static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
4352 const Value *RHS, const DataLayout &DL,
4353 unsigned Depth) {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004354 assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004355 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
4356 return true;
4357
4358 switch (Pred) {
4359 default:
4360 return false;
4361
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004362 case CmpInst::ICMP_SLE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004363 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004364
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004365 // LHS s<= LHS +_{nsw} C if C >= 0
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004366 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004367 return !C->isNegative();
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004368 return false;
4369 }
4370
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004371 case CmpInst::ICMP_ULE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004372 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004373
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004374 // LHS u<= LHS +_{nuw} C for any C
4375 if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasc01b4d22015-11-06 19:01:03 +00004376 return true;
Sanjoy Das92568102015-11-10 23:56:20 +00004377
4378 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
Pete Cooper35b00d52016-08-13 01:05:32 +00004379 auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B,
4380 const Value *&X,
Sanjoy Das92568102015-11-10 23:56:20 +00004381 const APInt *&CA, const APInt *&CB) {
4382 if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
4383 match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
4384 return true;
4385
4386 // If X & C == 0 then (X | C) == X +_{nuw} C
4387 if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
4388 match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
Craig Topperb45eabc2017-04-26 16:39:58 +00004389 KnownBits Known(CA->getBitWidth());
Chad Rosiere42b44b2017-07-28 14:39:06 +00004390 computeKnownBits(X, Known, DL, Depth + 1, /*AC*/ nullptr,
4391 /*CxtI*/ nullptr, /*DT*/ nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +00004392 if (CA->isSubsetOf(Known.Zero) && CB->isSubsetOf(Known.Zero))
Sanjoy Das92568102015-11-10 23:56:20 +00004393 return true;
4394 }
4395
4396 return false;
4397 };
4398
Pete Cooper35b00d52016-08-13 01:05:32 +00004399 const Value *X;
Sanjoy Das92568102015-11-10 23:56:20 +00004400 const APInt *CLHS, *CRHS;
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004401 if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
4402 return CLHS->ule(*CRHS);
Sanjoy Das92568102015-11-10 23:56:20 +00004403
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004404 return false;
4405 }
4406 }
4407}
4408
4409/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
Chad Rosier41dd31f2016-04-20 19:15:26 +00004410/// ALHS ARHS" is true. Otherwise, return None.
4411static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00004412isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS,
Chad Rosiere42b44b2017-07-28 14:39:06 +00004413 const Value *ARHS, const Value *BLHS, const Value *BRHS,
4414 const DataLayout &DL, unsigned Depth) {
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004415 switch (Pred) {
4416 default:
Chad Rosier41dd31f2016-04-20 19:15:26 +00004417 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004418
4419 case CmpInst::ICMP_SLT:
4420 case CmpInst::ICMP_SLE:
Chad Rosiere42b44b2017-07-28 14:39:06 +00004421 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth) &&
4422 isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004423 return true;
4424 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004425
4426 case CmpInst::ICMP_ULT:
4427 case CmpInst::ICMP_ULE:
Chad Rosiere42b44b2017-07-28 14:39:06 +00004428 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth) &&
4429 isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004430 return true;
4431 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004432 }
4433}
4434
Chad Rosier226a7342016-05-05 17:41:19 +00004435/// Return true if the operands of the two compares match. IsSwappedOps is true
4436/// when the operands match, but are swapped.
Pete Cooper35b00d52016-08-13 01:05:32 +00004437static bool isMatchingOps(const Value *ALHS, const Value *ARHS,
4438 const Value *BLHS, const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00004439 bool &IsSwappedOps) {
4440
4441 bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS);
4442 IsSwappedOps = (ALHS == BRHS && ARHS == BLHS);
4443 return IsMatchingOps || IsSwappedOps;
4444}
4445
Chad Rosier41dd31f2016-04-20 19:15:26 +00004446/// Return true if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS BRHS" is
4447/// true. Return false if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS
4448/// BRHS" is false. Otherwise, return None if we can't infer anything.
4449static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred,
Pete Cooper35b00d52016-08-13 01:05:32 +00004450 const Value *ALHS,
4451 const Value *ARHS,
Chad Rosier41dd31f2016-04-20 19:15:26 +00004452 CmpInst::Predicate BPred,
Pete Cooper35b00d52016-08-13 01:05:32 +00004453 const Value *BLHS,
4454 const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00004455 bool IsSwappedOps) {
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004456 // Canonicalize the operands so they're matching.
4457 if (IsSwappedOps) {
4458 std::swap(BLHS, BRHS);
4459 BPred = ICmpInst::getSwappedPredicate(BPred);
4460 }
Chad Rosier99bc4802016-04-21 16:18:02 +00004461 if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred))
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004462 return true;
Chad Rosier99bc4802016-04-21 16:18:02 +00004463 if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004464 return false;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004465
Chad Rosier41dd31f2016-04-20 19:15:26 +00004466 return None;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004467}
4468
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004469/// Return true if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS C2" is
4470/// true. Return false if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS
4471/// C2" is false. Otherwise, return None if we can't infer anything.
4472static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00004473isImpliedCondMatchingImmOperands(CmpInst::Predicate APred, const Value *ALHS,
4474 const ConstantInt *C1,
4475 CmpInst::Predicate BPred,
4476 const Value *BLHS, const ConstantInt *C2) {
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004477 assert(ALHS == BLHS && "LHS operands must match.");
4478 ConstantRange DomCR =
4479 ConstantRange::makeExactICmpRegion(APred, C1->getValue());
4480 ConstantRange CR =
4481 ConstantRange::makeAllowedICmpRegion(BPred, C2->getValue());
4482 ConstantRange Intersection = DomCR.intersectWith(CR);
4483 ConstantRange Difference = DomCR.difference(CR);
4484 if (Intersection.isEmptySet())
4485 return false;
4486 if (Difference.isEmptySet())
4487 return true;
4488 return None;
4489}
4490
Chad Rosier2f498032017-07-28 18:47:43 +00004491/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
4492/// false. Otherwise, return None if we can't infer anything.
4493static Optional<bool> isImpliedCondICmps(const ICmpInst *LHS,
4494 const ICmpInst *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00004495 const DataLayout &DL, bool LHSIsTrue,
Chad Rosier2f498032017-07-28 18:47:43 +00004496 unsigned Depth) {
4497 Value *ALHS = LHS->getOperand(0);
4498 Value *ARHS = LHS->getOperand(1);
Chad Rosiera72a9ff2017-07-06 20:00:25 +00004499 // The rest of the logic assumes the LHS condition is true. If that's not the
4500 // case, invert the predicate to make it so.
Chad Rosier2f498032017-07-28 18:47:43 +00004501 ICmpInst::Predicate APred =
Chad Rosierdfd1de62017-08-01 20:18:54 +00004502 LHSIsTrue ? LHS->getPredicate() : LHS->getInversePredicate();
Chad Rosier2f498032017-07-28 18:47:43 +00004503
4504 Value *BLHS = RHS->getOperand(0);
4505 Value *BRHS = RHS->getOperand(1);
4506 ICmpInst::Predicate BPred = RHS->getPredicate();
Chad Rosiere2cbd132016-04-25 17:23:36 +00004507
Chad Rosier226a7342016-05-05 17:41:19 +00004508 // Can we infer anything when the two compares have matching operands?
4509 bool IsSwappedOps;
4510 if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, IsSwappedOps)) {
4511 if (Optional<bool> Implication = isImpliedCondMatchingOperands(
4512 APred, ALHS, ARHS, BPred, BLHS, BRHS, IsSwappedOps))
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004513 return Implication;
Chad Rosier226a7342016-05-05 17:41:19 +00004514 // No amount of additional analysis will infer the second condition, so
4515 // early exit.
4516 return None;
4517 }
4518
4519 // Can we infer anything when the LHS operands match and the RHS operands are
4520 // constants (not necessarily matching)?
4521 if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) {
4522 if (Optional<bool> Implication = isImpliedCondMatchingImmOperands(
4523 APred, ALHS, cast<ConstantInt>(ARHS), BPred, BLHS,
4524 cast<ConstantInt>(BRHS)))
4525 return Implication;
4526 // No amount of additional analysis will infer the second condition, so
4527 // early exit.
4528 return None;
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004529 }
4530
Chad Rosier41dd31f2016-04-20 19:15:26 +00004531 if (APred == BPred)
Chad Rosiere42b44b2017-07-28 14:39:06 +00004532 return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth);
Chad Rosier41dd31f2016-04-20 19:15:26 +00004533 return None;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004534}
Chad Rosier2f498032017-07-28 18:47:43 +00004535
Chad Rosierf73a10d2017-08-01 19:22:36 +00004536/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
4537/// false. Otherwise, return None if we can't infer anything. We expect the
4538/// RHS to be an icmp and the LHS to be an 'and' or an 'or' instruction.
4539static Optional<bool> isImpliedCondAndOr(const BinaryOperator *LHS,
4540 const ICmpInst *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00004541 const DataLayout &DL, bool LHSIsTrue,
Chad Rosierf73a10d2017-08-01 19:22:36 +00004542 unsigned Depth) {
4543 // The LHS must be an 'or' or an 'and' instruction.
4544 assert((LHS->getOpcode() == Instruction::And ||
4545 LHS->getOpcode() == Instruction::Or) &&
4546 "Expected LHS to be 'and' or 'or'.");
4547
Davide Italiano1a943a92017-08-09 16:06:54 +00004548 assert(Depth <= MaxDepth && "Hit recursion limit");
Chad Rosierf73a10d2017-08-01 19:22:36 +00004549
4550 // If the result of an 'or' is false, then we know both legs of the 'or' are
4551 // false. Similarly, if the result of an 'and' is true, then we know both
4552 // legs of the 'and' are true.
4553 Value *ALHS, *ARHS;
Chad Rosierdfd1de62017-08-01 20:18:54 +00004554 if ((!LHSIsTrue && match(LHS, m_Or(m_Value(ALHS), m_Value(ARHS)))) ||
4555 (LHSIsTrue && match(LHS, m_And(m_Value(ALHS), m_Value(ARHS))))) {
Chad Rosierf73a10d2017-08-01 19:22:36 +00004556 // FIXME: Make this non-recursion.
4557 if (Optional<bool> Implication =
Chad Rosierdfd1de62017-08-01 20:18:54 +00004558 isImpliedCondition(ALHS, RHS, DL, LHSIsTrue, Depth + 1))
Chad Rosierf73a10d2017-08-01 19:22:36 +00004559 return Implication;
4560 if (Optional<bool> Implication =
Chad Rosierdfd1de62017-08-01 20:18:54 +00004561 isImpliedCondition(ARHS, RHS, DL, LHSIsTrue, Depth + 1))
Chad Rosierf73a10d2017-08-01 19:22:36 +00004562 return Implication;
4563 return None;
4564 }
4565 return None;
4566}
4567
Chad Rosier2f498032017-07-28 18:47:43 +00004568Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00004569 const DataLayout &DL, bool LHSIsTrue,
Chad Rosier2f498032017-07-28 18:47:43 +00004570 unsigned Depth) {
Davide Italiano30e51942017-08-09 15:13:50 +00004571 // Bail out when we hit the limit.
4572 if (Depth == MaxDepth)
4573 return None;
4574
Chad Rosierf73a10d2017-08-01 19:22:36 +00004575 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
4576 // example.
Chad Rosier2f498032017-07-28 18:47:43 +00004577 if (LHS->getType() != RHS->getType())
4578 return None;
4579
4580 Type *OpTy = LHS->getType();
Chad Rosierf73a10d2017-08-01 19:22:36 +00004581 assert(OpTy->isIntOrIntVectorTy(1) && "Expected integer type only!");
Chad Rosier2f498032017-07-28 18:47:43 +00004582
4583 // LHS ==> RHS by definition
4584 if (LHS == RHS)
Chad Rosierdfd1de62017-08-01 20:18:54 +00004585 return LHSIsTrue;
Chad Rosier2f498032017-07-28 18:47:43 +00004586
Chad Rosierf73a10d2017-08-01 19:22:36 +00004587 // FIXME: Extending the code below to handle vectors.
Chad Rosier2f498032017-07-28 18:47:43 +00004588 if (OpTy->isVectorTy())
Chad Rosier2f498032017-07-28 18:47:43 +00004589 return None;
Chad Rosierf73a10d2017-08-01 19:22:36 +00004590
Chad Rosier2f498032017-07-28 18:47:43 +00004591 assert(OpTy->isIntegerTy(1) && "implied by above");
4592
Chad Rosier2f498032017-07-28 18:47:43 +00004593 // Both LHS and RHS are icmps.
Chad Rosierf73a10d2017-08-01 19:22:36 +00004594 const ICmpInst *LHSCmp = dyn_cast<ICmpInst>(LHS);
4595 const ICmpInst *RHSCmp = dyn_cast<ICmpInst>(RHS);
4596 if (LHSCmp && RHSCmp)
Chad Rosierdfd1de62017-08-01 20:18:54 +00004597 return isImpliedCondICmps(LHSCmp, RHSCmp, DL, LHSIsTrue, Depth);
Chad Rosier2f498032017-07-28 18:47:43 +00004598
Chad Rosierf73a10d2017-08-01 19:22:36 +00004599 // The LHS should be an 'or' or an 'and' instruction. We expect the RHS to be
4600 // an icmp. FIXME: Add support for and/or on the RHS.
4601 const BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHS);
4602 if (LHSBO && RHSCmp) {
4603 if ((LHSBO->getOpcode() == Instruction::And ||
4604 LHSBO->getOpcode() == Instruction::Or))
Chad Rosierdfd1de62017-08-01 20:18:54 +00004605 return isImpliedCondAndOr(LHSBO, RHSCmp, DL, LHSIsTrue, Depth);
Chad Rosier2f498032017-07-28 18:47:43 +00004606 }
Chad Rosierf73a10d2017-08-01 19:22:36 +00004607 return None;
Chad Rosier2f498032017-07-28 18:47:43 +00004608}