blob: 411ede451b28df3c5e3323ff0501c8464e67a8aa [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"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000016#include "llvm/ADT/APFloat.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/None.h"
James Molloy493e57d2015-10-26 14:10:46 +000020#include "llvm/ADT/Optional.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000021#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000023#include "llvm/ADT/SmallSet.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/StringRef.h"
26#include "llvm/ADT/iterator_range.h"
27#include "llvm/Analysis/AliasAnalysis.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000028#include "llvm/Analysis/AssumptionCache.h"
Dan Gohman949ab782010-12-15 20:10:26 +000029#include "llvm/Analysis/InstructionSimplify.h"
Artur Pilipenko31bcca42016-02-24 12:49:04 +000030#include "llvm/Analysis/Loads.h"
Adam Nemete2b885c2015-04-23 20:09:20 +000031#include "llvm/Analysis/LoopInfo.h"
Adam Nemet0965da22017-10-09 23:19:02 +000032#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000033#include "llvm/Analysis/TargetLibraryInfo.h"
34#include "llvm/IR/Argument.h"
35#include "llvm/IR/Attributes.h"
36#include "llvm/IR/BasicBlock.h"
Nick Lewyckyec373542014-05-20 05:13:21 +000037#include "llvm/IR/CallSite.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000038#include "llvm/IR/Constant.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000039#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/Constants.h"
41#include "llvm/IR/DataLayout.h"
Matthias Braun50ec0b52017-05-19 22:37:09 +000042#include "llvm/IR/DerivedTypes.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000043#include "llvm/IR/DiagnosticInfo.h"
Hal Finkel60db0582014-09-07 18:57:58 +000044#include "llvm/IR/Dominators.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000045#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000046#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/GlobalAlias.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000048#include "llvm/IR/GlobalValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000049#include "llvm/IR/GlobalVariable.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000050#include "llvm/IR/InstrTypes.h"
51#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000052#include "llvm/IR/Instructions.h"
53#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000054#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/LLVMContext.h"
56#include "llvm/IR/Metadata.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000057#include "llvm/IR/Module.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000058#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000059#include "llvm/IR/PatternMatch.h"
Eugene Zelenko75075ef2017-09-01 21:37:29 +000060#include "llvm/IR/Type.h"
61#include "llvm/IR/User.h"
62#include "llvm/IR/Value.h"
63#include "llvm/Support/Casting.h"
64#include "llvm/Support/CommandLine.h"
65#include "llvm/Support/Compiler.h"
66#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000067#include "llvm/Support/KnownBits.h"
Chris Lattner965c7692008-06-02 01:18:21 +000068#include "llvm/Support/MathExtras.h"
Matthias Braun37e5d792016-01-28 06:29:33 +000069#include <algorithm>
70#include <array>
Eugene Zelenko75075ef2017-09-01 21:37:29 +000071#include <cassert>
72#include <cstdint>
73#include <iterator>
74#include <utility>
75
Chris Lattner965c7692008-06-02 01:18:21 +000076using namespace llvm;
Duncan Sandsd3951082011-01-25 09:38:29 +000077using namespace llvm::PatternMatch;
78
79const unsigned MaxDepth = 6;
80
Philip Reames1c292272015-03-10 22:43:20 +000081// Controls the number of uses of the value searched for possible
82// dominating comparisons.
83static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
Igor Laevskycea9ede2015-09-29 14:57:52 +000084 cl::Hidden, cl::init(20));
Philip Reames1c292272015-03-10 22:43:20 +000085
Craig Topper6b3940a2017-05-03 22:25:19 +000086/// Returns the bitwidth of the given scalar or pointer type. For vector types,
87/// returns the element type's bitwidth.
Mehdi Aminia28d91d2015-03-10 02:37:25 +000088static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
Duncan Sandsd3951082011-01-25 09:38:29 +000089 if (unsigned BitWidth = Ty->getScalarSizeInBits())
90 return BitWidth;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +000091
Elena Demikhovsky945b7e52018-02-14 06:58:08 +000092 return DL.getIndexTypeSizeInBits(Ty);
Duncan Sandsd3951082011-01-25 09:38:29 +000093}
Chris Lattner965c7692008-06-02 01:18:21 +000094
Benjamin Kramercfd8d902014-09-12 08:56:53 +000095namespace {
Eugene Zelenko75075ef2017-09-01 21:37:29 +000096
Hal Finkel60db0582014-09-07 18:57:58 +000097// Simplifying using an assume can only be done in a particular control-flow
98// context (the context instruction provides that context). If an assume and
99// the context instruction are not in the same block then the DT helps in
100// figuring out if we can use it.
101struct Query {
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000102 const DataLayout &DL;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000103 AssumptionCache *AC;
Hal Finkel60db0582014-09-07 18:57:58 +0000104 const Instruction *CxtI;
105 const DominatorTree *DT;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000106
Sanjay Patel54656ca2017-02-06 18:26:06 +0000107 // Unlike the other analyses, this may be a nullptr because not all clients
108 // provide it currently.
109 OptimizationRemarkEmitter *ORE;
Hal Finkel60db0582014-09-07 18:57:58 +0000110
Matthias Braun37e5d792016-01-28 06:29:33 +0000111 /// Set of assumptions that should be excluded from further queries.
112 /// This is because of the potential for mutual recursion to cause
113 /// computeKnownBits to repeatedly visit the same assume intrinsic. The
114 /// classic case of this is assume(x = y), which will attempt to determine
115 /// bits in x from bits in y, which will attempt to determine bits in y from
116 /// bits in x, etc. Regarding the mutual recursion, computeKnownBits can call
Craig Topper6e11a052017-05-08 16:22:48 +0000117 /// isKnownNonZero, which calls computeKnownBits and isKnownToBeAPowerOfTwo
118 /// (all of which can call computeKnownBits), and so on.
Li Huang755f75f2016-10-15 19:00:04 +0000119 std::array<const Value *, MaxDepth> Excluded;
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000120
121 unsigned NumExcluded = 0;
Matthias Braun37e5d792016-01-28 06:29:33 +0000122
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000123 Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI,
Sanjay Patel54656ca2017-02-06 18:26:06 +0000124 const DominatorTree *DT, OptimizationRemarkEmitter *ORE = nullptr)
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000125 : DL(DL), AC(AC), CxtI(CxtI), DT(DT), ORE(ORE) {}
Hal Finkel60db0582014-09-07 18:57:58 +0000126
127 Query(const Query &Q, const Value *NewExcl)
Sanjay Patel54656ca2017-02-06 18:26:06 +0000128 : DL(Q.DL), AC(Q.AC), CxtI(Q.CxtI), DT(Q.DT), ORE(Q.ORE),
129 NumExcluded(Q.NumExcluded) {
Matthias Braun37e5d792016-01-28 06:29:33 +0000130 Excluded = Q.Excluded;
131 Excluded[NumExcluded++] = NewExcl;
132 assert(NumExcluded <= Excluded.size());
133 }
134
135 bool isExcluded(const Value *Value) const {
136 if (NumExcluded == 0)
137 return false;
138 auto End = Excluded.begin() + NumExcluded;
139 return std::find(Excluded.begin(), End, Value) != End;
Hal Finkel60db0582014-09-07 18:57:58 +0000140 }
141};
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000142
Benjamin Kramercfd8d902014-09-12 08:56:53 +0000143} // end anonymous namespace
Hal Finkel60db0582014-09-07 18:57:58 +0000144
Sanjay Patel547e9752014-11-04 16:09:50 +0000145// Given the provided Value and, potentially, a context instruction, return
Hal Finkel60db0582014-09-07 18:57:58 +0000146// the preferred context instruction (if any).
147static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
148 // If we've been provided with a context instruction, then use that (provided
149 // it has been inserted).
150 if (CxtI && CxtI->getParent())
151 return CxtI;
152
153 // If the value is really an already-inserted instruction, then use that.
154 CxtI = dyn_cast<Instruction>(V);
155 if (CxtI && CxtI->getParent())
156 return CxtI;
157
158 return nullptr;
159}
160
Craig Topperb45eabc2017-04-26 16:39:58 +0000161static void computeKnownBits(const Value *V, KnownBits &Known,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000162 unsigned Depth, const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000163
Craig Topperb45eabc2017-04-26 16:39:58 +0000164void llvm::computeKnownBits(const Value *V, KnownBits &Known,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000165 const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000166 AssumptionCache *AC, const Instruction *CxtI,
Sanjay Patel54656ca2017-02-06 18:26:06 +0000167 const DominatorTree *DT,
168 OptimizationRemarkEmitter *ORE) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000169 ::computeKnownBits(V, Known, Depth,
Sanjay Patel54656ca2017-02-06 18:26:06 +0000170 Query(DL, AC, safeCxtI(V, CxtI), DT, ORE));
Hal Finkel60db0582014-09-07 18:57:58 +0000171}
172
Craig Topper6e11a052017-05-08 16:22:48 +0000173static KnownBits computeKnownBits(const Value *V, unsigned Depth,
174 const Query &Q);
175
176KnownBits llvm::computeKnownBits(const Value *V, const DataLayout &DL,
177 unsigned Depth, AssumptionCache *AC,
178 const Instruction *CxtI,
Craig Toppera2025ea2017-05-24 16:53:03 +0000179 const DominatorTree *DT,
180 OptimizationRemarkEmitter *ORE) {
181 return ::computeKnownBits(V, Depth,
182 Query(DL, AC, safeCxtI(V, CxtI), DT, ORE));
Craig Topper6e11a052017-05-08 16:22:48 +0000183}
184
Pete Cooper35b00d52016-08-13 01:05:32 +0000185bool llvm::haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
186 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000187 AssumptionCache *AC, const Instruction *CxtI,
Jingyue Wuca321902015-05-14 23:53:19 +0000188 const DominatorTree *DT) {
189 assert(LHS->getType() == RHS->getType() &&
190 "LHS and RHS should have the same type");
191 assert(LHS->getType()->isIntOrIntVectorTy() &&
192 "LHS and RHS should be integers");
193 IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
Craig Topperb45eabc2017-04-26 16:39:58 +0000194 KnownBits LHSKnown(IT->getBitWidth());
195 KnownBits RHSKnown(IT->getBitWidth());
196 computeKnownBits(LHS, LHSKnown, DL, 0, AC, CxtI, DT);
197 computeKnownBits(RHS, RHSKnown, DL, 0, AC, CxtI, DT);
198 return (LHSKnown.Zero | RHSKnown.Zero).isAllOnesValue();
Jingyue Wuca321902015-05-14 23:53:19 +0000199}
200
Zaara Syeda3a7578c2017-05-31 17:12:38 +0000201bool llvm::isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI) {
202 for (const User *U : CxtI->users()) {
203 if (const ICmpInst *IC = dyn_cast<ICmpInst>(U))
204 if (IC->isEquality())
205 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
206 if (C->isNullValue())
207 continue;
208 return false;
209 }
210 return true;
211}
212
Pete Cooper35b00d52016-08-13 01:05:32 +0000213static bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000214 const Query &Q);
Hal Finkel60db0582014-09-07 18:57:58 +0000215
Pete Cooper35b00d52016-08-13 01:05:32 +0000216bool llvm::isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
217 bool OrZero,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000218 unsigned Depth, AssumptionCache *AC,
219 const Instruction *CxtI,
Hal Finkel60db0582014-09-07 18:57:58 +0000220 const DominatorTree *DT) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000221 return ::isKnownToBeAPowerOfTwo(V, OrZero, Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000222 Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000223}
224
Pete Cooper35b00d52016-08-13 01:05:32 +0000225static bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000226
Pete Cooper35b00d52016-08-13 01:05:32 +0000227bool llvm::isKnownNonZero(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) {
230 return ::isKnownNonZero(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000231}
232
Pete Cooper35b00d52016-08-13 01:05:32 +0000233bool llvm::isKnownNonNegative(const Value *V, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000234 unsigned Depth,
235 AssumptionCache *AC, const Instruction *CxtI,
Jingyue Wu10fcea52015-08-20 18:27:04 +0000236 const DominatorTree *DT) {
Craig Topper6e11a052017-05-08 16:22:48 +0000237 KnownBits Known = computeKnownBits(V, DL, Depth, AC, CxtI, DT);
238 return Known.isNonNegative();
Jingyue Wu10fcea52015-08-20 18:27:04 +0000239}
240
Pete Cooper35b00d52016-08-13 01:05:32 +0000241bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000242 AssumptionCache *AC, const Instruction *CxtI,
243 const DominatorTree *DT) {
Philip Reames8f12eba2016-03-09 21:31:47 +0000244 if (auto *CI = dyn_cast<ConstantInt>(V))
245 return CI->getValue().isStrictlyPositive();
Sanjoy Das6082c1a2016-05-07 02:08:15 +0000246
Philip Reames8f12eba2016-03-09 21:31:47 +0000247 // TODO: We'd doing two recursive queries here. We should factor this such
248 // that only a single query is needed.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000249 return isKnownNonNegative(V, DL, Depth, AC, CxtI, DT) &&
250 isKnownNonZero(V, DL, Depth, AC, CxtI, DT);
Philip Reames8f12eba2016-03-09 21:31:47 +0000251}
252
Pete Cooper35b00d52016-08-13 01:05:32 +0000253bool llvm::isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000254 AssumptionCache *AC, const Instruction *CxtI,
255 const DominatorTree *DT) {
Craig Topper6e11a052017-05-08 16:22:48 +0000256 KnownBits Known = computeKnownBits(V, DL, Depth, AC, CxtI, DT);
257 return Known.isNegative();
Nick Lewycky762f8a82016-04-21 00:53:14 +0000258}
259
Pete Cooper35b00d52016-08-13 01:05:32 +0000260static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q);
James Molloy1d88d6f2015-10-22 13:18:42 +0000261
Pete Cooper35b00d52016-08-13 01:05:32 +0000262bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000263 const DataLayout &DL,
264 AssumptionCache *AC, const Instruction *CxtI,
Pete Cooper35b00d52016-08-13 01:05:32 +0000265 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000266 return ::isKnownNonEqual(V1, V2, Query(DL, AC,
267 safeCxtI(V1, safeCxtI(V2, CxtI)),
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000268 DT));
James Molloy1d88d6f2015-10-22 13:18:42 +0000269}
270
Pete Cooper35b00d52016-08-13 01:05:32 +0000271static bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000272 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000273
Pete Cooper35b00d52016-08-13 01:05:32 +0000274bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
275 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000276 unsigned Depth, AssumptionCache *AC,
277 const Instruction *CxtI, const DominatorTree *DT) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000278 return ::MaskedValueIsZero(V, Mask, Depth,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000279 Query(DL, AC, safeCxtI(V, CxtI), DT));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000280}
281
Pete Cooper35b00d52016-08-13 01:05:32 +0000282static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
283 const Query &Q);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000284
Pete Cooper35b00d52016-08-13 01:05:32 +0000285unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000286 unsigned Depth, AssumptionCache *AC,
287 const Instruction *CxtI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000288 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000289 return ::ComputeNumSignBits(V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT));
Hal Finkel60db0582014-09-07 18:57:58 +0000290}
291
Craig Topper8fbb74b2017-03-24 22:12:10 +0000292static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
293 bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000294 KnownBits &KnownOut, KnownBits &Known2,
Craig Topper8fbb74b2017-03-24 22:12:10 +0000295 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000296 unsigned BitWidth = KnownOut.getBitWidth();
Craig Topper8fbb74b2017-03-24 22:12:10 +0000297
298 // If an initial sequence of bits in the result is not needed, the
299 // corresponding bits in the operands are not needed.
Craig Topperb45eabc2017-04-26 16:39:58 +0000300 KnownBits LHSKnown(BitWidth);
301 computeKnownBits(Op0, LHSKnown, Depth + 1, Q);
302 computeKnownBits(Op1, Known2, Depth + 1, Q);
Craig Topper8fbb74b2017-03-24 22:12:10 +0000303
Craig Topperb498a232017-08-08 16:29:35 +0000304 KnownOut = KnownBits::computeForAddSub(Add, NSW, LHSKnown, Known2);
Nick Lewyckyfea3e002012-03-09 09:23:50 +0000305}
306
Pete Cooper35b00d52016-08-13 01:05:32 +0000307static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +0000308 KnownBits &Known, KnownBits &Known2,
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000309 unsigned Depth, const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000310 unsigned BitWidth = Known.getBitWidth();
311 computeKnownBits(Op1, Known, Depth + 1, Q);
312 computeKnownBits(Op0, Known2, Depth + 1, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000313
314 bool isKnownNegative = false;
315 bool isKnownNonNegative = false;
316 // If the multiplication is known not to overflow, compute the sign bit.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000317 if (NSW) {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000318 if (Op0 == Op1) {
319 // The product of a number with itself is non-negative.
320 isKnownNonNegative = true;
321 } else {
Craig Topperca48af32017-04-29 16:43:11 +0000322 bool isKnownNonNegativeOp1 = Known.isNonNegative();
323 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
324 bool isKnownNegativeOp1 = Known.isNegative();
325 bool isKnownNegativeOp0 = Known2.isNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000326 // The product of two numbers with the same sign is non-negative.
327 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
328 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
329 // The product of a negative number and a non-negative number is either
330 // negative or zero.
331 if (!isKnownNonNegative)
332 isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000333 isKnownNonZero(Op0, Depth, Q)) ||
Nick Lewyckyfa306072012-03-18 23:28:48 +0000334 (isKnownNegativeOp0 && isKnownNonNegativeOp1 &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000335 isKnownNonZero(Op1, Depth, Q));
Nick Lewyckyfa306072012-03-18 23:28:48 +0000336 }
337 }
338
Simon Dardis70dbd5f2017-12-09 23:25:57 +0000339 assert(!Known.hasConflict() && !Known2.hasConflict());
340 // Compute a conservative estimate for high known-0 bits.
Craig Topper8df66c62017-05-12 17:20:30 +0000341 unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
342 Known2.countMinLeadingZeros(),
Nick Lewyckyfa306072012-03-18 23:28:48 +0000343 BitWidth) - BitWidth;
Nick Lewyckyfa306072012-03-18 23:28:48 +0000344 LeadZ = std::min(LeadZ, BitWidth);
Simon Dardis70dbd5f2017-12-09 23:25:57 +0000345
346 // The result of the bottom bits of an integer multiply can be
347 // inferred by looking at the bottom bits of both operands and
348 // multiplying them together.
349 // We can infer at least the minimum number of known trailing bits
350 // of both operands. Depending on number of trailing zeros, we can
351 // infer more bits, because (a*b) <=> ((a/m) * (b/n)) * (m*n) assuming
352 // a and b are divisible by m and n respectively.
353 // We then calculate how many of those bits are inferrable and set
354 // the output. For example, the i8 mul:
355 // a = XXXX1100 (12)
356 // b = XXXX1110 (14)
357 // We know the bottom 3 bits are zero since the first can be divided by
358 // 4 and the second by 2, thus having ((12/4) * (14/2)) * (2*4).
359 // Applying the multiplication to the trimmed arguments gets:
360 // XX11 (3)
361 // X111 (7)
362 // -------
363 // XX11
364 // XX11
365 // XX11
366 // XX11
367 // -------
368 // XXXXX01
369 // Which allows us to infer the 2 LSBs. Since we're multiplying the result
370 // by 8, the bottom 3 bits will be 0, so we can infer a total of 5 bits.
371 // The proof for this can be described as:
372 // Pre: (C1 >= 0) && (C1 < (1 << C5)) && (C2 >= 0) && (C2 < (1 << C6)) &&
373 // (C7 == (1 << (umin(countTrailingZeros(C1), C5) +
374 // umin(countTrailingZeros(C2), C6) +
375 // umin(C5 - umin(countTrailingZeros(C1), C5),
376 // C6 - umin(countTrailingZeros(C2), C6)))) - 1)
377 // %aa = shl i8 %a, C5
378 // %bb = shl i8 %b, C6
379 // %aaa = or i8 %aa, C1
380 // %bbb = or i8 %bb, C2
381 // %mul = mul i8 %aaa, %bbb
382 // %mask = and i8 %mul, C7
383 // =>
384 // %mask = i8 ((C1*C2)&C7)
385 // Where C5, C6 describe the known bits of %a, %b
386 // C1, C2 describe the known bottom bits of %a, %b.
387 // C7 describes the mask of the known bits of the result.
388 APInt Bottom0 = Known.One;
389 APInt Bottom1 = Known2.One;
390
391 // How many times we'd be able to divide each argument by 2 (shr by 1).
392 // This gives us the number of trailing zeros on the multiplication result.
393 unsigned TrailBitsKnown0 = (Known.Zero | Known.One).countTrailingOnes();
394 unsigned TrailBitsKnown1 = (Known2.Zero | Known2.One).countTrailingOnes();
395 unsigned TrailZero0 = Known.countMinTrailingZeros();
396 unsigned TrailZero1 = Known2.countMinTrailingZeros();
397 unsigned TrailZ = TrailZero0 + TrailZero1;
398
399 // Figure out the fewest known-bits operand.
400 unsigned SmallestOperand = std::min(TrailBitsKnown0 - TrailZero0,
401 TrailBitsKnown1 - TrailZero1);
402 unsigned ResultBitsKnown = std::min(SmallestOperand + TrailZ, BitWidth);
403
404 APInt BottomKnown = Bottom0.getLoBits(TrailBitsKnown0) *
405 Bottom1.getLoBits(TrailBitsKnown1);
406
Craig Topperf0aeee02017-05-05 17:36:09 +0000407 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000408 Known.Zero.setHighBits(LeadZ);
Simon Dardis70dbd5f2017-12-09 23:25:57 +0000409 Known.Zero |= (~BottomKnown).getLoBits(ResultBitsKnown);
410 Known.One |= BottomKnown.getLoBits(ResultBitsKnown);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000411
412 // Only make use of no-wrap flags if we failed to compute the sign bit
413 // directly. This matters if the multiplication always overflows, in
414 // which case we prefer to follow the result of the direct computation,
415 // though as the program is invoking undefined behaviour we can choose
416 // whatever we like here.
Craig Topperca48af32017-04-29 16:43:11 +0000417 if (isKnownNonNegative && !Known.isNegative())
418 Known.makeNonNegative();
419 else if (isKnownNegative && !Known.isNonNegative())
420 Known.makeNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000421}
422
Jingyue Wu37fcb592014-06-19 16:50:16 +0000423void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
Craig Topperf42b23f2017-04-28 06:28:56 +0000424 KnownBits &Known) {
425 unsigned BitWidth = Known.getBitWidth();
Rafael Espindola53190532012-03-30 15:52:11 +0000426 unsigned NumRanges = Ranges.getNumOperands() / 2;
427 assert(NumRanges >= 1);
428
Craig Topperf42b23f2017-04-28 06:28:56 +0000429 Known.Zero.setAllBits();
430 Known.One.setAllBits();
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000431
Rafael Espindola53190532012-03-30 15:52:11 +0000432 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000433 ConstantInt *Lower =
434 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
435 ConstantInt *Upper =
436 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
Rafael Espindola53190532012-03-30 15:52:11 +0000437 ConstantRange Range(Lower->getValue(), Upper->getValue());
Rafael Espindola53190532012-03-30 15:52:11 +0000438
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000439 // The first CommonPrefixBits of all values in Range are equal.
440 unsigned CommonPrefixBits =
441 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
442
443 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
Craig Topperf42b23f2017-04-28 06:28:56 +0000444 Known.One &= Range.getUnsignedMax() & Mask;
445 Known.Zero &= ~Range.getUnsignedMax() & Mask;
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000446 }
Rafael Espindola53190532012-03-30 15:52:11 +0000447}
Jay Foad5a29c362014-05-15 12:12:55 +0000448
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000449static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
Hal Finkel60db0582014-09-07 18:57:58 +0000450 SmallVector<const Value *, 16> WorkSet(1, I);
451 SmallPtrSet<const Value *, 32> Visited;
452 SmallPtrSet<const Value *, 16> EphValues;
453
Hal Finkelf2199b22015-10-23 20:37:08 +0000454 // The instruction defining an assumption's condition itself is always
455 // considered ephemeral to that assumption (even if it has other
456 // non-ephemeral users). See r246696's test case for an example.
David Majnemer0a16c222016-08-11 21:15:00 +0000457 if (is_contained(I->operands(), E))
Hal Finkelf2199b22015-10-23 20:37:08 +0000458 return true;
459
Hal Finkel60db0582014-09-07 18:57:58 +0000460 while (!WorkSet.empty()) {
461 const Value *V = WorkSet.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +0000462 if (!Visited.insert(V).second)
Hal Finkel60db0582014-09-07 18:57:58 +0000463 continue;
464
465 // If all uses of this value are ephemeral, then so is this value.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000466 if (llvm::all_of(V->users(), [&](const User *U) {
467 return EphValues.count(U);
468 })) {
Hal Finkel60db0582014-09-07 18:57:58 +0000469 if (V == E)
470 return true;
471
Hal Finkelb03dd4b2017-08-14 17:11:43 +0000472 if (V == I || isSafeToSpeculativelyExecute(V)) {
473 EphValues.insert(V);
474 if (const User *U = dyn_cast<User>(V))
475 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
476 J != JE; ++J)
477 WorkSet.push_back(*J);
478 }
Hal Finkel60db0582014-09-07 18:57:58 +0000479 }
480 }
481
482 return false;
483}
484
485// Is this an intrinsic that cannot be speculated but also cannot trap?
Haicheng Wua4461512017-12-15 14:34:41 +0000486bool llvm::isAssumeLikeIntrinsic(const Instruction *I) {
Hal Finkel60db0582014-09-07 18:57:58 +0000487 if (const CallInst *CI = dyn_cast<CallInst>(I))
488 if (Function *F = CI->getCalledFunction())
489 switch (F->getIntrinsicID()) {
490 default: break;
491 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
492 case Intrinsic::assume:
Dan Gohman2c74fe92017-11-08 21:59:51 +0000493 case Intrinsic::sideeffect:
Hal Finkel60db0582014-09-07 18:57:58 +0000494 case Intrinsic::dbg_declare:
495 case Intrinsic::dbg_value:
496 case Intrinsic::invariant_start:
497 case Intrinsic::invariant_end:
498 case Intrinsic::lifetime_start:
499 case Intrinsic::lifetime_end:
500 case Intrinsic::objectsize:
501 case Intrinsic::ptr_annotation:
502 case Intrinsic::var_annotation:
503 return true;
504 }
505
506 return false;
507}
508
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000509bool llvm::isValidAssumeForContext(const Instruction *Inv,
510 const Instruction *CxtI,
511 const DominatorTree *DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000512 // There are two restrictions on the use of an assume:
513 // 1. The assume must dominate the context (or the control flow must
514 // reach the assume whenever it reaches the context).
515 // 2. The context must not be in the assume's set of ephemeral values
516 // (otherwise we will use the assume to prove that the condition
517 // feeding the assume is trivially true, thus causing the removal of
518 // the assume).
519
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000520 if (DT) {
Pete Cooper54a02552016-08-12 01:00:15 +0000521 if (DT->dominates(Inv, CxtI))
Hal Finkel60db0582014-09-07 18:57:58 +0000522 return true;
Pete Cooper54a02552016-08-12 01:00:15 +0000523 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
524 // We don't have a DT, but this trivially dominates.
525 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000526 }
527
Pete Cooper54a02552016-08-12 01:00:15 +0000528 // With or without a DT, the only remaining case we will check is if the
529 // instructions are in the same BB. Give up if that is not the case.
530 if (Inv->getParent() != CxtI->getParent())
531 return false;
532
Vedant Kumard3196742018-02-28 19:08:52 +0000533 // If we have a dom tree, then we now know that the assume doesn't dominate
Pete Cooper54a02552016-08-12 01:00:15 +0000534 // the other instruction. If we don't have a dom tree then we can check if
535 // the assume is first in the BB.
536 if (!DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000537 // Search forward from the assume until we reach the context (or the end
538 // of the block); the common case is that the assume will come first.
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000539 for (auto I = std::next(BasicBlock::const_iterator(Inv)),
Hal Finkel60db0582014-09-07 18:57:58 +0000540 IE = Inv->getParent()->end(); I != IE; ++I)
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000541 if (&*I == CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000542 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000543 }
544
Pete Cooper54a02552016-08-12 01:00:15 +0000545 // The context comes first, but they're both in the same block. Make sure
546 // there is nothing in between that might interrupt the control flow.
547 for (BasicBlock::const_iterator I =
548 std::next(BasicBlock::const_iterator(CxtI)), IE(Inv);
549 I != IE; ++I)
550 if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
551 return false;
552
553 return !isEphemeralValueOf(Inv, CxtI);
Hal Finkel60db0582014-09-07 18:57:58 +0000554}
555
Craig Topperb45eabc2017-04-26 16:39:58 +0000556static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known,
557 unsigned Depth, const Query &Q) {
Hal Finkel60db0582014-09-07 18:57:58 +0000558 // Use of assumptions is context-sensitive. If we don't have a context, we
559 // cannot use them!
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000560 if (!Q.AC || !Q.CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000561 return;
562
Craig Topperb45eabc2017-04-26 16:39:58 +0000563 unsigned BitWidth = Known.getBitWidth();
Hal Finkel60db0582014-09-07 18:57:58 +0000564
Hal Finkel8a9a7832017-01-11 13:24:24 +0000565 // Note that the patterns below need to be kept in sync with the code
566 // in AssumptionCache::updateAffectedValues.
567
568 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000569 if (!AssumeVH)
Chandler Carruth66b31302015-01-04 12:03:27 +0000570 continue;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000571 CallInst *I = cast<CallInst>(AssumeVH);
572 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
573 "Got assumption for the wrong function!");
574 if (Q.isExcluded(I))
Hal Finkel60db0582014-09-07 18:57:58 +0000575 continue;
576
Vedant Kumard3196742018-02-28 19:08:52 +0000577 // Warning: This loop can end up being somewhat performance sensitive.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000578 // We're running this loop for once for each value queried resulting in a
579 // runtime of ~O(#assumes * #values).
Philip Reames00d3b272014-11-24 23:44:28 +0000580
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000581 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
582 "must be an assume intrinsic");
583
584 Value *Arg = I->getArgOperand(0);
585
586 if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000587 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000588 Known.setAllOnes();
Hal Finkel60db0582014-09-07 18:57:58 +0000589 return;
590 }
Sanjay Patel96669962017-01-17 18:15:49 +0000591 if (match(Arg, m_Not(m_Specific(V))) &&
592 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
593 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000594 Known.setAllZero();
Sanjay Patel96669962017-01-17 18:15:49 +0000595 return;
596 }
Hal Finkel60db0582014-09-07 18:57:58 +0000597
David Majnemer9b609752014-12-12 23:59:29 +0000598 // The remaining tests are all recursive, so bail out if we hit the limit.
599 if (Depth == MaxDepth)
600 continue;
601
Hal Finkel60db0582014-09-07 18:57:58 +0000602 Value *A, *B;
603 auto m_V = m_CombineOr(m_Specific(V),
604 m_CombineOr(m_PtrToInt(m_Specific(V)),
605 m_BitCast(m_Specific(V))));
606
607 CmpInst::Predicate Pred;
Igor Laevskycec8f472017-12-05 12:18:15 +0000608 uint64_t C;
Hal Finkel60db0582014-09-07 18:57:58 +0000609 // assume(v = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000610 if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000611 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000612 KnownBits RHSKnown(BitWidth);
613 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
614 Known.Zero |= RHSKnown.Zero;
615 Known.One |= RHSKnown.One;
Hal Finkel60db0582014-09-07 18:57:58 +0000616 // assume(v & b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000617 } else if (match(Arg,
618 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000619 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000620 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000621 KnownBits RHSKnown(BitWidth);
622 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
623 KnownBits MaskKnown(BitWidth);
624 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel60db0582014-09-07 18:57:58 +0000625
626 // For those bits in the mask that are known to be one, we can propagate
627 // known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000628 Known.Zero |= RHSKnown.Zero & MaskKnown.One;
629 Known.One |= RHSKnown.One & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000630 // assume(~(v & b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000631 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
632 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000633 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000634 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000635 KnownBits RHSKnown(BitWidth);
636 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
637 KnownBits MaskKnown(BitWidth);
638 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000639
640 // For those bits in the mask that are known to be one, we can propagate
641 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000642 Known.Zero |= RHSKnown.One & MaskKnown.One;
643 Known.One |= RHSKnown.Zero & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000644 // assume(v | b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000645 } else if (match(Arg,
646 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000647 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000648 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000649 KnownBits RHSKnown(BitWidth);
650 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
651 KnownBits BKnown(BitWidth);
652 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000653
654 // For those bits in B that are known to be zero, we can propagate known
655 // bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000656 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
657 Known.One |= RHSKnown.One & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000658 // assume(~(v | b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000659 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
660 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000661 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000662 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000663 KnownBits RHSKnown(BitWidth);
664 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
665 KnownBits BKnown(BitWidth);
666 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000667
668 // For those bits in B that are known to be zero, we can propagate
669 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000670 Known.Zero |= RHSKnown.One & BKnown.Zero;
671 Known.One |= RHSKnown.Zero & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000672 // assume(v ^ b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000673 } else if (match(Arg,
674 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000675 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000676 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000677 KnownBits RHSKnown(BitWidth);
678 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
679 KnownBits BKnown(BitWidth);
680 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000681
682 // For those bits in B that are known to be zero, we can propagate known
683 // bits from the RHS to V. For those bits in B that are known to be one,
684 // we can propagate inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000685 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
686 Known.One |= RHSKnown.One & BKnown.Zero;
687 Known.Zero |= RHSKnown.One & BKnown.One;
688 Known.One |= RHSKnown.Zero & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000689 // assume(~(v ^ b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000690 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
691 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000692 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000693 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000694 KnownBits RHSKnown(BitWidth);
695 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
696 KnownBits BKnown(BitWidth);
697 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000698
699 // For those bits in B that are known to be zero, we can propagate
700 // inverted known bits from the RHS to V. For those bits in B that are
701 // known to be one, we can propagate known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000702 Known.Zero |= RHSKnown.One & BKnown.Zero;
703 Known.One |= RHSKnown.Zero & BKnown.Zero;
704 Known.Zero |= RHSKnown.Zero & BKnown.One;
705 Known.One |= RHSKnown.One & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000706 // assume(v << c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000707 } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
708 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000709 Pred == ICmpInst::ICMP_EQ &&
Igor Laevskycec8f472017-12-05 12:18:15 +0000710 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
711 C < BitWidth) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000712 KnownBits RHSKnown(BitWidth);
713 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000714 // For those bits in RHS that are known, we can propagate them to known
715 // bits in V shifted to the right by C.
Igor Laevskycec8f472017-12-05 12:18:15 +0000716 RHSKnown.Zero.lshrInPlace(C);
Craig Topperb45eabc2017-04-26 16:39:58 +0000717 Known.Zero |= RHSKnown.Zero;
Igor Laevskycec8f472017-12-05 12:18:15 +0000718 RHSKnown.One.lshrInPlace(C);
Craig Topperb45eabc2017-04-26 16:39:58 +0000719 Known.One |= RHSKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000720 // assume(~(v << c) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000721 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
722 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000723 Pred == ICmpInst::ICMP_EQ &&
Igor Laevskycec8f472017-12-05 12:18:15 +0000724 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
725 C < BitWidth) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000726 KnownBits RHSKnown(BitWidth);
727 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000728 // For those bits in RHS that are known, we can propagate them inverted
729 // to known bits in V shifted to the right by C.
Igor Laevskycec8f472017-12-05 12:18:15 +0000730 RHSKnown.One.lshrInPlace(C);
Craig Topperb45eabc2017-04-26 16:39:58 +0000731 Known.Zero |= RHSKnown.One;
Igor Laevskycec8f472017-12-05 12:18:15 +0000732 RHSKnown.Zero.lshrInPlace(C);
Craig Topperb45eabc2017-04-26 16:39:58 +0000733 Known.One |= RHSKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000734 // assume(v >> c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000735 } else if (match(Arg,
Craig Topper7b66ffe2017-06-24 06:24:04 +0000736 m_c_ICmp(Pred, m_Shr(m_V, m_ConstantInt(C)),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000737 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000738 Pred == ICmpInst::ICMP_EQ &&
Igor Laevskycec8f472017-12-05 12:18:15 +0000739 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
740 C < BitWidth) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000741 KnownBits RHSKnown(BitWidth);
742 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000743 // For those bits in RHS that are known, we can propagate them to known
744 // bits in V shifted to the right by C.
Igor Laevskycec8f472017-12-05 12:18:15 +0000745 Known.Zero |= RHSKnown.Zero << C;
746 Known.One |= RHSKnown.One << C;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000747 // assume(~(v >> c) = a)
Craig Topper7b66ffe2017-06-24 06:24:04 +0000748 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shr(m_V, m_ConstantInt(C))),
Philip Reames00d3b272014-11-24 23:44:28 +0000749 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000750 Pred == ICmpInst::ICMP_EQ &&
Igor Laevskycec8f472017-12-05 12:18:15 +0000751 isValidAssumeForContext(I, Q.CxtI, Q.DT) &&
752 C < BitWidth) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000753 KnownBits RHSKnown(BitWidth);
754 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000755 // For those bits in RHS that are known, we can propagate them inverted
756 // to known bits in V shifted to the right by C.
Igor Laevskycec8f472017-12-05 12:18:15 +0000757 Known.Zero |= RHSKnown.One << C;
758 Known.One |= RHSKnown.Zero << C;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000759 // assume(v >=_s c) where c is non-negative
Philip Reames00d3b272014-11-24 23:44:28 +0000760 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000761 Pred == ICmpInst::ICMP_SGE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000762 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000763 KnownBits RHSKnown(BitWidth);
764 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000765
Craig Topperca48af32017-04-29 16:43:11 +0000766 if (RHSKnown.isNonNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000767 // We know that the sign bit is zero.
Craig Topperca48af32017-04-29 16:43:11 +0000768 Known.makeNonNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000769 }
770 // assume(v >_s c) where c is at least -1.
Philip Reames00d3b272014-11-24 23:44:28 +0000771 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000772 Pred == ICmpInst::ICMP_SGT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000773 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000774 KnownBits RHSKnown(BitWidth);
775 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000776
Craig Topperf0aeee02017-05-05 17:36:09 +0000777 if (RHSKnown.isAllOnes() || RHSKnown.isNonNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000778 // We know that the sign bit is zero.
Craig Topperca48af32017-04-29 16:43:11 +0000779 Known.makeNonNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000780 }
781 // assume(v <=_s c) where c is negative
Philip Reames00d3b272014-11-24 23:44:28 +0000782 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000783 Pred == ICmpInst::ICMP_SLE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000784 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000785 KnownBits RHSKnown(BitWidth);
786 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000787
Craig Topperca48af32017-04-29 16:43:11 +0000788 if (RHSKnown.isNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000789 // We know that the sign bit is one.
Craig Topperca48af32017-04-29 16:43:11 +0000790 Known.makeNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000791 }
792 // assume(v <_s c) where c is non-positive
Philip Reames00d3b272014-11-24 23:44:28 +0000793 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000794 Pred == ICmpInst::ICMP_SLT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000795 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000796 KnownBits RHSKnown(BitWidth);
797 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000798
Craig Topperf0aeee02017-05-05 17:36:09 +0000799 if (RHSKnown.isZero() || RHSKnown.isNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000800 // We know that the sign bit is one.
Craig Topperca48af32017-04-29 16:43:11 +0000801 Known.makeNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000802 }
803 // assume(v <=_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000804 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000805 Pred == ICmpInst::ICMP_ULE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000806 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000807 KnownBits RHSKnown(BitWidth);
808 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000809
810 // Whatever high bits in c are zero are known to be zero.
Craig Topper8df66c62017-05-12 17:20:30 +0000811 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
812 // assume(v <_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000813 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000814 Pred == ICmpInst::ICMP_ULT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000815 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000816 KnownBits RHSKnown(BitWidth);
817 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000818
Sanjay Patela60aec12018-02-08 14:52:40 +0000819 // If the RHS is known zero, then this assumption must be wrong (nothing
820 // is unsigned less than zero). Signal a conflict and get out of here.
821 if (RHSKnown.isZero()) {
822 Known.Zero.setAllBits();
823 Known.One.setAllBits();
824 break;
825 }
826
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000827 // Whatever high bits in c are zero are known to be zero (if c is a power
828 // of 2, then one more).
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000829 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I)))
Craig Topper8df66c62017-05-12 17:20:30 +0000830 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros() + 1);
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000831 else
Craig Topper8df66c62017-05-12 17:20:30 +0000832 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
Hal Finkel60db0582014-09-07 18:57:58 +0000833 }
834 }
Sanjay Patel25f6d712017-02-01 15:41:32 +0000835
836 // If assumptions conflict with each other or previous known bits, then we
Sanjay Patel54656ca2017-02-06 18:26:06 +0000837 // have a logical fallacy. It's possible that the assumption is not reachable,
838 // so this isn't a real bug. On the other hand, the program may have undefined
839 // behavior, or we might have a bug in the compiler. We can't assert/crash, so
840 // clear out the known bits, try to warn the user, and hope for the best.
Craig Topperb45eabc2017-04-26 16:39:58 +0000841 if (Known.Zero.intersects(Known.One)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000842 Known.resetAll();
Sanjay Patel54656ca2017-02-06 18:26:06 +0000843
Vivek Pandya95906582017-10-11 17:12:59 +0000844 if (Q.ORE)
845 Q.ORE->emit([&]() {
846 auto *CxtI = const_cast<Instruction *>(Q.CxtI);
847 return OptimizationRemarkAnalysis("value-tracking", "BadAssumption",
848 CxtI)
849 << "Detected conflicting code assumptions. Program may "
850 "have undefined behavior, or compiler may have "
851 "internal error.";
852 });
Sanjay Patel25f6d712017-02-01 15:41:32 +0000853 }
Hal Finkel60db0582014-09-07 18:57:58 +0000854}
855
Sanjay Patelb7d12382017-10-16 14:46:37 +0000856/// Compute known bits from a shift operator, including those with a
857/// non-constant shift amount. Known is the output of this function. Known2 is a
858/// pre-allocated temporary with the same bit width as Known. KZF and KOF are
Vedant Kumard3196742018-02-28 19:08:52 +0000859/// operator-specific functions that, given the known-zero or known-one bits
Sanjay Patelb7d12382017-10-16 14:46:37 +0000860/// respectively, and a shift amount, compute the implied known-zero or
861/// known-one bits of the shift operator's result respectively for that shift
862/// amount. The results from calling KZF and KOF are conservatively combined for
863/// all permitted shift amounts.
David Majnemer54690dc2016-08-23 20:52:00 +0000864static void computeKnownBitsFromShiftOperator(
Craig Topperb45eabc2017-04-26 16:39:58 +0000865 const Operator *I, KnownBits &Known, KnownBits &Known2,
866 unsigned Depth, const Query &Q,
Sam McCalld0d43e62017-12-04 12:51:49 +0000867 function_ref<APInt(const APInt &, unsigned)> KZF,
868 function_ref<APInt(const APInt &, unsigned)> KOF) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000869 unsigned BitWidth = Known.getBitWidth();
Hal Finkelf2199b22015-10-23 20:37:08 +0000870
871 if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
872 unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1);
873
Craig Topperb45eabc2017-04-26 16:39:58 +0000874 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Sam McCalld0d43e62017-12-04 12:51:49 +0000875 Known.Zero = KZF(Known.Zero, ShiftAmt);
876 Known.One = KOF(Known.One, ShiftAmt);
Sanjay Patele272be72017-10-12 17:31:46 +0000877 // If the known bits conflict, this must be an overflowing left shift, so
878 // the shift result is poison. We can return anything we want. Choose 0 for
879 // the best folding opportunity.
880 if (Known.hasConflict())
881 Known.setAllZero();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +0000882
Hal Finkelf2199b22015-10-23 20:37:08 +0000883 return;
884 }
885
Craig Topperb45eabc2017-04-26 16:39:58 +0000886 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000887
Sanjay Patele272be72017-10-12 17:31:46 +0000888 // If the shift amount could be greater than or equal to the bit-width of the
889 // LHS, the value could be poison, but bail out because the check below is
890 // expensive. TODO: Should we just carry on?
Craig Topperb45eabc2017-04-26 16:39:58 +0000891 if ((~Known.Zero).uge(BitWidth)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000892 Known.resetAll();
Oliver Stannard06204112017-03-14 10:13:17 +0000893 return;
894 }
895
Craig Topperb45eabc2017-04-26 16:39:58 +0000896 // Note: We cannot use Known.Zero.getLimitedValue() here, because if
Hal Finkelf2199b22015-10-23 20:37:08 +0000897 // BitWidth > 64 and any upper bits are known, we'll end up returning the
898 // limit value (which implies all bits are known).
Craig Topperb45eabc2017-04-26 16:39:58 +0000899 uint64_t ShiftAmtKZ = Known.Zero.zextOrTrunc(64).getZExtValue();
900 uint64_t ShiftAmtKO = Known.One.zextOrTrunc(64).getZExtValue();
Hal Finkelf2199b22015-10-23 20:37:08 +0000901
902 // It would be more-clearly correct to use the two temporaries for this
903 // calculation. Reusing the APInts here to prevent unnecessary allocations.
Craig Topperf0aeee02017-05-05 17:36:09 +0000904 Known.resetAll();
Hal Finkelf2199b22015-10-23 20:37:08 +0000905
James Molloy493e57d2015-10-26 14:10:46 +0000906 // If we know the shifter operand is nonzero, we can sometimes infer more
907 // known bits. However this is expensive to compute, so be lazy about it and
908 // only compute it when absolutely necessary.
909 Optional<bool> ShifterOperandIsNonZero;
910
Hal Finkelf2199b22015-10-23 20:37:08 +0000911 // Early exit if we can't constrain any well-defined shift amount.
Craig Topperf93b7b12017-06-14 17:04:59 +0000912 if (!(ShiftAmtKZ & (PowerOf2Ceil(BitWidth) - 1)) &&
913 !(ShiftAmtKO & (PowerOf2Ceil(BitWidth) - 1))) {
Sanjay Patelb7d12382017-10-16 14:46:37 +0000914 ShifterOperandIsNonZero = isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000915 if (!*ShifterOperandIsNonZero)
916 return;
917 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000918
Craig Topperb45eabc2017-04-26 16:39:58 +0000919 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000920
Craig Topperb45eabc2017-04-26 16:39:58 +0000921 Known.Zero.setAllBits();
922 Known.One.setAllBits();
Hal Finkelf2199b22015-10-23 20:37:08 +0000923 for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
924 // Combine the shifted known input bits only for those shift amounts
925 // compatible with its known constraints.
926 if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
927 continue;
928 if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
929 continue;
James Molloy493e57d2015-10-26 14:10:46 +0000930 // If we know the shifter is nonzero, we may be able to infer more known
931 // bits. This check is sunk down as far as possible to avoid the expensive
932 // call to isKnownNonZero if the cheaper checks above fail.
933 if (ShiftAmt == 0) {
934 if (!ShifterOperandIsNonZero.hasValue())
935 ShifterOperandIsNonZero =
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000936 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000937 if (*ShifterOperandIsNonZero)
938 continue;
939 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000940
Sam McCalld0d43e62017-12-04 12:51:49 +0000941 Known.Zero &= KZF(Known2.Zero, ShiftAmt);
942 Known.One &= KOF(Known2.One, ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +0000943 }
944
Sanjay Patele272be72017-10-12 17:31:46 +0000945 // If the known bits conflict, the result is poison. Return a 0 and hope the
946 // caller can further optimize that.
947 if (Known.hasConflict())
948 Known.setAllZero();
Hal Finkelf2199b22015-10-23 20:37:08 +0000949}
950
Craig Topperb45eabc2017-04-26 16:39:58 +0000951static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known,
952 unsigned Depth, const Query &Q) {
953 unsigned BitWidth = Known.getBitWidth();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000954
Craig Topperb45eabc2017-04-26 16:39:58 +0000955 KnownBits Known2(Known);
Dan Gohman80ca01c2009-07-17 20:47:02 +0000956 switch (I->getOpcode()) {
Chris Lattner965c7692008-06-02 01:18:21 +0000957 default: break;
Rafael Espindola53190532012-03-30 15:52:11 +0000958 case Instruction::Load:
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000959 if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +0000960 computeKnownBitsFromRangeMetadata(*MD, Known);
Jay Foad5a29c362014-05-15 12:12:55 +0000961 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000962 case Instruction::And: {
963 // If either the LHS or the RHS are Zero, the result is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +0000964 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
965 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000966
Chris Lattner965c7692008-06-02 01:18:21 +0000967 // Output known-1 bits are only known if set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000968 Known.One &= Known2.One;
Chris Lattner965c7692008-06-02 01:18:21 +0000969 // Output known-0 are known to be clear if zero in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000970 Known.Zero |= Known2.Zero;
Philip Reames2d858742015-11-10 18:46:14 +0000971
972 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
973 // here we handle the more general case of adding any odd number by
974 // matching the form add(x, add(x, y)) where y is odd.
975 // TODO: This could be generalized to clearing any bit set in y where the
976 // following bit is known to be unset in y.
977 Value *Y = nullptr;
Craig Topperb45eabc2017-04-26 16:39:58 +0000978 if (!Known.Zero[0] && !Known.One[0] &&
Craig Toppera80f2042017-04-13 19:04:45 +0000979 (match(I->getOperand(0), m_Add(m_Specific(I->getOperand(1)),
980 m_Value(Y))) ||
981 match(I->getOperand(1), m_Add(m_Specific(I->getOperand(0)),
982 m_Value(Y))))) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000983 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000984 computeKnownBits(Y, Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +0000985 if (Known2.countMinTrailingOnes() > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +0000986 Known.Zero.setBit(0);
Philip Reames2d858742015-11-10 18:46:14 +0000987 }
Jay Foad5a29c362014-05-15 12:12:55 +0000988 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000989 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000990 case Instruction::Or:
Craig Topperb45eabc2017-04-26 16:39:58 +0000991 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
992 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000993
Chris Lattner965c7692008-06-02 01:18:21 +0000994 // Output known-0 bits are only known if clear in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000995 Known.Zero &= Known2.Zero;
Chris Lattner965c7692008-06-02 01:18:21 +0000996 // Output known-1 are known to be set if set in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000997 Known.One |= Known2.One;
Jay Foad5a29c362014-05-15 12:12:55 +0000998 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000999 case Instruction::Xor: {
Craig Topperb45eabc2017-04-26 16:39:58 +00001000 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
1001 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00001002
Chris Lattner965c7692008-06-02 01:18:21 +00001003 // Output known-0 bits are known if clear or set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001004 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
Chris Lattner965c7692008-06-02 01:18:21 +00001005 // Output known-1 are known to be set if set in only one of the LHS, RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001006 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
1007 Known.Zero = std::move(KnownZeroOut);
Jay Foad5a29c362014-05-15 12:12:55 +00001008 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001009 }
1010 case Instruction::Mul: {
Nick Lewyckyfa306072012-03-18 23:28:48 +00001011 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Craig Topperb45eabc2017-04-26 16:39:58 +00001012 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, Known,
1013 Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001014 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001015 }
1016 case Instruction::UDiv: {
1017 // For the purposes of computing leading zeros we can conservatively
1018 // treat a udiv as a logical right shift by the power of 2 known to
1019 // be less than the denominator.
Craig Topperb45eabc2017-04-26 16:39:58 +00001020 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001021 unsigned LeadZ = Known2.countMinLeadingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +00001022
Craig Topperf0aeee02017-05-05 17:36:09 +00001023 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001024 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001025 unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
1026 if (RHSMaxLeadingZeros != BitWidth)
1027 LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
Chris Lattner965c7692008-06-02 01:18:21 +00001028
Craig Topperb45eabc2017-04-26 16:39:58 +00001029 Known.Zero.setHighBits(LeadZ);
Jay Foad5a29c362014-05-15 12:12:55 +00001030 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001031 }
David Majnemera19d0f22016-08-06 08:16:00 +00001032 case Instruction::Select: {
Craig Toppere953dec2017-04-13 20:39:37 +00001033 const Value *LHS, *RHS;
David Majnemera19d0f22016-08-06 08:16:00 +00001034 SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
1035 if (SelectPatternResult::isMinOrMax(SPF)) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001036 computeKnownBits(RHS, Known, Depth + 1, Q);
1037 computeKnownBits(LHS, Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +00001038 } else {
Craig Topperb45eabc2017-04-26 16:39:58 +00001039 computeKnownBits(I->getOperand(2), Known, Depth + 1, Q);
1040 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +00001041 }
1042
1043 unsigned MaxHighOnes = 0;
1044 unsigned MaxHighZeros = 0;
1045 if (SPF == SPF_SMAX) {
1046 // If both sides are negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +00001047 if (Known.isNegative() && Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001048 // We can derive a lower bound on the result by taking the max of the
1049 // leading one bits.
Craig Topper8df66c62017-05-12 17:20:30 +00001050 MaxHighOnes =
1051 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001052 // If either side is non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +00001053 else if (Known.isNonNegative() || Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001054 MaxHighZeros = 1;
1055 } else if (SPF == SPF_SMIN) {
1056 // If both sides are non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +00001057 if (Known.isNonNegative() && Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001058 // We can derive an upper bound on the result by taking the max of the
1059 // leading zero bits.
Craig Topper8df66c62017-05-12 17:20:30 +00001060 MaxHighZeros = std::max(Known.countMinLeadingZeros(),
1061 Known2.countMinLeadingZeros());
David Majnemera19d0f22016-08-06 08:16:00 +00001062 // If either side is negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +00001063 else if (Known.isNegative() || Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +00001064 MaxHighOnes = 1;
1065 } else if (SPF == SPF_UMAX) {
1066 // We can derive a lower bound on the result by taking the max of the
1067 // leading one bits.
1068 MaxHighOnes =
Craig Topper8df66c62017-05-12 17:20:30 +00001069 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001070 } else if (SPF == SPF_UMIN) {
1071 // We can derive an upper bound on the result by taking the max of the
1072 // leading zero bits.
1073 MaxHighZeros =
Craig Topper8df66c62017-05-12 17:20:30 +00001074 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
David Majnemera19d0f22016-08-06 08:16:00 +00001075 }
1076
Chris Lattner965c7692008-06-02 01:18:21 +00001077 // Only known if known in both the LHS and RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001078 Known.One &= Known2.One;
1079 Known.Zero &= Known2.Zero;
David Majnemera19d0f22016-08-06 08:16:00 +00001080 if (MaxHighOnes > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001081 Known.One.setHighBits(MaxHighOnes);
David Majnemera19d0f22016-08-06 08:16:00 +00001082 if (MaxHighZeros > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001083 Known.Zero.setHighBits(MaxHighZeros);
Jay Foad5a29c362014-05-15 12:12:55 +00001084 break;
David Majnemera19d0f22016-08-06 08:16:00 +00001085 }
Chris Lattner965c7692008-06-02 01:18:21 +00001086 case Instruction::FPTrunc:
1087 case Instruction::FPExt:
1088 case Instruction::FPToUI:
1089 case Instruction::FPToSI:
1090 case Instruction::SIToFP:
1091 case Instruction::UIToFP:
Jay Foad5a29c362014-05-15 12:12:55 +00001092 break; // Can't work with floating point.
Chris Lattner965c7692008-06-02 01:18:21 +00001093 case Instruction::PtrToInt:
1094 case Instruction::IntToPtr:
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001095 // Fall through and handle them the same as zext/trunc.
1096 LLVM_FALLTHROUGH;
Chris Lattner965c7692008-06-02 01:18:21 +00001097 case Instruction::ZExt:
1098 case Instruction::Trunc: {
Chris Lattner229907c2011-07-18 04:54:35 +00001099 Type *SrcTy = I->getOperand(0)->getType();
Nadav Rotem15198e92012-10-26 17:17:05 +00001100
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001101 unsigned SrcBitWidth;
Chris Lattner965c7692008-06-02 01:18:21 +00001102 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1103 // which fall through here.
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001104 Type *ScalarTy = SrcTy->getScalarType();
1105 SrcBitWidth = ScalarTy->isPointerTy() ?
1106 Q.DL.getIndexTypeSizeInBits(ScalarTy) :
1107 Q.DL.getTypeSizeInBits(ScalarTy);
Nadav Rotem15198e92012-10-26 17:17:05 +00001108
1109 assert(SrcBitWidth && "SrcBitWidth can't be zero");
Craig Topperd938fd12017-05-03 22:07:25 +00001110 Known = Known.zextOrTrunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001111 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Craig Topperd938fd12017-05-03 22:07:25 +00001112 Known = Known.zextOrTrunc(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +00001113 // Any top bits are known to be zero.
1114 if (BitWidth > SrcBitWidth)
Craig Topperb45eabc2017-04-26 16:39:58 +00001115 Known.Zero.setBitsFrom(SrcBitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001116 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001117 }
1118 case Instruction::BitCast: {
Chris Lattner229907c2011-07-18 04:54:35 +00001119 Type *SrcTy = I->getOperand(0)->getType();
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001120 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattneredb84072009-07-02 16:04:08 +00001121 // TODO: For now, not handling conversions like:
1122 // (bitcast i64 %x to <2 x i32>)
Duncan Sands19d0b472010-02-16 11:11:14 +00001123 !I->getType()->isVectorTy()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001124 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Jay Foad5a29c362014-05-15 12:12:55 +00001125 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001126 }
1127 break;
1128 }
1129 case Instruction::SExt: {
1130 // Compute the bits in the result that are not present in the input.
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001131 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Craig Topper1bef2c82012-12-22 19:15:35 +00001132
Craig Topperd938fd12017-05-03 22:07:25 +00001133 Known = Known.trunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001134 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001135 // If the sign bit of the input is known set or clear, then we know the
1136 // top bits of the result.
Craig Topperd938fd12017-05-03 22:07:25 +00001137 Known = Known.sext(BitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001138 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001139 }
Hal Finkelf2199b22015-10-23 20:37:08 +00001140 case Instruction::Shl: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001141 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001142 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Sam McCalld0d43e62017-12-04 12:51:49 +00001143 auto KZF = [NSW](const APInt &KnownZero, unsigned ShiftAmt) {
1144 APInt KZResult = KnownZero << ShiftAmt;
1145 KZResult.setLowBits(ShiftAmt); // Low bits known 0.
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001146 // If this shift has "nsw" keyword, then the result is either a poison
1147 // value or has the same sign bit as the first operand.
Sam McCalld0d43e62017-12-04 12:51:49 +00001148 if (NSW && KnownZero.isSignBitSet())
1149 KZResult.setSignBit();
1150 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001151 };
1152
Sam McCalld0d43e62017-12-04 12:51:49 +00001153 auto KOF = [NSW](const APInt &KnownOne, unsigned ShiftAmt) {
1154 APInt KOResult = KnownOne << ShiftAmt;
1155 if (NSW && KnownOne.isSignBitSet())
1156 KOResult.setSignBit();
1157 return KOResult;
1158 };
1159
1160 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001161 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001162 }
1163 case Instruction::LShr: {
Sanjay Patelb7d12382017-10-16 14:46:37 +00001164 // (lshr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Sam McCalld0d43e62017-12-04 12:51:49 +00001165 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1166 APInt KZResult = KnownZero.lshr(ShiftAmt);
1167 // High bits known zero.
1168 KZResult.setHighBits(ShiftAmt);
1169 return KZResult;
Hal Finkelf2199b22015-10-23 20:37:08 +00001170 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001171
Sam McCalld0d43e62017-12-04 12:51:49 +00001172 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
1173 return KnownOne.lshr(ShiftAmt);
1174 };
1175
1176 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001177 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001178 }
1179 case Instruction::AShr: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001180 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Sam McCalld0d43e62017-12-04 12:51:49 +00001181 auto KZF = [](const APInt &KnownZero, unsigned ShiftAmt) {
1182 return KnownZero.ashr(ShiftAmt);
Hal Finkelf2199b22015-10-23 20:37:08 +00001183 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001184
Sam McCalld0d43e62017-12-04 12:51:49 +00001185 auto KOF = [](const APInt &KnownOne, unsigned ShiftAmt) {
1186 return KnownOne.ashr(ShiftAmt);
1187 };
1188
1189 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KZF, KOF);
Chris Lattner965c7692008-06-02 01:18:21 +00001190 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001191 }
Chris Lattner965c7692008-06-02 01:18:21 +00001192 case Instruction::Sub: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001193 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001194 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001195 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001196 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001197 }
Chris Lattner965c7692008-06-02 01:18:21 +00001198 case Instruction::Add: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001199 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001200 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001201 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001202 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001203 }
1204 case Instruction::SRem:
1205 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001206 APInt RA = Rem->getValue().abs();
1207 if (RA.isPowerOf2()) {
1208 APInt LowBits = RA - 1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001209 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001210
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001211 // The low bits of the first operand are unchanged by the srem.
Craig Topperb45eabc2017-04-26 16:39:58 +00001212 Known.Zero = Known2.Zero & LowBits;
1213 Known.One = Known2.One & LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001214
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001215 // If the first operand is non-negative or has all low bits zero, then
1216 // the upper bits are all zero.
Craig Topperca48af32017-04-29 16:43:11 +00001217 if (Known2.isNonNegative() || LowBits.isSubsetOf(Known2.Zero))
Craig Topperb45eabc2017-04-26 16:39:58 +00001218 Known.Zero |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001219
1220 // If the first operand is negative and not all low bits are zero, then
1221 // the upper bits are all one.
Craig Topperca48af32017-04-29 16:43:11 +00001222 if (Known2.isNegative() && LowBits.intersects(Known2.One))
Craig Topperb45eabc2017-04-26 16:39:58 +00001223 Known.One |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001224
Craig Topperb45eabc2017-04-26 16:39:58 +00001225 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Craig Topperda886c62017-04-16 21:46:12 +00001226 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001227 }
1228 }
Nick Lewyckye4679792011-03-07 01:50:10 +00001229
1230 // The sign bit is the LHS's sign bit, except when the result of the
1231 // remainder is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +00001232 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topperda886c62017-04-16 21:46:12 +00001233 // If it's known zero, our sign bit is also zero.
Craig Topperca48af32017-04-29 16:43:11 +00001234 if (Known2.isNonNegative())
1235 Known.makeNonNegative();
Nick Lewyckye4679792011-03-07 01:50:10 +00001236
Chris Lattner965c7692008-06-02 01:18:21 +00001237 break;
1238 case Instruction::URem: {
1239 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001240 const APInt &RA = Rem->getValue();
Chris Lattner965c7692008-06-02 01:18:21 +00001241 if (RA.isPowerOf2()) {
1242 APInt LowBits = (RA - 1);
Craig Topperb45eabc2017-04-26 16:39:58 +00001243 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1244 Known.Zero |= ~LowBits;
1245 Known.One &= LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001246 break;
1247 }
1248 }
1249
1250 // Since the result is less than or equal to either operand, any leading
1251 // zero bits in either operand must also exist in the result.
Craig Topperb45eabc2017-04-26 16:39:58 +00001252 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1253 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001254
Craig Topper8df66c62017-05-12 17:20:30 +00001255 unsigned Leaders =
1256 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
Craig Topperf0aeee02017-05-05 17:36:09 +00001257 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001258 Known.Zero.setHighBits(Leaders);
Chris Lattner965c7692008-06-02 01:18:21 +00001259 break;
1260 }
1261
Victor Hernandeza3aaf852009-10-17 01:18:07 +00001262 case Instruction::Alloca: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001263 const AllocaInst *AI = cast<AllocaInst>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001264 unsigned Align = AI->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001265 if (Align == 0)
Eduard Burtescu90c44492016-01-18 00:10:01 +00001266 Align = Q.DL.getABITypeAlignment(AI->getAllocatedType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001267
Chris Lattner965c7692008-06-02 01:18:21 +00001268 if (Align > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001269 Known.Zero.setLowBits(countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +00001270 break;
1271 }
1272 case Instruction::GetElementPtr: {
1273 // Analyze all of the subscripts of this getelementptr instruction
1274 // to determine if we can prove known low zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001275 KnownBits LocalKnown(BitWidth);
1276 computeKnownBits(I->getOperand(0), LocalKnown, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001277 unsigned TrailZ = LocalKnown.countMinTrailingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +00001278
1279 gep_type_iterator GTI = gep_type_begin(I);
1280 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1281 Value *Index = I->getOperand(i);
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001282 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chris Lattner965c7692008-06-02 01:18:21 +00001283 // Handle struct member offset arithmetic.
Matt Arsenault74742a12013-08-19 21:43:16 +00001284
1285 // Handle case when index is vector zeroinitializer
1286 Constant *CIndex = cast<Constant>(Index);
1287 if (CIndex->isZeroValue())
1288 continue;
1289
1290 if (CIndex->getType()->isVectorTy())
1291 Index = CIndex->getSplatValue();
1292
Chris Lattner965c7692008-06-02 01:18:21 +00001293 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001294 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chris Lattner965c7692008-06-02 01:18:21 +00001295 uint64_t Offset = SL->getElementOffset(Idx);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001296 TrailZ = std::min<unsigned>(TrailZ,
1297 countTrailingZeros(Offset));
Chris Lattner965c7692008-06-02 01:18:21 +00001298 } else {
1299 // Handle array index arithmetic.
Chris Lattner229907c2011-07-18 04:54:35 +00001300 Type *IndexedTy = GTI.getIndexedType();
Jay Foad5a29c362014-05-15 12:12:55 +00001301 if (!IndexedTy->isSized()) {
1302 TrailZ = 0;
1303 break;
1304 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001305 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001306 uint64_t TypeSize = Q.DL.getTypeAllocSize(IndexedTy);
Craig Topperb45eabc2017-04-26 16:39:58 +00001307 LocalKnown.Zero = LocalKnown.One = APInt(GEPOpiBits, 0);
1308 computeKnownBits(Index, LocalKnown, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001309 TrailZ = std::min(TrailZ,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001310 unsigned(countTrailingZeros(TypeSize) +
Craig Topper8df66c62017-05-12 17:20:30 +00001311 LocalKnown.countMinTrailingZeros()));
Chris Lattner965c7692008-06-02 01:18:21 +00001312 }
1313 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001314
Craig Topperb45eabc2017-04-26 16:39:58 +00001315 Known.Zero.setLowBits(TrailZ);
Chris Lattner965c7692008-06-02 01:18:21 +00001316 break;
1317 }
1318 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001319 const PHINode *P = cast<PHINode>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001320 // Handle the case of a simple two-predecessor recurrence PHI.
1321 // There's a lot more that could theoretically be done here, but
1322 // this is sufficient to catch some interesting cases.
1323 if (P->getNumIncomingValues() == 2) {
1324 for (unsigned i = 0; i != 2; ++i) {
1325 Value *L = P->getIncomingValue(i);
1326 Value *R = P->getIncomingValue(!i);
Dan Gohman80ca01c2009-07-17 20:47:02 +00001327 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner965c7692008-06-02 01:18:21 +00001328 if (!LU)
1329 continue;
Dan Gohman80ca01c2009-07-17 20:47:02 +00001330 unsigned Opcode = LU->getOpcode();
Chris Lattner965c7692008-06-02 01:18:21 +00001331 // Check for operations that have the property that if
1332 // both their operands have low zero bits, the result
Artur Pilipenkobc76eca2016-08-22 13:14:07 +00001333 // will have low zero bits.
Chris Lattner965c7692008-06-02 01:18:21 +00001334 if (Opcode == Instruction::Add ||
1335 Opcode == Instruction::Sub ||
1336 Opcode == Instruction::And ||
1337 Opcode == Instruction::Or ||
1338 Opcode == Instruction::Mul) {
1339 Value *LL = LU->getOperand(0);
1340 Value *LR = LU->getOperand(1);
1341 // Find a recurrence.
1342 if (LL == I)
1343 L = LR;
1344 else if (LR == I)
1345 L = LL;
1346 else
1347 break;
1348 // Ok, we have a PHI of the form L op= R. Check for low
1349 // zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001350 computeKnownBits(R, Known2, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001351
1352 // We need to take the minimum number of known bits
Craig Topperb45eabc2017-04-26 16:39:58 +00001353 KnownBits Known3(Known);
1354 computeKnownBits(L, Known3, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001355
Craig Topper8df66c62017-05-12 17:20:30 +00001356 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1357 Known3.countMinTrailingZeros()));
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001358
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001359 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(LU);
1360 if (OverflowOp && OverflowOp->hasNoSignedWrap()) {
1361 // If initial value of recurrence is nonnegative, and we are adding
1362 // a nonnegative number with nsw, the result can only be nonnegative
1363 // or poison value regardless of the number of times we execute the
1364 // add in phi recurrence. If initial value is negative and we are
1365 // adding a negative number with nsw, the result can only be
1366 // negative or poison value. Similar arguments apply to sub and mul.
1367 //
1368 // (add non-negative, non-negative) --> non-negative
1369 // (add negative, negative) --> negative
1370 if (Opcode == Instruction::Add) {
Craig Topperca48af32017-04-29 16:43:11 +00001371 if (Known2.isNonNegative() && Known3.isNonNegative())
1372 Known.makeNonNegative();
1373 else if (Known2.isNegative() && Known3.isNegative())
1374 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001375 }
1376
1377 // (sub nsw non-negative, negative) --> non-negative
1378 // (sub nsw negative, non-negative) --> negative
1379 else if (Opcode == Instruction::Sub && LL == I) {
Craig Topperca48af32017-04-29 16:43:11 +00001380 if (Known2.isNonNegative() && Known3.isNegative())
1381 Known.makeNonNegative();
1382 else if (Known2.isNegative() && Known3.isNonNegative())
1383 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001384 }
1385
1386 // (mul nsw non-negative, non-negative) --> non-negative
Craig Topperca48af32017-04-29 16:43:11 +00001387 else if (Opcode == Instruction::Mul && Known2.isNonNegative() &&
1388 Known3.isNonNegative())
1389 Known.makeNonNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001390 }
1391
Chris Lattner965c7692008-06-02 01:18:21 +00001392 break;
1393 }
1394 }
1395 }
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001396
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001397 // Unreachable blocks may have zero-operand PHI nodes.
1398 if (P->getNumIncomingValues() == 0)
Jay Foad5a29c362014-05-15 12:12:55 +00001399 break;
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001400
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001401 // Otherwise take the unions of the known bit sets of the operands,
1402 // taking conservative care to avoid excessive recursion.
Craig Topperb45eabc2017-04-26 16:39:58 +00001403 if (Depth < MaxDepth - 1 && !Known.Zero && !Known.One) {
Duncan Sands7dc3d472011-03-08 12:39:03 +00001404 // Skip if every incoming value references to ourself.
Nuno Lopes0d44a502012-07-03 21:15:40 +00001405 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
Duncan Sands7dc3d472011-03-08 12:39:03 +00001406 break;
1407
Craig Topperb45eabc2017-04-26 16:39:58 +00001408 Known.Zero.setAllBits();
1409 Known.One.setAllBits();
Pete Cooper833f34d2015-05-12 20:05:31 +00001410 for (Value *IncValue : P->incoming_values()) {
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001411 // Skip direct self references.
Pete Cooper833f34d2015-05-12 20:05:31 +00001412 if (IncValue == P) continue;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001413
Craig Topperb45eabc2017-04-26 16:39:58 +00001414 Known2 = KnownBits(BitWidth);
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001415 // Recurse, but cap the recursion to one level, because we don't
1416 // want to waste time spinning around in loops.
Craig Topperb45eabc2017-04-26 16:39:58 +00001417 computeKnownBits(IncValue, Known2, MaxDepth - 1, Q);
1418 Known.Zero &= Known2.Zero;
1419 Known.One &= Known2.One;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001420 // If all bits have been ruled out, there's no need to check
1421 // more operands.
Craig Topperb45eabc2017-04-26 16:39:58 +00001422 if (!Known.Zero && !Known.One)
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001423 break;
1424 }
1425 }
Chris Lattner965c7692008-06-02 01:18:21 +00001426 break;
1427 }
1428 case Instruction::Call:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001429 case Instruction::Invoke:
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001430 // If range metadata is attached to this call, set known bits from that,
1431 // and then intersect with known bits based on other properties of the
1432 // function.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001433 if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +00001434 computeKnownBitsFromRangeMetadata(*MD, Known);
Pete Cooper35b00d52016-08-13 01:05:32 +00001435 if (const Value *RV = ImmutableCallSite(I).getReturnedArgOperand()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001436 computeKnownBits(RV, Known2, Depth + 1, Q);
1437 Known.Zero |= Known2.Zero;
1438 Known.One |= Known2.One;
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001439 }
Pete Cooper35b00d52016-08-13 01:05:32 +00001440 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001441 switch (II->getIntrinsicID()) {
1442 default: break;
Chad Rosier85204292017-01-17 17:23:51 +00001443 case Intrinsic::bitreverse:
Craig Topperb45eabc2017-04-26 16:39:58 +00001444 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1445 Known.Zero |= Known2.Zero.reverseBits();
1446 Known.One |= Known2.One.reverseBits();
Chad Rosier85204292017-01-17 17:23:51 +00001447 break;
Philip Reames675418e2015-10-06 20:20:45 +00001448 case Intrinsic::bswap:
Craig Topperb45eabc2017-04-26 16:39:58 +00001449 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1450 Known.Zero |= Known2.Zero.byteSwap();
1451 Known.One |= Known2.One.byteSwap();
Philip Reames675418e2015-10-06 20:20:45 +00001452 break;
Craig Topper868813f2017-05-08 17:22:34 +00001453 case Intrinsic::ctlz: {
1454 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1455 // If we have a known 1, its position is our upper bound.
1456 unsigned PossibleLZ = Known2.One.countLeadingZeros();
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001457 // If this call is undefined for 0, the result will be less than 2^n.
1458 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
Craig Topper868813f2017-05-08 17:22:34 +00001459 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
1460 unsigned LowBits = Log2_32(PossibleLZ)+1;
1461 Known.Zero.setBitsFrom(LowBits);
1462 break;
1463 }
1464 case Intrinsic::cttz: {
1465 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1466 // If we have a known 1, its position is our upper bound.
1467 unsigned PossibleTZ = Known2.One.countTrailingZeros();
1468 // If this call is undefined for 0, the result will be less than 2^n.
1469 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1470 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
1471 unsigned LowBits = Log2_32(PossibleTZ)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001472 Known.Zero.setBitsFrom(LowBits);
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001473 break;
1474 }
1475 case Intrinsic::ctpop: {
Craig Topperb45eabc2017-04-26 16:39:58 +00001476 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001477 // We can bound the space the count needs. Also, bits known to be zero
1478 // can't contribute to the population.
Craig Topper8df66c62017-05-12 17:20:30 +00001479 unsigned BitsPossiblySet = Known2.countMaxPopulation();
Craig Topper66df10f2017-04-14 06:43:34 +00001480 unsigned LowBits = Log2_32(BitsPossiblySet)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001481 Known.Zero.setBitsFrom(LowBits);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001482 // TODO: we could bound KnownOne using the lower bound on the number
1483 // of bits which might be set provided by popcnt KnownOne2.
Chris Lattner965c7692008-06-02 01:18:21 +00001484 break;
1485 }
Chad Rosierb3628842011-05-26 23:13:19 +00001486 case Intrinsic::x86_sse42_crc32_64_64:
Craig Topperb45eabc2017-04-26 16:39:58 +00001487 Known.Zero.setBitsFrom(32);
Evan Cheng2a746bf2011-05-22 18:25:30 +00001488 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001489 }
1490 }
1491 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00001492 case Instruction::ExtractElement:
1493 // Look through extract element. At the moment we keep this simple and skip
1494 // tracking the specific element. But at least we might find information
1495 // valid for all elements of the vector (for example if vector is sign
1496 // extended, shifted, etc).
Craig Topperb45eabc2017-04-26 16:39:58 +00001497 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Bjorn Pettersson39616032016-10-06 09:56:21 +00001498 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001499 case Instruction::ExtractValue:
1500 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001501 const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001502 if (EVI->getNumIndices() != 1) break;
1503 if (EVI->getIndices()[0] == 0) {
1504 switch (II->getIntrinsicID()) {
1505 default: break;
1506 case Intrinsic::uadd_with_overflow:
1507 case Intrinsic::sadd_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001508 computeKnownBitsAddSub(true, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001509 II->getArgOperand(1), false, Known, Known2,
1510 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001511 break;
1512 case Intrinsic::usub_with_overflow:
1513 case Intrinsic::ssub_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001514 computeKnownBitsAddSub(false, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001515 II->getArgOperand(1), false, Known, Known2,
1516 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001517 break;
Nick Lewyckyfa306072012-03-18 23:28:48 +00001518 case Intrinsic::umul_with_overflow:
1519 case Intrinsic::smul_with_overflow:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001520 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
Craig Topperb45eabc2017-04-26 16:39:58 +00001521 Known, Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001522 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001523 }
1524 }
1525 }
Chris Lattner965c7692008-06-02 01:18:21 +00001526 }
Jingyue Wu12b0c282015-06-15 05:46:29 +00001527}
1528
1529/// Determine which bits of V are known to be either zero or one and return
Craig Topper6e11a052017-05-08 16:22:48 +00001530/// them.
1531KnownBits computeKnownBits(const Value *V, unsigned Depth, const Query &Q) {
1532 KnownBits Known(getBitWidth(V->getType(), Q.DL));
1533 computeKnownBits(V, Known, Depth, Q);
1534 return Known;
1535}
1536
1537/// Determine which bits of V are known to be either zero or one and return
Craig Topperb45eabc2017-04-26 16:39:58 +00001538/// them in the Known bit set.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001539///
1540/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
1541/// we cannot optimize based on the assumption that it is zero without changing
1542/// it to be an explicit zero. If we don't change it to zero, other code could
1543/// optimized based on the contradictory assumption that it is non-zero.
1544/// Because instcombine aggressively folds operations with undef args anyway,
1545/// this won't lose us code quality.
1546///
1547/// This function is defined on values with integer type, values with pointer
1548/// type, and vectors of integers. In the case
1549/// where V is a vector, known zero, and known one values are the
1550/// same width as the vector element, and the bit is set only if it is true
1551/// for all of the elements in the vector.
Craig Topperb45eabc2017-04-26 16:39:58 +00001552void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
1553 const Query &Q) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001554 assert(V && "No Value?");
1555 assert(Depth <= MaxDepth && "Limit Search Depth");
Craig Topperb45eabc2017-04-26 16:39:58 +00001556 unsigned BitWidth = Known.getBitWidth();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001557
Craig Topperfde47232017-07-09 07:04:03 +00001558 assert((V->getType()->isIntOrIntVectorTy(BitWidth) ||
Craig Topper95d23472017-07-09 07:04:00 +00001559 V->getType()->isPtrOrPtrVectorTy()) &&
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001560 "Not integer or pointer type!");
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001561
1562 Type *ScalarTy = V->getType()->getScalarType();
1563 unsigned ExpectedWidth = ScalarTy->isPointerTy() ?
1564 Q.DL.getIndexTypeSizeInBits(ScalarTy) : Q.DL.getTypeSizeInBits(ScalarTy);
1565 assert(ExpectedWidth == BitWidth && "V and Known should have same BitWidth");
Craig Topperd73c6b42017-03-23 07:06:39 +00001566 (void)BitWidth;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001567 (void)ExpectedWidth;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001568
Sanjay Patelc96f6db2016-09-16 21:20:36 +00001569 const APInt *C;
1570 if (match(V, m_APInt(C))) {
1571 // We know all of the bits for a scalar constant or a splat vector constant!
Craig Topperb45eabc2017-04-26 16:39:58 +00001572 Known.One = *C;
1573 Known.Zero = ~Known.One;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001574 return;
1575 }
1576 // Null and aggregate-zero are all-zeros.
Sanjay Patele8dc0902016-05-23 17:57:54 +00001577 if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001578 Known.setAllZero();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001579 return;
1580 }
1581 // Handle a constant vector by taking the intersection of the known bits of
David Majnemer3918cdd2016-05-04 06:13:33 +00001582 // each element.
Pete Cooper35b00d52016-08-13 01:05:32 +00001583 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001584 // We know that CDS must be a vector of integers. Take the intersection of
1585 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001586 Known.Zero.setAllBits(); Known.One.setAllBits();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001587 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Craig Topperb98ee582017-10-21 16:35:39 +00001588 APInt Elt = CDS->getElementAsAPInt(i);
Craig Topperb45eabc2017-04-26 16:39:58 +00001589 Known.Zero &= ~Elt;
1590 Known.One &= Elt;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001591 }
1592 return;
1593 }
1594
Pete Cooper35b00d52016-08-13 01:05:32 +00001595 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
David Majnemer3918cdd2016-05-04 06:13:33 +00001596 // We know that CV must be a vector of integers. Take the intersection of
1597 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001598 Known.Zero.setAllBits(); Known.One.setAllBits();
David Majnemer3918cdd2016-05-04 06:13:33 +00001599 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1600 Constant *Element = CV->getAggregateElement(i);
1601 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
1602 if (!ElementCI) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001603 Known.resetAll();
David Majnemer3918cdd2016-05-04 06:13:33 +00001604 return;
1605 }
Craig Topperb98ee582017-10-21 16:35:39 +00001606 const APInt &Elt = ElementCI->getValue();
Craig Topperb45eabc2017-04-26 16:39:58 +00001607 Known.Zero &= ~Elt;
1608 Known.One &= Elt;
David Majnemer3918cdd2016-05-04 06:13:33 +00001609 }
1610 return;
1611 }
1612
Jingyue Wu12b0c282015-06-15 05:46:29 +00001613 // Start out not knowing anything.
Craig Topperf0aeee02017-05-05 17:36:09 +00001614 Known.resetAll();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001615
Duncan P. N. Exon Smithb1b208a2016-09-24 20:42:02 +00001616 // We can't imply anything about undefs.
1617 if (isa<UndefValue>(V))
1618 return;
1619
1620 // There's no point in looking through other users of ConstantData for
1621 // assumptions. Confirm that we've handled them all.
1622 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
1623
Jingyue Wu12b0c282015-06-15 05:46:29 +00001624 // Limit search depth.
1625 // All recursive calls that increase depth must come after this.
1626 if (Depth == MaxDepth)
1627 return;
1628
1629 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1630 // the bits of its aliasee.
Pete Cooper35b00d52016-08-13 01:05:32 +00001631 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001632 if (!GA->isInterposable())
Craig Topperb45eabc2017-04-26 16:39:58 +00001633 computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001634 return;
1635 }
1636
Pete Cooper35b00d52016-08-13 01:05:32 +00001637 if (const Operator *I = dyn_cast<Operator>(V))
Craig Topperb45eabc2017-04-26 16:39:58 +00001638 computeKnownBitsFromOperator(I, Known, Depth, Q);
Sanjay Patela67559c2015-09-25 20:12:43 +00001639
Craig Topperb45eabc2017-04-26 16:39:58 +00001640 // Aligned pointers have trailing zeros - refine Known.Zero set
Artur Pilipenko029d8532015-09-30 11:55:45 +00001641 if (V->getType()->isPointerTy()) {
Artur Pilipenkoae51afc2016-02-24 12:25:10 +00001642 unsigned Align = V->getPointerAlignment(Q.DL);
Artur Pilipenko029d8532015-09-30 11:55:45 +00001643 if (Align)
Craig Topperb45eabc2017-04-26 16:39:58 +00001644 Known.Zero.setLowBits(countTrailingZeros(Align));
Artur Pilipenko029d8532015-09-30 11:55:45 +00001645 }
1646
Craig Topperb45eabc2017-04-26 16:39:58 +00001647 // computeKnownBitsFromAssume strictly refines Known.
1648 // Therefore, we run them after computeKnownBitsFromOperator.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001649
1650 // Check whether a nearby assume intrinsic can determine some known bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001651 computeKnownBitsFromAssume(V, Known, Depth, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001652
Craig Topperb45eabc2017-04-26 16:39:58 +00001653 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001654}
1655
Sanjay Patelaee84212014-11-04 16:27:42 +00001656/// Return true if the given value is known to have exactly one
Duncan Sandsd3951082011-01-25 09:38:29 +00001657/// bit set when defined. For vectors return true if every element is known to
Sanjay Patelaee84212014-11-04 16:27:42 +00001658/// be a power of two when defined. Supports values with integer or pointer
Duncan Sandsd3951082011-01-25 09:38:29 +00001659/// types and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001660bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001661 const Query &Q) {
Craig Topper7227eba2017-08-21 22:56:12 +00001662 assert(Depth <= MaxDepth && "Limit Search Depth");
1663
Simon Pilgrim9f2ae7e2018-02-06 18:39:23 +00001664 // Attempt to match against constants.
1665 if (OrZero && match(V, m_Power2OrZero()))
1666 return true;
1667 if (match(V, m_Power2()))
1668 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00001669
1670 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1671 // it is shifted off the end then the result is undefined.
1672 if (match(V, m_Shl(m_One(), m_Value())))
1673 return true;
1674
Craig Topperbcfd2d12017-04-20 16:56:25 +00001675 // (signmask) >>l X is clearly a power of two if the one is not shifted off
1676 // the bottom. If it is shifted off the bottom then the result is undefined.
1677 if (match(V, m_LShr(m_SignMask(), m_Value())))
Duncan Sandsd3951082011-01-25 09:38:29 +00001678 return true;
1679
1680 // The remaining tests are all recursive, so bail out if we hit the limit.
1681 if (Depth++ == MaxDepth)
1682 return false;
1683
Craig Topper9f008862014-04-15 04:59:12 +00001684 Value *X = nullptr, *Y = nullptr;
Sanjay Patel41160c22015-12-30 22:40:52 +00001685 // A shift left or a logical shift right of a power of two is a power of two
1686 // or zero.
Duncan Sands985ba632011-10-28 18:30:05 +00001687 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
Sanjay Patel41160c22015-12-30 22:40:52 +00001688 match(V, m_LShr(m_Value(X), m_Value()))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001689 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
Duncan Sands985ba632011-10-28 18:30:05 +00001690
Pete Cooper35b00d52016-08-13 01:05:32 +00001691 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001692 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001693
Pete Cooper35b00d52016-08-13 01:05:32 +00001694 if (const SelectInst *SI = dyn_cast<SelectInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001695 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1696 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
Duncan Sandsba286d72011-10-26 20:55:21 +00001697
Duncan Sandsba286d72011-10-26 20:55:21 +00001698 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1699 // A power of two and'd with anything is a power of two or zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001700 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
1701 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
Duncan Sandsba286d72011-10-26 20:55:21 +00001702 return true;
1703 // X & (-X) is always a power of two or zero.
1704 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1705 return true;
1706 return false;
1707 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001708
David Majnemerb7d54092013-07-30 21:01:36 +00001709 // Adding a power-of-two or zero to the same power-of-two or zero yields
1710 // either the original power-of-two, a larger power-of-two or zero.
1711 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001712 const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
David Majnemerb7d54092013-07-30 21:01:36 +00001713 if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1714 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1715 match(X, m_And(m_Value(), m_Specific(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001716 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001717 return true;
1718 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1719 match(Y, m_And(m_Value(), m_Specific(X))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001720 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001721 return true;
1722
1723 unsigned BitWidth = V->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00001724 KnownBits LHSBits(BitWidth);
1725 computeKnownBits(X, LHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001726
Craig Topperb45eabc2017-04-26 16:39:58 +00001727 KnownBits RHSBits(BitWidth);
1728 computeKnownBits(Y, RHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001729 // If i8 V is a power of two or zero:
1730 // ZeroBits: 1 1 1 0 1 1 1 1
1731 // ~ZeroBits: 0 0 0 1 0 0 0 0
Craig Topperb45eabc2017-04-26 16:39:58 +00001732 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
David Majnemerb7d54092013-07-30 21:01:36 +00001733 // If OrZero isn't set, we cannot give back a zero result.
1734 // Make sure either the LHS or RHS has a bit set.
Craig Topperb45eabc2017-04-26 16:39:58 +00001735 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
David Majnemerb7d54092013-07-30 21:01:36 +00001736 return true;
1737 }
1738 }
David Majnemerbeab5672013-05-18 19:30:37 +00001739
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001740 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewyckyf0469af2011-03-21 21:40:32 +00001741 // is a power of two only if the first operand is a power of two and not
1742 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001743 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1744 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
Hal Finkel60db0582014-09-07 18:57:58 +00001745 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001746 Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001747 }
1748
Duncan Sandsd3951082011-01-25 09:38:29 +00001749 return false;
1750}
1751
Chandler Carruth80d3e562012-12-07 02:08:58 +00001752/// \brief Test whether a GEP's result is known to be non-null.
1753///
1754/// Uses properties inherent in a GEP to try to determine whether it is known
1755/// to be non-null.
1756///
1757/// Currently this routine does not support vector GEPs.
Pete Cooper35b00d52016-08-13 01:05:32 +00001758static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001759 const Query &Q) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001760 if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1761 return false;
1762
1763 // FIXME: Support vector-GEPs.
1764 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1765
1766 // If the base pointer is non-null, we cannot walk to a null address with an
1767 // inbounds GEP in address space zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001768 if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001769 return true;
1770
Chandler Carruth80d3e562012-12-07 02:08:58 +00001771 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1772 // If so, then the GEP cannot produce a null pointer, as doing so would
1773 // inherently violate the inbounds contract within address space zero.
1774 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1775 GTI != GTE; ++GTI) {
1776 // Struct types are easy -- they must always be indexed by a constant.
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001777 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001778 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1779 unsigned ElementIdx = OpC->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001780 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chandler Carruth80d3e562012-12-07 02:08:58 +00001781 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1782 if (ElementOffset > 0)
1783 return true;
1784 continue;
1785 }
1786
1787 // If we have a zero-sized type, the index doesn't matter. Keep looping.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001788 if (Q.DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
Chandler Carruth80d3e562012-12-07 02:08:58 +00001789 continue;
1790
1791 // Fast path the constant operand case both for efficiency and so we don't
1792 // increment Depth when just zipping down an all-constant GEP.
1793 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1794 if (!OpC->isZero())
1795 return true;
1796 continue;
1797 }
1798
1799 // We post-increment Depth here because while isKnownNonZero increments it
1800 // as well, when we pop back up that increment won't persist. We don't want
1801 // to recurse 10k times just because we have 10k GEP operands. We don't
1802 // bail completely out because we want to handle constant GEPs regardless
1803 // of depth.
1804 if (Depth++ >= MaxDepth)
1805 continue;
1806
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001807 if (isKnownNonZero(GTI.getOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001808 return true;
1809 }
1810
1811 return false;
1812}
1813
Nuno Lopes404f1062017-09-09 18:23:11 +00001814static bool isKnownNonNullFromDominatingCondition(const Value *V,
1815 const Instruction *CtxI,
1816 const DominatorTree *DT) {
1817 assert(V->getType()->isPointerTy() && "V must be pointer type");
1818 assert(!isa<ConstantData>(V) && "Did not expect ConstantPointerNull");
1819
1820 if (!CtxI || !DT)
1821 return false;
1822
1823 unsigned NumUsesExplored = 0;
1824 for (auto *U : V->users()) {
1825 // Avoid massive lists
1826 if (NumUsesExplored >= DomConditionsMaxUses)
1827 break;
1828 NumUsesExplored++;
1829
1830 // If the value is used as an argument to a call or invoke, then argument
1831 // attributes may provide an answer about null-ness.
1832 if (auto CS = ImmutableCallSite(U))
1833 if (auto *CalledFunc = CS.getCalledFunction())
1834 for (const Argument &Arg : CalledFunc->args())
1835 if (CS.getArgOperand(Arg.getArgNo()) == V &&
1836 Arg.hasNonNullAttr() && DT->dominates(CS.getInstruction(), CtxI))
1837 return true;
1838
1839 // Consider only compare instructions uniquely controlling a branch
1840 CmpInst::Predicate Pred;
1841 if (!match(const_cast<User *>(U),
1842 m_c_ICmp(Pred, m_Specific(V), m_Zero())) ||
1843 (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE))
1844 continue;
1845
1846 for (auto *CmpU : U->users()) {
1847 if (const BranchInst *BI = dyn_cast<BranchInst>(CmpU)) {
1848 assert(BI->isConditional() && "uses a comparison!");
1849
1850 BasicBlock *NonNullSuccessor =
1851 BI->getSuccessor(Pred == ICmpInst::ICMP_EQ ? 1 : 0);
1852 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
1853 if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
1854 return true;
1855 } else if (Pred == ICmpInst::ICMP_NE &&
1856 match(CmpU, m_Intrinsic<Intrinsic::experimental_guard>()) &&
1857 DT->dominates(cast<Instruction>(CmpU), CtxI)) {
1858 return true;
1859 }
1860 }
1861 }
1862
1863 return false;
1864}
1865
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001866/// Does the 'Range' metadata (which must be a valid MD_range operand list)
1867/// ensure that the value it's attached to is never Value? 'RangeType' is
1868/// is the type of the value described by the range.
Pete Cooper35b00d52016-08-13 01:05:32 +00001869static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001870 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1871 assert(NumRanges >= 1);
1872 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001873 ConstantInt *Lower =
1874 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1875 ConstantInt *Upper =
1876 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001877 ConstantRange Range(Lower->getValue(), Upper->getValue());
1878 if (Range.contains(Value))
1879 return false;
1880 }
1881 return true;
1882}
1883
Sanjay Patel97e4b9872017-02-12 15:35:34 +00001884/// Return true if the given value is known to be non-zero when defined. For
1885/// vectors, return true if every element is known to be non-zero when
1886/// defined. For pointers, if the context instruction and dominator tree are
1887/// specified, perform context-sensitive analysis and return true if the
1888/// pointer couldn't possibly be null at the specified instruction.
1889/// Supports values with integer or pointer type and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001890bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q) {
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001891 if (auto *C = dyn_cast<Constant>(V)) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001892 if (C->isNullValue())
1893 return false;
1894 if (isa<ConstantInt>(C))
1895 // Must be non-zero due to null test above.
1896 return true;
Sanjay Patel23019d12016-05-24 14:18:49 +00001897
1898 // For constant vectors, check that all elements are undefined or known
1899 // non-zero to determine that the whole vector is known non-zero.
1900 if (auto *VecTy = dyn_cast<VectorType>(C->getType())) {
1901 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
1902 Constant *Elt = C->getAggregateElement(i);
1903 if (!Elt || Elt->isNullValue())
1904 return false;
1905 if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
1906 return false;
1907 }
1908 return true;
1909 }
1910
Nuno Lopes404f1062017-09-09 18:23:11 +00001911 // A global variable in address space 0 is non null unless extern weak
1912 // or an absolute symbol reference. Other address spaces may have null as a
1913 // valid address for a global, so we can't assume anything.
1914 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1915 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
1916 GV->getType()->getAddressSpace() == 0)
1917 return true;
1918 } else
1919 return false;
Duncan Sandsd3951082011-01-25 09:38:29 +00001920 }
1921
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001922 if (auto *I = dyn_cast<Instruction>(V)) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001923 if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001924 // If the possible ranges don't contain zero, then the value is
1925 // definitely non-zero.
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001926 if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001927 const APInt ZeroValue(Ty->getBitWidth(), 0);
1928 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
1929 return true;
1930 }
1931 }
1932 }
1933
Nuno Lopes404f1062017-09-09 18:23:11 +00001934 // Check for pointer simplifications.
1935 if (V->getType()->isPointerTy()) {
1936 // Alloca never returns null, malloc might.
1937 if (isa<AllocaInst>(V) && Q.DL.getAllocaAddrSpace() == 0)
1938 return true;
1939
1940 // A byval, inalloca, or nonnull argument is never null.
1941 if (const Argument *A = dyn_cast<Argument>(V))
1942 if (A->hasByValOrInAllocaAttr() || A->hasNonNullAttr())
1943 return true;
1944
1945 // A Load tagged with nonnull metadata is never null.
1946 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
1947 if (LI->getMetadata(LLVMContext::MD_nonnull))
1948 return true;
1949
1950 if (auto CS = ImmutableCallSite(V))
1951 if (CS.isReturnNonNull())
1952 return true;
1953 }
1954
Duncan Sandsd3951082011-01-25 09:38:29 +00001955 // The remaining tests are all recursive, so bail out if we hit the limit.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001956 if (Depth++ >= MaxDepth)
Duncan Sandsd3951082011-01-25 09:38:29 +00001957 return false;
1958
Nuno Lopes404f1062017-09-09 18:23:11 +00001959 // Check for recursive pointer simplifications.
Chandler Carruth80d3e562012-12-07 02:08:58 +00001960 if (V->getType()->isPointerTy()) {
Nuno Lopes404f1062017-09-09 18:23:11 +00001961 if (isKnownNonNullFromDominatingCondition(V, Q.CxtI, Q.DT))
Sanjoy Das6082c1a2016-05-07 02:08:15 +00001962 return true;
Nuno Lopes404f1062017-09-09 18:23:11 +00001963
Pete Cooper35b00d52016-08-13 01:05:32 +00001964 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001965 if (isGEPKnownNonNull(GEP, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001966 return true;
1967 }
1968
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001969 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001970
1971 // X | Y != 0 if X != 0 or Y != 0.
Craig Topper9f008862014-04-15 04:59:12 +00001972 Value *X = nullptr, *Y = nullptr;
Duncan Sandsd3951082011-01-25 09:38:29 +00001973 if (match(V, m_Or(m_Value(X), m_Value(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001974 return isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001975
1976 // ext X != 0 if X != 0.
1977 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001978 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001979
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001980 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd3951082011-01-25 09:38:29 +00001981 // if the lowest bit is shifted off the end.
Craig Topper6b3940a2017-05-03 22:25:19 +00001982 if (match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001983 // shl nuw can't remove any non-zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00001984 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001985 if (BO->hasNoUnsignedWrap())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001986 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001987
Craig Topperb45eabc2017-04-26 16:39:58 +00001988 KnownBits Known(BitWidth);
1989 computeKnownBits(X, Known, Depth, Q);
1990 if (Known.One[0])
Duncan Sandsd3951082011-01-25 09:38:29 +00001991 return true;
1992 }
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001993 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd3951082011-01-25 09:38:29 +00001994 // defined if the sign bit is shifted off the end.
1995 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001996 // shr exact can only shift out zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00001997 const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001998 if (BO->isExact())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001999 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002000
Craig Topper6e11a052017-05-08 16:22:48 +00002001 KnownBits Known = computeKnownBits(X, Depth, Q);
2002 if (Known.isNegative())
Duncan Sandsd3951082011-01-25 09:38:29 +00002003 return true;
James Molloyb6be1eb2015-09-24 16:06:32 +00002004
2005 // If the shifter operand is a constant, and all of the bits shifted
2006 // out are known to be zero, and X is known non-zero then at least one
2007 // non-zero bit must remain.
2008 if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
James Molloyb6be1eb2015-09-24 16:06:32 +00002009 auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
2010 // Is there a known one in the portion not shifted out?
Craig Topper8df66c62017-05-12 17:20:30 +00002011 if (Known.countMaxLeadingZeros() < BitWidth - ShiftVal)
James Molloyb6be1eb2015-09-24 16:06:32 +00002012 return true;
2013 // Are all the bits to be shifted out known zero?
NAKAMURA Takumi76bab1f2017-07-11 02:31:51 +00002014 if (Known.countMinTrailingZeros() >= ShiftVal)
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002015 return isKnownNonZero(X, Depth, Q);
James Molloyb6be1eb2015-09-24 16:06:32 +00002016 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002017 }
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002018 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer9442cd02012-01-01 17:55:30 +00002019 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002020 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00002021 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002022 // X + Y.
2023 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Craig Topper6e11a052017-05-08 16:22:48 +00002024 KnownBits XKnown = computeKnownBits(X, Depth, Q);
2025 KnownBits YKnown = computeKnownBits(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00002026
2027 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands9e9d5b22011-01-25 15:14:15 +00002028 // zero unless both X and Y are zero.
Craig Topper6e11a052017-05-08 16:22:48 +00002029 if (XKnown.isNonNegative() && YKnown.isNonNegative())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002030 if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q))
Duncan Sands9e9d5b22011-01-25 15:14:15 +00002031 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00002032
2033 // If X and Y are both negative (as signed values) then their sum is not
2034 // zero unless both X and Y equal INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002035 if (XKnown.isNegative() && YKnown.isNegative()) {
Duncan Sandsd3951082011-01-25 09:38:29 +00002036 APInt Mask = APInt::getSignedMaxValue(BitWidth);
2037 // The sign bit of X is set. If some other bit is set then X is not equal
2038 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002039 if (XKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00002040 return true;
2041 // The sign bit of Y is set. If some other bit is set then Y is not equal
2042 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00002043 if (YKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00002044 return true;
2045 }
2046
2047 // The sum of a non-negative number and a power of two is not zero.
Craig Topper6e11a052017-05-08 16:22:48 +00002048 if (XKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002049 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002050 return true;
Craig Topper6e11a052017-05-08 16:22:48 +00002051 if (YKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002052 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002053 return true;
2054 }
Duncan Sands7cb61e52011-10-27 19:16:21 +00002055 // X * Y.
2056 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00002057 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Duncan Sands7cb61e52011-10-27 19:16:21 +00002058 // If X and Y are non-zero then so is X * Y as long as the multiplication
2059 // does not overflow.
2060 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002061 isKnownNonZero(X, Depth, Q) && isKnownNonZero(Y, Depth, Q))
Duncan Sands7cb61e52011-10-27 19:16:21 +00002062 return true;
2063 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002064 // (C ? X : Y) != 0 if X != 0 and Y != 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00002065 else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002066 if (isKnownNonZero(SI->getTrueValue(), Depth, Q) &&
2067 isKnownNonZero(SI->getFalseValue(), Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00002068 return true;
2069 }
James Molloy897048b2015-09-29 14:08:45 +00002070 // PHI
Pete Cooper35b00d52016-08-13 01:05:32 +00002071 else if (const PHINode *PN = dyn_cast<PHINode>(V)) {
James Molloy897048b2015-09-29 14:08:45 +00002072 // Try and detect a recurrence that monotonically increases from a
2073 // starting value, as these are common as induction variables.
2074 if (PN->getNumIncomingValues() == 2) {
2075 Value *Start = PN->getIncomingValue(0);
2076 Value *Induction = PN->getIncomingValue(1);
2077 if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start))
2078 std::swap(Start, Induction);
2079 if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) {
2080 if (!C->isZero() && !C->isNegative()) {
2081 ConstantInt *X;
2082 if ((match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) ||
2083 match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) &&
2084 !X->isNegative())
2085 return true;
2086 }
2087 }
2088 }
Jun Bum Limca832662016-02-01 17:03:07 +00002089 // Check if all incoming values are non-zero constant.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002090 bool AllNonZeroConstants = llvm::all_of(PN->operands(), [](Value *V) {
Craig Topper79ab6432017-07-06 18:39:47 +00002091 return isa<ConstantInt>(V) && !cast<ConstantInt>(V)->isZero();
Jun Bum Limca832662016-02-01 17:03:07 +00002092 });
2093 if (AllNonZeroConstants)
2094 return true;
James Molloy897048b2015-09-29 14:08:45 +00002095 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002096
Craig Topperb45eabc2017-04-26 16:39:58 +00002097 KnownBits Known(BitWidth);
2098 computeKnownBits(V, Known, Depth, Q);
2099 return Known.One != 0;
Duncan Sandsd3951082011-01-25 09:38:29 +00002100}
2101
James Molloy1d88d6f2015-10-22 13:18:42 +00002102/// Return true if V2 == V1 + X, where X is known non-zero.
Pete Cooper35b00d52016-08-13 01:05:32 +00002103static bool isAddOfNonZero(const Value *V1, const Value *V2, const Query &Q) {
2104 const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
James Molloy1d88d6f2015-10-22 13:18:42 +00002105 if (!BO || BO->getOpcode() != Instruction::Add)
2106 return false;
2107 Value *Op = nullptr;
2108 if (V2 == BO->getOperand(0))
2109 Op = BO->getOperand(1);
2110 else if (V2 == BO->getOperand(1))
2111 Op = BO->getOperand(0);
2112 else
2113 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002114 return isKnownNonZero(Op, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00002115}
2116
2117/// Return true if it is known that V1 != V2.
Pete Cooper35b00d52016-08-13 01:05:32 +00002118static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q) {
Craig Topper3002d5b2017-06-06 07:13:15 +00002119 if (V1 == V2)
James Molloy1d88d6f2015-10-22 13:18:42 +00002120 return false;
2121 if (V1->getType() != V2->getType())
2122 // We can't look through casts yet.
2123 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002124 if (isAddOfNonZero(V1, V2, Q) || isAddOfNonZero(V2, V1, Q))
James Molloy1d88d6f2015-10-22 13:18:42 +00002125 return true;
2126
Craig Topper3002d5b2017-06-06 07:13:15 +00002127 if (V1->getType()->isIntOrIntVectorTy()) {
James Molloy1d88d6f2015-10-22 13:18:42 +00002128 // Are any known bits in V1 contradictory to known bits in V2? If V1
2129 // has a known zero where V2 has a known one, they must not be equal.
Craig Topper8e662f72017-06-06 07:13:11 +00002130 KnownBits Known1 = computeKnownBits(V1, 0, Q);
2131 KnownBits Known2 = computeKnownBits(V2, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00002132
Craig Topper8365df82017-06-06 07:13:09 +00002133 if (Known1.Zero.intersects(Known2.One) ||
2134 Known2.Zero.intersects(Known1.One))
James Molloy1d88d6f2015-10-22 13:18:42 +00002135 return true;
2136 }
2137 return false;
2138}
2139
Sanjay Patelaee84212014-11-04 16:27:42 +00002140/// Return true if 'V & Mask' is known to be zero. We use this predicate to
2141/// simplify operations downstream. Mask is known to be zero for bits that V
2142/// cannot have.
Chris Lattner4bc28252009-09-08 00:06:16 +00002143///
2144/// This function is defined on values with integer type, values with pointer
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002145/// type, and vectors of integers. In the case
Chris Lattner4bc28252009-09-08 00:06:16 +00002146/// where V is a vector, the mask, known zero, and known one values are the
2147/// same width as the vector element, and the bit is set only if it is true
2148/// for all of the elements in the vector.
Pete Cooper35b00d52016-08-13 01:05:32 +00002149bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002150 const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002151 KnownBits Known(Mask.getBitWidth());
2152 computeKnownBits(V, Known, Depth, Q);
2153 return Mask.isSubsetOf(Known.Zero);
Chris Lattner965c7692008-06-02 01:18:21 +00002154}
2155
Sanjay Patela06d9892016-06-22 19:20:59 +00002156/// For vector constants, loop over the elements and find the constant with the
2157/// minimum number of sign bits. Return 0 if the value is not a vector constant
2158/// or if any element was not analyzed; otherwise, return the count for the
2159/// element with the minimum number of sign bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002160static unsigned computeNumSignBitsVectorConstant(const Value *V,
2161 unsigned TyBits) {
2162 const auto *CV = dyn_cast<Constant>(V);
Sanjay Patela06d9892016-06-22 19:20:59 +00002163 if (!CV || !CV->getType()->isVectorTy())
2164 return 0;
Chris Lattner965c7692008-06-02 01:18:21 +00002165
Sanjay Patela06d9892016-06-22 19:20:59 +00002166 unsigned MinSignBits = TyBits;
2167 unsigned NumElts = CV->getType()->getVectorNumElements();
2168 for (unsigned i = 0; i != NumElts; ++i) {
2169 // If we find a non-ConstantInt, bail out.
2170 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
2171 if (!Elt)
2172 return 0;
2173
Craig Topper8e8b6ef2017-10-21 16:35:41 +00002174 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
Sanjay Patela06d9892016-06-22 19:20:59 +00002175 }
2176
2177 return MinSignBits;
2178}
Chris Lattner965c7692008-06-02 01:18:21 +00002179
Sanjoy Das39a684d2017-02-25 20:30:45 +00002180static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2181 const Query &Q);
2182
2183static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
2184 const Query &Q) {
2185 unsigned Result = ComputeNumSignBitsImpl(V, Depth, Q);
2186 assert(Result > 0 && "At least one sign bit needs to be present!");
2187 return Result;
2188}
2189
Sanjay Patelaee84212014-11-04 16:27:42 +00002190/// Return the number of times the sign bit of the register is replicated into
2191/// the other bits. We know that at least 1 bit is always equal to the sign bit
2192/// (itself), but other cases can give us information. For example, immediately
2193/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
Sanjay Patela06d9892016-06-22 19:20:59 +00002194/// other, so we return 3. For vectors, return the number of sign bits for the
Vedant Kumard3196742018-02-28 19:08:52 +00002195/// vector element with the minimum number of known sign bits.
Sanjoy Das39a684d2017-02-25 20:30:45 +00002196static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2197 const Query &Q) {
Craig Topper7227eba2017-08-21 22:56:12 +00002198 assert(Depth <= MaxDepth && "Limit Search Depth");
Sanjoy Das39a684d2017-02-25 20:30:45 +00002199
2200 // We return the minimum number of sign bits that are guaranteed to be present
2201 // in V, so for undef we have to conservatively return 1. We don't have the
2202 // same behavior for poison though -- that's a FIXME today.
2203
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00002204 Type *ScalarTy = V->getType()->getScalarType();
2205 unsigned TyBits = ScalarTy->isPointerTy() ?
2206 Q.DL.getIndexTypeSizeInBits(ScalarTy) :
2207 Q.DL.getTypeSizeInBits(ScalarTy);
2208
Chris Lattner965c7692008-06-02 01:18:21 +00002209 unsigned Tmp, Tmp2;
2210 unsigned FirstAnswer = 1;
2211
Jay Foada0653a32014-05-14 21:14:37 +00002212 // Note that ConstantInt is handled by the general computeKnownBits case
Chris Lattner2e01a692008-06-02 18:39:07 +00002213 // below.
2214
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002215 if (Depth == MaxDepth)
Chris Lattner965c7692008-06-02 01:18:21 +00002216 return 1; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002217
Pete Cooper35b00d52016-08-13 01:05:32 +00002218 const Operator *U = dyn_cast<Operator>(V);
Dan Gohman80ca01c2009-07-17 20:47:02 +00002219 switch (Operator::getOpcode(V)) {
Chris Lattner965c7692008-06-02 01:18:21 +00002220 default: break;
2221 case Instruction::SExt:
Mon P Wangbb3eac92009-12-02 04:59:58 +00002222 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002223 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
Craig Topper1bef2c82012-12-22 19:15:35 +00002224
Nadav Rotemc99a3872015-03-06 00:23:58 +00002225 case Instruction::SDiv: {
Nadav Rotem029c5c72015-03-03 21:39:02 +00002226 const APInt *Denominator;
2227 // sdiv X, C -> adds log(C) sign bits.
2228 if (match(U->getOperand(1), m_APInt(Denominator))) {
2229
2230 // Ignore non-positive denominator.
2231 if (!Denominator->isStrictlyPositive())
2232 break;
2233
2234 // Calculate the incoming numerator bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002235 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotem029c5c72015-03-03 21:39:02 +00002236
2237 // Add floor(log(C)) bits to the numerator bits.
2238 return std::min(TyBits, NumBits + Denominator->logBase2());
2239 }
2240 break;
Nadav Rotemc99a3872015-03-06 00:23:58 +00002241 }
2242
2243 case Instruction::SRem: {
2244 const APInt *Denominator;
Sanjoy Dase561fee2015-03-25 22:33:53 +00002245 // srem X, C -> we know that the result is within [-C+1,C) when C is a
2246 // positive constant. This let us put a lower bound on the number of sign
2247 // bits.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002248 if (match(U->getOperand(1), m_APInt(Denominator))) {
2249
2250 // Ignore non-positive denominator.
2251 if (!Denominator->isStrictlyPositive())
2252 break;
2253
2254 // Calculate the incoming numerator bits. SRem by a positive constant
2255 // can't lower the number of sign bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002256 unsigned NumrBits =
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002257 ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotemc99a3872015-03-06 00:23:58 +00002258
2259 // Calculate the leading sign bit constraints by examining the
Sanjoy Dase561fee2015-03-25 22:33:53 +00002260 // denominator. Given that the denominator is positive, there are two
2261 // cases:
2262 //
2263 // 1. the numerator is positive. The result range is [0,C) and [0,C) u<
2264 // (1 << ceilLogBase2(C)).
2265 //
2266 // 2. the numerator is negative. Then the result range is (-C,0] and
2267 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2268 //
2269 // Thus a lower bound on the number of sign bits is `TyBits -
2270 // ceilLogBase2(C)`.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002271
Sanjoy Dase561fee2015-03-25 22:33:53 +00002272 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
Nadav Rotemc99a3872015-03-06 00:23:58 +00002273 return std::max(NumrBits, ResBits);
2274 }
2275 break;
2276 }
Nadav Rotem029c5c72015-03-03 21:39:02 +00002277
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002278 case Instruction::AShr: {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002279 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002280 // ashr X, C -> adds C sign bits. Vectors too.
2281 const APInt *ShAmt;
2282 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Simon Pilgrim67207262018-01-01 22:44:59 +00002283 if (ShAmt->uge(TyBits))
Sanjoy Das39a684d2017-02-25 20:30:45 +00002284 break; // Bad shift.
Simon Pilgrim67207262018-01-01 22:44:59 +00002285 unsigned ShAmtLimited = ShAmt->getZExtValue();
Sanjoy Das39a684d2017-02-25 20:30:45 +00002286 Tmp += ShAmtLimited;
Chris Lattner965c7692008-06-02 01:18:21 +00002287 if (Tmp > TyBits) Tmp = TyBits;
2288 }
2289 return Tmp;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002290 }
2291 case Instruction::Shl: {
2292 const APInt *ShAmt;
2293 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner965c7692008-06-02 01:18:21 +00002294 // shl destroys sign bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002295 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Simon Pilgrim67207262018-01-01 22:44:59 +00002296 if (ShAmt->uge(TyBits) || // Bad shift.
2297 ShAmt->uge(Tmp)) break; // Shifted all sign bits out.
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002298 Tmp2 = ShAmt->getZExtValue();
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002299 return Tmp - Tmp2;
Chris Lattner965c7692008-06-02 01:18:21 +00002300 }
2301 break;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002302 }
Chris Lattner965c7692008-06-02 01:18:21 +00002303 case Instruction::And:
2304 case Instruction::Or:
2305 case Instruction::Xor: // NOT is handled here.
2306 // Logical binary ops preserve the number of sign bits at the worst.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002307 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002308 if (Tmp != 1) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002309 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002310 FirstAnswer = std::min(Tmp, Tmp2);
2311 // We computed what we know about the sign bits as our first
2312 // answer. Now proceed to the generic code that uses
Jay Foada0653a32014-05-14 21:14:37 +00002313 // computeKnownBits, and pick whichever answer is better.
Chris Lattner965c7692008-06-02 01:18:21 +00002314 }
2315 break;
2316
2317 case Instruction::Select:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002318 Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002319 if (Tmp == 1) return 1; // Early out.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002320 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002321 return std::min(Tmp, Tmp2);
Craig Topper1bef2c82012-12-22 19:15:35 +00002322
Chris Lattner965c7692008-06-02 01:18:21 +00002323 case Instruction::Add:
2324 // Add can have at most one carry bit. Thus we know that the output
2325 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002326 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002327 if (Tmp == 1) return 1; // Early out.
Craig Topper1bef2c82012-12-22 19:15:35 +00002328
Chris Lattner965c7692008-06-02 01:18:21 +00002329 // Special case decrementing a value (ADD X, -1):
David Majnemera55027f2014-12-26 09:20:17 +00002330 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
Chris Lattner965c7692008-06-02 01:18:21 +00002331 if (CRHS->isAllOnesValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002332 KnownBits Known(TyBits);
2333 computeKnownBits(U->getOperand(0), Known, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002334
Chris Lattner965c7692008-06-02 01:18:21 +00002335 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2336 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002337 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002338 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002339
Chris Lattner965c7692008-06-02 01:18:21 +00002340 // If we are subtracting one from a positive number, there is no carry
2341 // out of the result.
Craig Topperca48af32017-04-29 16:43:11 +00002342 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002343 return Tmp;
2344 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002345
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002346 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002347 if (Tmp2 == 1) return 1;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002348 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002349
Chris Lattner965c7692008-06-02 01:18:21 +00002350 case Instruction::Sub:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002351 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002352 if (Tmp2 == 1) return 1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002353
Chris Lattner965c7692008-06-02 01:18:21 +00002354 // Handle NEG.
David Majnemera55027f2014-12-26 09:20:17 +00002355 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
Chris Lattner965c7692008-06-02 01:18:21 +00002356 if (CLHS->isNullValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002357 KnownBits Known(TyBits);
2358 computeKnownBits(U->getOperand(1), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002359 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2360 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002361 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002362 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002363
Chris Lattner965c7692008-06-02 01:18:21 +00002364 // If the input is known to be positive (the sign bit is known clear),
2365 // the output of the NEG has the same number of sign bits as the input.
Craig Topperca48af32017-04-29 16:43:11 +00002366 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002367 return Tmp2;
Craig Topper1bef2c82012-12-22 19:15:35 +00002368
Chris Lattner965c7692008-06-02 01:18:21 +00002369 // Otherwise, we treat this like a SUB.
2370 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002371
Chris Lattner965c7692008-06-02 01:18:21 +00002372 // Sub can have at most one carry bit. Thus we know that the output
2373 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002374 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002375 if (Tmp == 1) return 1; // Early out.
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002376 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002377
Amjad Aboud88ffa3a2017-08-18 22:56:55 +00002378 case Instruction::Mul: {
2379 // The output of the Mul can be at most twice the valid bits in the inputs.
2380 unsigned SignBitsOp0 = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2381 if (SignBitsOp0 == 1) return 1; // Early out.
2382 unsigned SignBitsOp1 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2383 if (SignBitsOp1 == 1) return 1;
2384 unsigned OutValidBits =
2385 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
2386 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
2387 }
2388
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002389 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00002390 const PHINode *PN = cast<PHINode>(U);
David Majnemer6ee8d172015-01-04 07:06:53 +00002391 unsigned NumIncomingValues = PN->getNumIncomingValues();
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002392 // Don't analyze large in-degree PHIs.
David Majnemer6ee8d172015-01-04 07:06:53 +00002393 if (NumIncomingValues > 4) break;
2394 // Unreachable blocks may have zero-operand PHI nodes.
2395 if (NumIncomingValues == 0) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002396
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002397 // Take the minimum of all incoming values. This can't infinitely loop
2398 // because of our depth threshold.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002399 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), Depth + 1, Q);
David Majnemer6ee8d172015-01-04 07:06:53 +00002400 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002401 if (Tmp == 1) return Tmp;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002402 Tmp = std::min(
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002403 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, Q));
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002404 }
2405 return Tmp;
2406 }
2407
Chris Lattner965c7692008-06-02 01:18:21 +00002408 case Instruction::Trunc:
2409 // FIXME: it's tricky to do anything useful for this, but it is an important
2410 // case for targets like X86.
2411 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00002412
2413 case Instruction::ExtractElement:
2414 // Look through extract element. At the moment we keep this simple and skip
2415 // tracking the specific element. But at least we might find information
2416 // valid for all elements of the vector (for example if vector is sign
2417 // extended, shifted, etc).
2418 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002419 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002420
Chris Lattner965c7692008-06-02 01:18:21 +00002421 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2422 // use this information.
Sanjay Patela06d9892016-06-22 19:20:59 +00002423
2424 // If we can examine all elements of a vector constant successfully, we're
2425 // done (we can't do any better than that). If not, keep trying.
2426 if (unsigned VecSignBits = computeNumSignBitsVectorConstant(V, TyBits))
2427 return VecSignBits;
2428
Craig Topperb45eabc2017-04-26 16:39:58 +00002429 KnownBits Known(TyBits);
2430 computeKnownBits(V, Known, Depth, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002431
Sanjay Patele0536212016-06-23 17:41:59 +00002432 // If we know that the sign bit is either zero or one, determine the number of
2433 // identical bits in the top of the input value.
Craig Topper8df66c62017-05-12 17:20:30 +00002434 return std::max(FirstAnswer, Known.countMinSignBits());
Chris Lattner965c7692008-06-02 01:18:21 +00002435}
Chris Lattnera12a6de2008-06-02 01:29:46 +00002436
Sanjay Patelaee84212014-11-04 16:27:42 +00002437/// This function computes the integer multiple of Base that equals V.
2438/// If successful, it returns true and returns the multiple in
2439/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez47444882009-11-10 08:28:35 +00002440/// through SExt instructions only if LookThroughSExt is true.
2441bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman6a976bb2009-11-18 00:58:27 +00002442 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez47444882009-11-10 08:28:35 +00002443 const unsigned MaxDepth = 6;
2444
Dan Gohman6a976bb2009-11-18 00:58:27 +00002445 assert(V && "No Value?");
Victor Hernandez47444882009-11-10 08:28:35 +00002446 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002447 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez47444882009-11-10 08:28:35 +00002448
Chris Lattner229907c2011-07-18 04:54:35 +00002449 Type *T = V->getType();
Victor Hernandez47444882009-11-10 08:28:35 +00002450
Dan Gohman6a976bb2009-11-18 00:58:27 +00002451 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez47444882009-11-10 08:28:35 +00002452
2453 if (Base == 0)
2454 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002455
Victor Hernandez47444882009-11-10 08:28:35 +00002456 if (Base == 1) {
2457 Multiple = V;
2458 return true;
2459 }
2460
2461 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2462 Constant *BaseVal = ConstantInt::get(T, Base);
2463 if (CO && CO == BaseVal) {
2464 // Multiple is 1.
2465 Multiple = ConstantInt::get(T, 1);
2466 return true;
2467 }
2468
2469 if (CI && CI->getZExtValue() % Base == 0) {
2470 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
Craig Topper1bef2c82012-12-22 19:15:35 +00002471 return true;
Victor Hernandez47444882009-11-10 08:28:35 +00002472 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002473
Victor Hernandez47444882009-11-10 08:28:35 +00002474 if (Depth == MaxDepth) return false; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002475
Victor Hernandez47444882009-11-10 08:28:35 +00002476 Operator *I = dyn_cast<Operator>(V);
2477 if (!I) return false;
2478
2479 switch (I->getOpcode()) {
2480 default: break;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002481 case Instruction::SExt:
Victor Hernandez47444882009-11-10 08:28:35 +00002482 if (!LookThroughSExt) return false;
2483 // otherwise fall through to ZExt
Galina Kistanova244621f2017-05-31 22:16:24 +00002484 LLVM_FALLTHROUGH;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002485 case Instruction::ZExt:
Dan Gohman6a976bb2009-11-18 00:58:27 +00002486 return ComputeMultiple(I->getOperand(0), Base, Multiple,
2487 LookThroughSExt, Depth+1);
Victor Hernandez47444882009-11-10 08:28:35 +00002488 case Instruction::Shl:
2489 case Instruction::Mul: {
2490 Value *Op0 = I->getOperand(0);
2491 Value *Op1 = I->getOperand(1);
2492
2493 if (I->getOpcode() == Instruction::Shl) {
2494 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2495 if (!Op1CI) return false;
2496 // Turn Op0 << Op1 into Op0 * 2^Op1
2497 APInt Op1Int = Op1CI->getValue();
2498 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foad15084f02010-11-30 09:02:01 +00002499 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002500 API.setBit(BitToSet);
Jay Foad15084f02010-11-30 09:02:01 +00002501 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez47444882009-11-10 08:28:35 +00002502 }
2503
Craig Topper9f008862014-04-15 04:59:12 +00002504 Value *Mul0 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002505 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2506 if (Constant *Op1C = dyn_cast<Constant>(Op1))
2507 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002508 if (Op1C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002509 MulC->getType()->getPrimitiveSizeInBits())
2510 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002511 if (Op1C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002512 MulC->getType()->getPrimitiveSizeInBits())
2513 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002514
Chris Lattner72d283c2010-09-05 17:20:46 +00002515 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2516 Multiple = ConstantExpr::getMul(MulC, Op1C);
2517 return true;
2518 }
Victor Hernandez47444882009-11-10 08:28:35 +00002519
2520 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2521 if (Mul0CI->getValue() == 1) {
2522 // V == Base * Op1, so return Op1
2523 Multiple = Op1;
2524 return true;
2525 }
2526 }
2527
Craig Topper9f008862014-04-15 04:59:12 +00002528 Value *Mul1 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002529 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2530 if (Constant *Op0C = dyn_cast<Constant>(Op0))
2531 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002532 if (Op0C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002533 MulC->getType()->getPrimitiveSizeInBits())
2534 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002535 if (Op0C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002536 MulC->getType()->getPrimitiveSizeInBits())
2537 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002538
Chris Lattner72d283c2010-09-05 17:20:46 +00002539 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2540 Multiple = ConstantExpr::getMul(MulC, Op0C);
2541 return true;
2542 }
Victor Hernandez47444882009-11-10 08:28:35 +00002543
2544 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2545 if (Mul1CI->getValue() == 1) {
2546 // V == Base * Op0, so return Op0
2547 Multiple = Op0;
2548 return true;
2549 }
2550 }
Victor Hernandez47444882009-11-10 08:28:35 +00002551 }
2552 }
2553
2554 // We could not determine if V is a multiple of Base.
2555 return false;
2556}
2557
David Majnemerb4b27232016-04-19 19:10:21 +00002558Intrinsic::ID llvm::getIntrinsicForCallSite(ImmutableCallSite ICS,
2559 const TargetLibraryInfo *TLI) {
2560 const Function *F = ICS.getCalledFunction();
2561 if (!F)
2562 return Intrinsic::not_intrinsic;
2563
2564 if (F->isIntrinsic())
2565 return F->getIntrinsicID();
2566
2567 if (!TLI)
2568 return Intrinsic::not_intrinsic;
2569
David L. Jonesd21529f2017-01-23 23:16:46 +00002570 LibFunc Func;
David Majnemerb4b27232016-04-19 19:10:21 +00002571 // We're going to make assumptions on the semantics of the functions, check
2572 // that the target knows that it's available in this environment and it does
2573 // not have local linkage.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002574 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(*F, Func))
2575 return Intrinsic::not_intrinsic;
2576
2577 if (!ICS.onlyReadsMemory())
David Majnemerb4b27232016-04-19 19:10:21 +00002578 return Intrinsic::not_intrinsic;
2579
2580 // Otherwise check if we have a call to a function that can be turned into a
2581 // vector intrinsic.
2582 switch (Func) {
2583 default:
2584 break;
David L. Jonesd21529f2017-01-23 23:16:46 +00002585 case LibFunc_sin:
2586 case LibFunc_sinf:
2587 case LibFunc_sinl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002588 return Intrinsic::sin;
David L. Jonesd21529f2017-01-23 23:16:46 +00002589 case LibFunc_cos:
2590 case LibFunc_cosf:
2591 case LibFunc_cosl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002592 return Intrinsic::cos;
David L. Jonesd21529f2017-01-23 23:16:46 +00002593 case LibFunc_exp:
2594 case LibFunc_expf:
2595 case LibFunc_expl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002596 return Intrinsic::exp;
David L. Jonesd21529f2017-01-23 23:16:46 +00002597 case LibFunc_exp2:
2598 case LibFunc_exp2f:
2599 case LibFunc_exp2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002600 return Intrinsic::exp2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002601 case LibFunc_log:
2602 case LibFunc_logf:
2603 case LibFunc_logl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002604 return Intrinsic::log;
David L. Jonesd21529f2017-01-23 23:16:46 +00002605 case LibFunc_log10:
2606 case LibFunc_log10f:
2607 case LibFunc_log10l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002608 return Intrinsic::log10;
David L. Jonesd21529f2017-01-23 23:16:46 +00002609 case LibFunc_log2:
2610 case LibFunc_log2f:
2611 case LibFunc_log2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002612 return Intrinsic::log2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002613 case LibFunc_fabs:
2614 case LibFunc_fabsf:
2615 case LibFunc_fabsl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002616 return Intrinsic::fabs;
David L. Jonesd21529f2017-01-23 23:16:46 +00002617 case LibFunc_fmin:
2618 case LibFunc_fminf:
2619 case LibFunc_fminl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002620 return Intrinsic::minnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002621 case LibFunc_fmax:
2622 case LibFunc_fmaxf:
2623 case LibFunc_fmaxl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002624 return Intrinsic::maxnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002625 case LibFunc_copysign:
2626 case LibFunc_copysignf:
2627 case LibFunc_copysignl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002628 return Intrinsic::copysign;
David L. Jonesd21529f2017-01-23 23:16:46 +00002629 case LibFunc_floor:
2630 case LibFunc_floorf:
2631 case LibFunc_floorl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002632 return Intrinsic::floor;
David L. Jonesd21529f2017-01-23 23:16:46 +00002633 case LibFunc_ceil:
2634 case LibFunc_ceilf:
2635 case LibFunc_ceill:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002636 return Intrinsic::ceil;
David L. Jonesd21529f2017-01-23 23:16:46 +00002637 case LibFunc_trunc:
2638 case LibFunc_truncf:
2639 case LibFunc_truncl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002640 return Intrinsic::trunc;
David L. Jonesd21529f2017-01-23 23:16:46 +00002641 case LibFunc_rint:
2642 case LibFunc_rintf:
2643 case LibFunc_rintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002644 return Intrinsic::rint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002645 case LibFunc_nearbyint:
2646 case LibFunc_nearbyintf:
2647 case LibFunc_nearbyintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002648 return Intrinsic::nearbyint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002649 case LibFunc_round:
2650 case LibFunc_roundf:
2651 case LibFunc_roundl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002652 return Intrinsic::round;
David L. Jonesd21529f2017-01-23 23:16:46 +00002653 case LibFunc_pow:
2654 case LibFunc_powf:
2655 case LibFunc_powl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002656 return Intrinsic::pow;
David L. Jonesd21529f2017-01-23 23:16:46 +00002657 case LibFunc_sqrt:
2658 case LibFunc_sqrtf:
2659 case LibFunc_sqrtl:
Sanjay Patel86d24f12017-11-06 22:40:09 +00002660 return Intrinsic::sqrt;
David Majnemerb4b27232016-04-19 19:10:21 +00002661 }
2662
2663 return Intrinsic::not_intrinsic;
2664}
2665
Sanjay Patelaee84212014-11-04 16:27:42 +00002666/// Return true if we can prove that the specified FP value is never equal to
2667/// -0.0.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002668///
2669/// NOTE: this function will need to be revisited when we support non-default
2670/// rounding modes!
David Majnemer3ee5f342016-04-13 06:55:52 +00002671bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
2672 unsigned Depth) {
Sanjay Patel20df88a2017-11-13 17:56:23 +00002673 if (auto *CFP = dyn_cast<ConstantFP>(V))
Chris Lattnera12a6de2008-06-02 01:29:46 +00002674 return !CFP->getValueAPF().isNegZero();
Craig Topper1bef2c82012-12-22 19:15:35 +00002675
Sanjay Patel20df88a2017-11-13 17:56:23 +00002676 // Limit search depth.
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002677 if (Depth == MaxDepth)
Sanjay Patel20df88a2017-11-13 17:56:23 +00002678 return false;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002679
Sanjay Patel20df88a2017-11-13 17:56:23 +00002680 auto *Op = dyn_cast<Operator>(V);
2681 if (!Op)
2682 return false;
Michael Ilseman0f128372012-12-06 00:07:09 +00002683
Sanjay Patel20df88a2017-11-13 17:56:23 +00002684 // Check if the nsz fast-math flag is set.
2685 if (auto *FPO = dyn_cast<FPMathOperator>(Op))
Michael Ilseman0f128372012-12-06 00:07:09 +00002686 if (FPO->hasNoSignedZeros())
2687 return true;
2688
Sanjay Patel9e3d8f42017-11-13 17:40:47 +00002689 // (fadd x, 0.0) is guaranteed to return +0.0, not -0.0.
Sanjay Patel20df88a2017-11-13 17:56:23 +00002690 if (match(Op, m_FAdd(m_Value(), m_Zero())))
Sanjay Patel9e3d8f42017-11-13 17:40:47 +00002691 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002692
Chris Lattnera12a6de2008-06-02 01:29:46 +00002693 // sitofp and uitofp turn into +0.0 for zero.
Sanjay Patel20df88a2017-11-13 17:56:23 +00002694 if (isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op))
Chris Lattnera12a6de2008-06-02 01:29:46 +00002695 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002696
Sanjay Patel20df88a2017-11-13 17:56:23 +00002697 if (auto *Call = dyn_cast<CallInst>(Op)) {
2698 Intrinsic::ID IID = getIntrinsicForCallSite(Call, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002699 switch (IID) {
2700 default:
2701 break;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002702 // sqrt(-0.0) = -0.0, no other negative results are possible.
David Majnemer3ee5f342016-04-13 06:55:52 +00002703 case Intrinsic::sqrt:
Sanjay Patel20df88a2017-11-13 17:56:23 +00002704 return CannotBeNegativeZero(Call->getArgOperand(0), TLI, Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002705 // fabs(x) != -0.0
2706 case Intrinsic::fabs:
2707 return true;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002708 }
David Majnemer3ee5f342016-04-13 06:55:52 +00002709 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002710
Chris Lattnera12a6de2008-06-02 01:29:46 +00002711 return false;
2712}
2713
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002714/// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
2715/// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
2716/// bit despite comparing equal.
2717static bool cannotBeOrderedLessThanZeroImpl(const Value *V,
2718 const TargetLibraryInfo *TLI,
2719 bool SignBitOnly,
2720 unsigned Depth) {
Justin Lebar322c1272017-01-27 00:58:34 +00002721 // TODO: This function does not do the right thing when SignBitOnly is true
2722 // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform
2723 // which flips the sign bits of NaNs. See
2724 // https://llvm.org/bugs/show_bug.cgi?id=31702.
2725
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002726 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2727 return !CFP->getValueAPF().isNegative() ||
2728 (!SignBitOnly && CFP->getValueAPF().isZero());
2729 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002730
Craig Topper69c89722018-02-26 22:33:17 +00002731 // Handle vector of constants.
2732 if (auto *CV = dyn_cast<Constant>(V)) {
2733 if (CV->getType()->isVectorTy()) {
2734 unsigned NumElts = CV->getType()->getVectorNumElements();
2735 for (unsigned i = 0; i != NumElts; ++i) {
2736 auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i));
2737 if (!CFP)
2738 return false;
2739 if (CFP->getValueAPF().isNegative() &&
2740 (SignBitOnly || !CFP->getValueAPF().isZero()))
2741 return false;
2742 }
2743
2744 // All non-negative ConstantFPs.
2745 return true;
2746 }
2747 }
2748
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002749 if (Depth == MaxDepth)
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002750 return false; // Limit search depth.
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002751
2752 const Operator *I = dyn_cast<Operator>(V);
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002753 if (!I)
2754 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002755
2756 switch (I->getOpcode()) {
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002757 default:
2758 break;
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002759 // Unsigned integers are always nonnegative.
2760 case Instruction::UIToFP:
2761 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002762 case Instruction::FMul:
2763 // x*x is always non-negative or a NaN.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002764 if (I->getOperand(0) == I->getOperand(1) &&
2765 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002766 return true;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002767
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002768 LLVM_FALLTHROUGH;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002769 case Instruction::FAdd:
2770 case Instruction::FDiv:
2771 case Instruction::FRem:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002772 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2773 Depth + 1) &&
2774 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2775 Depth + 1);
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002776 case Instruction::Select:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002777 return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2778 Depth + 1) &&
2779 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2780 Depth + 1);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002781 case Instruction::FPExt:
2782 case Instruction::FPTrunc:
2783 // Widening/narrowing never change sign.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002784 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2785 Depth + 1);
Craig Topper30199102018-02-27 19:53:45 +00002786 case Instruction::ExtractElement:
2787 // Look through extract element. At the moment we keep this simple and skip
2788 // tracking the specific element. But at least we might find information
2789 // valid for all elements of the vector.
2790 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2791 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002792 case Instruction::Call:
Justin Lebar7e3184c2017-01-26 00:10:26 +00002793 const auto *CI = cast<CallInst>(I);
2794 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002795 switch (IID) {
2796 default:
2797 break;
2798 case Intrinsic::maxnum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002799 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2800 Depth + 1) ||
2801 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2802 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002803 case Intrinsic::minnum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002804 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2805 Depth + 1) &&
2806 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2807 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002808 case Intrinsic::exp:
2809 case Intrinsic::exp2:
2810 case Intrinsic::fabs:
David Majnemer3ee5f342016-04-13 06:55:52 +00002811 return true;
Justin Lebar7e3184c2017-01-26 00:10:26 +00002812
2813 case Intrinsic::sqrt:
2814 // sqrt(x) is always >= -0 or NaN. Moreover, sqrt(x) == -0 iff x == -0.
2815 if (!SignBitOnly)
2816 return true;
2817 return CI->hasNoNaNs() && (CI->hasNoSignedZeros() ||
2818 CannotBeNegativeZero(CI->getOperand(0), TLI));
2819
David Majnemer3ee5f342016-04-13 06:55:52 +00002820 case Intrinsic::powi:
Justin Lebar7e3184c2017-01-26 00:10:26 +00002821 if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) {
David Majnemer3ee5f342016-04-13 06:55:52 +00002822 // powi(x,n) is non-negative if n is even.
Justin Lebar7e3184c2017-01-26 00:10:26 +00002823 if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0)
David Majnemer3ee5f342016-04-13 06:55:52 +00002824 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002825 }
Justin Lebar322c1272017-01-27 00:58:34 +00002826 // TODO: This is not correct. Given that exp is an integer, here are the
2827 // ways that pow can return a negative value:
2828 //
2829 // pow(x, exp) --> negative if exp is odd and x is negative.
2830 // pow(-0, exp) --> -inf if exp is negative odd.
2831 // pow(-0, exp) --> -0 if exp is positive odd.
2832 // pow(-inf, exp) --> -0 if exp is negative odd.
2833 // pow(-inf, exp) --> -inf if exp is positive odd.
2834 //
2835 // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN,
2836 // but we must return false if x == -0. Unfortunately we do not currently
2837 // have a way of expressing this constraint. See details in
2838 // https://llvm.org/bugs/show_bug.cgi?id=31702.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002839 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2840 Depth + 1);
Justin Lebar322c1272017-01-27 00:58:34 +00002841
David Majnemer3ee5f342016-04-13 06:55:52 +00002842 case Intrinsic::fma:
2843 case Intrinsic::fmuladd:
2844 // x*x+y is non-negative if y is non-negative.
2845 return I->getOperand(0) == I->getOperand(1) &&
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002846 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
2847 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2848 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002849 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002850 break;
2851 }
Sanjoy Das6082c1a2016-05-07 02:08:15 +00002852 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002853}
2854
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002855bool llvm::CannotBeOrderedLessThanZero(const Value *V,
2856 const TargetLibraryInfo *TLI) {
2857 return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0);
2858}
2859
2860bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) {
2861 return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0);
2862}
2863
Sanjay Patel6840c5f2017-09-05 23:13:13 +00002864bool llvm::isKnownNeverNaN(const Value *V) {
2865 assert(V->getType()->isFPOrFPVectorTy() && "Querying for NaN on non-FP type");
2866
2867 // If we're told that NaNs won't happen, assume they won't.
2868 if (auto *FPMathOp = dyn_cast<FPMathOperator>(V))
2869 if (FPMathOp->hasNoNaNs())
2870 return true;
2871
2872 // TODO: Handle instructions and potentially recurse like other 'isKnown'
2873 // functions. For example, the result of sitofp is never NaN.
2874
2875 // Handle scalar constants.
2876 if (auto *CFP = dyn_cast<ConstantFP>(V))
2877 return !CFP->isNaN();
2878
2879 // Bail out for constant expressions, but try to handle vector constants.
2880 if (!V->getType()->isVectorTy() || !isa<Constant>(V))
2881 return false;
2882
2883 // For vectors, verify that each element is not NaN.
2884 unsigned NumElts = V->getType()->getVectorNumElements();
2885 for (unsigned i = 0; i != NumElts; ++i) {
2886 Constant *Elt = cast<Constant>(V)->getAggregateElement(i);
2887 if (!Elt)
2888 return false;
2889 if (isa<UndefValue>(Elt))
2890 continue;
2891 auto *CElt = dyn_cast<ConstantFP>(Elt);
2892 if (!CElt || CElt->isNaN())
2893 return false;
2894 }
2895 // All elements were confirmed not-NaN or undefined.
2896 return true;
2897}
2898
Sanjay Patelaee84212014-11-04 16:27:42 +00002899/// If the specified value can be set by repeating the same byte in memory,
2900/// return the i8 value that it is represented with. This is
Chris Lattner9cb10352010-12-26 20:15:01 +00002901/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2902/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
2903/// byte store (e.g. i16 0x1234), return null.
2904Value *llvm::isBytewiseValue(Value *V) {
2905 // All byte-wide stores are splatable, even of arbitrary variables.
2906 if (V->getType()->isIntegerTy(8)) return V;
Chris Lattneracf6b072011-02-19 19:35:49 +00002907
2908 // Handle 'null' ConstantArrayZero etc.
2909 if (Constant *C = dyn_cast<Constant>(V))
2910 if (C->isNullValue())
2911 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
Craig Topper1bef2c82012-12-22 19:15:35 +00002912
Chris Lattner9cb10352010-12-26 20:15:01 +00002913 // Constant float and double values can be handled as integer values if the
Craig Topper1bef2c82012-12-22 19:15:35 +00002914 // corresponding integer value is "byteable". An important case is 0.0.
Chris Lattner9cb10352010-12-26 20:15:01 +00002915 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2916 if (CFP->getType()->isFloatTy())
2917 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2918 if (CFP->getType()->isDoubleTy())
2919 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2920 // Don't handle long double formats, which have strange constraints.
2921 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002922
Benjamin Kramer17d90152015-02-07 19:29:02 +00002923 // We can handle constant integers that are multiple of 8 bits.
Chris Lattner9cb10352010-12-26 20:15:01 +00002924 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Benjamin Kramer17d90152015-02-07 19:29:02 +00002925 if (CI->getBitWidth() % 8 == 0) {
2926 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
Craig Topper1bef2c82012-12-22 19:15:35 +00002927
Benjamin Kramerb4b51502015-03-25 16:49:59 +00002928 if (!CI->getValue().isSplat(8))
Benjamin Kramer17d90152015-02-07 19:29:02 +00002929 return nullptr;
2930 return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
Chris Lattner9cb10352010-12-26 20:15:01 +00002931 }
2932 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002933
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002934 // A ConstantDataArray/Vector is splatable if all its members are equal and
2935 // also splatable.
2936 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2937 Value *Elt = CA->getElementAsConstant(0);
2938 Value *Val = isBytewiseValue(Elt);
Chris Lattner9cb10352010-12-26 20:15:01 +00002939 if (!Val)
Craig Topper9f008862014-04-15 04:59:12 +00002940 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002941
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002942 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2943 if (CA->getElementAsConstant(I) != Elt)
Craig Topper9f008862014-04-15 04:59:12 +00002944 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002945
Chris Lattner9cb10352010-12-26 20:15:01 +00002946 return Val;
2947 }
Chad Rosier8abf65a2011-12-06 00:19:08 +00002948
Chris Lattner9cb10352010-12-26 20:15:01 +00002949 // Conceptually, we could handle things like:
2950 // %a = zext i8 %X to i16
2951 // %b = shl i16 %a, 8
2952 // %c = or i16 %a, %b
2953 // but until there is an example that actually needs this, it doesn't seem
2954 // worth worrying about.
Craig Topper9f008862014-04-15 04:59:12 +00002955 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00002956}
2957
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002958// This is the recursive version of BuildSubAggregate. It takes a few different
2959// arguments. Idxs is the index within the nested struct From that we are
2960// looking at now (which is of type IndexedType). IdxSkip is the number of
2961// indices from Idxs that should be left out when inserting into the resulting
2962// struct. To is the result struct built so far, new insertvalue instructions
2963// build on that.
Chris Lattner229907c2011-07-18 04:54:35 +00002964static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Craig Topper2cd5ff82013-07-11 16:22:38 +00002965 SmallVectorImpl<unsigned> &Idxs,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002966 unsigned IdxSkip,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002967 Instruction *InsertBefore) {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002968 StructType *STy = dyn_cast<StructType>(IndexedType);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002969 if (STy) {
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002970 // Save the original To argument so we can modify it
2971 Value *OrigTo = To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002972 // General case, the type indexed by Idxs is a struct
2973 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2974 // Process each struct element recursively
2975 Idxs.push_back(i);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002976 Value *PrevTo = To;
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002977 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002978 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002979 Idxs.pop_back();
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002980 if (!To) {
2981 // Couldn't find any inserted value for this index? Cleanup
2982 while (PrevTo != OrigTo) {
2983 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
2984 PrevTo = Del->getAggregateOperand();
2985 Del->eraseFromParent();
2986 }
2987 // Stop processing elements
2988 break;
2989 }
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002990 }
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002991 // If we successfully found a value for each of our subaggregates
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002992 if (To)
2993 return To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002994 }
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002995 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
2996 // the struct's elements had a value that was inserted directly. In the latter
2997 // case, perhaps we can't determine each of the subelements individually, but
2998 // we might be able to find the complete struct somewhere.
Craig Topper1bef2c82012-12-22 19:15:35 +00002999
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003000 // Find the value that is at that particular spot
Jay Foad57aa6362011-07-13 10:26:04 +00003001 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003002
3003 if (!V)
Craig Topper9f008862014-04-15 04:59:12 +00003004 return nullptr;
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003005
Vedant Kumard3196742018-02-28 19:08:52 +00003006 // Insert the value in the new (sub) aggregate
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003007 return InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
3008 "tmp", InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003009}
3010
3011// This helper takes a nested struct and extracts a part of it (which is again a
3012// struct) into a new value. For example, given the struct:
3013// { a, { b, { c, d }, e } }
3014// and the indices "1, 1" this returns
3015// { c, d }.
3016//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003017// It does this by inserting an insertvalue for each element in the resulting
3018// struct, as opposed to just inserting a single struct. This will only work if
3019// each of the elements of the substruct are known (ie, inserted into From by an
3020// insertvalue instruction somewhere).
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003021//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003022// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foad57aa6362011-07-13 10:26:04 +00003023static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00003024 Instruction *InsertBefore) {
Matthijs Kooijman69801d42008-06-16 13:28:31 +00003025 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattner229907c2011-07-18 04:54:35 +00003026 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foad57aa6362011-07-13 10:26:04 +00003027 idx_range);
Owen Andersonb292b8c2009-07-30 23:03:37 +00003028 Value *To = UndefValue::get(IndexedType);
Jay Foad57aa6362011-07-13 10:26:04 +00003029 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003030 unsigned IdxSkip = Idxs.size();
3031
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003032 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003033}
3034
Vedant Kumard3196742018-02-28 19:08:52 +00003035/// Given an aggregate and a sequence of indices, see if the scalar value
3036/// indexed is already around as a register, for example if it was inserted
3037/// directly into the aggregate.
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00003038///
3039/// If InsertBefore is not null, this function will duplicate (modified)
3040/// insertvalues when a part of a nested struct is extracted.
Jay Foad57aa6362011-07-13 10:26:04 +00003041Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
3042 Instruction *InsertBefore) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003043 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003044 // recursion).
Jay Foad57aa6362011-07-13 10:26:04 +00003045 if (idx_range.empty())
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003046 return V;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003047 // We have indices, so V should have an indexable type.
3048 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
3049 "Not looking at a struct or array?");
3050 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
3051 "Invalid indices for type?");
Owen Andersonf1f17432009-07-06 22:37:39 +00003052
Chris Lattner67058832012-01-25 06:48:06 +00003053 if (Constant *C = dyn_cast<Constant>(V)) {
3054 C = C->getAggregateElement(idx_range[0]);
Craig Topper9f008862014-04-15 04:59:12 +00003055 if (!C) return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00003056 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
3057 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003058
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003059 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003060 // Loop the indices for the insertvalue instruction in parallel with the
3061 // requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00003062 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00003063 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
3064 i != e; ++i, ++req_idx) {
Jay Foad57aa6362011-07-13 10:26:04 +00003065 if (req_idx == idx_range.end()) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003066 // We can't handle this without inserting insertvalues
3067 if (!InsertBefore)
Craig Topper9f008862014-04-15 04:59:12 +00003068 return nullptr;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003069
3070 // The requested index identifies a part of a nested aggregate. Handle
3071 // this specially. For example,
3072 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
3073 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
3074 // %C = extractvalue {i32, { i32, i32 } } %B, 1
3075 // This can be changed into
3076 // %A = insertvalue {i32, i32 } undef, i32 10, 0
3077 // %C = insertvalue {i32, i32 } %A, i32 11, 1
3078 // which allows the unused 0,0 element from the nested struct to be
3079 // removed.
3080 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
3081 InsertBefore);
Duncan Sandsdb356ee2008-06-19 08:47:31 +00003082 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003083
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003084 // This insert value inserts something else than what we are looking for.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003085 // See if the (aggregate) value inserted into has the value we are
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003086 // looking for, then.
3087 if (*req_idx != *i)
Jay Foad57aa6362011-07-13 10:26:04 +00003088 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003089 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003090 }
3091 // If we end up here, the indices of the insertvalue match with those
3092 // requested (though possibly only partially). Now we recursively look at
3093 // the inserted value, passing any remaining indices.
Jay Foad57aa6362011-07-13 10:26:04 +00003094 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00003095 makeArrayRef(req_idx, idx_range.end()),
Nick Lewycky39dbfd32009-11-23 03:29:18 +00003096 InsertBefore);
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003097 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003098
Chris Lattnerf7eb5432012-01-24 07:54:10 +00003099 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00003100 // If we're extracting a value from an aggregate that was extracted from
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003101 // something else, we can extract from that something else directly instead.
3102 // However, we will need to chain I's indices with the requested indices.
Craig Topper1bef2c82012-12-22 19:15:35 +00003103
3104 // Calculate the number of indices required
Jay Foad57aa6362011-07-13 10:26:04 +00003105 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003106 // Allocate some space to put the new indices in
Matthijs Kooijman8369c672008-06-17 08:24:37 +00003107 SmallVector<unsigned, 5> Idxs;
3108 Idxs.reserve(size);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003109 // Add indices from the extract value instruction
Jay Foad57aa6362011-07-13 10:26:04 +00003110 Idxs.append(I->idx_begin(), I->idx_end());
Craig Topper1bef2c82012-12-22 19:15:35 +00003111
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003112 // Add requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00003113 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003114
Craig Topper1bef2c82012-12-22 19:15:35 +00003115 assert(Idxs.size() == size
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00003116 && "Number of indices added not correct?");
Craig Topper1bef2c82012-12-22 19:15:35 +00003117
Jay Foad57aa6362011-07-13 10:26:04 +00003118 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003119 }
3120 // Otherwise, we don't know (such as, extracting from a function return value
3121 // or load instruction)
Craig Topper9f008862014-04-15 04:59:12 +00003122 return nullptr;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003123}
Evan Chengda3db112008-06-30 07:31:25 +00003124
Sanjay Patelaee84212014-11-04 16:27:42 +00003125/// Analyze the specified pointer to see if it can be expressed as a base
3126/// pointer plus a constant offset. Return the base and offset to the caller.
Chris Lattnere28618d2010-11-30 22:25:26 +00003127Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003128 const DataLayout &DL) {
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003129 unsigned BitWidth = DL.getIndexTypeSizeInBits(Ptr->getType());
Nuno Lopes368c4d02012-12-31 20:48:35 +00003130 APInt ByteOffset(BitWidth, 0);
Chandler Carruth76641272016-01-04 07:23:12 +00003131
3132 // We walk up the defs but use a visited set to handle unreachable code. In
3133 // that case, we stop after accumulating the cycle once (not that it
3134 // matters).
3135 SmallPtrSet<Value *, 16> Visited;
3136 while (Visited.insert(Ptr).second) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00003137 if (Ptr->getType()->isVectorTy())
3138 break;
Craig Topper1bef2c82012-12-22 19:15:35 +00003139
Nuno Lopes368c4d02012-12-31 20:48:35 +00003140 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
Tom Stellard17eb3412016-10-07 14:23:29 +00003141 // If one of the values we have visited is an addrspacecast, then
3142 // the pointer type of this GEP may be different from the type
3143 // of the Ptr parameter which was passed to this function. This
3144 // means when we construct GEPOffset, we need to use the size
3145 // of GEP's pointer type rather than the size of the original
3146 // pointer type.
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00003147 APInt GEPOffset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003148 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
3149 break;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00003150
Tom Stellard17eb3412016-10-07 14:23:29 +00003151 ByteOffset += GEPOffset.getSExtValue();
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00003152
Nuno Lopes368c4d02012-12-31 20:48:35 +00003153 Ptr = GEP->getPointerOperand();
Tom Stellard17eb3412016-10-07 14:23:29 +00003154 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
3155 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00003156 Ptr = cast<Operator>(Ptr)->getOperand(0);
3157 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00003158 if (GA->isInterposable())
Nuno Lopes368c4d02012-12-31 20:48:35 +00003159 break;
3160 Ptr = GA->getAliasee();
Chris Lattnere28618d2010-11-30 22:25:26 +00003161 } else {
Nuno Lopes368c4d02012-12-31 20:48:35 +00003162 break;
Chris Lattnere28618d2010-11-30 22:25:26 +00003163 }
3164 }
Nuno Lopes368c4d02012-12-31 20:48:35 +00003165 Offset = ByteOffset.getSExtValue();
3166 return Ptr;
Chris Lattnere28618d2010-11-30 22:25:26 +00003167}
3168
Matthias Braun50ec0b52017-05-19 22:37:09 +00003169bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP,
3170 unsigned CharSize) {
David L Kreitzer752c1442016-04-13 14:31:06 +00003171 // Make sure the GEP has exactly three arguments.
3172 if (GEP->getNumOperands() != 3)
3173 return false;
3174
Matthias Braun50ec0b52017-05-19 22:37:09 +00003175 // Make sure the index-ee is a pointer to array of \p CharSize integers.
3176 // CharSize.
David L Kreitzer752c1442016-04-13 14:31:06 +00003177 ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
Matthias Braun50ec0b52017-05-19 22:37:09 +00003178 if (!AT || !AT->getElementType()->isIntegerTy(CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +00003179 return false;
3180
3181 // Check to make sure that the first operand of the GEP is an integer and
3182 // has value 0 so that we are sure we're indexing into the initializer.
3183 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
3184 if (!FirstIdx || !FirstIdx->isZero())
3185 return false;
3186
3187 return true;
Sanjoy Das6082c1a2016-05-07 02:08:15 +00003188}
Chris Lattnere28618d2010-11-30 22:25:26 +00003189
Matthias Braun50ec0b52017-05-19 22:37:09 +00003190bool llvm::getConstantDataArrayInfo(const Value *V,
3191 ConstantDataArraySlice &Slice,
3192 unsigned ElementSize, uint64_t Offset) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003193 assert(V);
Evan Chengda3db112008-06-30 07:31:25 +00003194
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003195 // Look through bitcast instructions and geps.
3196 V = V->stripPointerCasts();
Craig Topper1bef2c82012-12-22 19:15:35 +00003197
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00003198 // If the value is a GEP instruction or constant expression, treat it as an
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003199 // offset.
3200 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
David L Kreitzer752c1442016-04-13 14:31:06 +00003201 // The GEP operator should be based on a pointer to string constant, and is
3202 // indexing into the string constant.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003203 if (!isGEPBasedOnPointerToString(GEP, ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003204 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003205
Evan Chengda3db112008-06-30 07:31:25 +00003206 // If the second index isn't a ConstantInt, then this is a variable index
3207 // into the array. If this occurs, we can't say anything meaningful about
3208 // the string.
3209 uint64_t StartIdx = 0;
Dan Gohman0b4df042010-04-14 22:20:45 +00003210 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Chengda3db112008-06-30 07:31:25 +00003211 StartIdx = CI->getZExtValue();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003212 else
3213 return false;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003214 return getConstantDataArrayInfo(GEP->getOperand(0), Slice, ElementSize,
3215 StartIdx + Offset);
Evan Chengda3db112008-06-30 07:31:25 +00003216 }
Nick Lewycky46209882011-10-20 00:34:35 +00003217
Evan Chengda3db112008-06-30 07:31:25 +00003218 // The GEP instruction, constant or instruction, must reference a global
3219 // variable that is a constant and is initialized. The referenced constant
3220 // initializer is the array that we'll use for optimization.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003221 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00003222 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003223 return false;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003224
Matthias Braun50ec0b52017-05-19 22:37:09 +00003225 const ConstantDataArray *Array;
3226 ArrayType *ArrayTy;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003227 if (GV->getInitializer()->isNullValue()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003228 Type *GVTy = GV->getValueType();
3229 if ( (ArrayTy = dyn_cast<ArrayType>(GVTy)) ) {
Sanjay Patel2ad88f82017-06-12 22:34:37 +00003230 // A zeroinitializer for the array; there is no ConstantDataArray.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003231 Array = nullptr;
3232 } else {
3233 const DataLayout &DL = GV->getParent()->getDataLayout();
3234 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy);
3235 uint64_t Length = SizeInBytes / (ElementSize / 8);
3236 if (Length <= Offset)
3237 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003238
Matthias Braun50ec0b52017-05-19 22:37:09 +00003239 Slice.Array = nullptr;
3240 Slice.Offset = 0;
3241 Slice.Length = Length - Offset;
3242 return true;
3243 }
3244 } else {
3245 // This must be a ConstantDataArray.
3246 Array = dyn_cast<ConstantDataArray>(GV->getInitializer());
3247 if (!Array)
3248 return false;
3249 ArrayTy = Array->getType();
3250 }
3251 if (!ArrayTy->getElementType()->isIntegerTy(ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003252 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003253
Matthias Braun50ec0b52017-05-19 22:37:09 +00003254 uint64_t NumElts = ArrayTy->getArrayNumElements();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003255 if (Offset > NumElts)
3256 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003257
Matthias Braun50ec0b52017-05-19 22:37:09 +00003258 Slice.Array = Array;
3259 Slice.Offset = Offset;
3260 Slice.Length = NumElts - Offset;
3261 return true;
3262}
3263
3264/// This function computes the length of a null-terminated C string pointed to
3265/// by V. If successful, it returns true and returns the string in Str.
3266/// If unsuccessful, it returns false.
3267bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
3268 uint64_t Offset, bool TrimAtNul) {
3269 ConstantDataArraySlice Slice;
3270 if (!getConstantDataArrayInfo(V, Slice, 8, Offset))
3271 return false;
3272
3273 if (Slice.Array == nullptr) {
3274 if (TrimAtNul) {
3275 Str = StringRef();
3276 return true;
3277 }
3278 if (Slice.Length == 1) {
3279 Str = StringRef("", 1);
3280 return true;
3281 }
Sanjay Patelfef83e82017-06-09 14:21:18 +00003282 // We cannot instantiate a StringRef as we do not have an appropriate string
Matthias Braun50ec0b52017-05-19 22:37:09 +00003283 // of 0s at hand.
3284 return false;
3285 }
3286
3287 // Start out with the entire array in the StringRef.
3288 Str = Slice.Array->getAsString();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003289 // Skip over 'offset' bytes.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003290 Str = Str.substr(Slice.Offset);
Craig Topper1bef2c82012-12-22 19:15:35 +00003291
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003292 if (TrimAtNul) {
3293 // Trim off the \0 and anything after it. If the array is not nul
3294 // terminated, we just return the whole end of string. The client may know
3295 // some other way that the string is length-bound.
3296 Str = Str.substr(0, Str.find('\0'));
3297 }
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003298 return true;
Evan Chengda3db112008-06-30 07:31:25 +00003299}
Eric Christopher4899cbc2010-03-05 06:58:57 +00003300
3301// These next two are very similar to the above, but also look through PHI
3302// nodes.
3303// TODO: See if we can integrate these two together.
3304
Sanjay Patelaee84212014-11-04 16:27:42 +00003305/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003306/// the specified pointer, return 'len+1'. If we can't, return 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00003307static uint64_t GetStringLengthH(const Value *V,
Matthias Braun50ec0b52017-05-19 22:37:09 +00003308 SmallPtrSetImpl<const PHINode*> &PHIs,
3309 unsigned CharSize) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003310 // Look through noop bitcast instructions.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003311 V = V->stripPointerCasts();
Eric Christopher4899cbc2010-03-05 06:58:57 +00003312
3313 // If this is a PHI node, there are two cases: either we have already seen it
3314 // or we haven't.
Pete Cooper35b00d52016-08-13 01:05:32 +00003315 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
David Blaikie70573dc2014-11-19 07:49:26 +00003316 if (!PHIs.insert(PN).second)
Eric Christopher4899cbc2010-03-05 06:58:57 +00003317 return ~0ULL; // already in the set.
3318
3319 // If it was new, see if all the input strings are the same length.
3320 uint64_t LenSoFar = ~0ULL;
Pete Cooper833f34d2015-05-12 20:05:31 +00003321 for (Value *IncValue : PN->incoming_values()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003322 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003323 if (Len == 0) return 0; // Unknown length -> unknown.
3324
3325 if (Len == ~0ULL) continue;
3326
3327 if (Len != LenSoFar && LenSoFar != ~0ULL)
3328 return 0; // Disagree -> unknown.
3329 LenSoFar = Len;
3330 }
3331
3332 // Success, all agree.
3333 return LenSoFar;
3334 }
3335
3336 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
Pete Cooper35b00d52016-08-13 01:05:32 +00003337 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003338 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003339 if (Len1 == 0) return 0;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003340 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003341 if (Len2 == 0) return 0;
3342 if (Len1 == ~0ULL) return Len2;
3343 if (Len2 == ~0ULL) return Len1;
3344 if (Len1 != Len2) return 0;
3345 return Len1;
3346 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003347
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003348 // Otherwise, see if we can read the string.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003349 ConstantDataArraySlice Slice;
3350 if (!getConstantDataArrayInfo(V, Slice, CharSize))
Eric Christopher4899cbc2010-03-05 06:58:57 +00003351 return 0;
3352
Matthias Braun50ec0b52017-05-19 22:37:09 +00003353 if (Slice.Array == nullptr)
3354 return 1;
3355
3356 // Search for nul characters
3357 unsigned NullIndex = 0;
3358 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
3359 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
3360 break;
3361 }
3362
3363 return NullIndex + 1;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003364}
3365
Sanjay Patelaee84212014-11-04 16:27:42 +00003366/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003367/// the specified pointer, return 'len+1'. If we can't, return 0.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003368uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003369 if (!V->getType()->isPointerTy()) return 0;
3370
Pete Cooper35b00d52016-08-13 01:05:32 +00003371 SmallPtrSet<const PHINode*, 32> PHIs;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003372 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003373 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
3374 // an empty string as a length.
3375 return Len == ~0ULL ? 1 : Len;
3376}
Dan Gohmana4fcd242010-12-15 20:02:24 +00003377
Adam Nemete2b885c2015-04-23 20:09:20 +00003378/// \brief \p PN defines a loop-variant pointer to an object. Check if the
3379/// previous iteration of the loop was referring to the same object as \p PN.
Pete Cooper35b00d52016-08-13 01:05:32 +00003380static bool isSameUnderlyingObjectInLoop(const PHINode *PN,
3381 const LoopInfo *LI) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003382 // Find the loop-defined value.
3383 Loop *L = LI->getLoopFor(PN->getParent());
3384 if (PN->getNumIncomingValues() != 2)
3385 return true;
3386
3387 // Find the value from previous iteration.
3388 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
3389 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3390 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
3391 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3392 return true;
3393
3394 // If a new pointer is loaded in the loop, the pointer references a different
3395 // object in every iteration. E.g.:
3396 // for (i)
3397 // int *p = a[i];
3398 // ...
3399 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
3400 if (!L->isLoopInvariant(Load->getPointerOperand()))
3401 return false;
3402 return true;
3403}
3404
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003405Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
3406 unsigned MaxLookup) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003407 if (!V->getType()->isPointerTy())
3408 return V;
3409 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
3410 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3411 V = GEP->getPointerOperand();
Matt Arsenault70f4db882014-07-15 00:56:40 +00003412 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
3413 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003414 V = cast<Operator>(V)->getOperand(0);
3415 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00003416 if (GA->isInterposable())
Dan Gohmana4fcd242010-12-15 20:02:24 +00003417 return V;
3418 V = GA->getAliasee();
Craig Topper85482412017-04-12 22:29:23 +00003419 } else if (isa<AllocaInst>(V)) {
3420 // An alloca can't be further simplified.
3421 return V;
Dan Gohmana4fcd242010-12-15 20:02:24 +00003422 } else {
Hal Finkel5c12d8f2016-07-11 01:32:20 +00003423 if (auto CS = CallSite(V))
3424 if (Value *RV = CS.getReturnedArgOperand()) {
3425 V = RV;
3426 continue;
3427 }
3428
Dan Gohman05b18f12010-12-15 20:49:55 +00003429 // See if InstructionSimplify knows any relevant tricks.
3430 if (Instruction *I = dyn_cast<Instruction>(V))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003431 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00003432 if (Value *Simplified = SimplifyInstruction(I, {DL, I})) {
Dan Gohman05b18f12010-12-15 20:49:55 +00003433 V = Simplified;
3434 continue;
3435 }
3436
Dan Gohmana4fcd242010-12-15 20:02:24 +00003437 return V;
3438 }
3439 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
3440 }
3441 return V;
3442}
Nick Lewycky3e334a42011-06-27 04:20:45 +00003443
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003444void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
Adam Nemete2b885c2015-04-23 20:09:20 +00003445 const DataLayout &DL, LoopInfo *LI,
3446 unsigned MaxLookup) {
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003447 SmallPtrSet<Value *, 4> Visited;
3448 SmallVector<Value *, 4> Worklist;
3449 Worklist.push_back(V);
3450 do {
3451 Value *P = Worklist.pop_back_val();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003452 P = GetUnderlyingObject(P, DL, MaxLookup);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003453
David Blaikie70573dc2014-11-19 07:49:26 +00003454 if (!Visited.insert(P).second)
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003455 continue;
3456
3457 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
3458 Worklist.push_back(SI->getTrueValue());
3459 Worklist.push_back(SI->getFalseValue());
3460 continue;
3461 }
3462
3463 if (PHINode *PN = dyn_cast<PHINode>(P)) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003464 // If this PHI changes the underlying object in every iteration of the
3465 // loop, don't look through it. Consider:
3466 // int **A;
3467 // for (i) {
3468 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
3469 // Curr = A[i];
3470 // *Prev, *Curr;
3471 //
3472 // Prev is tracking Curr one iteration behind so they refer to different
3473 // underlying objects.
3474 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
3475 isSameUnderlyingObjectInLoop(PN, LI))
Pete Cooper833f34d2015-05-12 20:05:31 +00003476 for (Value *IncValue : PN->incoming_values())
3477 Worklist.push_back(IncValue);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003478 continue;
3479 }
3480
3481 Objects.push_back(P);
3482 } while (!Worklist.empty());
3483}
3484
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003485/// This is the function that does the work of looking through basic
3486/// ptrtoint+arithmetic+inttoptr sequences.
3487static const Value *getUnderlyingObjectFromInt(const Value *V) {
3488 do {
3489 if (const Operator *U = dyn_cast<Operator>(V)) {
3490 // If we find a ptrtoint, we can transfer control back to the
3491 // regular getUnderlyingObjectFromInt.
3492 if (U->getOpcode() == Instruction::PtrToInt)
3493 return U->getOperand(0);
3494 // If we find an add of a constant, a multiplied value, or a phi, it's
3495 // likely that the other operand will lead us to the base
3496 // object. We don't have to worry about the case where the
3497 // object address is somehow being computed by the multiply,
3498 // because our callers only care when the result is an
3499 // identifiable object.
3500 if (U->getOpcode() != Instruction::Add ||
3501 (!isa<ConstantInt>(U->getOperand(1)) &&
3502 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
3503 !isa<PHINode>(U->getOperand(1))))
3504 return V;
3505 V = U->getOperand(0);
3506 } else {
3507 return V;
3508 }
3509 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
3510 } while (true);
3511}
3512
3513/// This is a wrapper around GetUnderlyingObjects and adds support for basic
3514/// ptrtoint+arithmetic+inttoptr sequences.
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003515/// It returns false if unidentified object is found in GetUnderlyingObjects.
3516bool llvm::getUnderlyingObjectsForCodeGen(const Value *V,
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003517 SmallVectorImpl<Value *> &Objects,
3518 const DataLayout &DL) {
3519 SmallPtrSet<const Value *, 16> Visited;
3520 SmallVector<const Value *, 4> Working(1, V);
3521 do {
3522 V = Working.pop_back_val();
3523
3524 SmallVector<Value *, 4> Objs;
3525 GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
3526
3527 for (Value *V : Objs) {
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003528 if (!Visited.insert(V).second)
3529 continue;
3530 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
3531 const Value *O =
3532 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
3533 if (O->getType()->isPointerTy()) {
3534 Working.push_back(O);
3535 continue;
3536 }
3537 }
Hiroshi Inoue0bd906e2017-08-02 18:16:32 +00003538 // If GetUnderlyingObjects fails to find an identifiable object,
3539 // getUnderlyingObjectsForCodeGen also fails for safety.
3540 if (!isIdentifiedObject(V)) {
3541 Objects.clear();
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003542 return false;
Hiroshi Inoue0bd906e2017-08-02 18:16:32 +00003543 }
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003544 Objects.push_back(const_cast<Value *>(V));
3545 }
3546 } while (!Working.empty());
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003547 return true;
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003548}
3549
Sanjay Patelaee84212014-11-04 16:27:42 +00003550/// Return true if the only users of this pointer are lifetime markers.
Nick Lewycky3e334a42011-06-27 04:20:45 +00003551bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003552 for (const User *U : V->users()) {
3553 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Nick Lewycky3e334a42011-06-27 04:20:45 +00003554 if (!II) return false;
3555
3556 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
3557 II->getIntrinsicID() != Intrinsic::lifetime_end)
3558 return false;
3559 }
3560 return true;
3561}
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003562
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003563bool llvm::isSafeToSpeculativelyExecute(const Value *V,
3564 const Instruction *CtxI,
Sean Silva45835e72016-07-02 23:47:27 +00003565 const DominatorTree *DT) {
Dan Gohman7ac046a2012-01-04 23:01:09 +00003566 const Operator *Inst = dyn_cast<Operator>(V);
3567 if (!Inst)
3568 return false;
3569
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003570 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3571 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3572 if (C->canTrap())
3573 return false;
3574
3575 switch (Inst->getOpcode()) {
3576 default:
3577 return true;
3578 case Instruction::UDiv:
David Majnemerf20d7c42014-11-04 23:49:08 +00003579 case Instruction::URem: {
3580 // x / y is undefined if y == 0.
3581 const APInt *V;
3582 if (match(Inst->getOperand(1), m_APInt(V)))
3583 return *V != 0;
3584 return false;
3585 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003586 case Instruction::SDiv:
3587 case Instruction::SRem: {
David Majnemerf20d7c42014-11-04 23:49:08 +00003588 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
David Majnemer8a6578a2015-02-01 19:10:19 +00003589 const APInt *Numerator, *Denominator;
3590 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3591 return false;
3592 // We cannot hoist this division if the denominator is 0.
3593 if (*Denominator == 0)
3594 return false;
3595 // It's safe to hoist if the denominator is not 0 or -1.
3596 if (*Denominator != -1)
3597 return true;
3598 // At this point we know that the denominator is -1. It is safe to hoist as
3599 // long we know that the numerator is not INT_MIN.
3600 if (match(Inst->getOperand(0), m_APInt(Numerator)))
3601 return !Numerator->isMinSignedValue();
3602 // The numerator *might* be MinSignedValue.
David Majnemerf20d7c42014-11-04 23:49:08 +00003603 return false;
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003604 }
3605 case Instruction::Load: {
3606 const LoadInst *LI = cast<LoadInst>(Inst);
Kostya Serebryany0b458282013-11-21 07:29:28 +00003607 if (!LI->isUnordered() ||
3608 // Speculative load may create a race that did not exist in the source.
Sanjoy Dasb66374c2016-07-14 20:19:01 +00003609 LI->getFunction()->hasFnAttribute(Attribute::SanitizeThread) ||
Kostya Serebryany5cb86d52015-10-14 00:21:05 +00003610 // Speculative load may load data from dirty regions.
Evgeniy Stepanovc667c1f2017-12-09 00:21:41 +00003611 LI->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
3612 LI->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003613 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003614 const DataLayout &DL = LI->getModule()->getDataLayout();
Sean Silva45835e72016-07-02 23:47:27 +00003615 return isDereferenceableAndAlignedPointer(LI->getPointerOperand(),
3616 LI->getAlignment(), DL, CtxI, DT);
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003617 }
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003618 case Instruction::Call: {
Matt Arsenaultcf5e7fe2017-04-28 21:13:09 +00003619 auto *CI = cast<const CallInst>(Inst);
3620 const Function *Callee = CI->getCalledFunction();
David Majnemer0a92f862015-08-28 21:13:39 +00003621
Matt Arsenault6a288c12017-05-03 02:26:10 +00003622 // The called function could have undefined behavior or side-effects, even
3623 // if marked readnone nounwind.
3624 return Callee && Callee->isSpeculatable();
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003625 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003626 case Instruction::VAArg:
3627 case Instruction::Alloca:
3628 case Instruction::Invoke:
3629 case Instruction::PHI:
3630 case Instruction::Store:
3631 case Instruction::Ret:
3632 case Instruction::Br:
3633 case Instruction::IndirectBr:
3634 case Instruction::Switch:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003635 case Instruction::Unreachable:
3636 case Instruction::Fence:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003637 case Instruction::AtomicRMW:
3638 case Instruction::AtomicCmpXchg:
David Majnemer654e1302015-07-31 17:58:14 +00003639 case Instruction::LandingPad:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003640 case Instruction::Resume:
David Majnemer8a1c45d2015-12-12 05:38:55 +00003641 case Instruction::CatchSwitch:
David Majnemer654e1302015-07-31 17:58:14 +00003642 case Instruction::CatchPad:
David Majnemer654e1302015-07-31 17:58:14 +00003643 case Instruction::CatchRet:
3644 case Instruction::CleanupPad:
3645 case Instruction::CleanupRet:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003646 return false; // Misc instructions which have effects
3647 }
3648}
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003649
Quentin Colombet6443cce2015-08-06 18:44:34 +00003650bool llvm::mayBeMemoryDependent(const Instruction &I) {
3651 return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
3652}
3653
Pete Cooper35b00d52016-08-13 01:05:32 +00003654OverflowResult llvm::computeOverflowForUnsignedMul(const Value *LHS,
3655 const Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003656 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003657 AssumptionCache *AC,
David Majnemer491331a2015-01-02 07:29:43 +00003658 const Instruction *CxtI,
3659 const DominatorTree *DT) {
3660 // Multiplying n * m significant bits yields a result of n + m significant
3661 // bits. If the total number of significant bits does not exceed the
3662 // result bit width (minus 1), there is no overflow.
3663 // This means if we have enough leading zero bits in the operands
3664 // we can guarantee that the result does not overflow.
3665 // Ref: "Hacker's Delight" by Henry Warren
3666 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00003667 KnownBits LHSKnown(BitWidth);
3668 KnownBits RHSKnown(BitWidth);
3669 computeKnownBits(LHS, LHSKnown, DL, /*Depth=*/0, AC, CxtI, DT);
3670 computeKnownBits(RHS, RHSKnown, DL, /*Depth=*/0, AC, CxtI, DT);
David Majnemer491331a2015-01-02 07:29:43 +00003671 // Note that underestimating the number of zero bits gives a more
3672 // conservative answer.
Craig Topper8df66c62017-05-12 17:20:30 +00003673 unsigned ZeroBits = LHSKnown.countMinLeadingZeros() +
3674 RHSKnown.countMinLeadingZeros();
David Majnemer491331a2015-01-02 07:29:43 +00003675 // First handle the easy case: if we have enough zero bits there's
3676 // definitely no overflow.
3677 if (ZeroBits >= BitWidth)
3678 return OverflowResult::NeverOverflows;
3679
3680 // Get the largest possible values for each operand.
Craig Topperb45eabc2017-04-26 16:39:58 +00003681 APInt LHSMax = ~LHSKnown.Zero;
3682 APInt RHSMax = ~RHSKnown.Zero;
David Majnemer491331a2015-01-02 07:29:43 +00003683
3684 // We know the multiply operation doesn't overflow if the maximum values for
3685 // each operand will not overflow after we multiply them together.
David Majnemerc8a576b2015-01-02 07:29:47 +00003686 bool MaxOverflow;
Craig Topper9b71a402017-04-19 21:09:45 +00003687 (void)LHSMax.umul_ov(RHSMax, MaxOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00003688 if (!MaxOverflow)
3689 return OverflowResult::NeverOverflows;
David Majnemer491331a2015-01-02 07:29:43 +00003690
David Majnemerc8a576b2015-01-02 07:29:47 +00003691 // We know it always overflows if multiplying the smallest possible values for
3692 // the operands also results in overflow.
3693 bool MinOverflow;
Craig Topperb45eabc2017-04-26 16:39:58 +00003694 (void)LHSKnown.One.umul_ov(RHSKnown.One, MinOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00003695 if (MinOverflow)
3696 return OverflowResult::AlwaysOverflows;
3697
3698 return OverflowResult::MayOverflow;
David Majnemer491331a2015-01-02 07:29:43 +00003699}
David Majnemer5310c1e2015-01-07 00:39:50 +00003700
Pete Cooper35b00d52016-08-13 01:05:32 +00003701OverflowResult llvm::computeOverflowForUnsignedAdd(const Value *LHS,
3702 const Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003703 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003704 AssumptionCache *AC,
David Majnemer5310c1e2015-01-07 00:39:50 +00003705 const Instruction *CxtI,
3706 const DominatorTree *DT) {
Craig Topper6e11a052017-05-08 16:22:48 +00003707 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
3708 if (LHSKnown.isNonNegative() || LHSKnown.isNegative()) {
3709 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
David Majnemer5310c1e2015-01-07 00:39:50 +00003710
Craig Topper6e11a052017-05-08 16:22:48 +00003711 if (LHSKnown.isNegative() && RHSKnown.isNegative()) {
David Majnemer5310c1e2015-01-07 00:39:50 +00003712 // The sign bit is set in both cases: this MUST overflow.
3713 // Create a simple add instruction, and insert it into the struct.
3714 return OverflowResult::AlwaysOverflows;
3715 }
3716
Craig Topper6e11a052017-05-08 16:22:48 +00003717 if (LHSKnown.isNonNegative() && RHSKnown.isNonNegative()) {
David Majnemer5310c1e2015-01-07 00:39:50 +00003718 // The sign bit is clear in both cases: this CANNOT overflow.
3719 // Create a simple add instruction, and insert it into the struct.
3720 return OverflowResult::NeverOverflows;
3721 }
3722 }
3723
3724 return OverflowResult::MayOverflow;
3725}
James Molloy71b91c22015-05-11 14:42:20 +00003726
Craig Topperbb973722017-05-15 02:44:08 +00003727/// \brief Return true if we can prove that adding the two values of the
3728/// knownbits will not overflow.
3729/// Otherwise return false.
3730static bool checkRippleForSignedAdd(const KnownBits &LHSKnown,
3731 const KnownBits &RHSKnown) {
3732 // Addition of two 2's complement numbers having opposite signs will never
3733 // overflow.
3734 if ((LHSKnown.isNegative() && RHSKnown.isNonNegative()) ||
3735 (LHSKnown.isNonNegative() && RHSKnown.isNegative()))
3736 return true;
3737
3738 // If either of the values is known to be non-negative, adding them can only
3739 // overflow if the second is also non-negative, so we can assume that.
3740 // Two non-negative numbers will only overflow if there is a carry to the
3741 // sign bit, so we can check if even when the values are as big as possible
3742 // there is no overflow to the sign bit.
3743 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative()) {
3744 APInt MaxLHS = ~LHSKnown.Zero;
3745 MaxLHS.clearSignBit();
3746 APInt MaxRHS = ~RHSKnown.Zero;
3747 MaxRHS.clearSignBit();
3748 APInt Result = std::move(MaxLHS) + std::move(MaxRHS);
3749 return Result.isSignBitClear();
3750 }
3751
3752 // If either of the values is known to be negative, adding them can only
3753 // overflow if the second is also negative, so we can assume that.
3754 // Two negative number will only overflow if there is no carry to the sign
3755 // bit, so we can check if even when the values are as small as possible
3756 // there is overflow to the sign bit.
3757 if (LHSKnown.isNegative() || RHSKnown.isNegative()) {
3758 APInt MinLHS = LHSKnown.One;
3759 MinLHS.clearSignBit();
3760 APInt MinRHS = RHSKnown.One;
3761 MinRHS.clearSignBit();
3762 APInt Result = std::move(MinLHS) + std::move(MinRHS);
3763 return Result.isSignBitSet();
3764 }
3765
3766 // If we reached here it means that we know nothing about the sign bits.
3767 // In this case we can't know if there will be an overflow, since by
3768 // changing the sign bits any two values can be made to overflow.
3769 return false;
3770}
3771
Pete Cooper35b00d52016-08-13 01:05:32 +00003772static OverflowResult computeOverflowForSignedAdd(const Value *LHS,
3773 const Value *RHS,
3774 const AddOperator *Add,
3775 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003776 AssumptionCache *AC,
Pete Cooper35b00d52016-08-13 01:05:32 +00003777 const Instruction *CxtI,
3778 const DominatorTree *DT) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00003779 if (Add && Add->hasNoSignedWrap()) {
3780 return OverflowResult::NeverOverflows;
3781 }
3782
Craig Topperbb973722017-05-15 02:44:08 +00003783 // If LHS and RHS each have at least two sign bits, the addition will look
3784 // like
3785 //
3786 // XX..... +
3787 // YY.....
3788 //
3789 // If the carry into the most significant position is 0, X and Y can't both
3790 // be 1 and therefore the carry out of the addition is also 0.
3791 //
3792 // If the carry into the most significant position is 1, X and Y can't both
3793 // be 0 and therefore the carry out of the addition is also 1.
3794 //
3795 // Since the carry into the most significant position is always equal to
3796 // the carry out of the addition, there is no signed overflow.
3797 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
3798 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
3799 return OverflowResult::NeverOverflows;
3800
Craig Topper6e11a052017-05-08 16:22:48 +00003801 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
3802 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003803
Craig Topperbb973722017-05-15 02:44:08 +00003804 if (checkRippleForSignedAdd(LHSKnown, RHSKnown))
Jingyue Wu10fcea52015-08-20 18:27:04 +00003805 return OverflowResult::NeverOverflows;
Jingyue Wu10fcea52015-08-20 18:27:04 +00003806
3807 // The remaining code needs Add to be available. Early returns if not so.
3808 if (!Add)
3809 return OverflowResult::MayOverflow;
3810
3811 // If the sign of Add is the same as at least one of the operands, this add
3812 // CANNOT overflow. This is particularly useful when the sum is
3813 // @llvm.assume'ed non-negative rather than proved so from analyzing its
3814 // operands.
3815 bool LHSOrRHSKnownNonNegative =
Craig Topper6e11a052017-05-08 16:22:48 +00003816 (LHSKnown.isNonNegative() || RHSKnown.isNonNegative());
Craig Topperbb973722017-05-15 02:44:08 +00003817 bool LHSOrRHSKnownNegative =
3818 (LHSKnown.isNegative() || RHSKnown.isNegative());
Jingyue Wu10fcea52015-08-20 18:27:04 +00003819 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
Craig Topper6e11a052017-05-08 16:22:48 +00003820 KnownBits AddKnown = computeKnownBits(Add, DL, /*Depth=*/0, AC, CxtI, DT);
3821 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
3822 (AddKnown.isNegative() && LHSOrRHSKnownNegative)) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00003823 return OverflowResult::NeverOverflows;
3824 }
3825 }
3826
3827 return OverflowResult::MayOverflow;
3828}
3829
Pete Cooper35b00d52016-08-13 01:05:32 +00003830bool llvm::isOverflowIntrinsicNoWrap(const IntrinsicInst *II,
3831 const DominatorTree &DT) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003832#ifndef NDEBUG
3833 auto IID = II->getIntrinsicID();
3834 assert((IID == Intrinsic::sadd_with_overflow ||
3835 IID == Intrinsic::uadd_with_overflow ||
3836 IID == Intrinsic::ssub_with_overflow ||
3837 IID == Intrinsic::usub_with_overflow ||
3838 IID == Intrinsic::smul_with_overflow ||
3839 IID == Intrinsic::umul_with_overflow) &&
3840 "Not an overflow intrinsic!");
3841#endif
3842
Pete Cooper35b00d52016-08-13 01:05:32 +00003843 SmallVector<const BranchInst *, 2> GuardingBranches;
3844 SmallVector<const ExtractValueInst *, 2> Results;
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003845
Pete Cooper35b00d52016-08-13 01:05:32 +00003846 for (const User *U : II->users()) {
3847 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003848 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
3849
3850 if (EVI->getIndices()[0] == 0)
3851 Results.push_back(EVI);
3852 else {
3853 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
3854
Pete Cooper35b00d52016-08-13 01:05:32 +00003855 for (const auto *U : EVI->users())
3856 if (const auto *B = dyn_cast<BranchInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003857 assert(B->isConditional() && "How else is it using an i1?");
3858 GuardingBranches.push_back(B);
3859 }
3860 }
3861 } else {
3862 // We are using the aggregate directly in a way we don't want to analyze
3863 // here (storing it to a global, say).
3864 return false;
3865 }
3866 }
3867
Pete Cooper35b00d52016-08-13 01:05:32 +00003868 auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003869 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
3870 if (!NoWrapEdge.isSingleEdge())
3871 return false;
3872
3873 // Check if all users of the add are provably no-wrap.
Pete Cooper35b00d52016-08-13 01:05:32 +00003874 for (const auto *Result : Results) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003875 // If the extractvalue itself is not executed on overflow, the we don't
3876 // need to check each use separately, since domination is transitive.
3877 if (DT.dominates(NoWrapEdge, Result->getParent()))
3878 continue;
3879
3880 for (auto &RU : Result->uses())
3881 if (!DT.dominates(NoWrapEdge, RU))
3882 return false;
3883 }
3884
3885 return true;
3886 };
3887
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003888 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003889}
3890
3891
Pete Cooper35b00d52016-08-13 01:05:32 +00003892OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003893 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003894 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003895 const Instruction *CxtI,
3896 const DominatorTree *DT) {
3897 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003898 Add, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003899}
3900
Pete Cooper35b00d52016-08-13 01:05:32 +00003901OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS,
3902 const Value *RHS,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003903 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003904 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003905 const Instruction *CxtI,
3906 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003907 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003908}
3909
Jingyue Wu42f1d672015-07-28 18:22:40 +00003910bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003911 // A memory operation returns normally if it isn't volatile. A volatile
3912 // operation is allowed to trap.
3913 //
3914 // An atomic operation isn't guaranteed to return in a reasonable amount of
3915 // time because it's possible for another thread to interfere with it for an
3916 // arbitrary length of time, but programs aren't allowed to rely on that.
3917 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
3918 return !LI->isVolatile();
3919 if (const StoreInst *SI = dyn_cast<StoreInst>(I))
3920 return !SI->isVolatile();
3921 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
3922 return !CXI->isVolatile();
3923 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
3924 return !RMWI->isVolatile();
3925 if (const MemIntrinsic *MII = dyn_cast<MemIntrinsic>(I))
3926 return !MII->isVolatile();
Jingyue Wu42f1d672015-07-28 18:22:40 +00003927
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003928 // If there is no successor, then execution can't transfer to it.
3929 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I))
3930 return !CRI->unwindsToCaller();
3931 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I))
3932 return !CatchSwitch->unwindsToCaller();
3933 if (isa<ResumeInst>(I))
3934 return false;
3935 if (isa<ReturnInst>(I))
3936 return false;
Sebastian Pop4a4d2452017-03-08 01:54:50 +00003937 if (isa<UnreachableInst>(I))
3938 return false;
Sanjoy Das9a65cd22016-06-08 17:48:36 +00003939
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003940 // Calls can throw, or contain an infinite loop, or kill the process.
Sanjoy Das09455302016-12-31 22:12:31 +00003941 if (auto CS = ImmutableCallSite(I)) {
Sanjoy Das3bb2dbd2016-12-31 22:12:34 +00003942 // Call sites that throw have implicit non-local control flow.
3943 if (!CS.doesNotThrow())
3944 return false;
3945
3946 // Non-throwing call sites can loop infinitely, call exit/pthread_exit
3947 // etc. and thus not return. However, LLVM already assumes that
3948 //
3949 // - Thread exiting actions are modeled as writes to memory invisible to
3950 // the program.
3951 //
3952 // - Loops that don't have side effects (side effects are volatile/atomic
3953 // stores and IO) always terminate (see http://llvm.org/PR965).
3954 // Furthermore IO itself is also modeled as writes to memory invisible to
3955 // the program.
3956 //
3957 // We rely on those assumptions here, and use the memory effects of the call
3958 // target as a proxy for checking that it always returns.
3959
3960 // FIXME: This isn't aggressive enough; a call which only writes to a global
3961 // is guaranteed to return.
Sanjoy Dasd7e82062016-06-14 20:23:16 +00003962 return CS.onlyReadsMemory() || CS.onlyAccessesArgMemory() ||
Dan Gohman2c74fe92017-11-08 21:59:51 +00003963 match(I, m_Intrinsic<Intrinsic::assume>()) ||
3964 match(I, m_Intrinsic<Intrinsic::sideeffect>());
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003965 }
3966
3967 // Other instructions return normally.
3968 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003969}
3970
3971bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
3972 const Loop *L) {
3973 // The loop header is guaranteed to be executed for every iteration.
3974 //
3975 // FIXME: Relax this constraint to cover all basic blocks that are
3976 // guaranteed to be executed at every iteration.
3977 if (I->getParent() != L->getHeader()) return false;
3978
3979 for (const Instruction &LI : *L->getHeader()) {
3980 if (&LI == I) return true;
3981 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
3982 }
3983 llvm_unreachable("Instruction not contained in its own parent basic block.");
3984}
3985
3986bool llvm::propagatesFullPoison(const Instruction *I) {
3987 switch (I->getOpcode()) {
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003988 case Instruction::Add:
3989 case Instruction::Sub:
3990 case Instruction::Xor:
3991 case Instruction::Trunc:
3992 case Instruction::BitCast:
3993 case Instruction::AddrSpaceCast:
Sanjoy Das5cd6c5ca2017-02-22 06:52:32 +00003994 case Instruction::Mul:
3995 case Instruction::Shl:
3996 case Instruction::GetElementPtr:
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003997 // These operations all propagate poison unconditionally. Note that poison
3998 // is not any particular value, so xor or subtraction of poison with
3999 // itself still yields poison, not zero.
4000 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004001
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004002 case Instruction::AShr:
4003 case Instruction::SExt:
4004 // For these operations, one bit of the input is replicated across
4005 // multiple output bits. A replicated poison bit is still poison.
4006 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004007
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004008 case Instruction::ICmp:
4009 // Comparing poison with any value yields poison. This is why, for
4010 // instance, x s< (x +nsw 1) can be folded to true.
4011 return true;
Sanjoy Das70c2bbd2016-05-29 00:31:18 +00004012
Sanjoy Das7b0b4082017-02-21 02:42:42 +00004013 default:
4014 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004015 }
4016}
4017
4018const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
4019 switch (I->getOpcode()) {
4020 case Instruction::Store:
4021 return cast<StoreInst>(I)->getPointerOperand();
4022
4023 case Instruction::Load:
4024 return cast<LoadInst>(I)->getPointerOperand();
4025
4026 case Instruction::AtomicCmpXchg:
4027 return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
4028
4029 case Instruction::AtomicRMW:
4030 return cast<AtomicRMWInst>(I)->getPointerOperand();
4031
4032 case Instruction::UDiv:
4033 case Instruction::SDiv:
4034 case Instruction::URem:
4035 case Instruction::SRem:
4036 return I->getOperand(1);
4037
4038 default:
4039 return nullptr;
4040 }
4041}
4042
Sanjoy Das08989c72017-04-30 19:41:19 +00004043bool llvm::programUndefinedIfFullPoison(const Instruction *PoisonI) {
Jingyue Wu42f1d672015-07-28 18:22:40 +00004044 // We currently only look for uses of poison values within the same basic
4045 // block, as that makes it easier to guarantee that the uses will be
4046 // executed given that PoisonI is executed.
4047 //
4048 // FIXME: Expand this to consider uses beyond the same basic block. To do
4049 // this, look out for the distinction between post-dominance and strong
4050 // post-dominance.
4051 const BasicBlock *BB = PoisonI->getParent();
4052
4053 // Set of instructions that we have proved will yield poison if PoisonI
4054 // does.
4055 SmallSet<const Value *, 16> YieldsPoison;
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004056 SmallSet<const BasicBlock *, 4> Visited;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004057 YieldsPoison.insert(PoisonI);
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004058 Visited.insert(PoisonI->getParent());
Jingyue Wu42f1d672015-07-28 18:22:40 +00004059
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004060 BasicBlock::const_iterator Begin = PoisonI->getIterator(), End = BB->end();
Jingyue Wu42f1d672015-07-28 18:22:40 +00004061
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004062 unsigned Iter = 0;
4063 while (Iter++ < MaxDepth) {
4064 for (auto &I : make_range(Begin, End)) {
4065 if (&I != PoisonI) {
4066 const Value *NotPoison = getGuaranteedNonFullPoisonOp(&I);
4067 if (NotPoison != nullptr && YieldsPoison.count(NotPoison))
4068 return true;
4069 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
4070 return false;
4071 }
4072
4073 // Mark poison that propagates from I through uses of I.
4074 if (YieldsPoison.count(&I)) {
4075 for (const User *User : I.users()) {
4076 const Instruction *UserI = cast<Instruction>(User);
4077 if (propagatesFullPoison(UserI))
4078 YieldsPoison.insert(User);
4079 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00004080 }
4081 }
Sanjoy Dasa6155b62016-04-22 17:41:06 +00004082
4083 if (auto *NextBB = BB->getSingleSuccessor()) {
4084 if (Visited.insert(NextBB).second) {
4085 BB = NextBB;
4086 Begin = BB->getFirstNonPHI()->getIterator();
4087 End = BB->end();
4088 continue;
4089 }
4090 }
4091
4092 break;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00004093 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00004094 return false;
4095}
4096
Pete Cooper35b00d52016-08-13 01:05:32 +00004097static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
James Molloy134bec22015-08-11 09:12:57 +00004098 if (FMF.noNaNs())
4099 return true;
4100
4101 if (auto *C = dyn_cast<ConstantFP>(V))
4102 return !C->isNaN();
4103 return false;
4104}
4105
Pete Cooper35b00d52016-08-13 01:05:32 +00004106static bool isKnownNonZero(const Value *V) {
James Molloy134bec22015-08-11 09:12:57 +00004107 if (auto *C = dyn_cast<ConstantFP>(V))
4108 return !C->isZero();
4109 return false;
4110}
4111
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004112/// Match clamp pattern for float types without care about NaNs or signed zeros.
4113/// Given non-min/max outer cmp/select from the clamp pattern this
4114/// function recognizes if it can be substitued by a "canonical" min/max
4115/// pattern.
4116static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred,
4117 Value *CmpLHS, Value *CmpRHS,
4118 Value *TrueVal, Value *FalseVal,
4119 Value *&LHS, Value *&RHS) {
4120 // Try to match
4121 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
4122 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
4123 // and return description of the outer Max/Min.
4124
4125 // First, check if select has inverse order:
4126 if (CmpRHS == FalseVal) {
4127 std::swap(TrueVal, FalseVal);
4128 Pred = CmpInst::getInversePredicate(Pred);
4129 }
4130
4131 // Assume success now. If there's no match, callers should not use these anyway.
4132 LHS = TrueVal;
4133 RHS = FalseVal;
4134
4135 const APFloat *FC1;
4136 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
4137 return {SPF_UNKNOWN, SPNB_NA, false};
4138
4139 const APFloat *FC2;
4140 switch (Pred) {
4141 case CmpInst::FCMP_OLT:
4142 case CmpInst::FCMP_OLE:
4143 case CmpInst::FCMP_ULT:
4144 case CmpInst::FCMP_ULE:
4145 if (match(FalseVal,
4146 m_CombineOr(m_OrdFMin(m_Specific(CmpLHS), m_APFloat(FC2)),
4147 m_UnordFMin(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4148 FC1->compare(*FC2) == APFloat::cmpResult::cmpLessThan)
4149 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
4150 break;
4151 case CmpInst::FCMP_OGT:
4152 case CmpInst::FCMP_OGE:
4153 case CmpInst::FCMP_UGT:
4154 case CmpInst::FCMP_UGE:
4155 if (match(FalseVal,
4156 m_CombineOr(m_OrdFMax(m_Specific(CmpLHS), m_APFloat(FC2)),
4157 m_UnordFMax(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4158 FC1->compare(*FC2) == APFloat::cmpResult::cmpGreaterThan)
4159 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
4160 break;
4161 default:
4162 break;
4163 }
4164
4165 return {SPF_UNKNOWN, SPNB_NA, false};
4166}
4167
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004168/// Recognize variations of:
4169/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
4170static SelectPatternResult matchClamp(CmpInst::Predicate Pred,
4171 Value *CmpLHS, Value *CmpRHS,
4172 Value *TrueVal, Value *FalseVal) {
4173 // Swap the select operands and predicate to match the patterns below.
4174 if (CmpRHS != TrueVal) {
4175 Pred = ICmpInst::getSwappedPredicate(Pred);
4176 std::swap(TrueVal, FalseVal);
4177 }
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004178 const APInt *C1;
4179 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
4180 const APInt *C2;
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004181 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
4182 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004183 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004184 return {SPF_SMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004185
4186 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
4187 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004188 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004189 return {SPF_SMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004190
4191 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
4192 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004193 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004194 return {SPF_UMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004195
4196 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
4197 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004198 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004199 return {SPF_UMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004200 }
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004201 return {SPF_UNKNOWN, SPNB_NA, false};
4202}
4203
Sanjay Patel78114302018-01-02 20:56:45 +00004204/// Recognize variations of:
4205/// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
4206static SelectPatternResult matchMinMaxOfMinMax(CmpInst::Predicate Pred,
4207 Value *CmpLHS, Value *CmpRHS,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004208 Value *TVal, Value *FVal,
4209 unsigned Depth) {
Sanjay Patel78114302018-01-02 20:56:45 +00004210 // TODO: Allow FP min/max with nnan/nsz.
4211 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
4212
4213 Value *A, *B;
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004214 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
Sanjay Patel78114302018-01-02 20:56:45 +00004215 if (!SelectPatternResult::isMinOrMax(L.Flavor))
4216 return {SPF_UNKNOWN, SPNB_NA, false};
4217
4218 Value *C, *D;
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004219 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
Sanjay Patel78114302018-01-02 20:56:45 +00004220 if (L.Flavor != R.Flavor)
4221 return {SPF_UNKNOWN, SPNB_NA, false};
4222
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004223 // We have something like: x Pred y ? min(a, b) : min(c, d).
4224 // Try to match the compare to the min/max operations of the select operands.
4225 // First, make sure we have the right compare predicate.
Sanjay Patel78114302018-01-02 20:56:45 +00004226 switch (L.Flavor) {
4227 case SPF_SMIN:
4228 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
4229 Pred = ICmpInst::getSwappedPredicate(Pred);
4230 std::swap(CmpLHS, CmpRHS);
4231 }
4232 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
4233 break;
4234 return {SPF_UNKNOWN, SPNB_NA, false};
4235 case SPF_SMAX:
4236 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
4237 Pred = ICmpInst::getSwappedPredicate(Pred);
4238 std::swap(CmpLHS, CmpRHS);
4239 }
4240 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
4241 break;
4242 return {SPF_UNKNOWN, SPNB_NA, false};
4243 case SPF_UMIN:
4244 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
4245 Pred = ICmpInst::getSwappedPredicate(Pred);
4246 std::swap(CmpLHS, CmpRHS);
4247 }
4248 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
4249 break;
4250 return {SPF_UNKNOWN, SPNB_NA, false};
4251 case SPF_UMAX:
4252 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
4253 Pred = ICmpInst::getSwappedPredicate(Pred);
4254 std::swap(CmpLHS, CmpRHS);
4255 }
4256 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
4257 break;
4258 return {SPF_UNKNOWN, SPNB_NA, false};
4259 default:
Sanjay Patel7dfe96a2018-01-08 18:31:13 +00004260 return {SPF_UNKNOWN, SPNB_NA, false};
Sanjay Patel78114302018-01-02 20:56:45 +00004261 }
4262
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004263 // If there is a common operand in the already matched min/max and the other
4264 // min/max operands match the compare operands (either directly or inverted),
4265 // then this is min/max of the same flavor.
4266
Sanjay Patel78114302018-01-02 20:56:45 +00004267 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004268 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
4269 if (D == B) {
4270 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
4271 match(A, m_Not(m_Specific(CmpRHS)))))
4272 return {L.Flavor, SPNB_NA, false};
4273 }
Sanjay Patel78114302018-01-02 20:56:45 +00004274 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004275 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
4276 if (C == B) {
4277 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
4278 match(A, m_Not(m_Specific(CmpRHS)))))
4279 return {L.Flavor, SPNB_NA, false};
4280 }
Sanjay Patel78114302018-01-02 20:56:45 +00004281 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004282 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
4283 if (D == A) {
4284 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
4285 match(B, m_Not(m_Specific(CmpRHS)))))
4286 return {L.Flavor, SPNB_NA, false};
4287 }
Sanjay Patel78114302018-01-02 20:56:45 +00004288 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
Sanjay Patele63d8dd2018-01-11 15:13:47 +00004289 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
4290 if (C == A) {
4291 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
4292 match(B, m_Not(m_Specific(CmpRHS)))))
4293 return {L.Flavor, SPNB_NA, false};
4294 }
Sanjay Patel78114302018-01-02 20:56:45 +00004295
4296 return {SPF_UNKNOWN, SPNB_NA, false};
4297}
4298
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004299/// Match non-obvious integer minimum and maximum sequences.
4300static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
4301 Value *CmpLHS, Value *CmpRHS,
4302 Value *TrueVal, Value *FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004303 Value *&LHS, Value *&RHS,
4304 unsigned Depth) {
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004305 // Assume success. If there's no match, callers should not use these anyway.
4306 LHS = TrueVal;
4307 RHS = FalseVal;
4308
4309 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
4310 if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
4311 return SPR;
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004312
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004313 SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
Sanjay Patel78114302018-01-02 20:56:45 +00004314 if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
4315 return SPR;
4316
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004317 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
Sanjay Patel819f0962016-11-13 19:30:19 +00004318 return {SPF_UNKNOWN, SPNB_NA, false};
4319
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004320 // Z = X -nsw Y
4321 // (X >s Y) ? 0 : Z ==> (Z >s 0) ? 0 : Z ==> SMIN(Z, 0)
4322 // (X <s Y) ? 0 : Z ==> (Z <s 0) ? 0 : Z ==> SMAX(Z, 0)
4323 if (match(TrueVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004324 match(FalseVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004325 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004326
4327 // Z = X -nsw Y
4328 // (X >s Y) ? Z : 0 ==> (Z >s 0) ? Z : 0 ==> SMAX(Z, 0)
4329 // (X <s Y) ? Z : 0 ==> (Z <s 0) ? Z : 0 ==> SMIN(Z, 0)
4330 if (match(FalseVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004331 match(TrueVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004332 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004333
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004334 const APInt *C1;
Sanjay Patel819f0962016-11-13 19:30:19 +00004335 if (!match(CmpRHS, m_APInt(C1)))
4336 return {SPF_UNKNOWN, SPNB_NA, false};
4337
4338 // An unsigned min/max can be written with a signed compare.
4339 const APInt *C2;
4340 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
4341 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
4342 // Is the sign bit set?
4343 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
4344 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
Craig Topper81d772c2017-11-08 19:38:45 +00004345 if (Pred == CmpInst::ICMP_SLT && C1->isNullValue() &&
4346 C2->isMaxSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004347 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004348
4349 // Is the sign bit clear?
4350 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
4351 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004352 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnesValue() &&
4353 C2->isMinSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004354 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004355 }
4356
4357 // Look through 'not' ops to find disguised signed min/max.
4358 // (X >s C) ? ~X : ~C ==> (~X <s ~C) ? ~X : ~C ==> SMIN(~X, ~C)
4359 // (X <s C) ? ~X : ~C ==> (~X >s ~C) ? ~X : ~C ==> SMAX(~X, ~C)
4360 if (match(TrueVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004361 match(FalseVal, m_APInt(C2)) && ~(*C1) == *C2)
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004362 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004363
4364 // (X >s C) ? ~C : ~X ==> (~X <s ~C) ? ~C : ~X ==> SMAX(~C, ~X)
4365 // (X <s C) ? ~C : ~X ==> (~X >s ~C) ? ~C : ~X ==> SMIN(~C, ~X)
4366 if (match(FalseVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004367 match(TrueVal, m_APInt(C2)) && ~(*C1) == *C2)
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004368 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004369
4370 return {SPF_UNKNOWN, SPNB_NA, false};
4371}
4372
James Molloy134bec22015-08-11 09:12:57 +00004373static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
4374 FastMathFlags FMF,
James Molloy270ef8c2015-05-15 16:04:50 +00004375 Value *CmpLHS, Value *CmpRHS,
4376 Value *TrueVal, Value *FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004377 Value *&LHS, Value *&RHS,
4378 unsigned Depth) {
James Molloy71b91c22015-05-11 14:42:20 +00004379 LHS = CmpLHS;
4380 RHS = CmpRHS;
4381
Sanjay Patel9a399792017-12-26 15:09:19 +00004382 // Signed zero may return inconsistent results between implementations.
4383 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
4384 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
4385 // Therefore, we behave conservatively and only proceed if at least one of the
4386 // operands is known to not be zero or if we don't care about signed zero.
James Molloy134bec22015-08-11 09:12:57 +00004387 switch (Pred) {
4388 default: break;
Sanjay Patel9a399792017-12-26 15:09:19 +00004389 // FIXME: Include OGT/OLT/UGT/ULT.
James Molloy134bec22015-08-11 09:12:57 +00004390 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
4391 case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
4392 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4393 !isKnownNonZero(CmpRHS))
4394 return {SPF_UNKNOWN, SPNB_NA, false};
4395 }
4396
4397 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
4398 bool Ordered = false;
4399
4400 // When given one NaN and one non-NaN input:
4401 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
4402 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
4403 // ordered comparison fails), which could be NaN or non-NaN.
4404 // so here we discover exactly what NaN behavior is required/accepted.
4405 if (CmpInst::isFPPredicate(Pred)) {
4406 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
4407 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
4408
4409 if (LHSSafe && RHSSafe) {
4410 // Both operands are known non-NaN.
4411 NaNBehavior = SPNB_RETURNS_ANY;
4412 } else if (CmpInst::isOrdered(Pred)) {
4413 // An ordered comparison will return false when given a NaN, so it
4414 // returns the RHS.
4415 Ordered = true;
4416 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004417 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004418 NaNBehavior = SPNB_RETURNS_NAN;
4419 else if (RHSSafe)
4420 NaNBehavior = SPNB_RETURNS_OTHER;
4421 else
4422 // Completely unsafe.
4423 return {SPF_UNKNOWN, SPNB_NA, false};
4424 } else {
4425 Ordered = false;
4426 // An unordered comparison will return true when given a NaN, so it
4427 // returns the LHS.
4428 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004429 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004430 NaNBehavior = SPNB_RETURNS_OTHER;
4431 else if (RHSSafe)
4432 NaNBehavior = SPNB_RETURNS_NAN;
4433 else
4434 // Completely unsafe.
4435 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004436 }
4437 }
4438
James Molloy71b91c22015-05-11 14:42:20 +00004439 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
James Molloy134bec22015-08-11 09:12:57 +00004440 std::swap(CmpLHS, CmpRHS);
4441 Pred = CmpInst::getSwappedPredicate(Pred);
4442 if (NaNBehavior == SPNB_RETURNS_NAN)
4443 NaNBehavior = SPNB_RETURNS_OTHER;
4444 else if (NaNBehavior == SPNB_RETURNS_OTHER)
4445 NaNBehavior = SPNB_RETURNS_NAN;
4446 Ordered = !Ordered;
4447 }
4448
4449 // ([if]cmp X, Y) ? X : Y
4450 if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
James Molloy71b91c22015-05-11 14:42:20 +00004451 switch (Pred) {
James Molloy134bec22015-08-11 09:12:57 +00004452 default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
James Molloy71b91c22015-05-11 14:42:20 +00004453 case ICmpInst::ICMP_UGT:
James Molloy134bec22015-08-11 09:12:57 +00004454 case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004455 case ICmpInst::ICMP_SGT:
James Molloy134bec22015-08-11 09:12:57 +00004456 case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004457 case ICmpInst::ICMP_ULT:
James Molloy134bec22015-08-11 09:12:57 +00004458 case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004459 case ICmpInst::ICMP_SLT:
James Molloy134bec22015-08-11 09:12:57 +00004460 case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
4461 case FCmpInst::FCMP_UGT:
4462 case FCmpInst::FCMP_UGE:
4463 case FCmpInst::FCMP_OGT:
4464 case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
4465 case FCmpInst::FCMP_ULT:
4466 case FCmpInst::FCMP_ULE:
4467 case FCmpInst::FCMP_OLT:
4468 case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
James Molloy71b91c22015-05-11 14:42:20 +00004469 }
4470 }
4471
Sanjay Patele372aec2016-10-27 15:26:10 +00004472 const APInt *C1;
4473 if (match(CmpRHS, m_APInt(C1))) {
James Molloy71b91c22015-05-11 14:42:20 +00004474 if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) ||
4475 (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) {
4476
4477 // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X
4478 // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X
Craig Topper81d772c2017-11-08 19:38:45 +00004479 if (Pred == ICmpInst::ICMP_SGT &&
4480 (C1->isNullValue() || C1->isAllOnesValue())) {
James Molloy134bec22015-08-11 09:12:57 +00004481 return {(CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004482 }
4483
4484 // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X
4485 // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X
Craig Topper81d772c2017-11-08 19:38:45 +00004486 if (Pred == ICmpInst::ICMP_SLT &&
4487 (C1->isNullValue() || C1->isOneValue())) {
James Molloy134bec22015-08-11 09:12:57 +00004488 return {(CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004489 }
4490 }
James Molloy71b91c22015-05-11 14:42:20 +00004491 }
4492
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004493 if (CmpInst::isIntPredicate(Pred))
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004494 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004495
4496 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
4497 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
4498 // semantics than minNum. Be conservative in such case.
4499 if (NaNBehavior != SPNB_RETURNS_ANY ||
4500 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4501 !isKnownNonZero(CmpRHS)))
4502 return {SPF_UNKNOWN, SPNB_NA, false};
4503
4504 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
James Molloy71b91c22015-05-11 14:42:20 +00004505}
James Molloy270ef8c2015-05-15 16:04:50 +00004506
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004507/// Helps to match a select pattern in case of a type mismatch.
4508///
4509/// The function processes the case when type of true and false values of a
4510/// select instruction differs from type of the cmp instruction operands because
Vedant Kumar1a8456d2018-03-02 18:57:02 +00004511/// of a cast instruction. The function checks if it is legal to move the cast
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004512/// operation after "select". If yes, it returns the new second value of
4513/// "select" (with the assumption that cast is moved):
4514/// 1. As operand of cast instruction when both values of "select" are same cast
4515/// instructions.
4516/// 2. As restored constant (by applying reverse cast operation) when the first
4517/// value of the "select" is a cast operation and the second value is a
4518/// constant.
4519/// NOTE: We return only the new second value because the first value could be
4520/// accessed as operand of cast instruction.
James Molloy569cea62015-09-02 17:25:25 +00004521static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
4522 Instruction::CastOps *CastOp) {
Sanjay Patel14a4b812017-01-29 16:34:57 +00004523 auto *Cast1 = dyn_cast<CastInst>(V1);
4524 if (!Cast1)
James Molloy270ef8c2015-05-15 16:04:50 +00004525 return nullptr;
James Molloy270ef8c2015-05-15 16:04:50 +00004526
Sanjay Patel14a4b812017-01-29 16:34:57 +00004527 *CastOp = Cast1->getOpcode();
4528 Type *SrcTy = Cast1->getSrcTy();
4529 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
4530 // If V1 and V2 are both the same cast from the same type, look through V1.
4531 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
4532 return Cast2->getOperand(0);
James Molloy569cea62015-09-02 17:25:25 +00004533 return nullptr;
4534 }
4535
Sanjay Patel14a4b812017-01-29 16:34:57 +00004536 auto *C = dyn_cast<Constant>(V2);
4537 if (!C)
4538 return nullptr;
4539
David Majnemerd2a074b2016-04-29 18:40:34 +00004540 Constant *CastedTo = nullptr;
Sanjay Patel14a4b812017-01-29 16:34:57 +00004541 switch (*CastOp) {
4542 case Instruction::ZExt:
4543 if (CmpI->isUnsigned())
4544 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
4545 break;
4546 case Instruction::SExt:
4547 if (CmpI->isSigned())
4548 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
4549 break;
4550 case Instruction::Trunc:
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004551 Constant *CmpConst;
Nikolai Bozhenov9723f122017-10-18 14:24:50 +00004552 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
4553 CmpConst->getType() == SrcTy) {
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004554 // Here we have the following case:
4555 //
4556 // %cond = cmp iN %x, CmpConst
4557 // %tr = trunc iN %x to iK
4558 // %narrowsel = select i1 %cond, iK %t, iK C
4559 //
4560 // We can always move trunc after select operation:
4561 //
4562 // %cond = cmp iN %x, CmpConst
4563 // %widesel = select i1 %cond, iN %x, iN CmpConst
4564 // %tr = trunc iN %widesel to iK
4565 //
4566 // Note that C could be extended in any way because we don't care about
4567 // upper bits after truncation. It can't be abs pattern, because it would
4568 // look like:
4569 //
4570 // select i1 %cond, x, -x.
4571 //
4572 // So only min/max pattern could be matched. Such match requires widened C
4573 // == CmpConst. That is why set widened C = CmpConst, condition trunc
4574 // CmpConst == C is checked below.
4575 CastedTo = CmpConst;
4576 } else {
4577 CastedTo = ConstantExpr::getIntegerCast(C, SrcTy, CmpI->isSigned());
4578 }
Sanjay Patel14a4b812017-01-29 16:34:57 +00004579 break;
4580 case Instruction::FPTrunc:
4581 CastedTo = ConstantExpr::getFPExtend(C, SrcTy, true);
4582 break;
4583 case Instruction::FPExt:
4584 CastedTo = ConstantExpr::getFPTrunc(C, SrcTy, true);
4585 break;
4586 case Instruction::FPToUI:
4587 CastedTo = ConstantExpr::getUIToFP(C, SrcTy, true);
4588 break;
4589 case Instruction::FPToSI:
4590 CastedTo = ConstantExpr::getSIToFP(C, SrcTy, true);
4591 break;
4592 case Instruction::UIToFP:
4593 CastedTo = ConstantExpr::getFPToUI(C, SrcTy, true);
4594 break;
4595 case Instruction::SIToFP:
4596 CastedTo = ConstantExpr::getFPToSI(C, SrcTy, true);
4597 break;
4598 default:
4599 break;
4600 }
David Majnemerd2a074b2016-04-29 18:40:34 +00004601
4602 if (!CastedTo)
4603 return nullptr;
4604
David Majnemerd2a074b2016-04-29 18:40:34 +00004605 // Make sure the cast doesn't lose any information.
Sanjay Patel14a4b812017-01-29 16:34:57 +00004606 Constant *CastedBack =
4607 ConstantExpr::getCast(*CastOp, CastedTo, C->getType(), true);
David Majnemerd2a074b2016-04-29 18:40:34 +00004608 if (CastedBack != C)
4609 return nullptr;
4610
4611 return CastedTo;
James Molloy270ef8c2015-05-15 16:04:50 +00004612}
4613
Sanjay Patele8dc0902016-05-23 17:57:54 +00004614SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004615 Instruction::CastOps *CastOp,
4616 unsigned Depth) {
4617 if (Depth >= MaxDepth)
4618 return {SPF_UNKNOWN, SPNB_NA, false};
4619
James Molloy270ef8c2015-05-15 16:04:50 +00004620 SelectInst *SI = dyn_cast<SelectInst>(V);
James Molloy134bec22015-08-11 09:12:57 +00004621 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004622
James Molloy134bec22015-08-11 09:12:57 +00004623 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
4624 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004625
James Molloy134bec22015-08-11 09:12:57 +00004626 CmpInst::Predicate Pred = CmpI->getPredicate();
James Molloy270ef8c2015-05-15 16:04:50 +00004627 Value *CmpLHS = CmpI->getOperand(0);
4628 Value *CmpRHS = CmpI->getOperand(1);
4629 Value *TrueVal = SI->getTrueValue();
4630 Value *FalseVal = SI->getFalseValue();
James Molloy134bec22015-08-11 09:12:57 +00004631 FastMathFlags FMF;
4632 if (isa<FPMathOperator>(CmpI))
4633 FMF = CmpI->getFastMathFlags();
James Molloy270ef8c2015-05-15 16:04:50 +00004634
4635 // Bail out early.
4636 if (CmpI->isEquality())
James Molloy134bec22015-08-11 09:12:57 +00004637 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004638
4639 // Deal with type mismatches.
4640 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
Sanjay Patel9a399792017-12-26 15:09:19 +00004641 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
4642 // If this is a potential fmin/fmax with a cast to integer, then ignore
4643 // -0.0 because there is no corresponding integer value.
4644 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
4645 FMF.setNoSignedZeros();
James Molloy134bec22015-08-11 09:12:57 +00004646 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004647 cast<CastInst>(TrueVal)->getOperand(0), C,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004648 LHS, RHS, Depth);
Sanjay Patel9a399792017-12-26 15:09:19 +00004649 }
4650 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
4651 // If this is a potential fmin/fmax with a cast to integer, then ignore
4652 // -0.0 because there is no corresponding integer value.
4653 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
4654 FMF.setNoSignedZeros();
James Molloy134bec22015-08-11 09:12:57 +00004655 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004656 C, cast<CastInst>(FalseVal)->getOperand(0),
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004657 LHS, RHS, Depth);
Sanjay Patel9a399792017-12-26 15:09:19 +00004658 }
James Molloy270ef8c2015-05-15 16:04:50 +00004659 }
James Molloy134bec22015-08-11 09:12:57 +00004660 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
Sanjay Patel1d91ec32018-01-24 15:20:37 +00004661 LHS, RHS, Depth);
James Molloy270ef8c2015-05-15 16:04:50 +00004662}
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004663
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004664/// Return true if "icmp Pred LHS RHS" is always true.
Chad Rosiere42b44b2017-07-28 14:39:06 +00004665static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
4666 const Value *RHS, const DataLayout &DL,
4667 unsigned Depth) {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004668 assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004669 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
4670 return true;
4671
4672 switch (Pred) {
4673 default:
4674 return false;
4675
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004676 case CmpInst::ICMP_SLE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004677 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004678
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004679 // LHS s<= LHS +_{nsw} C if C >= 0
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004680 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004681 return !C->isNegative();
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004682 return false;
4683 }
4684
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004685 case CmpInst::ICMP_ULE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004686 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004687
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004688 // LHS u<= LHS +_{nuw} C for any C
4689 if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasc01b4d22015-11-06 19:01:03 +00004690 return true;
Sanjoy Das92568102015-11-10 23:56:20 +00004691
4692 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
Pete Cooper35b00d52016-08-13 01:05:32 +00004693 auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B,
4694 const Value *&X,
Sanjoy Das92568102015-11-10 23:56:20 +00004695 const APInt *&CA, const APInt *&CB) {
4696 if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
4697 match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
4698 return true;
4699
4700 // If X & C == 0 then (X | C) == X +_{nuw} C
4701 if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
4702 match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
Craig Topperb45eabc2017-04-26 16:39:58 +00004703 KnownBits Known(CA->getBitWidth());
Chad Rosiere42b44b2017-07-28 14:39:06 +00004704 computeKnownBits(X, Known, DL, Depth + 1, /*AC*/ nullptr,
4705 /*CxtI*/ nullptr, /*DT*/ nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +00004706 if (CA->isSubsetOf(Known.Zero) && CB->isSubsetOf(Known.Zero))
Sanjoy Das92568102015-11-10 23:56:20 +00004707 return true;
4708 }
4709
4710 return false;
4711 };
4712
Pete Cooper35b00d52016-08-13 01:05:32 +00004713 const Value *X;
Sanjoy Das92568102015-11-10 23:56:20 +00004714 const APInt *CLHS, *CRHS;
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004715 if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
4716 return CLHS->ule(*CRHS);
Sanjoy Das92568102015-11-10 23:56:20 +00004717
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004718 return false;
4719 }
4720 }
4721}
4722
4723/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
Chad Rosier41dd31f2016-04-20 19:15:26 +00004724/// ALHS ARHS" is true. Otherwise, return None.
4725static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00004726isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS,
Chad Rosiere42b44b2017-07-28 14:39:06 +00004727 const Value *ARHS, const Value *BLHS, const Value *BRHS,
4728 const DataLayout &DL, unsigned Depth) {
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004729 switch (Pred) {
4730 default:
Chad Rosier41dd31f2016-04-20 19:15:26 +00004731 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004732
4733 case CmpInst::ICMP_SLT:
4734 case CmpInst::ICMP_SLE:
Chad Rosiere42b44b2017-07-28 14:39:06 +00004735 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth) &&
4736 isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004737 return true;
4738 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004739
4740 case CmpInst::ICMP_ULT:
4741 case CmpInst::ICMP_ULE:
Chad Rosiere42b44b2017-07-28 14:39:06 +00004742 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth) &&
4743 isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004744 return true;
4745 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004746 }
4747}
4748
Chad Rosier226a7342016-05-05 17:41:19 +00004749/// Return true if the operands of the two compares match. IsSwappedOps is true
4750/// when the operands match, but are swapped.
Pete Cooper35b00d52016-08-13 01:05:32 +00004751static bool isMatchingOps(const Value *ALHS, const Value *ARHS,
4752 const Value *BLHS, const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00004753 bool &IsSwappedOps) {
4754
4755 bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS);
4756 IsSwappedOps = (ALHS == BRHS && ARHS == BLHS);
4757 return IsMatchingOps || IsSwappedOps;
4758}
4759
Chad Rosier41dd31f2016-04-20 19:15:26 +00004760/// Return true if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS BRHS" is
4761/// true. Return false if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS
4762/// BRHS" is false. Otherwise, return None if we can't infer anything.
4763static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred,
Pete Cooper35b00d52016-08-13 01:05:32 +00004764 const Value *ALHS,
4765 const Value *ARHS,
Chad Rosier41dd31f2016-04-20 19:15:26 +00004766 CmpInst::Predicate BPred,
Pete Cooper35b00d52016-08-13 01:05:32 +00004767 const Value *BLHS,
4768 const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00004769 bool IsSwappedOps) {
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004770 // Canonicalize the operands so they're matching.
4771 if (IsSwappedOps) {
4772 std::swap(BLHS, BRHS);
4773 BPred = ICmpInst::getSwappedPredicate(BPred);
4774 }
Chad Rosier99bc4802016-04-21 16:18:02 +00004775 if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred))
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004776 return true;
Chad Rosier99bc4802016-04-21 16:18:02 +00004777 if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004778 return false;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004779
Chad Rosier41dd31f2016-04-20 19:15:26 +00004780 return None;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004781}
4782
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004783/// Return true if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS C2" is
4784/// true. Return false if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS
4785/// C2" is false. Otherwise, return None if we can't infer anything.
4786static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00004787isImpliedCondMatchingImmOperands(CmpInst::Predicate APred, const Value *ALHS,
4788 const ConstantInt *C1,
4789 CmpInst::Predicate BPred,
4790 const Value *BLHS, const ConstantInt *C2) {
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004791 assert(ALHS == BLHS && "LHS operands must match.");
4792 ConstantRange DomCR =
4793 ConstantRange::makeExactICmpRegion(APred, C1->getValue());
4794 ConstantRange CR =
4795 ConstantRange::makeAllowedICmpRegion(BPred, C2->getValue());
4796 ConstantRange Intersection = DomCR.intersectWith(CR);
4797 ConstantRange Difference = DomCR.difference(CR);
4798 if (Intersection.isEmptySet())
4799 return false;
4800 if (Difference.isEmptySet())
4801 return true;
4802 return None;
4803}
4804
Chad Rosier2f498032017-07-28 18:47:43 +00004805/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
4806/// false. Otherwise, return None if we can't infer anything.
4807static Optional<bool> isImpliedCondICmps(const ICmpInst *LHS,
4808 const ICmpInst *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00004809 const DataLayout &DL, bool LHSIsTrue,
Chad Rosier2f498032017-07-28 18:47:43 +00004810 unsigned Depth) {
4811 Value *ALHS = LHS->getOperand(0);
4812 Value *ARHS = LHS->getOperand(1);
Chad Rosiera72a9ff2017-07-06 20:00:25 +00004813 // The rest of the logic assumes the LHS condition is true. If that's not the
4814 // case, invert the predicate to make it so.
Chad Rosier2f498032017-07-28 18:47:43 +00004815 ICmpInst::Predicate APred =
Chad Rosierdfd1de62017-08-01 20:18:54 +00004816 LHSIsTrue ? LHS->getPredicate() : LHS->getInversePredicate();
Chad Rosier2f498032017-07-28 18:47:43 +00004817
4818 Value *BLHS = RHS->getOperand(0);
4819 Value *BRHS = RHS->getOperand(1);
4820 ICmpInst::Predicate BPred = RHS->getPredicate();
Chad Rosiere2cbd132016-04-25 17:23:36 +00004821
Chad Rosier226a7342016-05-05 17:41:19 +00004822 // Can we infer anything when the two compares have matching operands?
4823 bool IsSwappedOps;
4824 if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, IsSwappedOps)) {
4825 if (Optional<bool> Implication = isImpliedCondMatchingOperands(
4826 APred, ALHS, ARHS, BPred, BLHS, BRHS, IsSwappedOps))
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004827 return Implication;
Chad Rosier226a7342016-05-05 17:41:19 +00004828 // No amount of additional analysis will infer the second condition, so
4829 // early exit.
4830 return None;
4831 }
4832
4833 // Can we infer anything when the LHS operands match and the RHS operands are
4834 // constants (not necessarily matching)?
4835 if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) {
4836 if (Optional<bool> Implication = isImpliedCondMatchingImmOperands(
4837 APred, ALHS, cast<ConstantInt>(ARHS), BPred, BLHS,
4838 cast<ConstantInt>(BRHS)))
4839 return Implication;
4840 // No amount of additional analysis will infer the second condition, so
4841 // early exit.
4842 return None;
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004843 }
4844
Chad Rosier41dd31f2016-04-20 19:15:26 +00004845 if (APred == BPred)
Chad Rosiere42b44b2017-07-28 14:39:06 +00004846 return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth);
Chad Rosier41dd31f2016-04-20 19:15:26 +00004847 return None;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004848}
Chad Rosier2f498032017-07-28 18:47:43 +00004849
Chad Rosierf73a10d2017-08-01 19:22:36 +00004850/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
4851/// false. Otherwise, return None if we can't infer anything. We expect the
4852/// RHS to be an icmp and the LHS to be an 'and' or an 'or' instruction.
4853static Optional<bool> isImpliedCondAndOr(const BinaryOperator *LHS,
4854 const ICmpInst *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00004855 const DataLayout &DL, bool LHSIsTrue,
Chad Rosierf73a10d2017-08-01 19:22:36 +00004856 unsigned Depth) {
4857 // The LHS must be an 'or' or an 'and' instruction.
4858 assert((LHS->getOpcode() == Instruction::And ||
4859 LHS->getOpcode() == Instruction::Or) &&
4860 "Expected LHS to be 'and' or 'or'.");
4861
Davide Italiano1a943a92017-08-09 16:06:54 +00004862 assert(Depth <= MaxDepth && "Hit recursion limit");
Chad Rosierf73a10d2017-08-01 19:22:36 +00004863
4864 // If the result of an 'or' is false, then we know both legs of the 'or' are
4865 // false. Similarly, if the result of an 'and' is true, then we know both
4866 // legs of the 'and' are true.
4867 Value *ALHS, *ARHS;
Chad Rosierdfd1de62017-08-01 20:18:54 +00004868 if ((!LHSIsTrue && match(LHS, m_Or(m_Value(ALHS), m_Value(ARHS)))) ||
4869 (LHSIsTrue && match(LHS, m_And(m_Value(ALHS), m_Value(ARHS))))) {
Chad Rosierf73a10d2017-08-01 19:22:36 +00004870 // FIXME: Make this non-recursion.
4871 if (Optional<bool> Implication =
Chad Rosierdfd1de62017-08-01 20:18:54 +00004872 isImpliedCondition(ALHS, RHS, DL, LHSIsTrue, Depth + 1))
Chad Rosierf73a10d2017-08-01 19:22:36 +00004873 return Implication;
4874 if (Optional<bool> Implication =
Chad Rosierdfd1de62017-08-01 20:18:54 +00004875 isImpliedCondition(ARHS, RHS, DL, LHSIsTrue, Depth + 1))
Chad Rosierf73a10d2017-08-01 19:22:36 +00004876 return Implication;
4877 return None;
4878 }
4879 return None;
4880}
4881
Chad Rosier2f498032017-07-28 18:47:43 +00004882Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00004883 const DataLayout &DL, bool LHSIsTrue,
Chad Rosier2f498032017-07-28 18:47:43 +00004884 unsigned Depth) {
Davide Italiano30e51942017-08-09 15:13:50 +00004885 // Bail out when we hit the limit.
4886 if (Depth == MaxDepth)
4887 return None;
4888
Chad Rosierf73a10d2017-08-01 19:22:36 +00004889 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
4890 // example.
Chad Rosier2f498032017-07-28 18:47:43 +00004891 if (LHS->getType() != RHS->getType())
4892 return None;
4893
4894 Type *OpTy = LHS->getType();
Chad Rosierf73a10d2017-08-01 19:22:36 +00004895 assert(OpTy->isIntOrIntVectorTy(1) && "Expected integer type only!");
Chad Rosier2f498032017-07-28 18:47:43 +00004896
4897 // LHS ==> RHS by definition
4898 if (LHS == RHS)
Chad Rosierdfd1de62017-08-01 20:18:54 +00004899 return LHSIsTrue;
Chad Rosier2f498032017-07-28 18:47:43 +00004900
Chad Rosierf73a10d2017-08-01 19:22:36 +00004901 // FIXME: Extending the code below to handle vectors.
Chad Rosier2f498032017-07-28 18:47:43 +00004902 if (OpTy->isVectorTy())
Chad Rosier2f498032017-07-28 18:47:43 +00004903 return None;
Chad Rosierf73a10d2017-08-01 19:22:36 +00004904
Chad Rosier2f498032017-07-28 18:47:43 +00004905 assert(OpTy->isIntegerTy(1) && "implied by above");
4906
Chad Rosier2f498032017-07-28 18:47:43 +00004907 // Both LHS and RHS are icmps.
Chad Rosierf73a10d2017-08-01 19:22:36 +00004908 const ICmpInst *LHSCmp = dyn_cast<ICmpInst>(LHS);
4909 const ICmpInst *RHSCmp = dyn_cast<ICmpInst>(RHS);
4910 if (LHSCmp && RHSCmp)
Chad Rosierdfd1de62017-08-01 20:18:54 +00004911 return isImpliedCondICmps(LHSCmp, RHSCmp, DL, LHSIsTrue, Depth);
Chad Rosier2f498032017-07-28 18:47:43 +00004912
Chad Rosierf73a10d2017-08-01 19:22:36 +00004913 // The LHS should be an 'or' or an 'and' instruction. We expect the RHS to be
4914 // an icmp. FIXME: Add support for and/or on the RHS.
4915 const BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHS);
4916 if (LHSBO && RHSCmp) {
4917 if ((LHSBO->getOpcode() == Instruction::And ||
4918 LHSBO->getOpcode() == Instruction::Or))
Chad Rosierdfd1de62017-08-01 20:18:54 +00004919 return isImpliedCondAndOr(LHSBO, RHSCmp, DL, LHSIsTrue, Depth);
Chad Rosier2f498032017-07-28 18:47:43 +00004920 }
Chad Rosierf73a10d2017-08-01 19:22:36 +00004921 return None;
Chad Rosier2f498032017-07-28 18:47:43 +00004922}