blob: 8020afffd45eda7d47aa8de5c35c9203bbef9a5d [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
Mehdi Aminia28d91d2015-03-10 02:37:25 +000092 return DL.getPointerTypeSizeInBits(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
339 // If low bits are zero in either operand, output low known-0 bits.
Sanjay Patel5dd66c32015-09-17 20:51:50 +0000340 // Also compute a conservative estimate for high known-0 bits.
Nick Lewyckyfa306072012-03-18 23:28:48 +0000341 // More trickiness is possible, but this is sufficient for the
342 // interesting case of alignment computation.
Craig Topper8df66c62017-05-12 17:20:30 +0000343 unsigned TrailZ = Known.countMinTrailingZeros() +
344 Known2.countMinTrailingZeros();
345 unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
346 Known2.countMinLeadingZeros(),
Nick Lewyckyfa306072012-03-18 23:28:48 +0000347 BitWidth) - BitWidth;
348
349 TrailZ = std::min(TrailZ, BitWidth);
350 LeadZ = std::min(LeadZ, BitWidth);
Craig Topperf0aeee02017-05-05 17:36:09 +0000351 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000352 Known.Zero.setLowBits(TrailZ);
353 Known.Zero.setHighBits(LeadZ);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000354
355 // Only make use of no-wrap flags if we failed to compute the sign bit
356 // directly. This matters if the multiplication always overflows, in
357 // which case we prefer to follow the result of the direct computation,
358 // though as the program is invoking undefined behaviour we can choose
359 // whatever we like here.
Craig Topperca48af32017-04-29 16:43:11 +0000360 if (isKnownNonNegative && !Known.isNegative())
361 Known.makeNonNegative();
362 else if (isKnownNegative && !Known.isNonNegative())
363 Known.makeNegative();
Nick Lewyckyfa306072012-03-18 23:28:48 +0000364}
365
Jingyue Wu37fcb592014-06-19 16:50:16 +0000366void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
Craig Topperf42b23f2017-04-28 06:28:56 +0000367 KnownBits &Known) {
368 unsigned BitWidth = Known.getBitWidth();
Rafael Espindola53190532012-03-30 15:52:11 +0000369 unsigned NumRanges = Ranges.getNumOperands() / 2;
370 assert(NumRanges >= 1);
371
Craig Topperf42b23f2017-04-28 06:28:56 +0000372 Known.Zero.setAllBits();
373 Known.One.setAllBits();
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000374
Rafael Espindola53190532012-03-30 15:52:11 +0000375 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000376 ConstantInt *Lower =
377 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
378 ConstantInt *Upper =
379 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
Rafael Espindola53190532012-03-30 15:52:11 +0000380 ConstantRange Range(Lower->getValue(), Upper->getValue());
Rafael Espindola53190532012-03-30 15:52:11 +0000381
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000382 // The first CommonPrefixBits of all values in Range are equal.
383 unsigned CommonPrefixBits =
384 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
385
386 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
Craig Topperf42b23f2017-04-28 06:28:56 +0000387 Known.One &= Range.getUnsignedMax() & Mask;
388 Known.Zero &= ~Range.getUnsignedMax() & Mask;
Sanjoy Das1d1929a2015-10-28 03:20:15 +0000389 }
Rafael Espindola53190532012-03-30 15:52:11 +0000390}
Jay Foad5a29c362014-05-15 12:12:55 +0000391
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000392static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
Hal Finkel60db0582014-09-07 18:57:58 +0000393 SmallVector<const Value *, 16> WorkSet(1, I);
394 SmallPtrSet<const Value *, 32> Visited;
395 SmallPtrSet<const Value *, 16> EphValues;
396
Hal Finkelf2199b22015-10-23 20:37:08 +0000397 // The instruction defining an assumption's condition itself is always
398 // considered ephemeral to that assumption (even if it has other
399 // non-ephemeral users). See r246696's test case for an example.
David Majnemer0a16c222016-08-11 21:15:00 +0000400 if (is_contained(I->operands(), E))
Hal Finkelf2199b22015-10-23 20:37:08 +0000401 return true;
402
Hal Finkel60db0582014-09-07 18:57:58 +0000403 while (!WorkSet.empty()) {
404 const Value *V = WorkSet.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +0000405 if (!Visited.insert(V).second)
Hal Finkel60db0582014-09-07 18:57:58 +0000406 continue;
407
408 // If all uses of this value are ephemeral, then so is this value.
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000409 if (llvm::all_of(V->users(), [&](const User *U) {
410 return EphValues.count(U);
411 })) {
Hal Finkel60db0582014-09-07 18:57:58 +0000412 if (V == E)
413 return true;
414
Hal Finkelb03dd4b2017-08-14 17:11:43 +0000415 if (V == I || isSafeToSpeculativelyExecute(V)) {
416 EphValues.insert(V);
417 if (const User *U = dyn_cast<User>(V))
418 for (User::const_op_iterator J = U->op_begin(), JE = U->op_end();
419 J != JE; ++J)
420 WorkSet.push_back(*J);
421 }
Hal Finkel60db0582014-09-07 18:57:58 +0000422 }
423 }
424
425 return false;
426}
427
428// Is this an intrinsic that cannot be speculated but also cannot trap?
429static bool isAssumeLikeIntrinsic(const Instruction *I) {
430 if (const CallInst *CI = dyn_cast<CallInst>(I))
431 if (Function *F = CI->getCalledFunction())
432 switch (F->getIntrinsicID()) {
433 default: break;
434 // FIXME: This list is repeated from NoTTI::getIntrinsicCost.
435 case Intrinsic::assume:
Dan Gohman2c74fe92017-11-08 21:59:51 +0000436 case Intrinsic::sideeffect:
Hal Finkel60db0582014-09-07 18:57:58 +0000437 case Intrinsic::dbg_declare:
438 case Intrinsic::dbg_value:
439 case Intrinsic::invariant_start:
440 case Intrinsic::invariant_end:
441 case Intrinsic::lifetime_start:
442 case Intrinsic::lifetime_end:
443 case Intrinsic::objectsize:
444 case Intrinsic::ptr_annotation:
445 case Intrinsic::var_annotation:
446 return true;
447 }
448
449 return false;
450}
451
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000452bool llvm::isValidAssumeForContext(const Instruction *Inv,
453 const Instruction *CxtI,
454 const DominatorTree *DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000455 // There are two restrictions on the use of an assume:
456 // 1. The assume must dominate the context (or the control flow must
457 // reach the assume whenever it reaches the context).
458 // 2. The context must not be in the assume's set of ephemeral values
459 // (otherwise we will use the assume to prove that the condition
460 // feeding the assume is trivially true, thus causing the removal of
461 // the assume).
462
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000463 if (DT) {
Pete Cooper54a02552016-08-12 01:00:15 +0000464 if (DT->dominates(Inv, CxtI))
Hal Finkel60db0582014-09-07 18:57:58 +0000465 return true;
Pete Cooper54a02552016-08-12 01:00:15 +0000466 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
467 // We don't have a DT, but this trivially dominates.
468 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000469 }
470
Pete Cooper54a02552016-08-12 01:00:15 +0000471 // With or without a DT, the only remaining case we will check is if the
472 // instructions are in the same BB. Give up if that is not the case.
473 if (Inv->getParent() != CxtI->getParent())
474 return false;
475
476 // If we have a dom tree, then we now know that the assume doens't dominate
477 // the other instruction. If we don't have a dom tree then we can check if
478 // the assume is first in the BB.
479 if (!DT) {
Hal Finkel60db0582014-09-07 18:57:58 +0000480 // Search forward from the assume until we reach the context (or the end
481 // of the block); the common case is that the assume will come first.
Pete Cooperfa7ae4f2016-08-11 22:23:07 +0000482 for (auto I = std::next(BasicBlock::const_iterator(Inv)),
Hal Finkel60db0582014-09-07 18:57:58 +0000483 IE = Inv->getParent()->end(); I != IE; ++I)
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000484 if (&*I == CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000485 return true;
Hal Finkel60db0582014-09-07 18:57:58 +0000486 }
487
Pete Cooper54a02552016-08-12 01:00:15 +0000488 // The context comes first, but they're both in the same block. Make sure
489 // there is nothing in between that might interrupt the control flow.
490 for (BasicBlock::const_iterator I =
491 std::next(BasicBlock::const_iterator(CxtI)), IE(Inv);
492 I != IE; ++I)
493 if (!isSafeToSpeculativelyExecute(&*I) && !isAssumeLikeIntrinsic(&*I))
494 return false;
495
496 return !isEphemeralValueOf(Inv, CxtI);
Hal Finkel60db0582014-09-07 18:57:58 +0000497}
498
Craig Topperb45eabc2017-04-26 16:39:58 +0000499static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known,
500 unsigned Depth, const Query &Q) {
Hal Finkel60db0582014-09-07 18:57:58 +0000501 // Use of assumptions is context-sensitive. If we don't have a context, we
502 // cannot use them!
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000503 if (!Q.AC || !Q.CxtI)
Hal Finkel60db0582014-09-07 18:57:58 +0000504 return;
505
Craig Topperb45eabc2017-04-26 16:39:58 +0000506 unsigned BitWidth = Known.getBitWidth();
Hal Finkel60db0582014-09-07 18:57:58 +0000507
Hal Finkel8a9a7832017-01-11 13:24:24 +0000508 // Note that the patterns below need to be kept in sync with the code
509 // in AssumptionCache::updateAffectedValues.
510
511 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000512 if (!AssumeVH)
Chandler Carruth66b31302015-01-04 12:03:27 +0000513 continue;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000514 CallInst *I = cast<CallInst>(AssumeVH);
515 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
516 "Got assumption for the wrong function!");
517 if (Q.isExcluded(I))
Hal Finkel60db0582014-09-07 18:57:58 +0000518 continue;
519
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000520 // Warning: This loop can end up being somewhat performance sensetive.
521 // We're running this loop for once for each value queried resulting in a
522 // runtime of ~O(#assumes * #values).
Philip Reames00d3b272014-11-24 23:44:28 +0000523
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000524 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&
525 "must be an assume intrinsic");
526
527 Value *Arg = I->getArgOperand(0);
528
529 if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Hal Finkel60db0582014-09-07 18:57:58 +0000530 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000531 Known.setAllOnes();
Hal Finkel60db0582014-09-07 18:57:58 +0000532 return;
533 }
Sanjay Patel96669962017-01-17 18:15:49 +0000534 if (match(Arg, m_Not(m_Specific(V))) &&
535 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
536 assert(BitWidth == 1 && "assume operand is not i1?");
Craig Topperf0aeee02017-05-05 17:36:09 +0000537 Known.setAllZero();
Sanjay Patel96669962017-01-17 18:15:49 +0000538 return;
539 }
Hal Finkel60db0582014-09-07 18:57:58 +0000540
David Majnemer9b609752014-12-12 23:59:29 +0000541 // The remaining tests are all recursive, so bail out if we hit the limit.
542 if (Depth == MaxDepth)
543 continue;
544
Hal Finkel60db0582014-09-07 18:57:58 +0000545 Value *A, *B;
546 auto m_V = m_CombineOr(m_Specific(V),
547 m_CombineOr(m_PtrToInt(m_Specific(V)),
548 m_BitCast(m_Specific(V))));
549
550 CmpInst::Predicate Pred;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000551 ConstantInt *C;
Hal Finkel60db0582014-09-07 18:57:58 +0000552 // assume(v = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000553 if (match(Arg, m_c_ICmp(Pred, m_V, m_Value(A))) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000554 Pred == ICmpInst::ICMP_EQ && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000555 KnownBits RHSKnown(BitWidth);
556 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
557 Known.Zero |= RHSKnown.Zero;
558 Known.One |= RHSKnown.One;
Hal Finkel60db0582014-09-07 18:57:58 +0000559 // assume(v & b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000560 } else if (match(Arg,
561 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000562 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000563 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000564 KnownBits RHSKnown(BitWidth);
565 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
566 KnownBits MaskKnown(BitWidth);
567 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel60db0582014-09-07 18:57:58 +0000568
569 // For those bits in the mask that are known to be one, we can propagate
570 // known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000571 Known.Zero |= RHSKnown.Zero & MaskKnown.One;
572 Known.One |= RHSKnown.One & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000573 // assume(~(v & b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000574 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
575 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000576 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000577 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000578 KnownBits RHSKnown(BitWidth);
579 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
580 KnownBits MaskKnown(BitWidth);
581 computeKnownBits(B, MaskKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000582
583 // For those bits in the mask that are known to be one, we can propagate
584 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000585 Known.Zero |= RHSKnown.One & MaskKnown.One;
586 Known.One |= RHSKnown.Zero & MaskKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000587 // assume(v | b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000588 } else if (match(Arg,
589 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000590 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000591 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000592 KnownBits RHSKnown(BitWidth);
593 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
594 KnownBits BKnown(BitWidth);
595 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000596
597 // For those bits in B that are known to be zero, we can propagate known
598 // bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000599 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
600 Known.One |= RHSKnown.One & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000601 // assume(~(v | b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000602 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
603 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000604 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000605 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000606 KnownBits RHSKnown(BitWidth);
607 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
608 KnownBits BKnown(BitWidth);
609 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000610
611 // For those bits in B that are known to be zero, we can propagate
612 // inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000613 Known.Zero |= RHSKnown.One & BKnown.Zero;
614 Known.One |= RHSKnown.Zero & BKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000615 // assume(v ^ b = a)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000616 } else if (match(Arg,
617 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000618 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000619 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000620 KnownBits RHSKnown(BitWidth);
621 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
622 KnownBits BKnown(BitWidth);
623 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000624
625 // For those bits in B that are known to be zero, we can propagate known
626 // bits from the RHS to V. For those bits in B that are known to be one,
627 // we can propagate inverted known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000628 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
629 Known.One |= RHSKnown.One & BKnown.Zero;
630 Known.Zero |= RHSKnown.One & BKnown.One;
631 Known.One |= RHSKnown.Zero & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000632 // assume(~(v ^ b) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000633 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
634 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000635 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000636 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000637 KnownBits RHSKnown(BitWidth);
638 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
639 KnownBits BKnown(BitWidth);
640 computeKnownBits(B, BKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000641
642 // For those bits in B that are known to be zero, we can propagate
643 // inverted known bits from the RHS to V. For those bits in B that are
644 // known to be one, we can propagate known bits from the RHS to V.
Craig Topperb45eabc2017-04-26 16:39:58 +0000645 Known.Zero |= RHSKnown.One & BKnown.Zero;
646 Known.One |= RHSKnown.Zero & BKnown.Zero;
647 Known.Zero |= RHSKnown.Zero & BKnown.One;
648 Known.One |= RHSKnown.One & BKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000649 // assume(v << c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000650 } else if (match(Arg, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
651 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000652 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000653 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000654 KnownBits RHSKnown(BitWidth);
655 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000656 // For those bits in RHS that are known, we can propagate them to known
657 // bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000658 RHSKnown.Zero.lshrInPlace(C->getZExtValue());
659 Known.Zero |= RHSKnown.Zero;
660 RHSKnown.One.lshrInPlace(C->getZExtValue());
661 Known.One |= RHSKnown.One;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000662 // assume(~(v << c) = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000663 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
664 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000665 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000666 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000667 KnownBits RHSKnown(BitWidth);
668 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000669 // For those bits in RHS that are known, we can propagate them inverted
670 // to known bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000671 RHSKnown.One.lshrInPlace(C->getZExtValue());
672 Known.Zero |= RHSKnown.One;
673 RHSKnown.Zero.lshrInPlace(C->getZExtValue());
674 Known.One |= RHSKnown.Zero;
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000675 // assume(v >> c = a)
Philip Reames00d3b272014-11-24 23:44:28 +0000676 } else if (match(Arg,
Craig Topper7b66ffe2017-06-24 06:24:04 +0000677 m_c_ICmp(Pred, m_Shr(m_V, m_ConstantInt(C)),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000678 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000679 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000680 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000681 KnownBits RHSKnown(BitWidth);
682 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000683 // For those bits in RHS that are known, we can propagate them to known
684 // bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000685 Known.Zero |= RHSKnown.Zero << C->getZExtValue();
686 Known.One |= RHSKnown.One << C->getZExtValue();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000687 // assume(~(v >> c) = a)
Craig Topper7b66ffe2017-06-24 06:24:04 +0000688 } else if (match(Arg, m_c_ICmp(Pred, m_Not(m_Shr(m_V, m_ConstantInt(C))),
Philip Reames00d3b272014-11-24 23:44:28 +0000689 m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000690 Pred == ICmpInst::ICMP_EQ &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000691 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000692 KnownBits RHSKnown(BitWidth);
693 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000694 // For those bits in RHS that are known, we can propagate them inverted
695 // to known bits in V shifted to the right by C.
Craig Topperb45eabc2017-04-26 16:39:58 +0000696 Known.Zero |= RHSKnown.One << C->getZExtValue();
697 Known.One |= RHSKnown.Zero << C->getZExtValue();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000698 // assume(v >=_s c) where c is non-negative
Philip Reames00d3b272014-11-24 23:44:28 +0000699 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000700 Pred == ICmpInst::ICMP_SGE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000701 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000702 KnownBits RHSKnown(BitWidth);
703 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000704
Craig Topperca48af32017-04-29 16:43:11 +0000705 if (RHSKnown.isNonNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000706 // We know that the sign bit is zero.
Craig Topperca48af32017-04-29 16:43:11 +0000707 Known.makeNonNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000708 }
709 // assume(v >_s c) where c is at least -1.
Philip Reames00d3b272014-11-24 23:44:28 +0000710 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000711 Pred == ICmpInst::ICMP_SGT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000712 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000713 KnownBits RHSKnown(BitWidth);
714 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000715
Craig Topperf0aeee02017-05-05 17:36:09 +0000716 if (RHSKnown.isAllOnes() || RHSKnown.isNonNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000717 // We know that the sign bit is zero.
Craig Topperca48af32017-04-29 16:43:11 +0000718 Known.makeNonNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000719 }
720 // assume(v <=_s c) where c is negative
Philip Reames00d3b272014-11-24 23:44:28 +0000721 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000722 Pred == ICmpInst::ICMP_SLE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000723 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000724 KnownBits RHSKnown(BitWidth);
725 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000726
Craig Topperca48af32017-04-29 16:43:11 +0000727 if (RHSKnown.isNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000728 // We know that the sign bit is one.
Craig Topperca48af32017-04-29 16:43:11 +0000729 Known.makeNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000730 }
731 // assume(v <_s c) where c is non-positive
Philip Reames00d3b272014-11-24 23:44:28 +0000732 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000733 Pred == ICmpInst::ICMP_SLT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000734 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000735 KnownBits RHSKnown(BitWidth);
736 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000737
Craig Topperf0aeee02017-05-05 17:36:09 +0000738 if (RHSKnown.isZero() || RHSKnown.isNegative()) {
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000739 // We know that the sign bit is one.
Craig Topperca48af32017-04-29 16:43:11 +0000740 Known.makeNegative();
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000741 }
742 // assume(v <=_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000743 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000744 Pred == ICmpInst::ICMP_ULE &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000745 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000746 KnownBits RHSKnown(BitWidth);
747 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000748
749 // Whatever high bits in c are zero are known to be zero.
Craig Topper8df66c62017-05-12 17:20:30 +0000750 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
751 // assume(v <_u c)
Philip Reames00d3b272014-11-24 23:44:28 +0000752 } else if (match(Arg, m_ICmp(Pred, m_V, m_Value(A))) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000753 Pred == ICmpInst::ICMP_ULT &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000754 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000755 KnownBits RHSKnown(BitWidth);
756 computeKnownBits(A, RHSKnown, Depth+1, Query(Q, I));
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000757
758 // Whatever high bits in c are zero are known to be zero (if c is a power
759 // of 2, then one more).
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000760 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, Query(Q, I)))
Craig Topper8df66c62017-05-12 17:20:30 +0000761 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros() + 1);
Hal Finkel15aeaaf2014-09-07 19:21:07 +0000762 else
Craig Topper8df66c62017-05-12 17:20:30 +0000763 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
Hal Finkel60db0582014-09-07 18:57:58 +0000764 }
765 }
Sanjay Patel25f6d712017-02-01 15:41:32 +0000766
767 // If assumptions conflict with each other or previous known bits, then we
Sanjay Patel54656ca2017-02-06 18:26:06 +0000768 // have a logical fallacy. It's possible that the assumption is not reachable,
769 // so this isn't a real bug. On the other hand, the program may have undefined
770 // behavior, or we might have a bug in the compiler. We can't assert/crash, so
771 // clear out the known bits, try to warn the user, and hope for the best.
Craig Topperb45eabc2017-04-26 16:39:58 +0000772 if (Known.Zero.intersects(Known.One)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000773 Known.resetAll();
Sanjay Patel54656ca2017-02-06 18:26:06 +0000774
Vivek Pandya95906582017-10-11 17:12:59 +0000775 if (Q.ORE)
776 Q.ORE->emit([&]() {
777 auto *CxtI = const_cast<Instruction *>(Q.CxtI);
778 return OptimizationRemarkAnalysis("value-tracking", "BadAssumption",
779 CxtI)
780 << "Detected conflicting code assumptions. Program may "
781 "have undefined behavior, or compiler may have "
782 "internal error.";
783 });
Sanjay Patel25f6d712017-02-01 15:41:32 +0000784 }
Hal Finkel60db0582014-09-07 18:57:58 +0000785}
786
Sanjay Patelb7d12382017-10-16 14:46:37 +0000787/// Compute known bits from a shift operator, including those with a
788/// non-constant shift amount. Known is the output of this function. Known2 is a
789/// pre-allocated temporary with the same bit width as Known. KZF and KOF are
790/// operator-specific functors that, given the known-zero or known-one bits
791/// respectively, and a shift amount, compute the implied known-zero or
792/// known-one bits of the shift operator's result respectively for that shift
793/// amount. The results from calling KZF and KOF are conservatively combined for
794/// all permitted shift amounts.
David Majnemer54690dc2016-08-23 20:52:00 +0000795static void computeKnownBitsFromShiftOperator(
Craig Topperb45eabc2017-04-26 16:39:58 +0000796 const Operator *I, KnownBits &Known, KnownBits &Known2,
797 unsigned Depth, const Query &Q,
Craig Topper199acd82017-12-02 23:42:17 +0000798 function_ref<KnownBits(KnownBits, unsigned)> KBF) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000799 unsigned BitWidth = Known.getBitWidth();
Hal Finkelf2199b22015-10-23 20:37:08 +0000800
801 if (auto *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
802 unsigned ShiftAmt = SA->getLimitedValue(BitWidth-1);
803
Craig Topperb45eabc2017-04-26 16:39:58 +0000804 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Craig Topper199acd82017-12-02 23:42:17 +0000805 Known = KBF(Known, ShiftAmt);
Sanjay Patele272be72017-10-12 17:31:46 +0000806 // If the known bits conflict, this must be an overflowing left shift, so
807 // the shift result is poison. We can return anything we want. Choose 0 for
808 // the best folding opportunity.
809 if (Known.hasConflict())
810 Known.setAllZero();
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +0000811
Hal Finkelf2199b22015-10-23 20:37:08 +0000812 return;
813 }
814
Craig Topperb45eabc2017-04-26 16:39:58 +0000815 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000816
Sanjay Patele272be72017-10-12 17:31:46 +0000817 // If the shift amount could be greater than or equal to the bit-width of the
818 // LHS, the value could be poison, but bail out because the check below is
819 // expensive. TODO: Should we just carry on?
Craig Topperb45eabc2017-04-26 16:39:58 +0000820 if ((~Known.Zero).uge(BitWidth)) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000821 Known.resetAll();
Oliver Stannard06204112017-03-14 10:13:17 +0000822 return;
823 }
824
Craig Topperb45eabc2017-04-26 16:39:58 +0000825 // Note: We cannot use Known.Zero.getLimitedValue() here, because if
Hal Finkelf2199b22015-10-23 20:37:08 +0000826 // BitWidth > 64 and any upper bits are known, we'll end up returning the
827 // limit value (which implies all bits are known).
Craig Topperb45eabc2017-04-26 16:39:58 +0000828 uint64_t ShiftAmtKZ = Known.Zero.zextOrTrunc(64).getZExtValue();
829 uint64_t ShiftAmtKO = Known.One.zextOrTrunc(64).getZExtValue();
Hal Finkelf2199b22015-10-23 20:37:08 +0000830
831 // It would be more-clearly correct to use the two temporaries for this
832 // calculation. Reusing the APInts here to prevent unnecessary allocations.
Craig Topperf0aeee02017-05-05 17:36:09 +0000833 Known.resetAll();
Hal Finkelf2199b22015-10-23 20:37:08 +0000834
James Molloy493e57d2015-10-26 14:10:46 +0000835 // If we know the shifter operand is nonzero, we can sometimes infer more
836 // known bits. However this is expensive to compute, so be lazy about it and
837 // only compute it when absolutely necessary.
838 Optional<bool> ShifterOperandIsNonZero;
839
Hal Finkelf2199b22015-10-23 20:37:08 +0000840 // Early exit if we can't constrain any well-defined shift amount.
Craig Topperf93b7b12017-06-14 17:04:59 +0000841 if (!(ShiftAmtKZ & (PowerOf2Ceil(BitWidth) - 1)) &&
842 !(ShiftAmtKO & (PowerOf2Ceil(BitWidth) - 1))) {
Sanjay Patelb7d12382017-10-16 14:46:37 +0000843 ShifterOperandIsNonZero = isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000844 if (!*ShifterOperandIsNonZero)
845 return;
846 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000847
Craig Topperb45eabc2017-04-26 16:39:58 +0000848 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Hal Finkelf2199b22015-10-23 20:37:08 +0000849
Craig Topperb45eabc2017-04-26 16:39:58 +0000850 Known.Zero.setAllBits();
851 Known.One.setAllBits();
Hal Finkelf2199b22015-10-23 20:37:08 +0000852 for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
853 // Combine the shifted known input bits only for those shift amounts
854 // compatible with its known constraints.
855 if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
856 continue;
857 if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
858 continue;
James Molloy493e57d2015-10-26 14:10:46 +0000859 // If we know the shifter is nonzero, we may be able to infer more known
860 // bits. This check is sunk down as far as possible to avoid the expensive
861 // call to isKnownNonZero if the cheaper checks above fail.
862 if (ShiftAmt == 0) {
863 if (!ShifterOperandIsNonZero.hasValue())
864 ShifterOperandIsNonZero =
Matthias Braunfeb81bc2016-01-15 22:22:04 +0000865 isKnownNonZero(I->getOperand(1), Depth + 1, Q);
James Molloy493e57d2015-10-26 14:10:46 +0000866 if (*ShifterOperandIsNonZero)
867 continue;
868 }
Hal Finkelf2199b22015-10-23 20:37:08 +0000869
Craig Topper199acd82017-12-02 23:42:17 +0000870 Known2 = KBF(Known2, ShiftAmt);
871 Known.Zero &= Known2.Zero;
872 Known.One &= Known2.One;
Hal Finkelf2199b22015-10-23 20:37:08 +0000873 }
874
Sanjay Patele272be72017-10-12 17:31:46 +0000875 // If the known bits conflict, the result is poison. Return a 0 and hope the
876 // caller can further optimize that.
877 if (Known.hasConflict())
878 Known.setAllZero();
Hal Finkelf2199b22015-10-23 20:37:08 +0000879}
880
Craig Topperb45eabc2017-04-26 16:39:58 +0000881static void computeKnownBitsFromOperator(const Operator *I, KnownBits &Known,
882 unsigned Depth, const Query &Q) {
883 unsigned BitWidth = Known.getBitWidth();
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000884
Craig Topperb45eabc2017-04-26 16:39:58 +0000885 KnownBits Known2(Known);
Dan Gohman80ca01c2009-07-17 20:47:02 +0000886 switch (I->getOpcode()) {
Chris Lattner965c7692008-06-02 01:18:21 +0000887 default: break;
Rafael Espindola53190532012-03-30 15:52:11 +0000888 case Instruction::Load:
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000889 if (MDNode *MD = cast<LoadInst>(I)->getMetadata(LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +0000890 computeKnownBitsFromRangeMetadata(*MD, Known);
Jay Foad5a29c362014-05-15 12:12:55 +0000891 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000892 case Instruction::And: {
893 // If either the LHS or the RHS are Zero, the result is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +0000894 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
895 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000896
Chris Lattner965c7692008-06-02 01:18:21 +0000897 // Output known-1 bits are only known if set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000898 Known.One &= Known2.One;
Chris Lattner965c7692008-06-02 01:18:21 +0000899 // Output known-0 are known to be clear if zero in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000900 Known.Zero |= Known2.Zero;
Philip Reames2d858742015-11-10 18:46:14 +0000901
902 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
903 // here we handle the more general case of adding any odd number by
904 // matching the form add(x, add(x, y)) where y is odd.
905 // TODO: This could be generalized to clearing any bit set in y where the
906 // following bit is known to be unset in y.
907 Value *Y = nullptr;
Craig Topperb45eabc2017-04-26 16:39:58 +0000908 if (!Known.Zero[0] && !Known.One[0] &&
Craig Toppera80f2042017-04-13 19:04:45 +0000909 (match(I->getOperand(0), m_Add(m_Specific(I->getOperand(1)),
910 m_Value(Y))) ||
911 match(I->getOperand(1), m_Add(m_Specific(I->getOperand(0)),
912 m_Value(Y))))) {
Craig Topperf0aeee02017-05-05 17:36:09 +0000913 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000914 computeKnownBits(Y, Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +0000915 if (Known2.countMinTrailingOnes() > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +0000916 Known.Zero.setBit(0);
Philip Reames2d858742015-11-10 18:46:14 +0000917 }
Jay Foad5a29c362014-05-15 12:12:55 +0000918 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000919 }
Eugene Zelenko75075ef2017-09-01 21:37:29 +0000920 case Instruction::Or:
Craig Topperb45eabc2017-04-26 16:39:58 +0000921 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
922 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000923
Chris Lattner965c7692008-06-02 01:18:21 +0000924 // Output known-0 bits are only known if clear in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000925 Known.Zero &= Known2.Zero;
Chris Lattner965c7692008-06-02 01:18:21 +0000926 // Output known-1 are known to be set if set in either the LHS | RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000927 Known.One |= Known2.One;
Jay Foad5a29c362014-05-15 12:12:55 +0000928 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000929 case Instruction::Xor: {
Craig Topperb45eabc2017-04-26 16:39:58 +0000930 computeKnownBits(I->getOperand(1), Known, Depth + 1, Q);
931 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +0000932
Chris Lattner965c7692008-06-02 01:18:21 +0000933 // Output known-0 bits are known if clear or set in both the LHS & RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000934 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
Chris Lattner965c7692008-06-02 01:18:21 +0000935 // Output known-1 are known to be set if set in only one of the LHS, RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +0000936 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
937 Known.Zero = std::move(KnownZeroOut);
Jay Foad5a29c362014-05-15 12:12:55 +0000938 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000939 }
940 case Instruction::Mul: {
Nick Lewyckyfa306072012-03-18 23:28:48 +0000941 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Craig Topperb45eabc2017-04-26 16:39:58 +0000942 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, Known,
943 Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +0000944 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000945 }
946 case Instruction::UDiv: {
947 // For the purposes of computing leading zeros we can conservatively
948 // treat a udiv as a logical right shift by the power of 2 known to
949 // be less than the denominator.
Craig Topperb45eabc2017-04-26 16:39:58 +0000950 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +0000951 unsigned LeadZ = Known2.countMinLeadingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +0000952
Craig Topperf0aeee02017-05-05 17:36:09 +0000953 Known2.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +0000954 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +0000955 unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
956 if (RHSMaxLeadingZeros != BitWidth)
957 LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
Chris Lattner965c7692008-06-02 01:18:21 +0000958
Craig Topperb45eabc2017-04-26 16:39:58 +0000959 Known.Zero.setHighBits(LeadZ);
Jay Foad5a29c362014-05-15 12:12:55 +0000960 break;
Chris Lattner965c7692008-06-02 01:18:21 +0000961 }
David Majnemera19d0f22016-08-06 08:16:00 +0000962 case Instruction::Select: {
Craig Toppere953dec2017-04-13 20:39:37 +0000963 const Value *LHS, *RHS;
David Majnemera19d0f22016-08-06 08:16:00 +0000964 SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
965 if (SelectPatternResult::isMinOrMax(SPF)) {
Craig Topperb45eabc2017-04-26 16:39:58 +0000966 computeKnownBits(RHS, Known, Depth + 1, Q);
967 computeKnownBits(LHS, Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +0000968 } else {
Craig Topperb45eabc2017-04-26 16:39:58 +0000969 computeKnownBits(I->getOperand(2), Known, Depth + 1, Q);
970 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
David Majnemera19d0f22016-08-06 08:16:00 +0000971 }
972
973 unsigned MaxHighOnes = 0;
974 unsigned MaxHighZeros = 0;
975 if (SPF == SPF_SMAX) {
976 // If both sides are negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +0000977 if (Known.isNegative() && Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +0000978 // We can derive a lower bound on the result by taking the max of the
979 // leading one bits.
Craig Topper8df66c62017-05-12 17:20:30 +0000980 MaxHighOnes =
981 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +0000982 // If either side is non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +0000983 else if (Known.isNonNegative() || Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +0000984 MaxHighZeros = 1;
985 } else if (SPF == SPF_SMIN) {
986 // If both sides are non-negative, the result is non-negative.
Craig Topperca48af32017-04-29 16:43:11 +0000987 if (Known.isNonNegative() && Known2.isNonNegative())
David Majnemera19d0f22016-08-06 08:16:00 +0000988 // We can derive an upper bound on the result by taking the max of the
989 // leading zero bits.
Craig Topper8df66c62017-05-12 17:20:30 +0000990 MaxHighZeros = std::max(Known.countMinLeadingZeros(),
991 Known2.countMinLeadingZeros());
David Majnemera19d0f22016-08-06 08:16:00 +0000992 // If either side is negative, the result is negative.
Craig Topperca48af32017-04-29 16:43:11 +0000993 else if (Known.isNegative() || Known2.isNegative())
David Majnemera19d0f22016-08-06 08:16:00 +0000994 MaxHighOnes = 1;
995 } else if (SPF == SPF_UMAX) {
996 // We can derive a lower bound on the result by taking the max of the
997 // leading one bits.
998 MaxHighOnes =
Craig Topper8df66c62017-05-12 17:20:30 +0000999 std::max(Known.countMinLeadingOnes(), Known2.countMinLeadingOnes());
David Majnemera19d0f22016-08-06 08:16:00 +00001000 } else if (SPF == SPF_UMIN) {
1001 // We can derive an upper bound on the result by taking the max of the
1002 // leading zero bits.
1003 MaxHighZeros =
Craig Topper8df66c62017-05-12 17:20:30 +00001004 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
David Majnemera19d0f22016-08-06 08:16:00 +00001005 }
1006
Chris Lattner965c7692008-06-02 01:18:21 +00001007 // Only known if known in both the LHS and RHS.
Craig Topperb45eabc2017-04-26 16:39:58 +00001008 Known.One &= Known2.One;
1009 Known.Zero &= Known2.Zero;
David Majnemera19d0f22016-08-06 08:16:00 +00001010 if (MaxHighOnes > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001011 Known.One.setHighBits(MaxHighOnes);
David Majnemera19d0f22016-08-06 08:16:00 +00001012 if (MaxHighZeros > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001013 Known.Zero.setHighBits(MaxHighZeros);
Jay Foad5a29c362014-05-15 12:12:55 +00001014 break;
David Majnemera19d0f22016-08-06 08:16:00 +00001015 }
Chris Lattner965c7692008-06-02 01:18:21 +00001016 case Instruction::FPTrunc:
1017 case Instruction::FPExt:
1018 case Instruction::FPToUI:
1019 case Instruction::FPToSI:
1020 case Instruction::SIToFP:
1021 case Instruction::UIToFP:
Jay Foad5a29c362014-05-15 12:12:55 +00001022 break; // Can't work with floating point.
Chris Lattner965c7692008-06-02 01:18:21 +00001023 case Instruction::PtrToInt:
1024 case Instruction::IntToPtr:
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001025 // Fall through and handle them the same as zext/trunc.
1026 LLVM_FALLTHROUGH;
Chris Lattner965c7692008-06-02 01:18:21 +00001027 case Instruction::ZExt:
1028 case Instruction::Trunc: {
Chris Lattner229907c2011-07-18 04:54:35 +00001029 Type *SrcTy = I->getOperand(0)->getType();
Nadav Rotem15198e92012-10-26 17:17:05 +00001030
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001031 unsigned SrcBitWidth;
Chris Lattner965c7692008-06-02 01:18:21 +00001032 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1033 // which fall through here.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001034 SrcBitWidth = Q.DL.getTypeSizeInBits(SrcTy->getScalarType());
Nadav Rotem15198e92012-10-26 17:17:05 +00001035
1036 assert(SrcBitWidth && "SrcBitWidth can't be zero");
Craig Topperd938fd12017-05-03 22:07:25 +00001037 Known = Known.zextOrTrunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001038 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Craig Topperd938fd12017-05-03 22:07:25 +00001039 Known = Known.zextOrTrunc(BitWidth);
Chris Lattner965c7692008-06-02 01:18:21 +00001040 // Any top bits are known to be zero.
1041 if (BitWidth > SrcBitWidth)
Craig Topperb45eabc2017-04-26 16:39:58 +00001042 Known.Zero.setBitsFrom(SrcBitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001043 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001044 }
1045 case Instruction::BitCast: {
Chris Lattner229907c2011-07-18 04:54:35 +00001046 Type *SrcTy = I->getOperand(0)->getType();
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001047 if ((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
Chris Lattneredb84072009-07-02 16:04:08 +00001048 // TODO: For now, not handling conversions like:
1049 // (bitcast i64 %x to <2 x i32>)
Duncan Sands19d0b472010-02-16 11:11:14 +00001050 !I->getType()->isVectorTy()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001051 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Jay Foad5a29c362014-05-15 12:12:55 +00001052 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001053 }
1054 break;
1055 }
1056 case Instruction::SExt: {
1057 // Compute the bits in the result that are not present in the input.
Chris Lattner0cdbc7a2009-09-08 00:13:52 +00001058 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
Craig Topper1bef2c82012-12-22 19:15:35 +00001059
Craig Topperd938fd12017-05-03 22:07:25 +00001060 Known = Known.trunc(SrcBitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001061 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001062 // If the sign bit of the input is known set or clear, then we know the
1063 // top bits of the result.
Craig Topperd938fd12017-05-03 22:07:25 +00001064 Known = Known.sext(BitWidth);
Jay Foad5a29c362014-05-15 12:12:55 +00001065 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001066 }
Hal Finkelf2199b22015-10-23 20:37:08 +00001067 case Instruction::Shl: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001068 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001069 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Craig Topper199acd82017-12-02 23:42:17 +00001070 auto KBF = [NSW](const KnownBits &Known, unsigned ShiftAmt) {
1071 KnownBits Result;
1072 Result.Zero = Known.Zero << ShiftAmt;
1073 Result.Zero.setLowBits(ShiftAmt); // Low bits known 0.
1074 Result.One = Known.One << ShiftAmt;
Evgeny Stupachenkod7f9c352016-08-24 23:01:33 +00001075 // If this shift has "nsw" keyword, then the result is either a poison
1076 // value or has the same sign bit as the first operand.
Craig Topper199acd82017-12-02 23:42:17 +00001077 if (NSW && Known.isNonNegative())
1078 Result.Zero.setSignBit();
1079 if (NSW && Known.isNegative())
1080 Result.One.setSignBit();
1081 return Result;
Hal Finkelf2199b22015-10-23 20:37:08 +00001082 };
1083
Craig Topper199acd82017-12-02 23:42:17 +00001084 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KBF);
Chris Lattner965c7692008-06-02 01:18:21 +00001085 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001086 }
1087 case Instruction::LShr: {
Sanjay Patelb7d12382017-10-16 14:46:37 +00001088 // (lshr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Craig Topper199acd82017-12-02 23:42:17 +00001089 auto KBF = [](const KnownBits &Known, unsigned ShiftAmt) {
1090 KnownBits Result;
1091 Result.Zero = Known.Zero.lshr(ShiftAmt);
1092 Result.Zero.setHighBits(ShiftAmt); // High bits known zero.
1093 Result.One = Known.One.lshr(ShiftAmt);
1094 return Result;
Hal Finkelf2199b22015-10-23 20:37:08 +00001095 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001096
Craig Topper199acd82017-12-02 23:42:17 +00001097 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KBF);
Chris Lattner965c7692008-06-02 01:18:21 +00001098 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001099 }
1100 case Instruction::AShr: {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001101 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Craig Topper199acd82017-12-02 23:42:17 +00001102 auto KBF = [](const KnownBits &Known, unsigned ShiftAmt) {
1103 KnownBits Result;
1104 Result.Zero = Known.Zero.ashr(ShiftAmt);
1105 Result.One = Known.One.ashr(ShiftAmt);
1106 return Result;
Hal Finkelf2199b22015-10-23 20:37:08 +00001107 };
Craig Topper1bef2c82012-12-22 19:15:35 +00001108
Craig Topper199acd82017-12-02 23:42:17 +00001109 computeKnownBitsFromShiftOperator(I, Known, Known2, Depth, Q, KBF);
Chris Lattner965c7692008-06-02 01:18:21 +00001110 break;
Hal Finkelf2199b22015-10-23 20:37:08 +00001111 }
Chris Lattner965c7692008-06-02 01:18:21 +00001112 case Instruction::Sub: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001113 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001114 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001115 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001116 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001117 }
Chris Lattner965c7692008-06-02 01:18:21 +00001118 case Instruction::Add: {
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001119 bool NSW = cast<OverflowingBinaryOperator>(I)->hasNoSignedWrap();
Jay Foada0653a32014-05-14 21:14:37 +00001120 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
Craig Topperb45eabc2017-04-26 16:39:58 +00001121 Known, Known2, Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001122 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001123 }
1124 case Instruction::SRem:
1125 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001126 APInt RA = Rem->getValue().abs();
1127 if (RA.isPowerOf2()) {
1128 APInt LowBits = RA - 1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001129 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001130
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001131 // The low bits of the first operand are unchanged by the srem.
Craig Topperb45eabc2017-04-26 16:39:58 +00001132 Known.Zero = Known2.Zero & LowBits;
1133 Known.One = Known2.One & LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001134
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001135 // If the first operand is non-negative or has all low bits zero, then
1136 // the upper bits are all zero.
Craig Topperca48af32017-04-29 16:43:11 +00001137 if (Known2.isNonNegative() || LowBits.isSubsetOf(Known2.Zero))
Craig Topperb45eabc2017-04-26 16:39:58 +00001138 Known.Zero |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001139
1140 // If the first operand is negative and not all low bits are zero, then
1141 // the upper bits are all one.
Craig Topperca48af32017-04-29 16:43:11 +00001142 if (Known2.isNegative() && LowBits.intersects(Known2.One))
Craig Topperb45eabc2017-04-26 16:39:58 +00001143 Known.One |= ~LowBits;
Duncan Sands26cd6bd2010-01-29 06:18:37 +00001144
Craig Topperb45eabc2017-04-26 16:39:58 +00001145 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Craig Topperda886c62017-04-16 21:46:12 +00001146 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001147 }
1148 }
Nick Lewyckye4679792011-03-07 01:50:10 +00001149
1150 // The sign bit is the LHS's sign bit, except when the result of the
1151 // remainder is zero.
Craig Topperb45eabc2017-04-26 16:39:58 +00001152 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Craig Topperda886c62017-04-16 21:46:12 +00001153 // If it's known zero, our sign bit is also zero.
Craig Topperca48af32017-04-29 16:43:11 +00001154 if (Known2.isNonNegative())
1155 Known.makeNonNegative();
Nick Lewyckye4679792011-03-07 01:50:10 +00001156
Chris Lattner965c7692008-06-02 01:18:21 +00001157 break;
1158 case Instruction::URem: {
1159 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001160 const APInt &RA = Rem->getValue();
Chris Lattner965c7692008-06-02 01:18:21 +00001161 if (RA.isPowerOf2()) {
1162 APInt LowBits = (RA - 1);
Craig Topperb45eabc2017-04-26 16:39:58 +00001163 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1164 Known.Zero |= ~LowBits;
1165 Known.One &= LowBits;
Chris Lattner965c7692008-06-02 01:18:21 +00001166 break;
1167 }
1168 }
1169
1170 // Since the result is less than or equal to either operand, any leading
1171 // zero bits in either operand must also exist in the result.
Craig Topperb45eabc2017-04-26 16:39:58 +00001172 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1173 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001174
Craig Topper8df66c62017-05-12 17:20:30 +00001175 unsigned Leaders =
1176 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
Craig Topperf0aeee02017-05-05 17:36:09 +00001177 Known.resetAll();
Craig Topperb45eabc2017-04-26 16:39:58 +00001178 Known.Zero.setHighBits(Leaders);
Chris Lattner965c7692008-06-02 01:18:21 +00001179 break;
1180 }
1181
Victor Hernandeza3aaf852009-10-17 01:18:07 +00001182 case Instruction::Alloca: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001183 const AllocaInst *AI = cast<AllocaInst>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001184 unsigned Align = AI->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001185 if (Align == 0)
Eduard Burtescu90c44492016-01-18 00:10:01 +00001186 Align = Q.DL.getABITypeAlignment(AI->getAllocatedType());
Craig Topper1bef2c82012-12-22 19:15:35 +00001187
Chris Lattner965c7692008-06-02 01:18:21 +00001188 if (Align > 0)
Craig Topperb45eabc2017-04-26 16:39:58 +00001189 Known.Zero.setLowBits(countTrailingZeros(Align));
Chris Lattner965c7692008-06-02 01:18:21 +00001190 break;
1191 }
1192 case Instruction::GetElementPtr: {
1193 // Analyze all of the subscripts of this getelementptr instruction
1194 // to determine if we can prove known low zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001195 KnownBits LocalKnown(BitWidth);
1196 computeKnownBits(I->getOperand(0), LocalKnown, Depth + 1, Q);
Craig Topper8df66c62017-05-12 17:20:30 +00001197 unsigned TrailZ = LocalKnown.countMinTrailingZeros();
Chris Lattner965c7692008-06-02 01:18:21 +00001198
1199 gep_type_iterator GTI = gep_type_begin(I);
1200 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1201 Value *Index = I->getOperand(i);
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001202 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chris Lattner965c7692008-06-02 01:18:21 +00001203 // Handle struct member offset arithmetic.
Matt Arsenault74742a12013-08-19 21:43:16 +00001204
1205 // Handle case when index is vector zeroinitializer
1206 Constant *CIndex = cast<Constant>(Index);
1207 if (CIndex->isZeroValue())
1208 continue;
1209
1210 if (CIndex->getType()->isVectorTy())
1211 Index = CIndex->getSplatValue();
1212
Chris Lattner965c7692008-06-02 01:18:21 +00001213 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001214 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chris Lattner965c7692008-06-02 01:18:21 +00001215 uint64_t Offset = SL->getElementOffset(Idx);
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001216 TrailZ = std::min<unsigned>(TrailZ,
1217 countTrailingZeros(Offset));
Chris Lattner965c7692008-06-02 01:18:21 +00001218 } else {
1219 // Handle array index arithmetic.
Chris Lattner229907c2011-07-18 04:54:35 +00001220 Type *IndexedTy = GTI.getIndexedType();
Jay Foad5a29c362014-05-15 12:12:55 +00001221 if (!IndexedTy->isSized()) {
1222 TrailZ = 0;
1223 break;
1224 }
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001225 unsigned GEPOpiBits = Index->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001226 uint64_t TypeSize = Q.DL.getTypeAllocSize(IndexedTy);
Craig Topperb45eabc2017-04-26 16:39:58 +00001227 LocalKnown.Zero = LocalKnown.One = APInt(GEPOpiBits, 0);
1228 computeKnownBits(Index, LocalKnown, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00001229 TrailZ = std::min(TrailZ,
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001230 unsigned(countTrailingZeros(TypeSize) +
Craig Topper8df66c62017-05-12 17:20:30 +00001231 LocalKnown.countMinTrailingZeros()));
Chris Lattner965c7692008-06-02 01:18:21 +00001232 }
1233 }
Craig Topper1bef2c82012-12-22 19:15:35 +00001234
Craig Topperb45eabc2017-04-26 16:39:58 +00001235 Known.Zero.setLowBits(TrailZ);
Chris Lattner965c7692008-06-02 01:18:21 +00001236 break;
1237 }
1238 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00001239 const PHINode *P = cast<PHINode>(I);
Chris Lattner965c7692008-06-02 01:18:21 +00001240 // Handle the case of a simple two-predecessor recurrence PHI.
1241 // There's a lot more that could theoretically be done here, but
1242 // this is sufficient to catch some interesting cases.
1243 if (P->getNumIncomingValues() == 2) {
1244 for (unsigned i = 0; i != 2; ++i) {
1245 Value *L = P->getIncomingValue(i);
1246 Value *R = P->getIncomingValue(!i);
Dan Gohman80ca01c2009-07-17 20:47:02 +00001247 Operator *LU = dyn_cast<Operator>(L);
Chris Lattner965c7692008-06-02 01:18:21 +00001248 if (!LU)
1249 continue;
Dan Gohman80ca01c2009-07-17 20:47:02 +00001250 unsigned Opcode = LU->getOpcode();
Chris Lattner965c7692008-06-02 01:18:21 +00001251 // Check for operations that have the property that if
1252 // both their operands have low zero bits, the result
Artur Pilipenkobc76eca2016-08-22 13:14:07 +00001253 // will have low zero bits.
Chris Lattner965c7692008-06-02 01:18:21 +00001254 if (Opcode == Instruction::Add ||
1255 Opcode == Instruction::Sub ||
1256 Opcode == Instruction::And ||
1257 Opcode == Instruction::Or ||
1258 Opcode == Instruction::Mul) {
1259 Value *LL = LU->getOperand(0);
1260 Value *LR = LU->getOperand(1);
1261 // Find a recurrence.
1262 if (LL == I)
1263 L = LR;
1264 else if (LR == I)
1265 L = LL;
1266 else
1267 break;
1268 // Ok, we have a PHI of the form L op= R. Check for low
1269 // zero bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001270 computeKnownBits(R, Known2, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001271
1272 // We need to take the minimum number of known bits
Craig Topperb45eabc2017-04-26 16:39:58 +00001273 KnownBits Known3(Known);
1274 computeKnownBits(L, Known3, Depth + 1, Q);
David Greeneaebd9e02008-10-27 23:24:03 +00001275
Craig Topper8df66c62017-05-12 17:20:30 +00001276 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1277 Known3.countMinTrailingZeros()));
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001278
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001279 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(LU);
1280 if (OverflowOp && OverflowOp->hasNoSignedWrap()) {
1281 // If initial value of recurrence is nonnegative, and we are adding
1282 // a nonnegative number with nsw, the result can only be nonnegative
1283 // or poison value regardless of the number of times we execute the
1284 // add in phi recurrence. If initial value is negative and we are
1285 // adding a negative number with nsw, the result can only be
1286 // negative or poison value. Similar arguments apply to sub and mul.
1287 //
1288 // (add non-negative, non-negative) --> non-negative
1289 // (add negative, negative) --> negative
1290 if (Opcode == Instruction::Add) {
Craig Topperca48af32017-04-29 16:43:11 +00001291 if (Known2.isNonNegative() && Known3.isNonNegative())
1292 Known.makeNonNegative();
1293 else if (Known2.isNegative() && Known3.isNegative())
1294 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001295 }
1296
1297 // (sub nsw non-negative, negative) --> non-negative
1298 // (sub nsw negative, non-negative) --> negative
1299 else if (Opcode == Instruction::Sub && LL == I) {
Craig Topperca48af32017-04-29 16:43:11 +00001300 if (Known2.isNonNegative() && Known3.isNegative())
1301 Known.makeNonNegative();
1302 else if (Known2.isNegative() && Known3.isNonNegative())
1303 Known.makeNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001304 }
1305
1306 // (mul nsw non-negative, non-negative) --> non-negative
Craig Topperca48af32017-04-29 16:43:11 +00001307 else if (Opcode == Instruction::Mul && Known2.isNonNegative() &&
1308 Known3.isNonNegative())
1309 Known.makeNonNegative();
Artur Pilipenkoc6eb6bd2016-10-12 16:18:43 +00001310 }
1311
Chris Lattner965c7692008-06-02 01:18:21 +00001312 break;
1313 }
1314 }
1315 }
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001316
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001317 // Unreachable blocks may have zero-operand PHI nodes.
1318 if (P->getNumIncomingValues() == 0)
Jay Foad5a29c362014-05-15 12:12:55 +00001319 break;
Nick Lewyckyac0b62c2011-02-10 23:54:10 +00001320
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001321 // Otherwise take the unions of the known bit sets of the operands,
1322 // taking conservative care to avoid excessive recursion.
Craig Topperb45eabc2017-04-26 16:39:58 +00001323 if (Depth < MaxDepth - 1 && !Known.Zero && !Known.One) {
Duncan Sands7dc3d472011-03-08 12:39:03 +00001324 // Skip if every incoming value references to ourself.
Nuno Lopes0d44a502012-07-03 21:15:40 +00001325 if (dyn_cast_or_null<UndefValue>(P->hasConstantValue()))
Duncan Sands7dc3d472011-03-08 12:39:03 +00001326 break;
1327
Craig Topperb45eabc2017-04-26 16:39:58 +00001328 Known.Zero.setAllBits();
1329 Known.One.setAllBits();
Pete Cooper833f34d2015-05-12 20:05:31 +00001330 for (Value *IncValue : P->incoming_values()) {
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001331 // Skip direct self references.
Pete Cooper833f34d2015-05-12 20:05:31 +00001332 if (IncValue == P) continue;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001333
Craig Topperb45eabc2017-04-26 16:39:58 +00001334 Known2 = KnownBits(BitWidth);
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001335 // Recurse, but cap the recursion to one level, because we don't
1336 // want to waste time spinning around in loops.
Craig Topperb45eabc2017-04-26 16:39:58 +00001337 computeKnownBits(IncValue, Known2, MaxDepth - 1, Q);
1338 Known.Zero &= Known2.Zero;
1339 Known.One &= Known2.One;
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001340 // If all bits have been ruled out, there's no need to check
1341 // more operands.
Craig Topperb45eabc2017-04-26 16:39:58 +00001342 if (!Known.Zero && !Known.One)
Dan Gohmanbf0002e2009-05-21 02:28:33 +00001343 break;
1344 }
1345 }
Chris Lattner965c7692008-06-02 01:18:21 +00001346 break;
1347 }
1348 case Instruction::Call:
Jingyue Wu37fcb592014-06-19 16:50:16 +00001349 case Instruction::Invoke:
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001350 // If range metadata is attached to this call, set known bits from that,
1351 // and then intersect with known bits based on other properties of the
1352 // function.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001353 if (MDNode *MD = cast<Instruction>(I)->getMetadata(LLVMContext::MD_range))
Craig Topperf42b23f2017-04-28 06:28:56 +00001354 computeKnownBitsFromRangeMetadata(*MD, Known);
Pete Cooper35b00d52016-08-13 01:05:32 +00001355 if (const Value *RV = ImmutableCallSite(I).getReturnedArgOperand()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00001356 computeKnownBits(RV, Known2, Depth + 1, Q);
1357 Known.Zero |= Known2.Zero;
1358 Known.One |= Known2.One;
Hal Finkel6fd5e1f2016-07-11 02:25:14 +00001359 }
Pete Cooper35b00d52016-08-13 01:05:32 +00001360 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chris Lattner965c7692008-06-02 01:18:21 +00001361 switch (II->getIntrinsicID()) {
1362 default: break;
Chad Rosier85204292017-01-17 17:23:51 +00001363 case Intrinsic::bitreverse:
Craig Topperb45eabc2017-04-26 16:39:58 +00001364 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1365 Known.Zero |= Known2.Zero.reverseBits();
1366 Known.One |= Known2.One.reverseBits();
Chad Rosier85204292017-01-17 17:23:51 +00001367 break;
Philip Reames675418e2015-10-06 20:20:45 +00001368 case Intrinsic::bswap:
Craig Topperb45eabc2017-04-26 16:39:58 +00001369 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1370 Known.Zero |= Known2.Zero.byteSwap();
1371 Known.One |= Known2.One.byteSwap();
Philip Reames675418e2015-10-06 20:20:45 +00001372 break;
Craig Topper868813f2017-05-08 17:22:34 +00001373 case Intrinsic::ctlz: {
1374 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1375 // If we have a known 1, its position is our upper bound.
1376 unsigned PossibleLZ = Known2.One.countLeadingZeros();
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001377 // If this call is undefined for 0, the result will be less than 2^n.
1378 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
Craig Topper868813f2017-05-08 17:22:34 +00001379 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
1380 unsigned LowBits = Log2_32(PossibleLZ)+1;
1381 Known.Zero.setBitsFrom(LowBits);
1382 break;
1383 }
1384 case Intrinsic::cttz: {
1385 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1386 // If we have a known 1, its position is our upper bound.
1387 unsigned PossibleTZ = Known2.One.countTrailingZeros();
1388 // If this call is undefined for 0, the result will be less than 2^n.
1389 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1390 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
1391 unsigned LowBits = Log2_32(PossibleTZ)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001392 Known.Zero.setBitsFrom(LowBits);
Benjamin Kramer4ee57472011-12-24 17:31:46 +00001393 break;
1394 }
1395 case Intrinsic::ctpop: {
Craig Topperb45eabc2017-04-26 16:39:58 +00001396 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001397 // We can bound the space the count needs. Also, bits known to be zero
1398 // can't contribute to the population.
Craig Topper8df66c62017-05-12 17:20:30 +00001399 unsigned BitsPossiblySet = Known2.countMaxPopulation();
Craig Topper66df10f2017-04-14 06:43:34 +00001400 unsigned LowBits = Log2_32(BitsPossiblySet)+1;
Craig Topperb45eabc2017-04-26 16:39:58 +00001401 Known.Zero.setBitsFrom(LowBits);
Philip Reamesddcf6b32015-10-14 22:42:12 +00001402 // TODO: we could bound KnownOne using the lower bound on the number
1403 // of bits which might be set provided by popcnt KnownOne2.
Chris Lattner965c7692008-06-02 01:18:21 +00001404 break;
1405 }
Chad Rosierb3628842011-05-26 23:13:19 +00001406 case Intrinsic::x86_sse42_crc32_64_64:
Craig Topperb45eabc2017-04-26 16:39:58 +00001407 Known.Zero.setBitsFrom(32);
Evan Cheng2a746bf2011-05-22 18:25:30 +00001408 break;
Chris Lattner965c7692008-06-02 01:18:21 +00001409 }
1410 }
1411 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00001412 case Instruction::ExtractElement:
1413 // Look through extract element. At the moment we keep this simple and skip
1414 // tracking the specific element. But at least we might find information
1415 // valid for all elements of the vector (for example if vector is sign
1416 // extended, shifted, etc).
Craig Topperb45eabc2017-04-26 16:39:58 +00001417 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
Bjorn Pettersson39616032016-10-06 09:56:21 +00001418 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001419 case Instruction::ExtractValue:
1420 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001421 const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001422 if (EVI->getNumIndices() != 1) break;
1423 if (EVI->getIndices()[0] == 0) {
1424 switch (II->getIntrinsicID()) {
1425 default: break;
1426 case Intrinsic::uadd_with_overflow:
1427 case Intrinsic::sadd_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001428 computeKnownBitsAddSub(true, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001429 II->getArgOperand(1), false, Known, Known2,
1430 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001431 break;
1432 case Intrinsic::usub_with_overflow:
1433 case Intrinsic::ssub_with_overflow:
Jay Foada0653a32014-05-14 21:14:37 +00001434 computeKnownBitsAddSub(false, II->getArgOperand(0),
Craig Topperb45eabc2017-04-26 16:39:58 +00001435 II->getArgOperand(1), false, Known, Known2,
1436 Depth, Q);
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001437 break;
Nick Lewyckyfa306072012-03-18 23:28:48 +00001438 case Intrinsic::umul_with_overflow:
1439 case Intrinsic::smul_with_overflow:
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001440 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
Craig Topperb45eabc2017-04-26 16:39:58 +00001441 Known, Known2, Depth, Q);
Nick Lewyckyfa306072012-03-18 23:28:48 +00001442 break;
Nick Lewyckyfea3e002012-03-09 09:23:50 +00001443 }
1444 }
1445 }
Chris Lattner965c7692008-06-02 01:18:21 +00001446 }
Jingyue Wu12b0c282015-06-15 05:46:29 +00001447}
1448
1449/// Determine which bits of V are known to be either zero or one and return
Craig Topper6e11a052017-05-08 16:22:48 +00001450/// them.
1451KnownBits computeKnownBits(const Value *V, unsigned Depth, const Query &Q) {
1452 KnownBits Known(getBitWidth(V->getType(), Q.DL));
1453 computeKnownBits(V, Known, Depth, Q);
1454 return Known;
1455}
1456
1457/// Determine which bits of V are known to be either zero or one and return
Craig Topperb45eabc2017-04-26 16:39:58 +00001458/// them in the Known bit set.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001459///
1460/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
1461/// we cannot optimize based on the assumption that it is zero without changing
1462/// it to be an explicit zero. If we don't change it to zero, other code could
1463/// optimized based on the contradictory assumption that it is non-zero.
1464/// Because instcombine aggressively folds operations with undef args anyway,
1465/// this won't lose us code quality.
1466///
1467/// This function is defined on values with integer type, values with pointer
1468/// type, and vectors of integers. In the case
1469/// where V is a vector, known zero, and known one values are the
1470/// same width as the vector element, and the bit is set only if it is true
1471/// for all of the elements in the vector.
Craig Topperb45eabc2017-04-26 16:39:58 +00001472void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
1473 const Query &Q) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001474 assert(V && "No Value?");
1475 assert(Depth <= MaxDepth && "Limit Search Depth");
Craig Topperb45eabc2017-04-26 16:39:58 +00001476 unsigned BitWidth = Known.getBitWidth();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001477
Craig Topperfde47232017-07-09 07:04:03 +00001478 assert((V->getType()->isIntOrIntVectorTy(BitWidth) ||
Craig Topper95d23472017-07-09 07:04:00 +00001479 V->getType()->isPtrOrPtrVectorTy()) &&
Sanjay Pateldba8b4c2016-06-02 20:01:37 +00001480 "Not integer or pointer type!");
Craig Topperfde47232017-07-09 07:04:03 +00001481 assert(Q.DL.getTypeSizeInBits(V->getType()->getScalarType()) == BitWidth &&
Craig Topperb45eabc2017-04-26 16:39:58 +00001482 "V and Known should have same BitWidth");
Craig Topperd73c6b42017-03-23 07:06:39 +00001483 (void)BitWidth;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001484
Sanjay Patelc96f6db2016-09-16 21:20:36 +00001485 const APInt *C;
1486 if (match(V, m_APInt(C))) {
1487 // We know all of the bits for a scalar constant or a splat vector constant!
Craig Topperb45eabc2017-04-26 16:39:58 +00001488 Known.One = *C;
1489 Known.Zero = ~Known.One;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001490 return;
1491 }
1492 // Null and aggregate-zero are all-zeros.
Sanjay Patele8dc0902016-05-23 17:57:54 +00001493 if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001494 Known.setAllZero();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001495 return;
1496 }
1497 // Handle a constant vector by taking the intersection of the known bits of
David Majnemer3918cdd2016-05-04 06:13:33 +00001498 // each element.
Pete Cooper35b00d52016-08-13 01:05:32 +00001499 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) {
Jingyue Wu12b0c282015-06-15 05:46:29 +00001500 // We know that CDS must be a vector of integers. Take the intersection of
1501 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001502 Known.Zero.setAllBits(); Known.One.setAllBits();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001503 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Craig Topperb98ee582017-10-21 16:35:39 +00001504 APInt Elt = CDS->getElementAsAPInt(i);
Craig Topperb45eabc2017-04-26 16:39:58 +00001505 Known.Zero &= ~Elt;
1506 Known.One &= Elt;
Jingyue Wu12b0c282015-06-15 05:46:29 +00001507 }
1508 return;
1509 }
1510
Pete Cooper35b00d52016-08-13 01:05:32 +00001511 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
David Majnemer3918cdd2016-05-04 06:13:33 +00001512 // We know that CV must be a vector of integers. Take the intersection of
1513 // each element.
Craig Topperb45eabc2017-04-26 16:39:58 +00001514 Known.Zero.setAllBits(); Known.One.setAllBits();
David Majnemer3918cdd2016-05-04 06:13:33 +00001515 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1516 Constant *Element = CV->getAggregateElement(i);
1517 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
1518 if (!ElementCI) {
Craig Topperf0aeee02017-05-05 17:36:09 +00001519 Known.resetAll();
David Majnemer3918cdd2016-05-04 06:13:33 +00001520 return;
1521 }
Craig Topperb98ee582017-10-21 16:35:39 +00001522 const APInt &Elt = ElementCI->getValue();
Craig Topperb45eabc2017-04-26 16:39:58 +00001523 Known.Zero &= ~Elt;
1524 Known.One &= Elt;
David Majnemer3918cdd2016-05-04 06:13:33 +00001525 }
1526 return;
1527 }
1528
Jingyue Wu12b0c282015-06-15 05:46:29 +00001529 // Start out not knowing anything.
Craig Topperf0aeee02017-05-05 17:36:09 +00001530 Known.resetAll();
Jingyue Wu12b0c282015-06-15 05:46:29 +00001531
Duncan P. N. Exon Smithb1b208a2016-09-24 20:42:02 +00001532 // We can't imply anything about undefs.
1533 if (isa<UndefValue>(V))
1534 return;
1535
1536 // There's no point in looking through other users of ConstantData for
1537 // assumptions. Confirm that we've handled them all.
1538 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
1539
Jingyue Wu12b0c282015-06-15 05:46:29 +00001540 // Limit search depth.
1541 // All recursive calls that increase depth must come after this.
1542 if (Depth == MaxDepth)
1543 return;
1544
1545 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
1546 // the bits of its aliasee.
Pete Cooper35b00d52016-08-13 01:05:32 +00001547 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00001548 if (!GA->isInterposable())
Craig Topperb45eabc2017-04-26 16:39:58 +00001549 computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001550 return;
1551 }
1552
Pete Cooper35b00d52016-08-13 01:05:32 +00001553 if (const Operator *I = dyn_cast<Operator>(V))
Craig Topperb45eabc2017-04-26 16:39:58 +00001554 computeKnownBitsFromOperator(I, Known, Depth, Q);
Sanjay Patela67559c2015-09-25 20:12:43 +00001555
Craig Topperb45eabc2017-04-26 16:39:58 +00001556 // Aligned pointers have trailing zeros - refine Known.Zero set
Artur Pilipenko029d8532015-09-30 11:55:45 +00001557 if (V->getType()->isPointerTy()) {
Artur Pilipenkoae51afc2016-02-24 12:25:10 +00001558 unsigned Align = V->getPointerAlignment(Q.DL);
Artur Pilipenko029d8532015-09-30 11:55:45 +00001559 if (Align)
Craig Topperb45eabc2017-04-26 16:39:58 +00001560 Known.Zero.setLowBits(countTrailingZeros(Align));
Artur Pilipenko029d8532015-09-30 11:55:45 +00001561 }
1562
Craig Topperb45eabc2017-04-26 16:39:58 +00001563 // computeKnownBitsFromAssume strictly refines Known.
1564 // Therefore, we run them after computeKnownBitsFromOperator.
Jingyue Wu12b0c282015-06-15 05:46:29 +00001565
1566 // Check whether a nearby assume intrinsic can determine some known bits.
Craig Topperb45eabc2017-04-26 16:39:58 +00001567 computeKnownBitsFromAssume(V, Known, Depth, Q);
Jingyue Wu12b0c282015-06-15 05:46:29 +00001568
Craig Topperb45eabc2017-04-26 16:39:58 +00001569 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
Chris Lattner965c7692008-06-02 01:18:21 +00001570}
1571
Sanjay Patelaee84212014-11-04 16:27:42 +00001572/// Return true if the given value is known to have exactly one
Duncan Sandsd3951082011-01-25 09:38:29 +00001573/// bit set when defined. For vectors return true if every element is known to
Sanjay Patelaee84212014-11-04 16:27:42 +00001574/// be a power of two when defined. Supports values with integer or pointer
Duncan Sandsd3951082011-01-25 09:38:29 +00001575/// types and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001576bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001577 const Query &Q) {
Craig Topper7227eba2017-08-21 22:56:12 +00001578 assert(Depth <= MaxDepth && "Limit Search Depth");
1579
Pete Cooper35b00d52016-08-13 01:05:32 +00001580 if (const Constant *C = dyn_cast<Constant>(V)) {
Duncan Sandsba286d72011-10-26 20:55:21 +00001581 if (C->isNullValue())
1582 return OrZero;
Sanjay Patele2e89ef2016-05-22 15:41:53 +00001583
1584 const APInt *ConstIntOrConstSplatInt;
1585 if (match(C, m_APInt(ConstIntOrConstSplatInt)))
1586 return ConstIntOrConstSplatInt->isPowerOf2();
Duncan Sandsba286d72011-10-26 20:55:21 +00001587 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001588
1589 // 1 << X is clearly a power of two if the one is not shifted off the end. If
1590 // it is shifted off the end then the result is undefined.
1591 if (match(V, m_Shl(m_One(), m_Value())))
1592 return true;
1593
Craig Topperbcfd2d12017-04-20 16:56:25 +00001594 // (signmask) >>l X is clearly a power of two if the one is not shifted off
1595 // the bottom. If it is shifted off the bottom then the result is undefined.
1596 if (match(V, m_LShr(m_SignMask(), m_Value())))
Duncan Sandsd3951082011-01-25 09:38:29 +00001597 return true;
1598
1599 // The remaining tests are all recursive, so bail out if we hit the limit.
1600 if (Depth++ == MaxDepth)
1601 return false;
1602
Craig Topper9f008862014-04-15 04:59:12 +00001603 Value *X = nullptr, *Y = nullptr;
Sanjay Patel41160c22015-12-30 22:40:52 +00001604 // A shift left or a logical shift right of a power of two is a power of two
1605 // or zero.
Duncan Sands985ba632011-10-28 18:30:05 +00001606 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
Sanjay Patel41160c22015-12-30 22:40:52 +00001607 match(V, m_LShr(m_Value(X), m_Value()))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001608 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
Duncan Sands985ba632011-10-28 18:30:05 +00001609
Pete Cooper35b00d52016-08-13 01:05:32 +00001610 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001611 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001612
Pete Cooper35b00d52016-08-13 01:05:32 +00001613 if (const SelectInst *SI = dyn_cast<SelectInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001614 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
1615 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
Duncan Sandsba286d72011-10-26 20:55:21 +00001616
Duncan Sandsba286d72011-10-26 20:55:21 +00001617 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
1618 // A power of two and'd with anything is a power of two or zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001619 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
1620 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
Duncan Sandsba286d72011-10-26 20:55:21 +00001621 return true;
1622 // X & (-X) is always a power of two or zero.
1623 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
1624 return true;
1625 return false;
1626 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001627
David Majnemerb7d54092013-07-30 21:01:36 +00001628 // Adding a power-of-two or zero to the same power-of-two or zero yields
1629 // either the original power-of-two, a larger power-of-two or zero.
1630 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001631 const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
David Majnemerb7d54092013-07-30 21:01:36 +00001632 if (OrZero || VOBO->hasNoUnsignedWrap() || VOBO->hasNoSignedWrap()) {
1633 if (match(X, m_And(m_Specific(Y), m_Value())) ||
1634 match(X, m_And(m_Value(), m_Specific(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001635 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001636 return true;
1637 if (match(Y, m_And(m_Specific(X), m_Value())) ||
1638 match(Y, m_And(m_Value(), m_Specific(X))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001639 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
David Majnemerb7d54092013-07-30 21:01:36 +00001640 return true;
1641
1642 unsigned BitWidth = V->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00001643 KnownBits LHSBits(BitWidth);
1644 computeKnownBits(X, LHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001645
Craig Topperb45eabc2017-04-26 16:39:58 +00001646 KnownBits RHSBits(BitWidth);
1647 computeKnownBits(Y, RHSBits, Depth, Q);
David Majnemerb7d54092013-07-30 21:01:36 +00001648 // If i8 V is a power of two or zero:
1649 // ZeroBits: 1 1 1 0 1 1 1 1
1650 // ~ZeroBits: 0 0 0 1 0 0 0 0
Craig Topperb45eabc2017-04-26 16:39:58 +00001651 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
David Majnemerb7d54092013-07-30 21:01:36 +00001652 // If OrZero isn't set, we cannot give back a zero result.
1653 // Make sure either the LHS or RHS has a bit set.
Craig Topperb45eabc2017-04-26 16:39:58 +00001654 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
David Majnemerb7d54092013-07-30 21:01:36 +00001655 return true;
1656 }
1657 }
David Majnemerbeab5672013-05-18 19:30:37 +00001658
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001659 // An exact divide or right shift can only shift off zero bits, so the result
Nick Lewyckyf0469af2011-03-21 21:40:32 +00001660 // is a power of two only if the first operand is a power of two and not
1661 // copying a sign bit (sdiv int_min, 2).
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001662 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
1663 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
Hal Finkel60db0582014-09-07 18:57:58 +00001664 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001665 Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001666 }
1667
Duncan Sandsd3951082011-01-25 09:38:29 +00001668 return false;
1669}
1670
Chandler Carruth80d3e562012-12-07 02:08:58 +00001671/// \brief Test whether a GEP's result is known to be non-null.
1672///
1673/// Uses properties inherent in a GEP to try to determine whether it is known
1674/// to be non-null.
1675///
1676/// Currently this routine does not support vector GEPs.
Pete Cooper35b00d52016-08-13 01:05:32 +00001677static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001678 const Query &Q) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001679 if (!GEP->isInBounds() || GEP->getPointerAddressSpace() != 0)
1680 return false;
1681
1682 // FIXME: Support vector-GEPs.
1683 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
1684
1685 // If the base pointer is non-null, we cannot walk to a null address with an
1686 // inbounds GEP in address space zero.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001687 if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001688 return true;
1689
Chandler Carruth80d3e562012-12-07 02:08:58 +00001690 // Walk the GEP operands and see if any operand introduces a non-zero offset.
1691 // If so, then the GEP cannot produce a null pointer, as doing so would
1692 // inherently violate the inbounds contract within address space zero.
1693 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1694 GTI != GTE; ++GTI) {
1695 // Struct types are easy -- they must always be indexed by a constant.
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001696 if (StructType *STy = GTI.getStructTypeOrNull()) {
Chandler Carruth80d3e562012-12-07 02:08:58 +00001697 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
1698 unsigned ElementIdx = OpC->getZExtValue();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001699 const StructLayout *SL = Q.DL.getStructLayout(STy);
Chandler Carruth80d3e562012-12-07 02:08:58 +00001700 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
1701 if (ElementOffset > 0)
1702 return true;
1703 continue;
1704 }
1705
1706 // If we have a zero-sized type, the index doesn't matter. Keep looping.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001707 if (Q.DL.getTypeAllocSize(GTI.getIndexedType()) == 0)
Chandler Carruth80d3e562012-12-07 02:08:58 +00001708 continue;
1709
1710 // Fast path the constant operand case both for efficiency and so we don't
1711 // increment Depth when just zipping down an all-constant GEP.
1712 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
1713 if (!OpC->isZero())
1714 return true;
1715 continue;
1716 }
1717
1718 // We post-increment Depth here because while isKnownNonZero increments it
1719 // as well, when we pop back up that increment won't persist. We don't want
1720 // to recurse 10k times just because we have 10k GEP operands. We don't
1721 // bail completely out because we want to handle constant GEPs regardless
1722 // of depth.
1723 if (Depth++ >= MaxDepth)
1724 continue;
1725
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001726 if (isKnownNonZero(GTI.getOperand(), Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001727 return true;
1728 }
1729
1730 return false;
1731}
1732
Nuno Lopes404f1062017-09-09 18:23:11 +00001733static bool isKnownNonNullFromDominatingCondition(const Value *V,
1734 const Instruction *CtxI,
1735 const DominatorTree *DT) {
1736 assert(V->getType()->isPointerTy() && "V must be pointer type");
1737 assert(!isa<ConstantData>(V) && "Did not expect ConstantPointerNull");
1738
1739 if (!CtxI || !DT)
1740 return false;
1741
1742 unsigned NumUsesExplored = 0;
1743 for (auto *U : V->users()) {
1744 // Avoid massive lists
1745 if (NumUsesExplored >= DomConditionsMaxUses)
1746 break;
1747 NumUsesExplored++;
1748
1749 // If the value is used as an argument to a call or invoke, then argument
1750 // attributes may provide an answer about null-ness.
1751 if (auto CS = ImmutableCallSite(U))
1752 if (auto *CalledFunc = CS.getCalledFunction())
1753 for (const Argument &Arg : CalledFunc->args())
1754 if (CS.getArgOperand(Arg.getArgNo()) == V &&
1755 Arg.hasNonNullAttr() && DT->dominates(CS.getInstruction(), CtxI))
1756 return true;
1757
1758 // Consider only compare instructions uniquely controlling a branch
1759 CmpInst::Predicate Pred;
1760 if (!match(const_cast<User *>(U),
1761 m_c_ICmp(Pred, m_Specific(V), m_Zero())) ||
1762 (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE))
1763 continue;
1764
1765 for (auto *CmpU : U->users()) {
1766 if (const BranchInst *BI = dyn_cast<BranchInst>(CmpU)) {
1767 assert(BI->isConditional() && "uses a comparison!");
1768
1769 BasicBlock *NonNullSuccessor =
1770 BI->getSuccessor(Pred == ICmpInst::ICMP_EQ ? 1 : 0);
1771 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
1772 if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
1773 return true;
1774 } else if (Pred == ICmpInst::ICMP_NE &&
1775 match(CmpU, m_Intrinsic<Intrinsic::experimental_guard>()) &&
1776 DT->dominates(cast<Instruction>(CmpU), CtxI)) {
1777 return true;
1778 }
1779 }
1780 }
1781
1782 return false;
1783}
1784
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001785/// Does the 'Range' metadata (which must be a valid MD_range operand list)
1786/// ensure that the value it's attached to is never Value? 'RangeType' is
1787/// is the type of the value described by the range.
Pete Cooper35b00d52016-08-13 01:05:32 +00001788static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001789 const unsigned NumRanges = Ranges->getNumOperands() / 2;
1790 assert(NumRanges >= 1);
1791 for (unsigned i = 0; i < NumRanges; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001792 ConstantInt *Lower =
1793 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
1794 ConstantInt *Upper =
1795 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001796 ConstantRange Range(Lower->getValue(), Upper->getValue());
1797 if (Range.contains(Value))
1798 return false;
1799 }
1800 return true;
1801}
1802
Sanjay Patel97e4b9872017-02-12 15:35:34 +00001803/// Return true if the given value is known to be non-zero when defined. For
1804/// vectors, return true if every element is known to be non-zero when
1805/// defined. For pointers, if the context instruction and dominator tree are
1806/// specified, perform context-sensitive analysis and return true if the
1807/// pointer couldn't possibly be null at the specified instruction.
1808/// Supports values with integer or pointer type and vectors of integers.
Pete Cooper35b00d52016-08-13 01:05:32 +00001809bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q) {
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001810 if (auto *C = dyn_cast<Constant>(V)) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001811 if (C->isNullValue())
1812 return false;
1813 if (isa<ConstantInt>(C))
1814 // Must be non-zero due to null test above.
1815 return true;
Sanjay Patel23019d12016-05-24 14:18:49 +00001816
1817 // For constant vectors, check that all elements are undefined or known
1818 // non-zero to determine that the whole vector is known non-zero.
1819 if (auto *VecTy = dyn_cast<VectorType>(C->getType())) {
1820 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
1821 Constant *Elt = C->getAggregateElement(i);
1822 if (!Elt || Elt->isNullValue())
1823 return false;
1824 if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
1825 return false;
1826 }
1827 return true;
1828 }
1829
Nuno Lopes404f1062017-09-09 18:23:11 +00001830 // A global variable in address space 0 is non null unless extern weak
1831 // or an absolute symbol reference. Other address spaces may have null as a
1832 // valid address for a global, so we can't assume anything.
1833 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1834 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
1835 GV->getType()->getAddressSpace() == 0)
1836 return true;
1837 } else
1838 return false;
Duncan Sandsd3951082011-01-25 09:38:29 +00001839 }
1840
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001841 if (auto *I = dyn_cast<Instruction>(V)) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001842 if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range)) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001843 // If the possible ranges don't contain zero, then the value is
1844 // definitely non-zero.
Sanjay Patel8ec7e7c2016-05-22 16:07:20 +00001845 if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
Philip Reames4cb4d3e2014-10-30 20:25:19 +00001846 const APInt ZeroValue(Ty->getBitWidth(), 0);
1847 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
1848 return true;
1849 }
1850 }
1851 }
1852
Nuno Lopes404f1062017-09-09 18:23:11 +00001853 // Check for pointer simplifications.
1854 if (V->getType()->isPointerTy()) {
1855 // Alloca never returns null, malloc might.
1856 if (isa<AllocaInst>(V) && Q.DL.getAllocaAddrSpace() == 0)
1857 return true;
1858
1859 // A byval, inalloca, or nonnull argument is never null.
1860 if (const Argument *A = dyn_cast<Argument>(V))
1861 if (A->hasByValOrInAllocaAttr() || A->hasNonNullAttr())
1862 return true;
1863
1864 // A Load tagged with nonnull metadata is never null.
1865 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
1866 if (LI->getMetadata(LLVMContext::MD_nonnull))
1867 return true;
1868
1869 if (auto CS = ImmutableCallSite(V))
1870 if (CS.isReturnNonNull())
1871 return true;
1872 }
1873
Duncan Sandsd3951082011-01-25 09:38:29 +00001874 // The remaining tests are all recursive, so bail out if we hit the limit.
Duncan Sands7cb61e52011-10-27 19:16:21 +00001875 if (Depth++ >= MaxDepth)
Duncan Sandsd3951082011-01-25 09:38:29 +00001876 return false;
1877
Nuno Lopes404f1062017-09-09 18:23:11 +00001878 // Check for recursive pointer simplifications.
Chandler Carruth80d3e562012-12-07 02:08:58 +00001879 if (V->getType()->isPointerTy()) {
Nuno Lopes404f1062017-09-09 18:23:11 +00001880 if (isKnownNonNullFromDominatingCondition(V, Q.CxtI, Q.DT))
Sanjoy Das6082c1a2016-05-07 02:08:15 +00001881 return true;
Nuno Lopes404f1062017-09-09 18:23:11 +00001882
Pete Cooper35b00d52016-08-13 01:05:32 +00001883 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001884 if (isGEPKnownNonNull(GEP, Depth, Q))
Chandler Carruth80d3e562012-12-07 02:08:58 +00001885 return true;
1886 }
1887
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001888 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001889
1890 // X | Y != 0 if X != 0 or Y != 0.
Craig Topper9f008862014-04-15 04:59:12 +00001891 Value *X = nullptr, *Y = nullptr;
Duncan Sandsd3951082011-01-25 09:38:29 +00001892 if (match(V, m_Or(m_Value(X), m_Value(Y))))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001893 return isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001894
1895 // ext X != 0 if X != 0.
1896 if (isa<SExtInst>(V) || isa<ZExtInst>(V))
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001897 return isKnownNonZero(cast<Instruction>(V)->getOperand(0), Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001898
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001899 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
Duncan Sandsd3951082011-01-25 09:38:29 +00001900 // if the lowest bit is shifted off the end.
Craig Topper6b3940a2017-05-03 22:25:19 +00001901 if (match(V, m_Shl(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001902 // shl nuw can't remove any non-zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00001903 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001904 if (BO->hasNoUnsignedWrap())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001905 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001906
Craig Topperb45eabc2017-04-26 16:39:58 +00001907 KnownBits Known(BitWidth);
1908 computeKnownBits(X, Known, Depth, Q);
1909 if (Known.One[0])
Duncan Sandsd3951082011-01-25 09:38:29 +00001910 return true;
1911 }
Duncan Sands2e9e4f12011-01-29 13:27:00 +00001912 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
Duncan Sandsd3951082011-01-25 09:38:29 +00001913 // defined if the sign bit is shifted off the end.
1914 else if (match(V, m_Shr(m_Value(X), m_Value(Y)))) {
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001915 // shr exact can only shift out zero bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00001916 const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001917 if (BO->isExact())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001918 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001919
Craig Topper6e11a052017-05-08 16:22:48 +00001920 KnownBits Known = computeKnownBits(X, Depth, Q);
1921 if (Known.isNegative())
Duncan Sandsd3951082011-01-25 09:38:29 +00001922 return true;
James Molloyb6be1eb2015-09-24 16:06:32 +00001923
1924 // If the shifter operand is a constant, and all of the bits shifted
1925 // out are known to be zero, and X is known non-zero then at least one
1926 // non-zero bit must remain.
1927 if (ConstantInt *Shift = dyn_cast<ConstantInt>(Y)) {
James Molloyb6be1eb2015-09-24 16:06:32 +00001928 auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
1929 // Is there a known one in the portion not shifted out?
Craig Topper8df66c62017-05-12 17:20:30 +00001930 if (Known.countMaxLeadingZeros() < BitWidth - ShiftVal)
James Molloyb6be1eb2015-09-24 16:06:32 +00001931 return true;
1932 // Are all the bits to be shifted out known zero?
NAKAMURA Takumi76bab1f2017-07-11 02:31:51 +00001933 if (Known.countMinTrailingZeros() >= ShiftVal)
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001934 return isKnownNonZero(X, Depth, Q);
James Molloyb6be1eb2015-09-24 16:06:32 +00001935 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001936 }
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001937 // div exact can only produce a zero if the dividend is zero.
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001938 else if (match(V, m_Exact(m_IDiv(m_Value(X), m_Value())))) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001939 return isKnownNonZero(X, Depth, Q);
Nick Lewyckyc9aab852011-02-28 08:02:21 +00001940 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001941 // X + Y.
1942 else if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
Craig Topper6e11a052017-05-08 16:22:48 +00001943 KnownBits XKnown = computeKnownBits(X, Depth, Q);
1944 KnownBits YKnown = computeKnownBits(Y, Depth, Q);
Duncan Sandsd3951082011-01-25 09:38:29 +00001945
1946 // If X and Y are both non-negative (as signed values) then their sum is not
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001947 // zero unless both X and Y are zero.
Craig Topper6e11a052017-05-08 16:22:48 +00001948 if (XKnown.isNonNegative() && YKnown.isNonNegative())
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001949 if (isKnownNonZero(X, Depth, Q) || isKnownNonZero(Y, Depth, Q))
Duncan Sands9e9d5b22011-01-25 15:14:15 +00001950 return true;
Duncan Sandsd3951082011-01-25 09:38:29 +00001951
1952 // If X and Y are both negative (as signed values) then their sum is not
1953 // zero unless both X and Y equal INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00001954 if (XKnown.isNegative() && YKnown.isNegative()) {
Duncan Sandsd3951082011-01-25 09:38:29 +00001955 APInt Mask = APInt::getSignedMaxValue(BitWidth);
1956 // The sign bit of X is set. If some other bit is set then X is not equal
1957 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00001958 if (XKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00001959 return true;
1960 // The sign bit of Y is set. If some other bit is set then Y is not equal
1961 // to INT_MIN.
Craig Topper6e11a052017-05-08 16:22:48 +00001962 if (YKnown.One.intersects(Mask))
Duncan Sandsd3951082011-01-25 09:38:29 +00001963 return true;
1964 }
1965
1966 // The sum of a non-negative number and a power of two is not zero.
Craig Topper6e11a052017-05-08 16:22:48 +00001967 if (XKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001968 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001969 return true;
Craig Topper6e11a052017-05-08 16:22:48 +00001970 if (YKnown.isNonNegative() &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001971 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001972 return true;
1973 }
Duncan Sands7cb61e52011-10-27 19:16:21 +00001974 // X * Y.
1975 else if (match(V, m_Mul(m_Value(X), m_Value(Y)))) {
Pete Cooper35b00d52016-08-13 01:05:32 +00001976 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
Duncan Sands7cb61e52011-10-27 19:16:21 +00001977 // If X and Y are non-zero then so is X * Y as long as the multiplication
1978 // does not overflow.
1979 if ((BO->hasNoSignedWrap() || BO->hasNoUnsignedWrap()) &&
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001980 isKnownNonZero(X, Depth, Q) && isKnownNonZero(Y, Depth, Q))
Duncan Sands7cb61e52011-10-27 19:16:21 +00001981 return true;
1982 }
Duncan Sandsd3951082011-01-25 09:38:29 +00001983 // (C ? X : Y) != 0 if X != 0 and Y != 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00001984 else if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00001985 if (isKnownNonZero(SI->getTrueValue(), Depth, Q) &&
1986 isKnownNonZero(SI->getFalseValue(), Depth, Q))
Duncan Sandsd3951082011-01-25 09:38:29 +00001987 return true;
1988 }
James Molloy897048b2015-09-29 14:08:45 +00001989 // PHI
Pete Cooper35b00d52016-08-13 01:05:32 +00001990 else if (const PHINode *PN = dyn_cast<PHINode>(V)) {
James Molloy897048b2015-09-29 14:08:45 +00001991 // Try and detect a recurrence that monotonically increases from a
1992 // starting value, as these are common as induction variables.
1993 if (PN->getNumIncomingValues() == 2) {
1994 Value *Start = PN->getIncomingValue(0);
1995 Value *Induction = PN->getIncomingValue(1);
1996 if (isa<ConstantInt>(Induction) && !isa<ConstantInt>(Start))
1997 std::swap(Start, Induction);
1998 if (ConstantInt *C = dyn_cast<ConstantInt>(Start)) {
1999 if (!C->isZero() && !C->isNegative()) {
2000 ConstantInt *X;
2001 if ((match(Induction, m_NSWAdd(m_Specific(PN), m_ConstantInt(X))) ||
2002 match(Induction, m_NUWAdd(m_Specific(PN), m_ConstantInt(X)))) &&
2003 !X->isNegative())
2004 return true;
2005 }
2006 }
2007 }
Jun Bum Limca832662016-02-01 17:03:07 +00002008 // Check if all incoming values are non-zero constant.
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002009 bool AllNonZeroConstants = llvm::all_of(PN->operands(), [](Value *V) {
Craig Topper79ab6432017-07-06 18:39:47 +00002010 return isa<ConstantInt>(V) && !cast<ConstantInt>(V)->isZero();
Jun Bum Limca832662016-02-01 17:03:07 +00002011 });
2012 if (AllNonZeroConstants)
2013 return true;
James Molloy897048b2015-09-29 14:08:45 +00002014 }
Duncan Sandsd3951082011-01-25 09:38:29 +00002015
Craig Topperb45eabc2017-04-26 16:39:58 +00002016 KnownBits Known(BitWidth);
2017 computeKnownBits(V, Known, Depth, Q);
2018 return Known.One != 0;
Duncan Sandsd3951082011-01-25 09:38:29 +00002019}
2020
James Molloy1d88d6f2015-10-22 13:18:42 +00002021/// Return true if V2 == V1 + X, where X is known non-zero.
Pete Cooper35b00d52016-08-13 01:05:32 +00002022static bool isAddOfNonZero(const Value *V1, const Value *V2, const Query &Q) {
2023 const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
James Molloy1d88d6f2015-10-22 13:18:42 +00002024 if (!BO || BO->getOpcode() != Instruction::Add)
2025 return false;
2026 Value *Op = nullptr;
2027 if (V2 == BO->getOperand(0))
2028 Op = BO->getOperand(1);
2029 else if (V2 == BO->getOperand(1))
2030 Op = BO->getOperand(0);
2031 else
2032 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002033 return isKnownNonZero(Op, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00002034}
2035
2036/// Return true if it is known that V1 != V2.
Pete Cooper35b00d52016-08-13 01:05:32 +00002037static bool isKnownNonEqual(const Value *V1, const Value *V2, const Query &Q) {
Craig Topper3002d5b2017-06-06 07:13:15 +00002038 if (V1 == V2)
James Molloy1d88d6f2015-10-22 13:18:42 +00002039 return false;
2040 if (V1->getType() != V2->getType())
2041 // We can't look through casts yet.
2042 return false;
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002043 if (isAddOfNonZero(V1, V2, Q) || isAddOfNonZero(V2, V1, Q))
James Molloy1d88d6f2015-10-22 13:18:42 +00002044 return true;
2045
Craig Topper3002d5b2017-06-06 07:13:15 +00002046 if (V1->getType()->isIntOrIntVectorTy()) {
James Molloy1d88d6f2015-10-22 13:18:42 +00002047 // Are any known bits in V1 contradictory to known bits in V2? If V1
2048 // has a known zero where V2 has a known one, they must not be equal.
Craig Topper8e662f72017-06-06 07:13:11 +00002049 KnownBits Known1 = computeKnownBits(V1, 0, Q);
2050 KnownBits Known2 = computeKnownBits(V2, 0, Q);
James Molloy1d88d6f2015-10-22 13:18:42 +00002051
Craig Topper8365df82017-06-06 07:13:09 +00002052 if (Known1.Zero.intersects(Known2.One) ||
2053 Known2.Zero.intersects(Known1.One))
James Molloy1d88d6f2015-10-22 13:18:42 +00002054 return true;
2055 }
2056 return false;
2057}
2058
Sanjay Patelaee84212014-11-04 16:27:42 +00002059/// Return true if 'V & Mask' is known to be zero. We use this predicate to
2060/// simplify operations downstream. Mask is known to be zero for bits that V
2061/// cannot have.
Chris Lattner4bc28252009-09-08 00:06:16 +00002062///
2063/// This function is defined on values with integer type, values with pointer
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002064/// type, and vectors of integers. In the case
Chris Lattner4bc28252009-09-08 00:06:16 +00002065/// where V is a vector, the mask, known zero, and known one values are the
2066/// same width as the vector element, and the bit is set only if it is true
2067/// for all of the elements in the vector.
Pete Cooper35b00d52016-08-13 01:05:32 +00002068bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002069 const Query &Q) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002070 KnownBits Known(Mask.getBitWidth());
2071 computeKnownBits(V, Known, Depth, Q);
2072 return Mask.isSubsetOf(Known.Zero);
Chris Lattner965c7692008-06-02 01:18:21 +00002073}
2074
Sanjay Patela06d9892016-06-22 19:20:59 +00002075/// For vector constants, loop over the elements and find the constant with the
2076/// minimum number of sign bits. Return 0 if the value is not a vector constant
2077/// or if any element was not analyzed; otherwise, return the count for the
2078/// element with the minimum number of sign bits.
Pete Cooper35b00d52016-08-13 01:05:32 +00002079static unsigned computeNumSignBitsVectorConstant(const Value *V,
2080 unsigned TyBits) {
2081 const auto *CV = dyn_cast<Constant>(V);
Sanjay Patela06d9892016-06-22 19:20:59 +00002082 if (!CV || !CV->getType()->isVectorTy())
2083 return 0;
Chris Lattner965c7692008-06-02 01:18:21 +00002084
Sanjay Patela06d9892016-06-22 19:20:59 +00002085 unsigned MinSignBits = TyBits;
2086 unsigned NumElts = CV->getType()->getVectorNumElements();
2087 for (unsigned i = 0; i != NumElts; ++i) {
2088 // If we find a non-ConstantInt, bail out.
2089 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
2090 if (!Elt)
2091 return 0;
2092
Craig Topper8e8b6ef2017-10-21 16:35:41 +00002093 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
Sanjay Patela06d9892016-06-22 19:20:59 +00002094 }
2095
2096 return MinSignBits;
2097}
Chris Lattner965c7692008-06-02 01:18:21 +00002098
Sanjoy Das39a684d2017-02-25 20:30:45 +00002099static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2100 const Query &Q);
2101
2102static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
2103 const Query &Q) {
2104 unsigned Result = ComputeNumSignBitsImpl(V, Depth, Q);
2105 assert(Result > 0 && "At least one sign bit needs to be present!");
2106 return Result;
2107}
2108
Sanjay Patelaee84212014-11-04 16:27:42 +00002109/// Return the number of times the sign bit of the register is replicated into
2110/// the other bits. We know that at least 1 bit is always equal to the sign bit
2111/// (itself), but other cases can give us information. For example, immediately
2112/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
Sanjay Patela06d9892016-06-22 19:20:59 +00002113/// other, so we return 3. For vectors, return the number of sign bits for the
2114/// vector element with the mininum number of known sign bits.
Sanjoy Das39a684d2017-02-25 20:30:45 +00002115static unsigned ComputeNumSignBitsImpl(const Value *V, unsigned Depth,
2116 const Query &Q) {
Craig Topper7227eba2017-08-21 22:56:12 +00002117 assert(Depth <= MaxDepth && "Limit Search Depth");
Sanjoy Das39a684d2017-02-25 20:30:45 +00002118
2119 // We return the minimum number of sign bits that are guaranteed to be present
2120 // in V, so for undef we have to conservatively return 1. We don't have the
2121 // same behavior for poison though -- that's a FIXME today.
2122
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002123 unsigned TyBits = Q.DL.getTypeSizeInBits(V->getType()->getScalarType());
Chris Lattner965c7692008-06-02 01:18:21 +00002124 unsigned Tmp, Tmp2;
2125 unsigned FirstAnswer = 1;
2126
Jay Foada0653a32014-05-14 21:14:37 +00002127 // Note that ConstantInt is handled by the general computeKnownBits case
Chris Lattner2e01a692008-06-02 18:39:07 +00002128 // below.
2129
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002130 if (Depth == MaxDepth)
Chris Lattner965c7692008-06-02 01:18:21 +00002131 return 1; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002132
Pete Cooper35b00d52016-08-13 01:05:32 +00002133 const Operator *U = dyn_cast<Operator>(V);
Dan Gohman80ca01c2009-07-17 20:47:02 +00002134 switch (Operator::getOpcode(V)) {
Chris Lattner965c7692008-06-02 01:18:21 +00002135 default: break;
2136 case Instruction::SExt:
Mon P Wangbb3eac92009-12-02 04:59:58 +00002137 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002138 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
Craig Topper1bef2c82012-12-22 19:15:35 +00002139
Nadav Rotemc99a3872015-03-06 00:23:58 +00002140 case Instruction::SDiv: {
Nadav Rotem029c5c72015-03-03 21:39:02 +00002141 const APInt *Denominator;
2142 // sdiv X, C -> adds log(C) sign bits.
2143 if (match(U->getOperand(1), m_APInt(Denominator))) {
2144
2145 // Ignore non-positive denominator.
2146 if (!Denominator->isStrictlyPositive())
2147 break;
2148
2149 // Calculate the incoming numerator bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002150 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotem029c5c72015-03-03 21:39:02 +00002151
2152 // Add floor(log(C)) bits to the numerator bits.
2153 return std::min(TyBits, NumBits + Denominator->logBase2());
2154 }
2155 break;
Nadav Rotemc99a3872015-03-06 00:23:58 +00002156 }
2157
2158 case Instruction::SRem: {
2159 const APInt *Denominator;
Sanjoy Dase561fee2015-03-25 22:33:53 +00002160 // srem X, C -> we know that the result is within [-C+1,C) when C is a
2161 // positive constant. This let us put a lower bound on the number of sign
2162 // bits.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002163 if (match(U->getOperand(1), m_APInt(Denominator))) {
2164
2165 // Ignore non-positive denominator.
2166 if (!Denominator->isStrictlyPositive())
2167 break;
2168
2169 // Calculate the incoming numerator bits. SRem by a positive constant
2170 // can't lower the number of sign bits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002171 unsigned NumrBits =
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002172 ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Nadav Rotemc99a3872015-03-06 00:23:58 +00002173
2174 // Calculate the leading sign bit constraints by examining the
Sanjoy Dase561fee2015-03-25 22:33:53 +00002175 // denominator. Given that the denominator is positive, there are two
2176 // cases:
2177 //
2178 // 1. the numerator is positive. The result range is [0,C) and [0,C) u<
2179 // (1 << ceilLogBase2(C)).
2180 //
2181 // 2. the numerator is negative. Then the result range is (-C,0] and
2182 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
2183 //
2184 // Thus a lower bound on the number of sign bits is `TyBits -
2185 // ceilLogBase2(C)`.
Nadav Rotemc99a3872015-03-06 00:23:58 +00002186
Sanjoy Dase561fee2015-03-25 22:33:53 +00002187 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
Nadav Rotemc99a3872015-03-06 00:23:58 +00002188 return std::max(NumrBits, ResBits);
2189 }
2190 break;
2191 }
Nadav Rotem029c5c72015-03-03 21:39:02 +00002192
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002193 case Instruction::AShr: {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002194 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002195 // ashr X, C -> adds C sign bits. Vectors too.
2196 const APInt *ShAmt;
2197 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Sanjoy Das39a684d2017-02-25 20:30:45 +00002198 unsigned ShAmtLimited = ShAmt->getZExtValue();
2199 if (ShAmtLimited >= TyBits)
2200 break; // Bad shift.
2201 Tmp += ShAmtLimited;
Chris Lattner965c7692008-06-02 01:18:21 +00002202 if (Tmp > TyBits) Tmp = TyBits;
2203 }
2204 return Tmp;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002205 }
2206 case Instruction::Shl: {
2207 const APInt *ShAmt;
2208 if (match(U->getOperand(1), m_APInt(ShAmt))) {
Chris Lattner965c7692008-06-02 01:18:21 +00002209 // shl destroys sign bits.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002210 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002211 Tmp2 = ShAmt->getZExtValue();
2212 if (Tmp2 >= TyBits || // Bad shift.
2213 Tmp2 >= Tmp) break; // Shifted all sign bits out.
2214 return Tmp - Tmp2;
Chris Lattner965c7692008-06-02 01:18:21 +00002215 }
2216 break;
Chris Lattner61a1d6c2012-01-26 21:37:55 +00002217 }
Chris Lattner965c7692008-06-02 01:18:21 +00002218 case Instruction::And:
2219 case Instruction::Or:
2220 case Instruction::Xor: // NOT is handled here.
2221 // Logical binary ops preserve the number of sign bits at the worst.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002222 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002223 if (Tmp != 1) {
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002224 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002225 FirstAnswer = std::min(Tmp, Tmp2);
2226 // We computed what we know about the sign bits as our first
2227 // answer. Now proceed to the generic code that uses
Jay Foada0653a32014-05-14 21:14:37 +00002228 // computeKnownBits, and pick whichever answer is better.
Chris Lattner965c7692008-06-02 01:18:21 +00002229 }
2230 break;
2231
2232 case Instruction::Select:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002233 Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002234 if (Tmp == 1) return 1; // Early out.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002235 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002236 return std::min(Tmp, Tmp2);
Craig Topper1bef2c82012-12-22 19:15:35 +00002237
Chris Lattner965c7692008-06-02 01:18:21 +00002238 case Instruction::Add:
2239 // Add can have at most one carry bit. Thus we know that the output
2240 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002241 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002242 if (Tmp == 1) return 1; // Early out.
Craig Topper1bef2c82012-12-22 19:15:35 +00002243
Chris Lattner965c7692008-06-02 01:18:21 +00002244 // Special case decrementing a value (ADD X, -1):
David Majnemera55027f2014-12-26 09:20:17 +00002245 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
Chris Lattner965c7692008-06-02 01:18:21 +00002246 if (CRHS->isAllOnesValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002247 KnownBits Known(TyBits);
2248 computeKnownBits(U->getOperand(0), Known, Depth + 1, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002249
Chris Lattner965c7692008-06-02 01:18:21 +00002250 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2251 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002252 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002253 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002254
Chris Lattner965c7692008-06-02 01:18:21 +00002255 // If we are subtracting one from a positive number, there is no carry
2256 // out of the result.
Craig Topperca48af32017-04-29 16:43:11 +00002257 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002258 return Tmp;
2259 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002260
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002261 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002262 if (Tmp2 == 1) return 1;
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002263 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002264
Chris Lattner965c7692008-06-02 01:18:21 +00002265 case Instruction::Sub:
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002266 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002267 if (Tmp2 == 1) return 1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002268
Chris Lattner965c7692008-06-02 01:18:21 +00002269 // Handle NEG.
David Majnemera55027f2014-12-26 09:20:17 +00002270 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
Chris Lattner965c7692008-06-02 01:18:21 +00002271 if (CLHS->isNullValue()) {
Craig Topperb45eabc2017-04-26 16:39:58 +00002272 KnownBits Known(TyBits);
2273 computeKnownBits(U->getOperand(1), Known, Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002274 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2275 // sign bits set.
Craig Topperb45eabc2017-04-26 16:39:58 +00002276 if ((Known.Zero | 1).isAllOnesValue())
Chris Lattner965c7692008-06-02 01:18:21 +00002277 return TyBits;
Craig Topper1bef2c82012-12-22 19:15:35 +00002278
Chris Lattner965c7692008-06-02 01:18:21 +00002279 // If the input is known to be positive (the sign bit is known clear),
2280 // the output of the NEG has the same number of sign bits as the input.
Craig Topperca48af32017-04-29 16:43:11 +00002281 if (Known.isNonNegative())
Chris Lattner965c7692008-06-02 01:18:21 +00002282 return Tmp2;
Craig Topper1bef2c82012-12-22 19:15:35 +00002283
Chris Lattner965c7692008-06-02 01:18:21 +00002284 // Otherwise, we treat this like a SUB.
2285 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002286
Chris Lattner965c7692008-06-02 01:18:21 +00002287 // Sub can have at most one carry bit. Thus we know that the output
2288 // is, at worst, one more bit than the inputs.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002289 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002290 if (Tmp == 1) return 1; // Early out.
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002291 return std::min(Tmp, Tmp2)-1;
Craig Topper1bef2c82012-12-22 19:15:35 +00002292
Amjad Aboud88ffa3a2017-08-18 22:56:55 +00002293 case Instruction::Mul: {
2294 // The output of the Mul can be at most twice the valid bits in the inputs.
2295 unsigned SignBitsOp0 = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
2296 if (SignBitsOp0 == 1) return 1; // Early out.
2297 unsigned SignBitsOp1 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
2298 if (SignBitsOp1 == 1) return 1;
2299 unsigned OutValidBits =
2300 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
2301 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
2302 }
2303
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002304 case Instruction::PHI: {
Pete Cooper35b00d52016-08-13 01:05:32 +00002305 const PHINode *PN = cast<PHINode>(U);
David Majnemer6ee8d172015-01-04 07:06:53 +00002306 unsigned NumIncomingValues = PN->getNumIncomingValues();
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002307 // Don't analyze large in-degree PHIs.
David Majnemer6ee8d172015-01-04 07:06:53 +00002308 if (NumIncomingValues > 4) break;
2309 // Unreachable blocks may have zero-operand PHI nodes.
2310 if (NumIncomingValues == 0) break;
Craig Topper1bef2c82012-12-22 19:15:35 +00002311
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002312 // Take the minimum of all incoming values. This can't infinitely loop
2313 // because of our depth threshold.
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002314 Tmp = ComputeNumSignBits(PN->getIncomingValue(0), Depth + 1, Q);
David Majnemer6ee8d172015-01-04 07:06:53 +00002315 for (unsigned i = 1, e = NumIncomingValues; i != e; ++i) {
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002316 if (Tmp == 1) return Tmp;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002317 Tmp = std::min(
Matthias Braunfeb81bc2016-01-15 22:22:04 +00002318 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, Q));
Chris Lattner35d3b9d2010-01-07 23:44:37 +00002319 }
2320 return Tmp;
2321 }
2322
Chris Lattner965c7692008-06-02 01:18:21 +00002323 case Instruction::Trunc:
2324 // FIXME: it's tricky to do anything useful for this, but it is an important
2325 // case for targets like X86.
2326 break;
Bjorn Pettersson39616032016-10-06 09:56:21 +00002327
2328 case Instruction::ExtractElement:
2329 // Look through extract element. At the moment we keep this simple and skip
2330 // tracking the specific element. But at least we might find information
2331 // valid for all elements of the vector (for example if vector is sign
2332 // extended, shifted, etc).
2333 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
Chris Lattner965c7692008-06-02 01:18:21 +00002334 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002335
Chris Lattner965c7692008-06-02 01:18:21 +00002336 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2337 // use this information.
Sanjay Patela06d9892016-06-22 19:20:59 +00002338
2339 // If we can examine all elements of a vector constant successfully, we're
2340 // done (we can't do any better than that). If not, keep trying.
2341 if (unsigned VecSignBits = computeNumSignBitsVectorConstant(V, TyBits))
2342 return VecSignBits;
2343
Craig Topperb45eabc2017-04-26 16:39:58 +00002344 KnownBits Known(TyBits);
2345 computeKnownBits(V, Known, Depth, Q);
Craig Topper1bef2c82012-12-22 19:15:35 +00002346
Sanjay Patele0536212016-06-23 17:41:59 +00002347 // If we know that the sign bit is either zero or one, determine the number of
2348 // identical bits in the top of the input value.
Craig Topper8df66c62017-05-12 17:20:30 +00002349 return std::max(FirstAnswer, Known.countMinSignBits());
Chris Lattner965c7692008-06-02 01:18:21 +00002350}
Chris Lattnera12a6de2008-06-02 01:29:46 +00002351
Sanjay Patelaee84212014-11-04 16:27:42 +00002352/// This function computes the integer multiple of Base that equals V.
2353/// If successful, it returns true and returns the multiple in
2354/// Multiple. If unsuccessful, it returns false. It looks
Victor Hernandez47444882009-11-10 08:28:35 +00002355/// through SExt instructions only if LookThroughSExt is true.
2356bool llvm::ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
Dan Gohman6a976bb2009-11-18 00:58:27 +00002357 bool LookThroughSExt, unsigned Depth) {
Victor Hernandez47444882009-11-10 08:28:35 +00002358 const unsigned MaxDepth = 6;
2359
Dan Gohman6a976bb2009-11-18 00:58:27 +00002360 assert(V && "No Value?");
Victor Hernandez47444882009-11-10 08:28:35 +00002361 assert(Depth <= MaxDepth && "Limit Search Depth");
Duncan Sands9dff9be2010-02-15 16:12:20 +00002362 assert(V->getType()->isIntegerTy() && "Not integer or pointer type!");
Victor Hernandez47444882009-11-10 08:28:35 +00002363
Chris Lattner229907c2011-07-18 04:54:35 +00002364 Type *T = V->getType();
Victor Hernandez47444882009-11-10 08:28:35 +00002365
Dan Gohman6a976bb2009-11-18 00:58:27 +00002366 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Victor Hernandez47444882009-11-10 08:28:35 +00002367
2368 if (Base == 0)
2369 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00002370
Victor Hernandez47444882009-11-10 08:28:35 +00002371 if (Base == 1) {
2372 Multiple = V;
2373 return true;
2374 }
2375
2376 ConstantExpr *CO = dyn_cast<ConstantExpr>(V);
2377 Constant *BaseVal = ConstantInt::get(T, Base);
2378 if (CO && CO == BaseVal) {
2379 // Multiple is 1.
2380 Multiple = ConstantInt::get(T, 1);
2381 return true;
2382 }
2383
2384 if (CI && CI->getZExtValue() % Base == 0) {
2385 Multiple = ConstantInt::get(T, CI->getZExtValue() / Base);
Craig Topper1bef2c82012-12-22 19:15:35 +00002386 return true;
Victor Hernandez47444882009-11-10 08:28:35 +00002387 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002388
Victor Hernandez47444882009-11-10 08:28:35 +00002389 if (Depth == MaxDepth) return false; // Limit search depth.
Craig Topper1bef2c82012-12-22 19:15:35 +00002390
Victor Hernandez47444882009-11-10 08:28:35 +00002391 Operator *I = dyn_cast<Operator>(V);
2392 if (!I) return false;
2393
2394 switch (I->getOpcode()) {
2395 default: break;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002396 case Instruction::SExt:
Victor Hernandez47444882009-11-10 08:28:35 +00002397 if (!LookThroughSExt) return false;
2398 // otherwise fall through to ZExt
Galina Kistanova244621f2017-05-31 22:16:24 +00002399 LLVM_FALLTHROUGH;
Chris Lattner4f0b47d2009-11-26 01:50:12 +00002400 case Instruction::ZExt:
Dan Gohman6a976bb2009-11-18 00:58:27 +00002401 return ComputeMultiple(I->getOperand(0), Base, Multiple,
2402 LookThroughSExt, Depth+1);
Victor Hernandez47444882009-11-10 08:28:35 +00002403 case Instruction::Shl:
2404 case Instruction::Mul: {
2405 Value *Op0 = I->getOperand(0);
2406 Value *Op1 = I->getOperand(1);
2407
2408 if (I->getOpcode() == Instruction::Shl) {
2409 ConstantInt *Op1CI = dyn_cast<ConstantInt>(Op1);
2410 if (!Op1CI) return false;
2411 // Turn Op0 << Op1 into Op0 * 2^Op1
2412 APInt Op1Int = Op1CI->getValue();
2413 uint64_t BitToSet = Op1Int.getLimitedValue(Op1Int.getBitWidth() - 1);
Jay Foad15084f02010-11-30 09:02:01 +00002414 APInt API(Op1Int.getBitWidth(), 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00002415 API.setBit(BitToSet);
Jay Foad15084f02010-11-30 09:02:01 +00002416 Op1 = ConstantInt::get(V->getContext(), API);
Victor Hernandez47444882009-11-10 08:28:35 +00002417 }
2418
Craig Topper9f008862014-04-15 04:59:12 +00002419 Value *Mul0 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002420 if (ComputeMultiple(Op0, Base, Mul0, LookThroughSExt, Depth+1)) {
2421 if (Constant *Op1C = dyn_cast<Constant>(Op1))
2422 if (Constant *MulC = dyn_cast<Constant>(Mul0)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002423 if (Op1C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002424 MulC->getType()->getPrimitiveSizeInBits())
2425 Op1C = ConstantExpr::getZExt(Op1C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002426 if (Op1C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002427 MulC->getType()->getPrimitiveSizeInBits())
2428 MulC = ConstantExpr::getZExt(MulC, Op1C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002429
Chris Lattner72d283c2010-09-05 17:20:46 +00002430 // V == Base * (Mul0 * Op1), so return (Mul0 * Op1)
2431 Multiple = ConstantExpr::getMul(MulC, Op1C);
2432 return true;
2433 }
Victor Hernandez47444882009-11-10 08:28:35 +00002434
2435 if (ConstantInt *Mul0CI = dyn_cast<ConstantInt>(Mul0))
2436 if (Mul0CI->getValue() == 1) {
2437 // V == Base * Op1, so return Op1
2438 Multiple = Op1;
2439 return true;
2440 }
2441 }
2442
Craig Topper9f008862014-04-15 04:59:12 +00002443 Value *Mul1 = nullptr;
Chris Lattner72d283c2010-09-05 17:20:46 +00002444 if (ComputeMultiple(Op1, Base, Mul1, LookThroughSExt, Depth+1)) {
2445 if (Constant *Op0C = dyn_cast<Constant>(Op0))
2446 if (Constant *MulC = dyn_cast<Constant>(Mul1)) {
Craig Topper1bef2c82012-12-22 19:15:35 +00002447 if (Op0C->getType()->getPrimitiveSizeInBits() <
Chris Lattner72d283c2010-09-05 17:20:46 +00002448 MulC->getType()->getPrimitiveSizeInBits())
2449 Op0C = ConstantExpr::getZExt(Op0C, MulC->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002450 if (Op0C->getType()->getPrimitiveSizeInBits() >
Chris Lattner72d283c2010-09-05 17:20:46 +00002451 MulC->getType()->getPrimitiveSizeInBits())
2452 MulC = ConstantExpr::getZExt(MulC, Op0C->getType());
Craig Topper1bef2c82012-12-22 19:15:35 +00002453
Chris Lattner72d283c2010-09-05 17:20:46 +00002454 // V == Base * (Mul1 * Op0), so return (Mul1 * Op0)
2455 Multiple = ConstantExpr::getMul(MulC, Op0C);
2456 return true;
2457 }
Victor Hernandez47444882009-11-10 08:28:35 +00002458
2459 if (ConstantInt *Mul1CI = dyn_cast<ConstantInt>(Mul1))
2460 if (Mul1CI->getValue() == 1) {
2461 // V == Base * Op0, so return Op0
2462 Multiple = Op0;
2463 return true;
2464 }
2465 }
Victor Hernandez47444882009-11-10 08:28:35 +00002466 }
2467 }
2468
2469 // We could not determine if V is a multiple of Base.
2470 return false;
2471}
2472
David Majnemerb4b27232016-04-19 19:10:21 +00002473Intrinsic::ID llvm::getIntrinsicForCallSite(ImmutableCallSite ICS,
2474 const TargetLibraryInfo *TLI) {
2475 const Function *F = ICS.getCalledFunction();
2476 if (!F)
2477 return Intrinsic::not_intrinsic;
2478
2479 if (F->isIntrinsic())
2480 return F->getIntrinsicID();
2481
2482 if (!TLI)
2483 return Intrinsic::not_intrinsic;
2484
David L. Jonesd21529f2017-01-23 23:16:46 +00002485 LibFunc Func;
David Majnemerb4b27232016-04-19 19:10:21 +00002486 // We're going to make assumptions on the semantics of the functions, check
2487 // that the target knows that it's available in this environment and it does
2488 // not have local linkage.
Ahmed Bougachad765a822016-04-27 19:04:35 +00002489 if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(*F, Func))
2490 return Intrinsic::not_intrinsic;
2491
2492 if (!ICS.onlyReadsMemory())
David Majnemerb4b27232016-04-19 19:10:21 +00002493 return Intrinsic::not_intrinsic;
2494
2495 // Otherwise check if we have a call to a function that can be turned into a
2496 // vector intrinsic.
2497 switch (Func) {
2498 default:
2499 break;
David L. Jonesd21529f2017-01-23 23:16:46 +00002500 case LibFunc_sin:
2501 case LibFunc_sinf:
2502 case LibFunc_sinl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002503 return Intrinsic::sin;
David L. Jonesd21529f2017-01-23 23:16:46 +00002504 case LibFunc_cos:
2505 case LibFunc_cosf:
2506 case LibFunc_cosl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002507 return Intrinsic::cos;
David L. Jonesd21529f2017-01-23 23:16:46 +00002508 case LibFunc_exp:
2509 case LibFunc_expf:
2510 case LibFunc_expl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002511 return Intrinsic::exp;
David L. Jonesd21529f2017-01-23 23:16:46 +00002512 case LibFunc_exp2:
2513 case LibFunc_exp2f:
2514 case LibFunc_exp2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002515 return Intrinsic::exp2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002516 case LibFunc_log:
2517 case LibFunc_logf:
2518 case LibFunc_logl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002519 return Intrinsic::log;
David L. Jonesd21529f2017-01-23 23:16:46 +00002520 case LibFunc_log10:
2521 case LibFunc_log10f:
2522 case LibFunc_log10l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002523 return Intrinsic::log10;
David L. Jonesd21529f2017-01-23 23:16:46 +00002524 case LibFunc_log2:
2525 case LibFunc_log2f:
2526 case LibFunc_log2l:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002527 return Intrinsic::log2;
David L. Jonesd21529f2017-01-23 23:16:46 +00002528 case LibFunc_fabs:
2529 case LibFunc_fabsf:
2530 case LibFunc_fabsl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002531 return Intrinsic::fabs;
David L. Jonesd21529f2017-01-23 23:16:46 +00002532 case LibFunc_fmin:
2533 case LibFunc_fminf:
2534 case LibFunc_fminl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002535 return Intrinsic::minnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002536 case LibFunc_fmax:
2537 case LibFunc_fmaxf:
2538 case LibFunc_fmaxl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002539 return Intrinsic::maxnum;
David L. Jonesd21529f2017-01-23 23:16:46 +00002540 case LibFunc_copysign:
2541 case LibFunc_copysignf:
2542 case LibFunc_copysignl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002543 return Intrinsic::copysign;
David L. Jonesd21529f2017-01-23 23:16:46 +00002544 case LibFunc_floor:
2545 case LibFunc_floorf:
2546 case LibFunc_floorl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002547 return Intrinsic::floor;
David L. Jonesd21529f2017-01-23 23:16:46 +00002548 case LibFunc_ceil:
2549 case LibFunc_ceilf:
2550 case LibFunc_ceill:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002551 return Intrinsic::ceil;
David L. Jonesd21529f2017-01-23 23:16:46 +00002552 case LibFunc_trunc:
2553 case LibFunc_truncf:
2554 case LibFunc_truncl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002555 return Intrinsic::trunc;
David L. Jonesd21529f2017-01-23 23:16:46 +00002556 case LibFunc_rint:
2557 case LibFunc_rintf:
2558 case LibFunc_rintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002559 return Intrinsic::rint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002560 case LibFunc_nearbyint:
2561 case LibFunc_nearbyintf:
2562 case LibFunc_nearbyintl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002563 return Intrinsic::nearbyint;
David L. Jonesd21529f2017-01-23 23:16:46 +00002564 case LibFunc_round:
2565 case LibFunc_roundf:
2566 case LibFunc_roundl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002567 return Intrinsic::round;
David L. Jonesd21529f2017-01-23 23:16:46 +00002568 case LibFunc_pow:
2569 case LibFunc_powf:
2570 case LibFunc_powl:
Ahmed Bougachad765a822016-04-27 19:04:35 +00002571 return Intrinsic::pow;
David L. Jonesd21529f2017-01-23 23:16:46 +00002572 case LibFunc_sqrt:
2573 case LibFunc_sqrtf:
2574 case LibFunc_sqrtl:
Sanjay Patel86d24f12017-11-06 22:40:09 +00002575 return Intrinsic::sqrt;
David Majnemerb4b27232016-04-19 19:10:21 +00002576 }
2577
2578 return Intrinsic::not_intrinsic;
2579}
2580
Sanjay Patelaee84212014-11-04 16:27:42 +00002581/// Return true if we can prove that the specified FP value is never equal to
2582/// -0.0.
Chris Lattnera12a6de2008-06-02 01:29:46 +00002583///
2584/// NOTE: this function will need to be revisited when we support non-default
2585/// rounding modes!
David Majnemer3ee5f342016-04-13 06:55:52 +00002586bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
2587 unsigned Depth) {
Sanjay Patel20df88a2017-11-13 17:56:23 +00002588 if (auto *CFP = dyn_cast<ConstantFP>(V))
Chris Lattnera12a6de2008-06-02 01:29:46 +00002589 return !CFP->getValueAPF().isNegZero();
Craig Topper1bef2c82012-12-22 19:15:35 +00002590
Sanjay Patel20df88a2017-11-13 17:56:23 +00002591 // Limit search depth.
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002592 if (Depth == MaxDepth)
Sanjay Patel20df88a2017-11-13 17:56:23 +00002593 return false;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002594
Sanjay Patel20df88a2017-11-13 17:56:23 +00002595 auto *Op = dyn_cast<Operator>(V);
2596 if (!Op)
2597 return false;
Michael Ilseman0f128372012-12-06 00:07:09 +00002598
Sanjay Patel20df88a2017-11-13 17:56:23 +00002599 // Check if the nsz fast-math flag is set.
2600 if (auto *FPO = dyn_cast<FPMathOperator>(Op))
Michael Ilseman0f128372012-12-06 00:07:09 +00002601 if (FPO->hasNoSignedZeros())
2602 return true;
2603
Sanjay Patel9e3d8f42017-11-13 17:40:47 +00002604 // (fadd x, 0.0) is guaranteed to return +0.0, not -0.0.
Sanjay Patel20df88a2017-11-13 17:56:23 +00002605 if (match(Op, m_FAdd(m_Value(), m_Zero())))
Sanjay Patel9e3d8f42017-11-13 17:40:47 +00002606 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002607
Chris Lattnera12a6de2008-06-02 01:29:46 +00002608 // sitofp and uitofp turn into +0.0 for zero.
Sanjay Patel20df88a2017-11-13 17:56:23 +00002609 if (isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op))
Chris Lattnera12a6de2008-06-02 01:29:46 +00002610 return true;
Craig Topper1bef2c82012-12-22 19:15:35 +00002611
Sanjay Patel20df88a2017-11-13 17:56:23 +00002612 if (auto *Call = dyn_cast<CallInst>(Op)) {
2613 Intrinsic::ID IID = getIntrinsicForCallSite(Call, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002614 switch (IID) {
2615 default:
2616 break;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002617 // sqrt(-0.0) = -0.0, no other negative results are possible.
David Majnemer3ee5f342016-04-13 06:55:52 +00002618 case Intrinsic::sqrt:
Sanjay Patel20df88a2017-11-13 17:56:23 +00002619 return CannotBeNegativeZero(Call->getArgOperand(0), TLI, Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002620 // fabs(x) != -0.0
2621 case Intrinsic::fabs:
2622 return true;
Chris Lattnera12a6de2008-06-02 01:29:46 +00002623 }
David Majnemer3ee5f342016-04-13 06:55:52 +00002624 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002625
Chris Lattnera12a6de2008-06-02 01:29:46 +00002626 return false;
2627}
2628
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002629/// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
2630/// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
2631/// bit despite comparing equal.
2632static bool cannotBeOrderedLessThanZeroImpl(const Value *V,
2633 const TargetLibraryInfo *TLI,
2634 bool SignBitOnly,
2635 unsigned Depth) {
Justin Lebar322c1272017-01-27 00:58:34 +00002636 // TODO: This function does not do the right thing when SignBitOnly is true
2637 // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform
2638 // which flips the sign bits of NaNs. See
2639 // https://llvm.org/bugs/show_bug.cgi?id=31702.
2640
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002641 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2642 return !CFP->getValueAPF().isNegative() ||
2643 (!SignBitOnly && CFP->getValueAPF().isZero());
2644 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002645
Matt Arsenaultcb2a7eb2016-12-20 19:06:15 +00002646 if (Depth == MaxDepth)
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002647 return false; // Limit search depth.
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002648
2649 const Operator *I = dyn_cast<Operator>(V);
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002650 if (!I)
2651 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002652
2653 switch (I->getOpcode()) {
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002654 default:
2655 break;
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002656 // Unsigned integers are always nonnegative.
2657 case Instruction::UIToFP:
2658 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002659 case Instruction::FMul:
2660 // x*x is always non-negative or a NaN.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002661 if (I->getOperand(0) == I->getOperand(1) &&
2662 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002663 return true;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002664
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002665 LLVM_FALLTHROUGH;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002666 case Instruction::FAdd:
2667 case Instruction::FDiv:
2668 case Instruction::FRem:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002669 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2670 Depth + 1) &&
2671 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2672 Depth + 1);
Fiona Glaserdb7824f2016-01-12 23:37:30 +00002673 case Instruction::Select:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002674 return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2675 Depth + 1) &&
2676 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2677 Depth + 1);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002678 case Instruction::FPExt:
2679 case Instruction::FPTrunc:
2680 // Widening/narrowing never change sign.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002681 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2682 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002683 case Instruction::Call:
Justin Lebar7e3184c2017-01-26 00:10:26 +00002684 const auto *CI = cast<CallInst>(I);
2685 Intrinsic::ID IID = getIntrinsicForCallSite(CI, TLI);
David Majnemer3ee5f342016-04-13 06:55:52 +00002686 switch (IID) {
2687 default:
2688 break;
2689 case Intrinsic::maxnum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002690 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2691 Depth + 1) ||
2692 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2693 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002694 case Intrinsic::minnum:
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002695 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2696 Depth + 1) &&
2697 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
2698 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002699 case Intrinsic::exp:
2700 case Intrinsic::exp2:
2701 case Intrinsic::fabs:
David Majnemer3ee5f342016-04-13 06:55:52 +00002702 return true;
Justin Lebar7e3184c2017-01-26 00:10:26 +00002703
2704 case Intrinsic::sqrt:
2705 // sqrt(x) is always >= -0 or NaN. Moreover, sqrt(x) == -0 iff x == -0.
2706 if (!SignBitOnly)
2707 return true;
2708 return CI->hasNoNaNs() && (CI->hasNoSignedZeros() ||
2709 CannotBeNegativeZero(CI->getOperand(0), TLI));
2710
David Majnemer3ee5f342016-04-13 06:55:52 +00002711 case Intrinsic::powi:
Justin Lebar7e3184c2017-01-26 00:10:26 +00002712 if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) {
David Majnemer3ee5f342016-04-13 06:55:52 +00002713 // powi(x,n) is non-negative if n is even.
Justin Lebar7e3184c2017-01-26 00:10:26 +00002714 if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0)
David Majnemer3ee5f342016-04-13 06:55:52 +00002715 return true;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002716 }
Justin Lebar322c1272017-01-27 00:58:34 +00002717 // TODO: This is not correct. Given that exp is an integer, here are the
2718 // ways that pow can return a negative value:
2719 //
2720 // pow(x, exp) --> negative if exp is odd and x is negative.
2721 // pow(-0, exp) --> -inf if exp is negative odd.
2722 // pow(-0, exp) --> -0 if exp is positive odd.
2723 // pow(-inf, exp) --> -0 if exp is negative odd.
2724 // pow(-inf, exp) --> -inf if exp is positive odd.
2725 //
2726 // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN,
2727 // but we must return false if x == -0. Unfortunately we do not currently
2728 // have a way of expressing this constraint. See details in
2729 // https://llvm.org/bugs/show_bug.cgi?id=31702.
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002730 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
2731 Depth + 1);
Justin Lebar322c1272017-01-27 00:58:34 +00002732
David Majnemer3ee5f342016-04-13 06:55:52 +00002733 case Intrinsic::fma:
2734 case Intrinsic::fmuladd:
2735 // x*x+y is non-negative if y is non-negative.
2736 return I->getOperand(0) == I->getOperand(1) &&
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002737 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
2738 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
2739 Depth + 1);
David Majnemer3ee5f342016-04-13 06:55:52 +00002740 }
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002741 break;
2742 }
Sanjoy Das6082c1a2016-05-07 02:08:15 +00002743 return false;
Elena Demikhovsky45f04482015-01-28 08:03:58 +00002744}
2745
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00002746bool llvm::CannotBeOrderedLessThanZero(const Value *V,
2747 const TargetLibraryInfo *TLI) {
2748 return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0);
2749}
2750
2751bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) {
2752 return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0);
2753}
2754
Sanjay Patel6840c5f2017-09-05 23:13:13 +00002755bool llvm::isKnownNeverNaN(const Value *V) {
2756 assert(V->getType()->isFPOrFPVectorTy() && "Querying for NaN on non-FP type");
2757
2758 // If we're told that NaNs won't happen, assume they won't.
2759 if (auto *FPMathOp = dyn_cast<FPMathOperator>(V))
2760 if (FPMathOp->hasNoNaNs())
2761 return true;
2762
2763 // TODO: Handle instructions and potentially recurse like other 'isKnown'
2764 // functions. For example, the result of sitofp is never NaN.
2765
2766 // Handle scalar constants.
2767 if (auto *CFP = dyn_cast<ConstantFP>(V))
2768 return !CFP->isNaN();
2769
2770 // Bail out for constant expressions, but try to handle vector constants.
2771 if (!V->getType()->isVectorTy() || !isa<Constant>(V))
2772 return false;
2773
2774 // For vectors, verify that each element is not NaN.
2775 unsigned NumElts = V->getType()->getVectorNumElements();
2776 for (unsigned i = 0; i != NumElts; ++i) {
2777 Constant *Elt = cast<Constant>(V)->getAggregateElement(i);
2778 if (!Elt)
2779 return false;
2780 if (isa<UndefValue>(Elt))
2781 continue;
2782 auto *CElt = dyn_cast<ConstantFP>(Elt);
2783 if (!CElt || CElt->isNaN())
2784 return false;
2785 }
2786 // All elements were confirmed not-NaN or undefined.
2787 return true;
2788}
2789
Sanjay Patelaee84212014-11-04 16:27:42 +00002790/// If the specified value can be set by repeating the same byte in memory,
2791/// return the i8 value that it is represented with. This is
Chris Lattner9cb10352010-12-26 20:15:01 +00002792/// true for all i8 values obviously, but is also true for i32 0, i32 -1,
2793/// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
2794/// byte store (e.g. i16 0x1234), return null.
2795Value *llvm::isBytewiseValue(Value *V) {
2796 // All byte-wide stores are splatable, even of arbitrary variables.
2797 if (V->getType()->isIntegerTy(8)) return V;
Chris Lattneracf6b072011-02-19 19:35:49 +00002798
2799 // Handle 'null' ConstantArrayZero etc.
2800 if (Constant *C = dyn_cast<Constant>(V))
2801 if (C->isNullValue())
2802 return Constant::getNullValue(Type::getInt8Ty(V->getContext()));
Craig Topper1bef2c82012-12-22 19:15:35 +00002803
Chris Lattner9cb10352010-12-26 20:15:01 +00002804 // Constant float and double values can be handled as integer values if the
Craig Topper1bef2c82012-12-22 19:15:35 +00002805 // corresponding integer value is "byteable". An important case is 0.0.
Chris Lattner9cb10352010-12-26 20:15:01 +00002806 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2807 if (CFP->getType()->isFloatTy())
2808 V = ConstantExpr::getBitCast(CFP, Type::getInt32Ty(V->getContext()));
2809 if (CFP->getType()->isDoubleTy())
2810 V = ConstantExpr::getBitCast(CFP, Type::getInt64Ty(V->getContext()));
2811 // Don't handle long double formats, which have strange constraints.
2812 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002813
Benjamin Kramer17d90152015-02-07 19:29:02 +00002814 // We can handle constant integers that are multiple of 8 bits.
Chris Lattner9cb10352010-12-26 20:15:01 +00002815 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
Benjamin Kramer17d90152015-02-07 19:29:02 +00002816 if (CI->getBitWidth() % 8 == 0) {
2817 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!");
Craig Topper1bef2c82012-12-22 19:15:35 +00002818
Benjamin Kramerb4b51502015-03-25 16:49:59 +00002819 if (!CI->getValue().isSplat(8))
Benjamin Kramer17d90152015-02-07 19:29:02 +00002820 return nullptr;
2821 return ConstantInt::get(V->getContext(), CI->getValue().trunc(8));
Chris Lattner9cb10352010-12-26 20:15:01 +00002822 }
2823 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002824
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002825 // A ConstantDataArray/Vector is splatable if all its members are equal and
2826 // also splatable.
2827 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(V)) {
2828 Value *Elt = CA->getElementAsConstant(0);
2829 Value *Val = isBytewiseValue(Elt);
Chris Lattner9cb10352010-12-26 20:15:01 +00002830 if (!Val)
Craig Topper9f008862014-04-15 04:59:12 +00002831 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002832
Chris Lattnercf9e8f62012-02-05 02:29:43 +00002833 for (unsigned I = 1, E = CA->getNumElements(); I != E; ++I)
2834 if (CA->getElementAsConstant(I) != Elt)
Craig Topper9f008862014-04-15 04:59:12 +00002835 return nullptr;
Craig Topper1bef2c82012-12-22 19:15:35 +00002836
Chris Lattner9cb10352010-12-26 20:15:01 +00002837 return Val;
2838 }
Chad Rosier8abf65a2011-12-06 00:19:08 +00002839
Chris Lattner9cb10352010-12-26 20:15:01 +00002840 // Conceptually, we could handle things like:
2841 // %a = zext i8 %X to i16
2842 // %b = shl i16 %a, 8
2843 // %c = or i16 %a, %b
2844 // but until there is an example that actually needs this, it doesn't seem
2845 // worth worrying about.
Craig Topper9f008862014-04-15 04:59:12 +00002846 return nullptr;
Chris Lattner9cb10352010-12-26 20:15:01 +00002847}
2848
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002849// This is the recursive version of BuildSubAggregate. It takes a few different
2850// arguments. Idxs is the index within the nested struct From that we are
2851// looking at now (which is of type IndexedType). IdxSkip is the number of
2852// indices from Idxs that should be left out when inserting into the resulting
2853// struct. To is the result struct built so far, new insertvalue instructions
2854// build on that.
Chris Lattner229907c2011-07-18 04:54:35 +00002855static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
Craig Topper2cd5ff82013-07-11 16:22:38 +00002856 SmallVectorImpl<unsigned> &Idxs,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002857 unsigned IdxSkip,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002858 Instruction *InsertBefore) {
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002859 StructType *STy = dyn_cast<StructType>(IndexedType);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002860 if (STy) {
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002861 // Save the original To argument so we can modify it
2862 Value *OrigTo = To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002863 // General case, the type indexed by Idxs is a struct
2864 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2865 // Process each struct element recursively
2866 Idxs.push_back(i);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002867 Value *PrevTo = To;
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002868 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002869 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002870 Idxs.pop_back();
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002871 if (!To) {
2872 // Couldn't find any inserted value for this index? Cleanup
2873 while (PrevTo != OrigTo) {
2874 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
2875 PrevTo = Del->getAggregateOperand();
2876 Del->eraseFromParent();
2877 }
2878 // Stop processing elements
2879 break;
2880 }
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002881 }
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002882 // If we successfully found a value for each of our subaggregates
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002883 if (To)
2884 return To;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002885 }
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002886 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
2887 // the struct's elements had a value that was inserted directly. In the latter
2888 // case, perhaps we can't determine each of the subelements individually, but
2889 // we might be able to find the complete struct somewhere.
Craig Topper1bef2c82012-12-22 19:15:35 +00002890
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002891 // Find the value that is at that particular spot
Jay Foad57aa6362011-07-13 10:26:04 +00002892 Value *V = FindInsertedValue(From, Idxs);
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002893
2894 if (!V)
Craig Topper9f008862014-04-15 04:59:12 +00002895 return nullptr;
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002896
2897 // Insert the value in the new (sub) aggregrate
Eugene Zelenko75075ef2017-09-01 21:37:29 +00002898 return InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
2899 "tmp", InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002900}
2901
2902// This helper takes a nested struct and extracts a part of it (which is again a
2903// struct) into a new value. For example, given the struct:
2904// { a, { b, { c, d }, e } }
2905// and the indices "1, 1" this returns
2906// { c, d }.
2907//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002908// It does this by inserting an insertvalue for each element in the resulting
2909// struct, as opposed to just inserting a single struct. This will only work if
2910// each of the elements of the substruct are known (ie, inserted into From by an
2911// insertvalue instruction somewhere).
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002912//
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002913// All inserted insertvalue instructions are inserted before InsertBefore
Jay Foad57aa6362011-07-13 10:26:04 +00002914static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
Dan Gohmana6d0afc2009-08-07 01:32:21 +00002915 Instruction *InsertBefore) {
Matthijs Kooijman69801d42008-06-16 13:28:31 +00002916 assert(InsertBefore && "Must have someplace to insert!");
Chris Lattner229907c2011-07-18 04:54:35 +00002917 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
Jay Foad57aa6362011-07-13 10:26:04 +00002918 idx_range);
Owen Andersonb292b8c2009-07-30 23:03:37 +00002919 Value *To = UndefValue::get(IndexedType);
Jay Foad57aa6362011-07-13 10:26:04 +00002920 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002921 unsigned IdxSkip = Idxs.size();
2922
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002923 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002924}
2925
Sanjay Patelaee84212014-11-04 16:27:42 +00002926/// Given an aggregrate and an sequence of indices, see if
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002927/// the scalar value indexed is already around as a register, for example if it
2928/// were inserted directly into the aggregrate.
Matthijs Kooijmanfa4d0b82008-06-16 14:13:46 +00002929///
2930/// If InsertBefore is not null, this function will duplicate (modified)
2931/// insertvalues when a part of a nested struct is extracted.
Jay Foad57aa6362011-07-13 10:26:04 +00002932Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
2933 Instruction *InsertBefore) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002934 // Nothing to index? Just return V then (this is useful at the end of our
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002935 // recursion).
Jay Foad57aa6362011-07-13 10:26:04 +00002936 if (idx_range.empty())
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002937 return V;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002938 // We have indices, so V should have an indexable type.
2939 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
2940 "Not looking at a struct or array?");
2941 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
2942 "Invalid indices for type?");
Owen Andersonf1f17432009-07-06 22:37:39 +00002943
Chris Lattner67058832012-01-25 06:48:06 +00002944 if (Constant *C = dyn_cast<Constant>(V)) {
2945 C = C->getAggregateElement(idx_range[0]);
Craig Topper9f008862014-04-15 04:59:12 +00002946 if (!C) return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00002947 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
2948 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002949
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002950 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002951 // Loop the indices for the insertvalue instruction in parallel with the
2952 // requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00002953 const unsigned *req_idx = idx_range.begin();
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00002954 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
2955 i != e; ++i, ++req_idx) {
Jay Foad57aa6362011-07-13 10:26:04 +00002956 if (req_idx == idx_range.end()) {
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002957 // We can't handle this without inserting insertvalues
2958 if (!InsertBefore)
Craig Topper9f008862014-04-15 04:59:12 +00002959 return nullptr;
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002960
2961 // The requested index identifies a part of a nested aggregate. Handle
2962 // this specially. For example,
2963 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
2964 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
2965 // %C = extractvalue {i32, { i32, i32 } } %B, 1
2966 // This can be changed into
2967 // %A = insertvalue {i32, i32 } undef, i32 10, 0
2968 // %C = insertvalue {i32, i32 } %A, i32 11, 1
2969 // which allows the unused 0,0 element from the nested struct to be
2970 // removed.
2971 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
2972 InsertBefore);
Duncan Sandsdb356ee2008-06-19 08:47:31 +00002973 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002974
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002975 // This insert value inserts something else than what we are looking for.
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002976 // See if the (aggregate) value inserted into has the value we are
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002977 // looking for, then.
2978 if (*req_idx != *i)
Jay Foad57aa6362011-07-13 10:26:04 +00002979 return FindInsertedValue(I->getAggregateOperand(), idx_range,
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002980 InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002981 }
2982 // If we end up here, the indices of the insertvalue match with those
2983 // requested (though possibly only partially). Now we recursively look at
2984 // the inserted value, passing any remaining indices.
Jay Foad57aa6362011-07-13 10:26:04 +00002985 return FindInsertedValue(I->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002986 makeArrayRef(req_idx, idx_range.end()),
Nick Lewycky39dbfd32009-11-23 03:29:18 +00002987 InsertBefore);
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002988 }
Craig Topper1bef2c82012-12-22 19:15:35 +00002989
Chris Lattnerf7eb5432012-01-24 07:54:10 +00002990 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00002991 // If we're extracting a value from an aggregate that was extracted from
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002992 // something else, we can extract from that something else directly instead.
2993 // However, we will need to chain I's indices with the requested indices.
Craig Topper1bef2c82012-12-22 19:15:35 +00002994
2995 // Calculate the number of indices required
Jay Foad57aa6362011-07-13 10:26:04 +00002996 unsigned size = I->getNumIndices() + idx_range.size();
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00002997 // Allocate some space to put the new indices in
Matthijs Kooijman8369c672008-06-17 08:24:37 +00002998 SmallVector<unsigned, 5> Idxs;
2999 Idxs.reserve(size);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003000 // Add indices from the extract value instruction
Jay Foad57aa6362011-07-13 10:26:04 +00003001 Idxs.append(I->idx_begin(), I->idx_end());
Craig Topper1bef2c82012-12-22 19:15:35 +00003002
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003003 // Add requested indices
Jay Foad57aa6362011-07-13 10:26:04 +00003004 Idxs.append(idx_range.begin(), idx_range.end());
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003005
Craig Topper1bef2c82012-12-22 19:15:35 +00003006 assert(Idxs.size() == size
Matthijs Kooijman5cb38772008-06-16 12:57:37 +00003007 && "Number of indices added not correct?");
Craig Topper1bef2c82012-12-22 19:15:35 +00003008
Jay Foad57aa6362011-07-13 10:26:04 +00003009 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003010 }
3011 // Otherwise, we don't know (such as, extracting from a function return value
3012 // or load instruction)
Craig Topper9f008862014-04-15 04:59:12 +00003013 return nullptr;
Matthijs Kooijmane92e18b2008-06-16 12:48:21 +00003014}
Evan Chengda3db112008-06-30 07:31:25 +00003015
Sanjay Patelaee84212014-11-04 16:27:42 +00003016/// Analyze the specified pointer to see if it can be expressed as a base
3017/// pointer plus a constant offset. Return the base and offset to the caller.
Chris Lattnere28618d2010-11-30 22:25:26 +00003018Value *llvm::GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003019 const DataLayout &DL) {
3020 unsigned BitWidth = DL.getPointerTypeSizeInBits(Ptr->getType());
Nuno Lopes368c4d02012-12-31 20:48:35 +00003021 APInt ByteOffset(BitWidth, 0);
Chandler Carruth76641272016-01-04 07:23:12 +00003022
3023 // We walk up the defs but use a visited set to handle unreachable code. In
3024 // that case, we stop after accumulating the cycle once (not that it
3025 // matters).
3026 SmallPtrSet<Value *, 16> Visited;
3027 while (Visited.insert(Ptr).second) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00003028 if (Ptr->getType()->isVectorTy())
3029 break;
Craig Topper1bef2c82012-12-22 19:15:35 +00003030
Nuno Lopes368c4d02012-12-31 20:48:35 +00003031 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
Tom Stellard17eb3412016-10-07 14:23:29 +00003032 // If one of the values we have visited is an addrspacecast, then
3033 // the pointer type of this GEP may be different from the type
3034 // of the Ptr parameter which was passed to this function. This
3035 // means when we construct GEPOffset, we need to use the size
3036 // of GEP's pointer type rather than the size of the original
3037 // pointer type.
3038 APInt GEPOffset(DL.getPointerTypeSizeInBits(Ptr->getType()), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003039 if (!GEP->accumulateConstantOffset(DL, GEPOffset))
3040 break;
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00003041
Tom Stellard17eb3412016-10-07 14:23:29 +00003042 ByteOffset += GEPOffset.getSExtValue();
Matt Arsenaultf55e5e72013-08-10 17:34:08 +00003043
Nuno Lopes368c4d02012-12-31 20:48:35 +00003044 Ptr = GEP->getPointerOperand();
Tom Stellard17eb3412016-10-07 14:23:29 +00003045 } else if (Operator::getOpcode(Ptr) == Instruction::BitCast ||
3046 Operator::getOpcode(Ptr) == Instruction::AddrSpaceCast) {
Nuno Lopes368c4d02012-12-31 20:48:35 +00003047 Ptr = cast<Operator>(Ptr)->getOperand(0);
3048 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00003049 if (GA->isInterposable())
Nuno Lopes368c4d02012-12-31 20:48:35 +00003050 break;
3051 Ptr = GA->getAliasee();
Chris Lattnere28618d2010-11-30 22:25:26 +00003052 } else {
Nuno Lopes368c4d02012-12-31 20:48:35 +00003053 break;
Chris Lattnere28618d2010-11-30 22:25:26 +00003054 }
3055 }
Nuno Lopes368c4d02012-12-31 20:48:35 +00003056 Offset = ByteOffset.getSExtValue();
3057 return Ptr;
Chris Lattnere28618d2010-11-30 22:25:26 +00003058}
3059
Matthias Braun50ec0b52017-05-19 22:37:09 +00003060bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP,
3061 unsigned CharSize) {
David L Kreitzer752c1442016-04-13 14:31:06 +00003062 // Make sure the GEP has exactly three arguments.
3063 if (GEP->getNumOperands() != 3)
3064 return false;
3065
Matthias Braun50ec0b52017-05-19 22:37:09 +00003066 // Make sure the index-ee is a pointer to array of \p CharSize integers.
3067 // CharSize.
David L Kreitzer752c1442016-04-13 14:31:06 +00003068 ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
Matthias Braun50ec0b52017-05-19 22:37:09 +00003069 if (!AT || !AT->getElementType()->isIntegerTy(CharSize))
David L Kreitzer752c1442016-04-13 14:31:06 +00003070 return false;
3071
3072 // Check to make sure that the first operand of the GEP is an integer and
3073 // has value 0 so that we are sure we're indexing into the initializer.
3074 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
3075 if (!FirstIdx || !FirstIdx->isZero())
3076 return false;
3077
3078 return true;
Sanjoy Das6082c1a2016-05-07 02:08:15 +00003079}
Chris Lattnere28618d2010-11-30 22:25:26 +00003080
Matthias Braun50ec0b52017-05-19 22:37:09 +00003081bool llvm::getConstantDataArrayInfo(const Value *V,
3082 ConstantDataArraySlice &Slice,
3083 unsigned ElementSize, uint64_t Offset) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003084 assert(V);
Evan Chengda3db112008-06-30 07:31:25 +00003085
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003086 // Look through bitcast instructions and geps.
3087 V = V->stripPointerCasts();
Craig Topper1bef2c82012-12-22 19:15:35 +00003088
Benjamin Kramer0248a3e2015-03-21 15:36:06 +00003089 // If the value is a GEP instruction or constant expression, treat it as an
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003090 // offset.
3091 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
David L Kreitzer752c1442016-04-13 14:31:06 +00003092 // The GEP operator should be based on a pointer to string constant, and is
3093 // indexing into the string constant.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003094 if (!isGEPBasedOnPointerToString(GEP, ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003095 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003096
Evan Chengda3db112008-06-30 07:31:25 +00003097 // If the second index isn't a ConstantInt, then this is a variable index
3098 // into the array. If this occurs, we can't say anything meaningful about
3099 // the string.
3100 uint64_t StartIdx = 0;
Dan Gohman0b4df042010-04-14 22:20:45 +00003101 if (const ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
Evan Chengda3db112008-06-30 07:31:25 +00003102 StartIdx = CI->getZExtValue();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003103 else
3104 return false;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003105 return getConstantDataArrayInfo(GEP->getOperand(0), Slice, ElementSize,
3106 StartIdx + Offset);
Evan Chengda3db112008-06-30 07:31:25 +00003107 }
Nick Lewycky46209882011-10-20 00:34:35 +00003108
Evan Chengda3db112008-06-30 07:31:25 +00003109 // The GEP instruction, constant or instruction, must reference a global
3110 // variable that is a constant and is initialized. The referenced constant
3111 // initializer is the array that we'll use for optimization.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003112 const GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00003113 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003114 return false;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003115
Matthias Braun50ec0b52017-05-19 22:37:09 +00003116 const ConstantDataArray *Array;
3117 ArrayType *ArrayTy;
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003118 if (GV->getInitializer()->isNullValue()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003119 Type *GVTy = GV->getValueType();
3120 if ( (ArrayTy = dyn_cast<ArrayType>(GVTy)) ) {
Sanjay Patel2ad88f82017-06-12 22:34:37 +00003121 // A zeroinitializer for the array; there is no ConstantDataArray.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003122 Array = nullptr;
3123 } else {
3124 const DataLayout &DL = GV->getParent()->getDataLayout();
3125 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy);
3126 uint64_t Length = SizeInBytes / (ElementSize / 8);
3127 if (Length <= Offset)
3128 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003129
Matthias Braun50ec0b52017-05-19 22:37:09 +00003130 Slice.Array = nullptr;
3131 Slice.Offset = 0;
3132 Slice.Length = Length - Offset;
3133 return true;
3134 }
3135 } else {
3136 // This must be a ConstantDataArray.
3137 Array = dyn_cast<ConstantDataArray>(GV->getInitializer());
3138 if (!Array)
3139 return false;
3140 ArrayTy = Array->getType();
3141 }
3142 if (!ArrayTy->getElementType()->isIntegerTy(ElementSize))
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003143 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003144
Matthias Braun50ec0b52017-05-19 22:37:09 +00003145 uint64_t NumElts = ArrayTy->getArrayNumElements();
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003146 if (Offset > NumElts)
3147 return false;
Craig Topper1bef2c82012-12-22 19:15:35 +00003148
Matthias Braun50ec0b52017-05-19 22:37:09 +00003149 Slice.Array = Array;
3150 Slice.Offset = Offset;
3151 Slice.Length = NumElts - Offset;
3152 return true;
3153}
3154
3155/// This function computes the length of a null-terminated C string pointed to
3156/// by V. If successful, it returns true and returns the string in Str.
3157/// If unsuccessful, it returns false.
3158bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
3159 uint64_t Offset, bool TrimAtNul) {
3160 ConstantDataArraySlice Slice;
3161 if (!getConstantDataArrayInfo(V, Slice, 8, Offset))
3162 return false;
3163
3164 if (Slice.Array == nullptr) {
3165 if (TrimAtNul) {
3166 Str = StringRef();
3167 return true;
3168 }
3169 if (Slice.Length == 1) {
3170 Str = StringRef("", 1);
3171 return true;
3172 }
Sanjay Patelfef83e82017-06-09 14:21:18 +00003173 // We cannot instantiate a StringRef as we do not have an appropriate string
Matthias Braun50ec0b52017-05-19 22:37:09 +00003174 // of 0s at hand.
3175 return false;
3176 }
3177
3178 // Start out with the entire array in the StringRef.
3179 Str = Slice.Array->getAsString();
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003180 // Skip over 'offset' bytes.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003181 Str = Str.substr(Slice.Offset);
Craig Topper1bef2c82012-12-22 19:15:35 +00003182
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003183 if (TrimAtNul) {
3184 // Trim off the \0 and anything after it. If the array is not nul
3185 // terminated, we just return the whole end of string. The client may know
3186 // some other way that the string is length-bound.
3187 Str = Str.substr(0, Str.find('\0'));
3188 }
Bill Wendlingfa54bc22009-03-13 04:39:26 +00003189 return true;
Evan Chengda3db112008-06-30 07:31:25 +00003190}
Eric Christopher4899cbc2010-03-05 06:58:57 +00003191
3192// These next two are very similar to the above, but also look through PHI
3193// nodes.
3194// TODO: See if we can integrate these two together.
3195
Sanjay Patelaee84212014-11-04 16:27:42 +00003196/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003197/// the specified pointer, return 'len+1'. If we can't, return 0.
Pete Cooper35b00d52016-08-13 01:05:32 +00003198static uint64_t GetStringLengthH(const Value *V,
Matthias Braun50ec0b52017-05-19 22:37:09 +00003199 SmallPtrSetImpl<const PHINode*> &PHIs,
3200 unsigned CharSize) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003201 // Look through noop bitcast instructions.
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003202 V = V->stripPointerCasts();
Eric Christopher4899cbc2010-03-05 06:58:57 +00003203
3204 // If this is a PHI node, there are two cases: either we have already seen it
3205 // or we haven't.
Pete Cooper35b00d52016-08-13 01:05:32 +00003206 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
David Blaikie70573dc2014-11-19 07:49:26 +00003207 if (!PHIs.insert(PN).second)
Eric Christopher4899cbc2010-03-05 06:58:57 +00003208 return ~0ULL; // already in the set.
3209
3210 // If it was new, see if all the input strings are the same length.
3211 uint64_t LenSoFar = ~0ULL;
Pete Cooper833f34d2015-05-12 20:05:31 +00003212 for (Value *IncValue : PN->incoming_values()) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003213 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003214 if (Len == 0) return 0; // Unknown length -> unknown.
3215
3216 if (Len == ~0ULL) continue;
3217
3218 if (Len != LenSoFar && LenSoFar != ~0ULL)
3219 return 0; // Disagree -> unknown.
3220 LenSoFar = Len;
3221 }
3222
3223 // Success, all agree.
3224 return LenSoFar;
3225 }
3226
3227 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
Pete Cooper35b00d52016-08-13 01:05:32 +00003228 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
Matthias Braun50ec0b52017-05-19 22:37:09 +00003229 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003230 if (Len1 == 0) return 0;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003231 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003232 if (Len2 == 0) return 0;
3233 if (Len1 == ~0ULL) return Len2;
3234 if (Len2 == ~0ULL) return Len1;
3235 if (Len1 != Len2) return 0;
3236 return Len1;
3237 }
Craig Topper1bef2c82012-12-22 19:15:35 +00003238
Chris Lattnercf9e8f62012-02-05 02:29:43 +00003239 // Otherwise, see if we can read the string.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003240 ConstantDataArraySlice Slice;
3241 if (!getConstantDataArrayInfo(V, Slice, CharSize))
Eric Christopher4899cbc2010-03-05 06:58:57 +00003242 return 0;
3243
Matthias Braun50ec0b52017-05-19 22:37:09 +00003244 if (Slice.Array == nullptr)
3245 return 1;
3246
3247 // Search for nul characters
3248 unsigned NullIndex = 0;
3249 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
3250 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
3251 break;
3252 }
3253
3254 return NullIndex + 1;
Eric Christopher4899cbc2010-03-05 06:58:57 +00003255}
3256
Sanjay Patelaee84212014-11-04 16:27:42 +00003257/// If we can compute the length of the string pointed to by
Eric Christopher4899cbc2010-03-05 06:58:57 +00003258/// the specified pointer, return 'len+1'. If we can't, return 0.
Matthias Braun50ec0b52017-05-19 22:37:09 +00003259uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
Eric Christopher4899cbc2010-03-05 06:58:57 +00003260 if (!V->getType()->isPointerTy()) return 0;
3261
Pete Cooper35b00d52016-08-13 01:05:32 +00003262 SmallPtrSet<const PHINode*, 32> PHIs;
Matthias Braun50ec0b52017-05-19 22:37:09 +00003263 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
Eric Christopher4899cbc2010-03-05 06:58:57 +00003264 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
3265 // an empty string as a length.
3266 return Len == ~0ULL ? 1 : Len;
3267}
Dan Gohmana4fcd242010-12-15 20:02:24 +00003268
Adam Nemete2b885c2015-04-23 20:09:20 +00003269/// \brief \p PN defines a loop-variant pointer to an object. Check if the
3270/// previous iteration of the loop was referring to the same object as \p PN.
Pete Cooper35b00d52016-08-13 01:05:32 +00003271static bool isSameUnderlyingObjectInLoop(const PHINode *PN,
3272 const LoopInfo *LI) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003273 // Find the loop-defined value.
3274 Loop *L = LI->getLoopFor(PN->getParent());
3275 if (PN->getNumIncomingValues() != 2)
3276 return true;
3277
3278 // Find the value from previous iteration.
3279 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
3280 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3281 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
3282 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
3283 return true;
3284
3285 // If a new pointer is loaded in the loop, the pointer references a different
3286 // object in every iteration. E.g.:
3287 // for (i)
3288 // int *p = a[i];
3289 // ...
3290 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
3291 if (!L->isLoopInvariant(Load->getPointerOperand()))
3292 return false;
3293 return true;
3294}
3295
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003296Value *llvm::GetUnderlyingObject(Value *V, const DataLayout &DL,
3297 unsigned MaxLookup) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003298 if (!V->getType()->isPointerTy())
3299 return V;
3300 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
3301 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
3302 V = GEP->getPointerOperand();
Matt Arsenault70f4db882014-07-15 00:56:40 +00003303 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
3304 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
Dan Gohmana4fcd242010-12-15 20:02:24 +00003305 V = cast<Operator>(V)->getOperand(0);
3306 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +00003307 if (GA->isInterposable())
Dan Gohmana4fcd242010-12-15 20:02:24 +00003308 return V;
3309 V = GA->getAliasee();
Craig Topper85482412017-04-12 22:29:23 +00003310 } else if (isa<AllocaInst>(V)) {
3311 // An alloca can't be further simplified.
3312 return V;
Dan Gohmana4fcd242010-12-15 20:02:24 +00003313 } else {
Hal Finkel5c12d8f2016-07-11 01:32:20 +00003314 if (auto CS = CallSite(V))
3315 if (Value *RV = CS.getReturnedArgOperand()) {
3316 V = RV;
3317 continue;
3318 }
3319
Dan Gohman05b18f12010-12-15 20:49:55 +00003320 // See if InstructionSimplify knows any relevant tricks.
3321 if (Instruction *I = dyn_cast<Instruction>(V))
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003322 // TODO: Acquire a DominatorTree and AssumptionCache and use them.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00003323 if (Value *Simplified = SimplifyInstruction(I, {DL, I})) {
Dan Gohman05b18f12010-12-15 20:49:55 +00003324 V = Simplified;
3325 continue;
3326 }
3327
Dan Gohmana4fcd242010-12-15 20:02:24 +00003328 return V;
3329 }
3330 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
3331 }
3332 return V;
3333}
Nick Lewycky3e334a42011-06-27 04:20:45 +00003334
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003335void llvm::GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
Adam Nemete2b885c2015-04-23 20:09:20 +00003336 const DataLayout &DL, LoopInfo *LI,
3337 unsigned MaxLookup) {
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003338 SmallPtrSet<Value *, 4> Visited;
3339 SmallVector<Value *, 4> Worklist;
3340 Worklist.push_back(V);
3341 do {
3342 Value *P = Worklist.pop_back_val();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003343 P = GetUnderlyingObject(P, DL, MaxLookup);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003344
David Blaikie70573dc2014-11-19 07:49:26 +00003345 if (!Visited.insert(P).second)
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003346 continue;
3347
3348 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
3349 Worklist.push_back(SI->getTrueValue());
3350 Worklist.push_back(SI->getFalseValue());
3351 continue;
3352 }
3353
3354 if (PHINode *PN = dyn_cast<PHINode>(P)) {
Adam Nemete2b885c2015-04-23 20:09:20 +00003355 // If this PHI changes the underlying object in every iteration of the
3356 // loop, don't look through it. Consider:
3357 // int **A;
3358 // for (i) {
3359 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
3360 // Curr = A[i];
3361 // *Prev, *Curr;
3362 //
3363 // Prev is tracking Curr one iteration behind so they refer to different
3364 // underlying objects.
3365 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
3366 isSameUnderlyingObjectInLoop(PN, LI))
Pete Cooper833f34d2015-05-12 20:05:31 +00003367 for (Value *IncValue : PN->incoming_values())
3368 Worklist.push_back(IncValue);
Dan Gohmaned7c24e22012-05-10 18:57:38 +00003369 continue;
3370 }
3371
3372 Objects.push_back(P);
3373 } while (!Worklist.empty());
3374}
3375
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003376/// This is the function that does the work of looking through basic
3377/// ptrtoint+arithmetic+inttoptr sequences.
3378static const Value *getUnderlyingObjectFromInt(const Value *V) {
3379 do {
3380 if (const Operator *U = dyn_cast<Operator>(V)) {
3381 // If we find a ptrtoint, we can transfer control back to the
3382 // regular getUnderlyingObjectFromInt.
3383 if (U->getOpcode() == Instruction::PtrToInt)
3384 return U->getOperand(0);
3385 // If we find an add of a constant, a multiplied value, or a phi, it's
3386 // likely that the other operand will lead us to the base
3387 // object. We don't have to worry about the case where the
3388 // object address is somehow being computed by the multiply,
3389 // because our callers only care when the result is an
3390 // identifiable object.
3391 if (U->getOpcode() != Instruction::Add ||
3392 (!isa<ConstantInt>(U->getOperand(1)) &&
3393 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
3394 !isa<PHINode>(U->getOperand(1))))
3395 return V;
3396 V = U->getOperand(0);
3397 } else {
3398 return V;
3399 }
3400 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
3401 } while (true);
3402}
3403
3404/// This is a wrapper around GetUnderlyingObjects and adds support for basic
3405/// ptrtoint+arithmetic+inttoptr sequences.
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003406/// It returns false if unidentified object is found in GetUnderlyingObjects.
3407bool llvm::getUnderlyingObjectsForCodeGen(const Value *V,
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003408 SmallVectorImpl<Value *> &Objects,
3409 const DataLayout &DL) {
3410 SmallPtrSet<const Value *, 16> Visited;
3411 SmallVector<const Value *, 4> Working(1, V);
3412 do {
3413 V = Working.pop_back_val();
3414
3415 SmallVector<Value *, 4> Objs;
3416 GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
3417
3418 for (Value *V : Objs) {
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003419 if (!Visited.insert(V).second)
3420 continue;
3421 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
3422 const Value *O =
3423 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
3424 if (O->getType()->isPointerTy()) {
3425 Working.push_back(O);
3426 continue;
3427 }
3428 }
Hiroshi Inoue0bd906e2017-08-02 18:16:32 +00003429 // If GetUnderlyingObjects fails to find an identifiable object,
3430 // getUnderlyingObjectsForCodeGen also fails for safety.
3431 if (!isIdentifiedObject(V)) {
3432 Objects.clear();
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003433 return false;
Hiroshi Inoue0bd906e2017-08-02 18:16:32 +00003434 }
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003435 Objects.push_back(const_cast<Value *>(V));
3436 }
3437 } while (!Working.empty());
Hiroshi Inoueb49b0152017-10-12 06:26:04 +00003438 return true;
Hiroshi Inoueb9417db2017-08-01 03:32:15 +00003439}
3440
Sanjay Patelaee84212014-11-04 16:27:42 +00003441/// Return true if the only users of this pointer are lifetime markers.
Nick Lewycky3e334a42011-06-27 04:20:45 +00003442bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003443 for (const User *U : V->users()) {
3444 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Nick Lewycky3e334a42011-06-27 04:20:45 +00003445 if (!II) return false;
3446
3447 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
3448 II->getIntrinsicID() != Intrinsic::lifetime_end)
3449 return false;
3450 }
3451 return true;
3452}
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003453
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00003454bool llvm::isSafeToSpeculativelyExecute(const Value *V,
3455 const Instruction *CtxI,
Sean Silva45835e72016-07-02 23:47:27 +00003456 const DominatorTree *DT) {
Dan Gohman7ac046a2012-01-04 23:01:09 +00003457 const Operator *Inst = dyn_cast<Operator>(V);
3458 if (!Inst)
3459 return false;
3460
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003461 for (unsigned i = 0, e = Inst->getNumOperands(); i != e; ++i)
3462 if (Constant *C = dyn_cast<Constant>(Inst->getOperand(i)))
3463 if (C->canTrap())
3464 return false;
3465
3466 switch (Inst->getOpcode()) {
3467 default:
3468 return true;
3469 case Instruction::UDiv:
David Majnemerf20d7c42014-11-04 23:49:08 +00003470 case Instruction::URem: {
3471 // x / y is undefined if y == 0.
3472 const APInt *V;
3473 if (match(Inst->getOperand(1), m_APInt(V)))
3474 return *V != 0;
3475 return false;
3476 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003477 case Instruction::SDiv:
3478 case Instruction::SRem: {
David Majnemerf20d7c42014-11-04 23:49:08 +00003479 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
David Majnemer8a6578a2015-02-01 19:10:19 +00003480 const APInt *Numerator, *Denominator;
3481 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
3482 return false;
3483 // We cannot hoist this division if the denominator is 0.
3484 if (*Denominator == 0)
3485 return false;
3486 // It's safe to hoist if the denominator is not 0 or -1.
3487 if (*Denominator != -1)
3488 return true;
3489 // At this point we know that the denominator is -1. It is safe to hoist as
3490 // long we know that the numerator is not INT_MIN.
3491 if (match(Inst->getOperand(0), m_APInt(Numerator)))
3492 return !Numerator->isMinSignedValue();
3493 // The numerator *might* be MinSignedValue.
David Majnemerf20d7c42014-11-04 23:49:08 +00003494 return false;
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003495 }
3496 case Instruction::Load: {
3497 const LoadInst *LI = cast<LoadInst>(Inst);
Kostya Serebryany0b458282013-11-21 07:29:28 +00003498 if (!LI->isUnordered() ||
3499 // Speculative load may create a race that did not exist in the source.
Sanjoy Dasb66374c2016-07-14 20:19:01 +00003500 LI->getFunction()->hasFnAttribute(Attribute::SanitizeThread) ||
Kostya Serebryany5cb86d52015-10-14 00:21:05 +00003501 // Speculative load may load data from dirty regions.
Sanjoy Dasb66374c2016-07-14 20:19:01 +00003502 LI->getFunction()->hasFnAttribute(Attribute::SanitizeAddress))
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003503 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003504 const DataLayout &DL = LI->getModule()->getDataLayout();
Sean Silva45835e72016-07-02 23:47:27 +00003505 return isDereferenceableAndAlignedPointer(LI->getPointerOperand(),
3506 LI->getAlignment(), DL, CtxI, DT);
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003507 }
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003508 case Instruction::Call: {
Matt Arsenaultcf5e7fe2017-04-28 21:13:09 +00003509 auto *CI = cast<const CallInst>(Inst);
3510 const Function *Callee = CI->getCalledFunction();
David Majnemer0a92f862015-08-28 21:13:39 +00003511
Matt Arsenault6a288c12017-05-03 02:26:10 +00003512 // The called function could have undefined behavior or side-effects, even
3513 // if marked readnone nounwind.
3514 return Callee && Callee->isSpeculatable();
Nick Lewyckyb4039f62011-12-21 05:52:02 +00003515 }
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003516 case Instruction::VAArg:
3517 case Instruction::Alloca:
3518 case Instruction::Invoke:
3519 case Instruction::PHI:
3520 case Instruction::Store:
3521 case Instruction::Ret:
3522 case Instruction::Br:
3523 case Instruction::IndirectBr:
3524 case Instruction::Switch:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003525 case Instruction::Unreachable:
3526 case Instruction::Fence:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003527 case Instruction::AtomicRMW:
3528 case Instruction::AtomicCmpXchg:
David Majnemer654e1302015-07-31 17:58:14 +00003529 case Instruction::LandingPad:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003530 case Instruction::Resume:
David Majnemer8a1c45d2015-12-12 05:38:55 +00003531 case Instruction::CatchSwitch:
David Majnemer654e1302015-07-31 17:58:14 +00003532 case Instruction::CatchPad:
David Majnemer654e1302015-07-31 17:58:14 +00003533 case Instruction::CatchRet:
3534 case Instruction::CleanupPad:
3535 case Instruction::CleanupRet:
Dan Gohman75d7d5e2011-12-14 23:49:11 +00003536 return false; // Misc instructions which have effects
3537 }
3538}
Dan Gohman1b0f79d2013-01-31 02:40:59 +00003539
Quentin Colombet6443cce2015-08-06 18:44:34 +00003540bool llvm::mayBeMemoryDependent(const Instruction &I) {
3541 return I.mayReadOrWriteMemory() || !isSafeToSpeculativelyExecute(&I);
3542}
3543
Pete Cooper35b00d52016-08-13 01:05:32 +00003544OverflowResult llvm::computeOverflowForUnsignedMul(const Value *LHS,
3545 const Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003546 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003547 AssumptionCache *AC,
David Majnemer491331a2015-01-02 07:29:43 +00003548 const Instruction *CxtI,
3549 const DominatorTree *DT) {
3550 // Multiplying n * m significant bits yields a result of n + m significant
3551 // bits. If the total number of significant bits does not exceed the
3552 // result bit width (minus 1), there is no overflow.
3553 // This means if we have enough leading zero bits in the operands
3554 // we can guarantee that the result does not overflow.
3555 // Ref: "Hacker's Delight" by Henry Warren
3556 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00003557 KnownBits LHSKnown(BitWidth);
3558 KnownBits RHSKnown(BitWidth);
3559 computeKnownBits(LHS, LHSKnown, DL, /*Depth=*/0, AC, CxtI, DT);
3560 computeKnownBits(RHS, RHSKnown, DL, /*Depth=*/0, AC, CxtI, DT);
David Majnemer491331a2015-01-02 07:29:43 +00003561 // Note that underestimating the number of zero bits gives a more
3562 // conservative answer.
Craig Topper8df66c62017-05-12 17:20:30 +00003563 unsigned ZeroBits = LHSKnown.countMinLeadingZeros() +
3564 RHSKnown.countMinLeadingZeros();
David Majnemer491331a2015-01-02 07:29:43 +00003565 // First handle the easy case: if we have enough zero bits there's
3566 // definitely no overflow.
3567 if (ZeroBits >= BitWidth)
3568 return OverflowResult::NeverOverflows;
3569
3570 // Get the largest possible values for each operand.
Craig Topperb45eabc2017-04-26 16:39:58 +00003571 APInt LHSMax = ~LHSKnown.Zero;
3572 APInt RHSMax = ~RHSKnown.Zero;
David Majnemer491331a2015-01-02 07:29:43 +00003573
3574 // We know the multiply operation doesn't overflow if the maximum values for
3575 // each operand will not overflow after we multiply them together.
David Majnemerc8a576b2015-01-02 07:29:47 +00003576 bool MaxOverflow;
Craig Topper9b71a402017-04-19 21:09:45 +00003577 (void)LHSMax.umul_ov(RHSMax, MaxOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00003578 if (!MaxOverflow)
3579 return OverflowResult::NeverOverflows;
David Majnemer491331a2015-01-02 07:29:43 +00003580
David Majnemerc8a576b2015-01-02 07:29:47 +00003581 // We know it always overflows if multiplying the smallest possible values for
3582 // the operands also results in overflow.
3583 bool MinOverflow;
Craig Topperb45eabc2017-04-26 16:39:58 +00003584 (void)LHSKnown.One.umul_ov(RHSKnown.One, MinOverflow);
David Majnemerc8a576b2015-01-02 07:29:47 +00003585 if (MinOverflow)
3586 return OverflowResult::AlwaysOverflows;
3587
3588 return OverflowResult::MayOverflow;
David Majnemer491331a2015-01-02 07:29:43 +00003589}
David Majnemer5310c1e2015-01-07 00:39:50 +00003590
Pete Cooper35b00d52016-08-13 01:05:32 +00003591OverflowResult llvm::computeOverflowForUnsignedAdd(const Value *LHS,
3592 const Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003593 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003594 AssumptionCache *AC,
David Majnemer5310c1e2015-01-07 00:39:50 +00003595 const Instruction *CxtI,
3596 const DominatorTree *DT) {
Craig Topper6e11a052017-05-08 16:22:48 +00003597 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
3598 if (LHSKnown.isNonNegative() || LHSKnown.isNegative()) {
3599 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
David Majnemer5310c1e2015-01-07 00:39:50 +00003600
Craig Topper6e11a052017-05-08 16:22:48 +00003601 if (LHSKnown.isNegative() && RHSKnown.isNegative()) {
David Majnemer5310c1e2015-01-07 00:39:50 +00003602 // The sign bit is set in both cases: this MUST overflow.
3603 // Create a simple add instruction, and insert it into the struct.
3604 return OverflowResult::AlwaysOverflows;
3605 }
3606
Craig Topper6e11a052017-05-08 16:22:48 +00003607 if (LHSKnown.isNonNegative() && RHSKnown.isNonNegative()) {
David Majnemer5310c1e2015-01-07 00:39:50 +00003608 // The sign bit is clear in both cases: this CANNOT overflow.
3609 // Create a simple add instruction, and insert it into the struct.
3610 return OverflowResult::NeverOverflows;
3611 }
3612 }
3613
3614 return OverflowResult::MayOverflow;
3615}
James Molloy71b91c22015-05-11 14:42:20 +00003616
Craig Topperbb973722017-05-15 02:44:08 +00003617/// \brief Return true if we can prove that adding the two values of the
3618/// knownbits will not overflow.
3619/// Otherwise return false.
3620static bool checkRippleForSignedAdd(const KnownBits &LHSKnown,
3621 const KnownBits &RHSKnown) {
3622 // Addition of two 2's complement numbers having opposite signs will never
3623 // overflow.
3624 if ((LHSKnown.isNegative() && RHSKnown.isNonNegative()) ||
3625 (LHSKnown.isNonNegative() && RHSKnown.isNegative()))
3626 return true;
3627
3628 // If either of the values is known to be non-negative, adding them can only
3629 // overflow if the second is also non-negative, so we can assume that.
3630 // Two non-negative numbers will only overflow if there is a carry to the
3631 // sign bit, so we can check if even when the values are as big as possible
3632 // there is no overflow to the sign bit.
3633 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative()) {
3634 APInt MaxLHS = ~LHSKnown.Zero;
3635 MaxLHS.clearSignBit();
3636 APInt MaxRHS = ~RHSKnown.Zero;
3637 MaxRHS.clearSignBit();
3638 APInt Result = std::move(MaxLHS) + std::move(MaxRHS);
3639 return Result.isSignBitClear();
3640 }
3641
3642 // If either of the values is known to be negative, adding them can only
3643 // overflow if the second is also negative, so we can assume that.
3644 // Two negative number will only overflow if there is no carry to the sign
3645 // bit, so we can check if even when the values are as small as possible
3646 // there is overflow to the sign bit.
3647 if (LHSKnown.isNegative() || RHSKnown.isNegative()) {
3648 APInt MinLHS = LHSKnown.One;
3649 MinLHS.clearSignBit();
3650 APInt MinRHS = RHSKnown.One;
3651 MinRHS.clearSignBit();
3652 APInt Result = std::move(MinLHS) + std::move(MinRHS);
3653 return Result.isSignBitSet();
3654 }
3655
3656 // If we reached here it means that we know nothing about the sign bits.
3657 // In this case we can't know if there will be an overflow, since by
3658 // changing the sign bits any two values can be made to overflow.
3659 return false;
3660}
3661
Pete Cooper35b00d52016-08-13 01:05:32 +00003662static OverflowResult computeOverflowForSignedAdd(const Value *LHS,
3663 const Value *RHS,
3664 const AddOperator *Add,
3665 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003666 AssumptionCache *AC,
Pete Cooper35b00d52016-08-13 01:05:32 +00003667 const Instruction *CxtI,
3668 const DominatorTree *DT) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00003669 if (Add && Add->hasNoSignedWrap()) {
3670 return OverflowResult::NeverOverflows;
3671 }
3672
Craig Topperbb973722017-05-15 02:44:08 +00003673 // If LHS and RHS each have at least two sign bits, the addition will look
3674 // like
3675 //
3676 // XX..... +
3677 // YY.....
3678 //
3679 // If the carry into the most significant position is 0, X and Y can't both
3680 // be 1 and therefore the carry out of the addition is also 0.
3681 //
3682 // If the carry into the most significant position is 1, X and Y can't both
3683 // be 0 and therefore the carry out of the addition is also 1.
3684 //
3685 // Since the carry into the most significant position is always equal to
3686 // the carry out of the addition, there is no signed overflow.
3687 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
3688 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
3689 return OverflowResult::NeverOverflows;
3690
Craig Topper6e11a052017-05-08 16:22:48 +00003691 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT);
3692 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003693
Craig Topperbb973722017-05-15 02:44:08 +00003694 if (checkRippleForSignedAdd(LHSKnown, RHSKnown))
Jingyue Wu10fcea52015-08-20 18:27:04 +00003695 return OverflowResult::NeverOverflows;
Jingyue Wu10fcea52015-08-20 18:27:04 +00003696
3697 // The remaining code needs Add to be available. Early returns if not so.
3698 if (!Add)
3699 return OverflowResult::MayOverflow;
3700
3701 // If the sign of Add is the same as at least one of the operands, this add
3702 // CANNOT overflow. This is particularly useful when the sum is
3703 // @llvm.assume'ed non-negative rather than proved so from analyzing its
3704 // operands.
3705 bool LHSOrRHSKnownNonNegative =
Craig Topper6e11a052017-05-08 16:22:48 +00003706 (LHSKnown.isNonNegative() || RHSKnown.isNonNegative());
Craig Topperbb973722017-05-15 02:44:08 +00003707 bool LHSOrRHSKnownNegative =
3708 (LHSKnown.isNegative() || RHSKnown.isNegative());
Jingyue Wu10fcea52015-08-20 18:27:04 +00003709 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
Craig Topper6e11a052017-05-08 16:22:48 +00003710 KnownBits AddKnown = computeKnownBits(Add, DL, /*Depth=*/0, AC, CxtI, DT);
3711 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
3712 (AddKnown.isNegative() && LHSOrRHSKnownNegative)) {
Jingyue Wu10fcea52015-08-20 18:27:04 +00003713 return OverflowResult::NeverOverflows;
3714 }
3715 }
3716
3717 return OverflowResult::MayOverflow;
3718}
3719
Pete Cooper35b00d52016-08-13 01:05:32 +00003720bool llvm::isOverflowIntrinsicNoWrap(const IntrinsicInst *II,
3721 const DominatorTree &DT) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003722#ifndef NDEBUG
3723 auto IID = II->getIntrinsicID();
3724 assert((IID == Intrinsic::sadd_with_overflow ||
3725 IID == Intrinsic::uadd_with_overflow ||
3726 IID == Intrinsic::ssub_with_overflow ||
3727 IID == Intrinsic::usub_with_overflow ||
3728 IID == Intrinsic::smul_with_overflow ||
3729 IID == Intrinsic::umul_with_overflow) &&
3730 "Not an overflow intrinsic!");
3731#endif
3732
Pete Cooper35b00d52016-08-13 01:05:32 +00003733 SmallVector<const BranchInst *, 2> GuardingBranches;
3734 SmallVector<const ExtractValueInst *, 2> Results;
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003735
Pete Cooper35b00d52016-08-13 01:05:32 +00003736 for (const User *U : II->users()) {
3737 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003738 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
3739
3740 if (EVI->getIndices()[0] == 0)
3741 Results.push_back(EVI);
3742 else {
3743 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
3744
Pete Cooper35b00d52016-08-13 01:05:32 +00003745 for (const auto *U : EVI->users())
3746 if (const auto *B = dyn_cast<BranchInst>(U)) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003747 assert(B->isConditional() && "How else is it using an i1?");
3748 GuardingBranches.push_back(B);
3749 }
3750 }
3751 } else {
3752 // We are using the aggregate directly in a way we don't want to analyze
3753 // here (storing it to a global, say).
3754 return false;
3755 }
3756 }
3757
Pete Cooper35b00d52016-08-13 01:05:32 +00003758 auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003759 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
3760 if (!NoWrapEdge.isSingleEdge())
3761 return false;
3762
3763 // Check if all users of the add are provably no-wrap.
Pete Cooper35b00d52016-08-13 01:05:32 +00003764 for (const auto *Result : Results) {
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003765 // If the extractvalue itself is not executed on overflow, the we don't
3766 // need to check each use separately, since domination is transitive.
3767 if (DT.dominates(NoWrapEdge, Result->getParent()))
3768 continue;
3769
3770 for (auto &RU : Result->uses())
3771 if (!DT.dominates(NoWrapEdge, RU))
3772 return false;
3773 }
3774
3775 return true;
3776 };
3777
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003778 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
Sanjoy Dasf49ca522016-05-29 00:34:42 +00003779}
3780
3781
Pete Cooper35b00d52016-08-13 01:05:32 +00003782OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003783 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003784 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003785 const Instruction *CxtI,
3786 const DominatorTree *DT) {
3787 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003788 Add, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003789}
3790
Pete Cooper35b00d52016-08-13 01:05:32 +00003791OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS,
3792 const Value *RHS,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003793 const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003794 AssumptionCache *AC,
Jingyue Wu10fcea52015-08-20 18:27:04 +00003795 const Instruction *CxtI,
3796 const DominatorTree *DT) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003797 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
Jingyue Wu10fcea52015-08-20 18:27:04 +00003798}
3799
Jingyue Wu42f1d672015-07-28 18:22:40 +00003800bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003801 // A memory operation returns normally if it isn't volatile. A volatile
3802 // operation is allowed to trap.
3803 //
3804 // An atomic operation isn't guaranteed to return in a reasonable amount of
3805 // time because it's possible for another thread to interfere with it for an
3806 // arbitrary length of time, but programs aren't allowed to rely on that.
3807 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
3808 return !LI->isVolatile();
3809 if (const StoreInst *SI = dyn_cast<StoreInst>(I))
3810 return !SI->isVolatile();
3811 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I))
3812 return !CXI->isVolatile();
3813 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I))
3814 return !RMWI->isVolatile();
3815 if (const MemIntrinsic *MII = dyn_cast<MemIntrinsic>(I))
3816 return !MII->isVolatile();
Jingyue Wu42f1d672015-07-28 18:22:40 +00003817
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003818 // If there is no successor, then execution can't transfer to it.
3819 if (const auto *CRI = dyn_cast<CleanupReturnInst>(I))
3820 return !CRI->unwindsToCaller();
3821 if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(I))
3822 return !CatchSwitch->unwindsToCaller();
3823 if (isa<ResumeInst>(I))
3824 return false;
3825 if (isa<ReturnInst>(I))
3826 return false;
Sebastian Pop4a4d2452017-03-08 01:54:50 +00003827 if (isa<UnreachableInst>(I))
3828 return false;
Sanjoy Das9a65cd22016-06-08 17:48:36 +00003829
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003830 // Calls can throw, or contain an infinite loop, or kill the process.
Sanjoy Das09455302016-12-31 22:12:31 +00003831 if (auto CS = ImmutableCallSite(I)) {
Sanjoy Das3bb2dbd2016-12-31 22:12:34 +00003832 // Call sites that throw have implicit non-local control flow.
3833 if (!CS.doesNotThrow())
3834 return false;
3835
3836 // Non-throwing call sites can loop infinitely, call exit/pthread_exit
3837 // etc. and thus not return. However, LLVM already assumes that
3838 //
3839 // - Thread exiting actions are modeled as writes to memory invisible to
3840 // the program.
3841 //
3842 // - Loops that don't have side effects (side effects are volatile/atomic
3843 // stores and IO) always terminate (see http://llvm.org/PR965).
3844 // Furthermore IO itself is also modeled as writes to memory invisible to
3845 // the program.
3846 //
3847 // We rely on those assumptions here, and use the memory effects of the call
3848 // target as a proxy for checking that it always returns.
3849
3850 // FIXME: This isn't aggressive enough; a call which only writes to a global
3851 // is guaranteed to return.
Sanjoy Dasd7e82062016-06-14 20:23:16 +00003852 return CS.onlyReadsMemory() || CS.onlyAccessesArgMemory() ||
Dan Gohman2c74fe92017-11-08 21:59:51 +00003853 match(I, m_Intrinsic<Intrinsic::assume>()) ||
3854 match(I, m_Intrinsic<Intrinsic::sideeffect>());
Eli Friedmanf1da33e2016-06-11 21:48:25 +00003855 }
3856
3857 // Other instructions return normally.
3858 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003859}
3860
3861bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
3862 const Loop *L) {
3863 // The loop header is guaranteed to be executed for every iteration.
3864 //
3865 // FIXME: Relax this constraint to cover all basic blocks that are
3866 // guaranteed to be executed at every iteration.
3867 if (I->getParent() != L->getHeader()) return false;
3868
3869 for (const Instruction &LI : *L->getHeader()) {
3870 if (&LI == I) return true;
3871 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
3872 }
3873 llvm_unreachable("Instruction not contained in its own parent basic block.");
3874}
3875
3876bool llvm::propagatesFullPoison(const Instruction *I) {
3877 switch (I->getOpcode()) {
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003878 case Instruction::Add:
3879 case Instruction::Sub:
3880 case Instruction::Xor:
3881 case Instruction::Trunc:
3882 case Instruction::BitCast:
3883 case Instruction::AddrSpaceCast:
Sanjoy Das5cd6c5ca2017-02-22 06:52:32 +00003884 case Instruction::Mul:
3885 case Instruction::Shl:
3886 case Instruction::GetElementPtr:
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003887 // These operations all propagate poison unconditionally. Note that poison
3888 // is not any particular value, so xor or subtraction of poison with
3889 // itself still yields poison, not zero.
3890 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003891
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003892 case Instruction::AShr:
3893 case Instruction::SExt:
3894 // For these operations, one bit of the input is replicated across
3895 // multiple output bits. A replicated poison bit is still poison.
3896 return true;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003897
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003898 case Instruction::ICmp:
3899 // Comparing poison with any value yields poison. This is why, for
3900 // instance, x s< (x +nsw 1) can be folded to true.
3901 return true;
Sanjoy Das70c2bbd2016-05-29 00:31:18 +00003902
Sanjoy Das7b0b4082017-02-21 02:42:42 +00003903 default:
3904 return false;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003905 }
3906}
3907
3908const Value *llvm::getGuaranteedNonFullPoisonOp(const Instruction *I) {
3909 switch (I->getOpcode()) {
3910 case Instruction::Store:
3911 return cast<StoreInst>(I)->getPointerOperand();
3912
3913 case Instruction::Load:
3914 return cast<LoadInst>(I)->getPointerOperand();
3915
3916 case Instruction::AtomicCmpXchg:
3917 return cast<AtomicCmpXchgInst>(I)->getPointerOperand();
3918
3919 case Instruction::AtomicRMW:
3920 return cast<AtomicRMWInst>(I)->getPointerOperand();
3921
3922 case Instruction::UDiv:
3923 case Instruction::SDiv:
3924 case Instruction::URem:
3925 case Instruction::SRem:
3926 return I->getOperand(1);
3927
3928 default:
3929 return nullptr;
3930 }
3931}
3932
Sanjoy Das08989c72017-04-30 19:41:19 +00003933bool llvm::programUndefinedIfFullPoison(const Instruction *PoisonI) {
Jingyue Wu42f1d672015-07-28 18:22:40 +00003934 // We currently only look for uses of poison values within the same basic
3935 // block, as that makes it easier to guarantee that the uses will be
3936 // executed given that PoisonI is executed.
3937 //
3938 // FIXME: Expand this to consider uses beyond the same basic block. To do
3939 // this, look out for the distinction between post-dominance and strong
3940 // post-dominance.
3941 const BasicBlock *BB = PoisonI->getParent();
3942
3943 // Set of instructions that we have proved will yield poison if PoisonI
3944 // does.
3945 SmallSet<const Value *, 16> YieldsPoison;
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003946 SmallSet<const BasicBlock *, 4> Visited;
Jingyue Wu42f1d672015-07-28 18:22:40 +00003947 YieldsPoison.insert(PoisonI);
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003948 Visited.insert(PoisonI->getParent());
Jingyue Wu42f1d672015-07-28 18:22:40 +00003949
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003950 BasicBlock::const_iterator Begin = PoisonI->getIterator(), End = BB->end();
Jingyue Wu42f1d672015-07-28 18:22:40 +00003951
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003952 unsigned Iter = 0;
3953 while (Iter++ < MaxDepth) {
3954 for (auto &I : make_range(Begin, End)) {
3955 if (&I != PoisonI) {
3956 const Value *NotPoison = getGuaranteedNonFullPoisonOp(&I);
3957 if (NotPoison != nullptr && YieldsPoison.count(NotPoison))
3958 return true;
3959 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
3960 return false;
3961 }
3962
3963 // Mark poison that propagates from I through uses of I.
3964 if (YieldsPoison.count(&I)) {
3965 for (const User *User : I.users()) {
3966 const Instruction *UserI = cast<Instruction>(User);
3967 if (propagatesFullPoison(UserI))
3968 YieldsPoison.insert(User);
3969 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003970 }
3971 }
Sanjoy Dasa6155b62016-04-22 17:41:06 +00003972
3973 if (auto *NextBB = BB->getSingleSuccessor()) {
3974 if (Visited.insert(NextBB).second) {
3975 BB = NextBB;
3976 Begin = BB->getFirstNonPHI()->getIterator();
3977 End = BB->end();
3978 continue;
3979 }
3980 }
3981
3982 break;
Eugene Zelenko75075ef2017-09-01 21:37:29 +00003983 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003984 return false;
3985}
3986
Pete Cooper35b00d52016-08-13 01:05:32 +00003987static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
James Molloy134bec22015-08-11 09:12:57 +00003988 if (FMF.noNaNs())
3989 return true;
3990
3991 if (auto *C = dyn_cast<ConstantFP>(V))
3992 return !C->isNaN();
3993 return false;
3994}
3995
Pete Cooper35b00d52016-08-13 01:05:32 +00003996static bool isKnownNonZero(const Value *V) {
James Molloy134bec22015-08-11 09:12:57 +00003997 if (auto *C = dyn_cast<ConstantFP>(V))
3998 return !C->isZero();
3999 return false;
4000}
4001
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004002/// Match clamp pattern for float types without care about NaNs or signed zeros.
4003/// Given non-min/max outer cmp/select from the clamp pattern this
4004/// function recognizes if it can be substitued by a "canonical" min/max
4005/// pattern.
4006static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred,
4007 Value *CmpLHS, Value *CmpRHS,
4008 Value *TrueVal, Value *FalseVal,
4009 Value *&LHS, Value *&RHS) {
4010 // Try to match
4011 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
4012 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
4013 // and return description of the outer Max/Min.
4014
4015 // First, check if select has inverse order:
4016 if (CmpRHS == FalseVal) {
4017 std::swap(TrueVal, FalseVal);
4018 Pred = CmpInst::getInversePredicate(Pred);
4019 }
4020
4021 // Assume success now. If there's no match, callers should not use these anyway.
4022 LHS = TrueVal;
4023 RHS = FalseVal;
4024
4025 const APFloat *FC1;
4026 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
4027 return {SPF_UNKNOWN, SPNB_NA, false};
4028
4029 const APFloat *FC2;
4030 switch (Pred) {
4031 case CmpInst::FCMP_OLT:
4032 case CmpInst::FCMP_OLE:
4033 case CmpInst::FCMP_ULT:
4034 case CmpInst::FCMP_ULE:
4035 if (match(FalseVal,
4036 m_CombineOr(m_OrdFMin(m_Specific(CmpLHS), m_APFloat(FC2)),
4037 m_UnordFMin(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4038 FC1->compare(*FC2) == APFloat::cmpResult::cmpLessThan)
4039 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
4040 break;
4041 case CmpInst::FCMP_OGT:
4042 case CmpInst::FCMP_OGE:
4043 case CmpInst::FCMP_UGT:
4044 case CmpInst::FCMP_UGE:
4045 if (match(FalseVal,
4046 m_CombineOr(m_OrdFMax(m_Specific(CmpLHS), m_APFloat(FC2)),
4047 m_UnordFMax(m_Specific(CmpLHS), m_APFloat(FC2)))) &&
4048 FC1->compare(*FC2) == APFloat::cmpResult::cmpGreaterThan)
4049 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
4050 break;
4051 default:
4052 break;
4053 }
4054
4055 return {SPF_UNKNOWN, SPNB_NA, false};
4056}
4057
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004058/// Recognize variations of:
4059/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
4060static SelectPatternResult matchClamp(CmpInst::Predicate Pred,
4061 Value *CmpLHS, Value *CmpRHS,
4062 Value *TrueVal, Value *FalseVal) {
4063 // Swap the select operands and predicate to match the patterns below.
4064 if (CmpRHS != TrueVal) {
4065 Pred = ICmpInst::getSwappedPredicate(Pred);
4066 std::swap(TrueVal, FalseVal);
4067 }
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004068 const APInt *C1;
4069 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
4070 const APInt *C2;
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004071 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
4072 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004073 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004074 return {SPF_SMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004075
4076 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
4077 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004078 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004079 return {SPF_SMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004080
4081 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
4082 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004083 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004084 return {SPF_UMAX, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004085
4086 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
4087 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004088 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004089 return {SPF_UMIN, SPNB_NA, false};
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004090 }
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004091 return {SPF_UNKNOWN, SPNB_NA, false};
4092}
4093
4094/// Match non-obvious integer minimum and maximum sequences.
4095static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
4096 Value *CmpLHS, Value *CmpRHS,
4097 Value *TrueVal, Value *FalseVal,
4098 Value *&LHS, Value *&RHS) {
4099 // Assume success. If there's no match, callers should not use these anyway.
4100 LHS = TrueVal;
4101 RHS = FalseVal;
4102
4103 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
4104 if (SPR.Flavor != SelectPatternFlavor::SPF_UNKNOWN)
4105 return SPR;
Sanjay Patel0c1c70a2017-01-20 22:18:47 +00004106
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004107 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
Sanjay Patel819f0962016-11-13 19:30:19 +00004108 return {SPF_UNKNOWN, SPNB_NA, false};
4109
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004110 // Z = X -nsw Y
4111 // (X >s Y) ? 0 : Z ==> (Z >s 0) ? 0 : Z ==> SMIN(Z, 0)
4112 // (X <s Y) ? 0 : Z ==> (Z <s 0) ? 0 : Z ==> SMAX(Z, 0)
4113 if (match(TrueVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004114 match(FalseVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004115 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004116
4117 // Z = X -nsw Y
4118 // (X >s Y) ? Z : 0 ==> (Z >s 0) ? Z : 0 ==> SMAX(Z, 0)
4119 // (X <s Y) ? Z : 0 ==> (Z <s 0) ? Z : 0 ==> SMIN(Z, 0)
4120 if (match(FalseVal, m_Zero()) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004121 match(TrueVal, m_NSWSub(m_Specific(CmpLHS), m_Specific(CmpRHS))))
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004122 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patelcfcc42b2016-11-13 20:04:52 +00004123
Artur Gainullinaf7ba8f2017-10-27 20:53:41 +00004124 const APInt *C1;
Sanjay Patel819f0962016-11-13 19:30:19 +00004125 if (!match(CmpRHS, m_APInt(C1)))
4126 return {SPF_UNKNOWN, SPNB_NA, false};
4127
4128 // An unsigned min/max can be written with a signed compare.
4129 const APInt *C2;
4130 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
4131 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
4132 // Is the sign bit set?
4133 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
4134 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
Craig Topper81d772c2017-11-08 19:38:45 +00004135 if (Pred == CmpInst::ICMP_SLT && C1->isNullValue() &&
4136 C2->isMaxSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004137 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004138
4139 // Is the sign bit clear?
4140 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
4141 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004142 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnesValue() &&
4143 C2->isMinSignedValue())
Sanjay Patel819f0962016-11-13 19:30:19 +00004144 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004145 }
4146
4147 // Look through 'not' ops to find disguised signed min/max.
4148 // (X >s C) ? ~X : ~C ==> (~X <s ~C) ? ~X : ~C ==> SMIN(~X, ~C)
4149 // (X <s C) ? ~X : ~C ==> (~X >s ~C) ? ~X : ~C ==> SMAX(~X, ~C)
4150 if (match(TrueVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004151 match(FalseVal, m_APInt(C2)) && ~(*C1) == *C2)
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004152 return {Pred == CmpInst::ICMP_SGT ? SPF_SMIN : SPF_SMAX, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004153
4154 // (X >s C) ? ~C : ~X ==> (~X <s ~C) ? ~C : ~X ==> SMAX(~C, ~X)
4155 // (X <s C) ? ~C : ~X ==> (~X >s ~C) ? ~C : ~X ==> SMIN(~C, ~X)
4156 if (match(FalseVal, m_Not(m_Specific(CmpLHS))) &&
Sanjay Patel24c6f882017-01-21 17:51:25 +00004157 match(TrueVal, m_APInt(C2)) && ~(*C1) == *C2)
Nikolai Bozhenov8dcab542017-10-19 15:36:18 +00004158 return {Pred == CmpInst::ICMP_SGT ? SPF_SMAX : SPF_SMIN, SPNB_NA, false};
Sanjay Patel819f0962016-11-13 19:30:19 +00004159
4160 return {SPF_UNKNOWN, SPNB_NA, false};
4161}
4162
James Molloy134bec22015-08-11 09:12:57 +00004163static SelectPatternResult matchSelectPattern(CmpInst::Predicate Pred,
4164 FastMathFlags FMF,
James Molloy270ef8c2015-05-15 16:04:50 +00004165 Value *CmpLHS, Value *CmpRHS,
4166 Value *TrueVal, Value *FalseVal,
4167 Value *&LHS, Value *&RHS) {
James Molloy71b91c22015-05-11 14:42:20 +00004168 LHS = CmpLHS;
4169 RHS = CmpRHS;
4170
James Molloy134bec22015-08-11 09:12:57 +00004171 // If the predicate is an "or-equal" (FP) predicate, then signed zeroes may
4172 // return inconsistent results between implementations.
4173 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
4174 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
4175 // Therefore we behave conservatively and only proceed if at least one of the
4176 // operands is known to not be zero, or if we don't care about signed zeroes.
4177 switch (Pred) {
4178 default: break;
4179 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLE:
4180 case CmpInst::FCMP_UGE: case CmpInst::FCMP_ULE:
4181 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4182 !isKnownNonZero(CmpRHS))
4183 return {SPF_UNKNOWN, SPNB_NA, false};
4184 }
4185
4186 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
4187 bool Ordered = false;
4188
4189 // When given one NaN and one non-NaN input:
4190 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
4191 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
4192 // ordered comparison fails), which could be NaN or non-NaN.
4193 // so here we discover exactly what NaN behavior is required/accepted.
4194 if (CmpInst::isFPPredicate(Pred)) {
4195 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
4196 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
4197
4198 if (LHSSafe && RHSSafe) {
4199 // Both operands are known non-NaN.
4200 NaNBehavior = SPNB_RETURNS_ANY;
4201 } else if (CmpInst::isOrdered(Pred)) {
4202 // An ordered comparison will return false when given a NaN, so it
4203 // returns the RHS.
4204 Ordered = true;
4205 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004206 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004207 NaNBehavior = SPNB_RETURNS_NAN;
4208 else if (RHSSafe)
4209 NaNBehavior = SPNB_RETURNS_OTHER;
4210 else
4211 // Completely unsafe.
4212 return {SPF_UNKNOWN, SPNB_NA, false};
4213 } else {
4214 Ordered = false;
4215 // An unordered comparison will return true when given a NaN, so it
4216 // returns the LHS.
4217 if (LHSSafe)
James Molloy8990b062015-08-12 15:11:43 +00004218 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
James Molloy134bec22015-08-11 09:12:57 +00004219 NaNBehavior = SPNB_RETURNS_OTHER;
4220 else if (RHSSafe)
4221 NaNBehavior = SPNB_RETURNS_NAN;
4222 else
4223 // Completely unsafe.
4224 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004225 }
4226 }
4227
James Molloy71b91c22015-05-11 14:42:20 +00004228 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
James Molloy134bec22015-08-11 09:12:57 +00004229 std::swap(CmpLHS, CmpRHS);
4230 Pred = CmpInst::getSwappedPredicate(Pred);
4231 if (NaNBehavior == SPNB_RETURNS_NAN)
4232 NaNBehavior = SPNB_RETURNS_OTHER;
4233 else if (NaNBehavior == SPNB_RETURNS_OTHER)
4234 NaNBehavior = SPNB_RETURNS_NAN;
4235 Ordered = !Ordered;
4236 }
4237
4238 // ([if]cmp X, Y) ? X : Y
4239 if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
James Molloy71b91c22015-05-11 14:42:20 +00004240 switch (Pred) {
James Molloy134bec22015-08-11 09:12:57 +00004241 default: return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
James Molloy71b91c22015-05-11 14:42:20 +00004242 case ICmpInst::ICMP_UGT:
James Molloy134bec22015-08-11 09:12:57 +00004243 case ICmpInst::ICMP_UGE: return {SPF_UMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004244 case ICmpInst::ICMP_SGT:
James Molloy134bec22015-08-11 09:12:57 +00004245 case ICmpInst::ICMP_SGE: return {SPF_SMAX, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004246 case ICmpInst::ICMP_ULT:
James Molloy134bec22015-08-11 09:12:57 +00004247 case ICmpInst::ICMP_ULE: return {SPF_UMIN, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004248 case ICmpInst::ICMP_SLT:
James Molloy134bec22015-08-11 09:12:57 +00004249 case ICmpInst::ICMP_SLE: return {SPF_SMIN, SPNB_NA, false};
4250 case FCmpInst::FCMP_UGT:
4251 case FCmpInst::FCMP_UGE:
4252 case FCmpInst::FCMP_OGT:
4253 case FCmpInst::FCMP_OGE: return {SPF_FMAXNUM, NaNBehavior, Ordered};
4254 case FCmpInst::FCMP_ULT:
4255 case FCmpInst::FCMP_ULE:
4256 case FCmpInst::FCMP_OLT:
4257 case FCmpInst::FCMP_OLE: return {SPF_FMINNUM, NaNBehavior, Ordered};
James Molloy71b91c22015-05-11 14:42:20 +00004258 }
4259 }
4260
Sanjay Patele372aec2016-10-27 15:26:10 +00004261 const APInt *C1;
4262 if (match(CmpRHS, m_APInt(C1))) {
James Molloy71b91c22015-05-11 14:42:20 +00004263 if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) ||
4264 (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) {
4265
4266 // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X
4267 // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X
Craig Topper81d772c2017-11-08 19:38:45 +00004268 if (Pred == ICmpInst::ICMP_SGT &&
4269 (C1->isNullValue() || C1->isAllOnesValue())) {
James Molloy134bec22015-08-11 09:12:57 +00004270 return {(CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004271 }
4272
4273 // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X
4274 // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X
Craig Topper81d772c2017-11-08 19:38:45 +00004275 if (Pred == ICmpInst::ICMP_SLT &&
4276 (C1->isNullValue() || C1->isOneValue())) {
James Molloy134bec22015-08-11 09:12:57 +00004277 return {(CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS, SPNB_NA, false};
James Molloy71b91c22015-05-11 14:42:20 +00004278 }
4279 }
James Molloy71b91c22015-05-11 14:42:20 +00004280 }
4281
Nikolai Bozhenov1545eb32017-08-04 12:22:17 +00004282 if (CmpInst::isIntPredicate(Pred))
4283 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
4284
4285 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
4286 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
4287 // semantics than minNum. Be conservative in such case.
4288 if (NaNBehavior != SPNB_RETURNS_ANY ||
4289 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
4290 !isKnownNonZero(CmpRHS)))
4291 return {SPF_UNKNOWN, SPNB_NA, false};
4292
4293 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
James Molloy71b91c22015-05-11 14:42:20 +00004294}
James Molloy270ef8c2015-05-15 16:04:50 +00004295
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004296/// Helps to match a select pattern in case of a type mismatch.
4297///
4298/// The function processes the case when type of true and false values of a
4299/// select instruction differs from type of the cmp instruction operands because
4300/// of a cast instructon. The function checks if it is legal to move the cast
4301/// operation after "select". If yes, it returns the new second value of
4302/// "select" (with the assumption that cast is moved):
4303/// 1. As operand of cast instruction when both values of "select" are same cast
4304/// instructions.
4305/// 2. As restored constant (by applying reverse cast operation) when the first
4306/// value of the "select" is a cast operation and the second value is a
4307/// constant.
4308/// NOTE: We return only the new second value because the first value could be
4309/// accessed as operand of cast instruction.
James Molloy569cea62015-09-02 17:25:25 +00004310static Value *lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2,
4311 Instruction::CastOps *CastOp) {
Sanjay Patel14a4b812017-01-29 16:34:57 +00004312 auto *Cast1 = dyn_cast<CastInst>(V1);
4313 if (!Cast1)
James Molloy270ef8c2015-05-15 16:04:50 +00004314 return nullptr;
James Molloy270ef8c2015-05-15 16:04:50 +00004315
Sanjay Patel14a4b812017-01-29 16:34:57 +00004316 *CastOp = Cast1->getOpcode();
4317 Type *SrcTy = Cast1->getSrcTy();
4318 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
4319 // If V1 and V2 are both the same cast from the same type, look through V1.
4320 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
4321 return Cast2->getOperand(0);
James Molloy569cea62015-09-02 17:25:25 +00004322 return nullptr;
4323 }
4324
Sanjay Patel14a4b812017-01-29 16:34:57 +00004325 auto *C = dyn_cast<Constant>(V2);
4326 if (!C)
4327 return nullptr;
4328
David Majnemerd2a074b2016-04-29 18:40:34 +00004329 Constant *CastedTo = nullptr;
Sanjay Patel14a4b812017-01-29 16:34:57 +00004330 switch (*CastOp) {
4331 case Instruction::ZExt:
4332 if (CmpI->isUnsigned())
4333 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
4334 break;
4335 case Instruction::SExt:
4336 if (CmpI->isSigned())
4337 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
4338 break;
4339 case Instruction::Trunc:
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004340 Constant *CmpConst;
Nikolai Bozhenov9723f122017-10-18 14:24:50 +00004341 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
4342 CmpConst->getType() == SrcTy) {
Nikolai Bozhenov74c047e2017-10-18 09:28:09 +00004343 // Here we have the following case:
4344 //
4345 // %cond = cmp iN %x, CmpConst
4346 // %tr = trunc iN %x to iK
4347 // %narrowsel = select i1 %cond, iK %t, iK C
4348 //
4349 // We can always move trunc after select operation:
4350 //
4351 // %cond = cmp iN %x, CmpConst
4352 // %widesel = select i1 %cond, iN %x, iN CmpConst
4353 // %tr = trunc iN %widesel to iK
4354 //
4355 // Note that C could be extended in any way because we don't care about
4356 // upper bits after truncation. It can't be abs pattern, because it would
4357 // look like:
4358 //
4359 // select i1 %cond, x, -x.
4360 //
4361 // So only min/max pattern could be matched. Such match requires widened C
4362 // == CmpConst. That is why set widened C = CmpConst, condition trunc
4363 // CmpConst == C is checked below.
4364 CastedTo = CmpConst;
4365 } else {
4366 CastedTo = ConstantExpr::getIntegerCast(C, SrcTy, CmpI->isSigned());
4367 }
Sanjay Patel14a4b812017-01-29 16:34:57 +00004368 break;
4369 case Instruction::FPTrunc:
4370 CastedTo = ConstantExpr::getFPExtend(C, SrcTy, true);
4371 break;
4372 case Instruction::FPExt:
4373 CastedTo = ConstantExpr::getFPTrunc(C, SrcTy, true);
4374 break;
4375 case Instruction::FPToUI:
4376 CastedTo = ConstantExpr::getUIToFP(C, SrcTy, true);
4377 break;
4378 case Instruction::FPToSI:
4379 CastedTo = ConstantExpr::getSIToFP(C, SrcTy, true);
4380 break;
4381 case Instruction::UIToFP:
4382 CastedTo = ConstantExpr::getFPToUI(C, SrcTy, true);
4383 break;
4384 case Instruction::SIToFP:
4385 CastedTo = ConstantExpr::getFPToSI(C, SrcTy, true);
4386 break;
4387 default:
4388 break;
4389 }
David Majnemerd2a074b2016-04-29 18:40:34 +00004390
4391 if (!CastedTo)
4392 return nullptr;
4393
David Majnemerd2a074b2016-04-29 18:40:34 +00004394 // Make sure the cast doesn't lose any information.
Sanjay Patel14a4b812017-01-29 16:34:57 +00004395 Constant *CastedBack =
4396 ConstantExpr::getCast(*CastOp, CastedTo, C->getType(), true);
David Majnemerd2a074b2016-04-29 18:40:34 +00004397 if (CastedBack != C)
4398 return nullptr;
4399
4400 return CastedTo;
James Molloy270ef8c2015-05-15 16:04:50 +00004401}
4402
Sanjay Patele8dc0902016-05-23 17:57:54 +00004403SelectPatternResult llvm::matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004404 Instruction::CastOps *CastOp) {
4405 SelectInst *SI = dyn_cast<SelectInst>(V);
James Molloy134bec22015-08-11 09:12:57 +00004406 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004407
James Molloy134bec22015-08-11 09:12:57 +00004408 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
4409 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004410
James Molloy134bec22015-08-11 09:12:57 +00004411 CmpInst::Predicate Pred = CmpI->getPredicate();
James Molloy270ef8c2015-05-15 16:04:50 +00004412 Value *CmpLHS = CmpI->getOperand(0);
4413 Value *CmpRHS = CmpI->getOperand(1);
4414 Value *TrueVal = SI->getTrueValue();
4415 Value *FalseVal = SI->getFalseValue();
James Molloy134bec22015-08-11 09:12:57 +00004416 FastMathFlags FMF;
4417 if (isa<FPMathOperator>(CmpI))
4418 FMF = CmpI->getFastMathFlags();
James Molloy270ef8c2015-05-15 16:04:50 +00004419
4420 // Bail out early.
4421 if (CmpI->isEquality())
James Molloy134bec22015-08-11 09:12:57 +00004422 return {SPF_UNKNOWN, SPNB_NA, false};
James Molloy270ef8c2015-05-15 16:04:50 +00004423
4424 // Deal with type mismatches.
4425 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
James Molloy569cea62015-09-02 17:25:25 +00004426 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp))
James Molloy134bec22015-08-11 09:12:57 +00004427 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004428 cast<CastInst>(TrueVal)->getOperand(0), C,
4429 LHS, RHS);
James Molloy569cea62015-09-02 17:25:25 +00004430 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp))
James Molloy134bec22015-08-11 09:12:57 +00004431 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
James Molloy270ef8c2015-05-15 16:04:50 +00004432 C, cast<CastInst>(FalseVal)->getOperand(0),
4433 LHS, RHS);
4434 }
James Molloy134bec22015-08-11 09:12:57 +00004435 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
James Molloy270ef8c2015-05-15 16:04:50 +00004436 LHS, RHS);
4437}
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004438
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004439/// Return true if "icmp Pred LHS RHS" is always true.
Chad Rosiere42b44b2017-07-28 14:39:06 +00004440static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
4441 const Value *RHS, const DataLayout &DL,
4442 unsigned Depth) {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004443 assert(!LHS->getType()->isVectorTy() && "TODO: extend to handle vectors!");
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004444 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
4445 return true;
4446
4447 switch (Pred) {
4448 default:
4449 return false;
4450
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004451 case CmpInst::ICMP_SLE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004452 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004453
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004454 // LHS s<= LHS +_{nsw} C if C >= 0
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004455 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004456 return !C->isNegative();
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004457 return false;
4458 }
4459
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004460 case CmpInst::ICMP_ULE: {
Sanjoy Dasaf1400f2015-11-10 23:56:15 +00004461 const APInt *C;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004462
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004463 // LHS u<= LHS +_{nuw} C for any C
4464 if (match(RHS, m_NUWAdd(m_Specific(LHS), m_APInt(C))))
Sanjoy Dasc01b4d22015-11-06 19:01:03 +00004465 return true;
Sanjoy Das92568102015-11-10 23:56:20 +00004466
4467 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
Pete Cooper35b00d52016-08-13 01:05:32 +00004468 auto MatchNUWAddsToSameValue = [&](const Value *A, const Value *B,
4469 const Value *&X,
Sanjoy Das92568102015-11-10 23:56:20 +00004470 const APInt *&CA, const APInt *&CB) {
4471 if (match(A, m_NUWAdd(m_Value(X), m_APInt(CA))) &&
4472 match(B, m_NUWAdd(m_Specific(X), m_APInt(CB))))
4473 return true;
4474
4475 // If X & C == 0 then (X | C) == X +_{nuw} C
4476 if (match(A, m_Or(m_Value(X), m_APInt(CA))) &&
4477 match(B, m_Or(m_Specific(X), m_APInt(CB)))) {
Craig Topperb45eabc2017-04-26 16:39:58 +00004478 KnownBits Known(CA->getBitWidth());
Chad Rosiere42b44b2017-07-28 14:39:06 +00004479 computeKnownBits(X, Known, DL, Depth + 1, /*AC*/ nullptr,
4480 /*CxtI*/ nullptr, /*DT*/ nullptr);
Craig Topperb45eabc2017-04-26 16:39:58 +00004481 if (CA->isSubsetOf(Known.Zero) && CB->isSubsetOf(Known.Zero))
Sanjoy Das92568102015-11-10 23:56:20 +00004482 return true;
4483 }
4484
4485 return false;
4486 };
4487
Pete Cooper35b00d52016-08-13 01:05:32 +00004488 const Value *X;
Sanjoy Das92568102015-11-10 23:56:20 +00004489 const APInt *CLHS, *CRHS;
Sanjoy Dasdc26df42015-11-11 00:16:41 +00004490 if (MatchNUWAddsToSameValue(LHS, RHS, X, CLHS, CRHS))
4491 return CLHS->ule(*CRHS);
Sanjoy Das92568102015-11-10 23:56:20 +00004492
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004493 return false;
4494 }
4495 }
4496}
4497
4498/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
Chad Rosier41dd31f2016-04-20 19:15:26 +00004499/// ALHS ARHS" is true. Otherwise, return None.
4500static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00004501isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS,
Chad Rosiere42b44b2017-07-28 14:39:06 +00004502 const Value *ARHS, const Value *BLHS, const Value *BRHS,
4503 const DataLayout &DL, unsigned Depth) {
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004504 switch (Pred) {
4505 default:
Chad Rosier41dd31f2016-04-20 19:15:26 +00004506 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004507
4508 case CmpInst::ICMP_SLT:
4509 case CmpInst::ICMP_SLE:
Chad Rosiere42b44b2017-07-28 14:39:06 +00004510 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS, DL, Depth) &&
4511 isTruePredicate(CmpInst::ICMP_SLE, ARHS, BRHS, DL, Depth))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004512 return true;
4513 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004514
4515 case CmpInst::ICMP_ULT:
4516 case CmpInst::ICMP_ULE:
Chad Rosiere42b44b2017-07-28 14:39:06 +00004517 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS, DL, Depth) &&
4518 isTruePredicate(CmpInst::ICMP_ULE, ARHS, BRHS, DL, Depth))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004519 return true;
4520 return None;
Sanjoy Das9349dcc2015-11-06 19:00:57 +00004521 }
4522}
4523
Chad Rosier226a7342016-05-05 17:41:19 +00004524/// Return true if the operands of the two compares match. IsSwappedOps is true
4525/// when the operands match, but are swapped.
Pete Cooper35b00d52016-08-13 01:05:32 +00004526static bool isMatchingOps(const Value *ALHS, const Value *ARHS,
4527 const Value *BLHS, const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00004528 bool &IsSwappedOps) {
4529
4530 bool IsMatchingOps = (ALHS == BLHS && ARHS == BRHS);
4531 IsSwappedOps = (ALHS == BRHS && ARHS == BLHS);
4532 return IsMatchingOps || IsSwappedOps;
4533}
4534
Chad Rosier41dd31f2016-04-20 19:15:26 +00004535/// Return true if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS BRHS" is
4536/// true. Return false if "icmp1 APred ALHS ARHS" implies "icmp2 BPred BLHS
4537/// BRHS" is false. Otherwise, return None if we can't infer anything.
4538static Optional<bool> isImpliedCondMatchingOperands(CmpInst::Predicate APred,
Pete Cooper35b00d52016-08-13 01:05:32 +00004539 const Value *ALHS,
4540 const Value *ARHS,
Chad Rosier41dd31f2016-04-20 19:15:26 +00004541 CmpInst::Predicate BPred,
Pete Cooper35b00d52016-08-13 01:05:32 +00004542 const Value *BLHS,
4543 const Value *BRHS,
Chad Rosier226a7342016-05-05 17:41:19 +00004544 bool IsSwappedOps) {
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004545 // Canonicalize the operands so they're matching.
4546 if (IsSwappedOps) {
4547 std::swap(BLHS, BRHS);
4548 BPred = ICmpInst::getSwappedPredicate(BPred);
4549 }
Chad Rosier99bc4802016-04-21 16:18:02 +00004550 if (CmpInst::isImpliedTrueByMatchingCmp(APred, BPred))
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004551 return true;
Chad Rosier99bc4802016-04-21 16:18:02 +00004552 if (CmpInst::isImpliedFalseByMatchingCmp(APred, BPred))
Chad Rosier41dd31f2016-04-20 19:15:26 +00004553 return false;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004554
Chad Rosier41dd31f2016-04-20 19:15:26 +00004555 return None;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00004556}
4557
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004558/// Return true if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS C2" is
4559/// true. Return false if "icmp1 APred ALHS C1" implies "icmp2 BPred BLHS
4560/// C2" is false. Otherwise, return None if we can't infer anything.
4561static Optional<bool>
Pete Cooper35b00d52016-08-13 01:05:32 +00004562isImpliedCondMatchingImmOperands(CmpInst::Predicate APred, const Value *ALHS,
4563 const ConstantInt *C1,
4564 CmpInst::Predicate BPred,
4565 const Value *BLHS, const ConstantInt *C2) {
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004566 assert(ALHS == BLHS && "LHS operands must match.");
4567 ConstantRange DomCR =
4568 ConstantRange::makeExactICmpRegion(APred, C1->getValue());
4569 ConstantRange CR =
4570 ConstantRange::makeAllowedICmpRegion(BPred, C2->getValue());
4571 ConstantRange Intersection = DomCR.intersectWith(CR);
4572 ConstantRange Difference = DomCR.difference(CR);
4573 if (Intersection.isEmptySet())
4574 return false;
4575 if (Difference.isEmptySet())
4576 return true;
4577 return None;
4578}
4579
Chad Rosier2f498032017-07-28 18:47:43 +00004580/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
4581/// false. Otherwise, return None if we can't infer anything.
4582static Optional<bool> isImpliedCondICmps(const ICmpInst *LHS,
4583 const ICmpInst *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00004584 const DataLayout &DL, bool LHSIsTrue,
Chad Rosier2f498032017-07-28 18:47:43 +00004585 unsigned Depth) {
4586 Value *ALHS = LHS->getOperand(0);
4587 Value *ARHS = LHS->getOperand(1);
Chad Rosiera72a9ff2017-07-06 20:00:25 +00004588 // The rest of the logic assumes the LHS condition is true. If that's not the
4589 // case, invert the predicate to make it so.
Chad Rosier2f498032017-07-28 18:47:43 +00004590 ICmpInst::Predicate APred =
Chad Rosierdfd1de62017-08-01 20:18:54 +00004591 LHSIsTrue ? LHS->getPredicate() : LHS->getInversePredicate();
Chad Rosier2f498032017-07-28 18:47:43 +00004592
4593 Value *BLHS = RHS->getOperand(0);
4594 Value *BRHS = RHS->getOperand(1);
4595 ICmpInst::Predicate BPred = RHS->getPredicate();
Chad Rosiere2cbd132016-04-25 17:23:36 +00004596
Chad Rosier226a7342016-05-05 17:41:19 +00004597 // Can we infer anything when the two compares have matching operands?
4598 bool IsSwappedOps;
4599 if (isMatchingOps(ALHS, ARHS, BLHS, BRHS, IsSwappedOps)) {
4600 if (Optional<bool> Implication = isImpliedCondMatchingOperands(
4601 APred, ALHS, ARHS, BPred, BLHS, BRHS, IsSwappedOps))
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004602 return Implication;
Chad Rosier226a7342016-05-05 17:41:19 +00004603 // No amount of additional analysis will infer the second condition, so
4604 // early exit.
4605 return None;
4606 }
4607
4608 // Can we infer anything when the LHS operands match and the RHS operands are
4609 // constants (not necessarily matching)?
4610 if (ALHS == BLHS && isa<ConstantInt>(ARHS) && isa<ConstantInt>(BRHS)) {
4611 if (Optional<bool> Implication = isImpliedCondMatchingImmOperands(
4612 APred, ALHS, cast<ConstantInt>(ARHS), BPred, BLHS,
4613 cast<ConstantInt>(BRHS)))
4614 return Implication;
4615 // No amount of additional analysis will infer the second condition, so
4616 // early exit.
4617 return None;
Chad Rosier25cfb7d2016-05-05 15:39:18 +00004618 }
4619
Chad Rosier41dd31f2016-04-20 19:15:26 +00004620 if (APred == BPred)
Chad Rosiere42b44b2017-07-28 14:39:06 +00004621 return isImpliedCondOperands(APred, ALHS, ARHS, BLHS, BRHS, DL, Depth);
Chad Rosier41dd31f2016-04-20 19:15:26 +00004622 return None;
Sanjoy Das3ef1e682015-10-28 03:20:19 +00004623}
Chad Rosier2f498032017-07-28 18:47:43 +00004624
Chad Rosierf73a10d2017-08-01 19:22:36 +00004625/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
4626/// false. Otherwise, return None if we can't infer anything. We expect the
4627/// RHS to be an icmp and the LHS to be an 'and' or an 'or' instruction.
4628static Optional<bool> isImpliedCondAndOr(const BinaryOperator *LHS,
4629 const ICmpInst *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00004630 const DataLayout &DL, bool LHSIsTrue,
Chad Rosierf73a10d2017-08-01 19:22:36 +00004631 unsigned Depth) {
4632 // The LHS must be an 'or' or an 'and' instruction.
4633 assert((LHS->getOpcode() == Instruction::And ||
4634 LHS->getOpcode() == Instruction::Or) &&
4635 "Expected LHS to be 'and' or 'or'.");
4636
Davide Italiano1a943a92017-08-09 16:06:54 +00004637 assert(Depth <= MaxDepth && "Hit recursion limit");
Chad Rosierf73a10d2017-08-01 19:22:36 +00004638
4639 // If the result of an 'or' is false, then we know both legs of the 'or' are
4640 // false. Similarly, if the result of an 'and' is true, then we know both
4641 // legs of the 'and' are true.
4642 Value *ALHS, *ARHS;
Chad Rosierdfd1de62017-08-01 20:18:54 +00004643 if ((!LHSIsTrue && match(LHS, m_Or(m_Value(ALHS), m_Value(ARHS)))) ||
4644 (LHSIsTrue && match(LHS, m_And(m_Value(ALHS), m_Value(ARHS))))) {
Chad Rosierf73a10d2017-08-01 19:22:36 +00004645 // FIXME: Make this non-recursion.
4646 if (Optional<bool> Implication =
Chad Rosierdfd1de62017-08-01 20:18:54 +00004647 isImpliedCondition(ALHS, RHS, DL, LHSIsTrue, Depth + 1))
Chad Rosierf73a10d2017-08-01 19:22:36 +00004648 return Implication;
4649 if (Optional<bool> Implication =
Chad Rosierdfd1de62017-08-01 20:18:54 +00004650 isImpliedCondition(ARHS, RHS, DL, LHSIsTrue, Depth + 1))
Chad Rosierf73a10d2017-08-01 19:22:36 +00004651 return Implication;
4652 return None;
4653 }
4654 return None;
4655}
4656
Chad Rosier2f498032017-07-28 18:47:43 +00004657Optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
Chad Rosierdfd1de62017-08-01 20:18:54 +00004658 const DataLayout &DL, bool LHSIsTrue,
Chad Rosier2f498032017-07-28 18:47:43 +00004659 unsigned Depth) {
Davide Italiano30e51942017-08-09 15:13:50 +00004660 // Bail out when we hit the limit.
4661 if (Depth == MaxDepth)
4662 return None;
4663
Chad Rosierf73a10d2017-08-01 19:22:36 +00004664 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
4665 // example.
Chad Rosier2f498032017-07-28 18:47:43 +00004666 if (LHS->getType() != RHS->getType())
4667 return None;
4668
4669 Type *OpTy = LHS->getType();
Chad Rosierf73a10d2017-08-01 19:22:36 +00004670 assert(OpTy->isIntOrIntVectorTy(1) && "Expected integer type only!");
Chad Rosier2f498032017-07-28 18:47:43 +00004671
4672 // LHS ==> RHS by definition
4673 if (LHS == RHS)
Chad Rosierdfd1de62017-08-01 20:18:54 +00004674 return LHSIsTrue;
Chad Rosier2f498032017-07-28 18:47:43 +00004675
Chad Rosierf73a10d2017-08-01 19:22:36 +00004676 // FIXME: Extending the code below to handle vectors.
Chad Rosier2f498032017-07-28 18:47:43 +00004677 if (OpTy->isVectorTy())
Chad Rosier2f498032017-07-28 18:47:43 +00004678 return None;
Chad Rosierf73a10d2017-08-01 19:22:36 +00004679
Chad Rosier2f498032017-07-28 18:47:43 +00004680 assert(OpTy->isIntegerTy(1) && "implied by above");
4681
Chad Rosier2f498032017-07-28 18:47:43 +00004682 // Both LHS and RHS are icmps.
Chad Rosierf73a10d2017-08-01 19:22:36 +00004683 const ICmpInst *LHSCmp = dyn_cast<ICmpInst>(LHS);
4684 const ICmpInst *RHSCmp = dyn_cast<ICmpInst>(RHS);
4685 if (LHSCmp && RHSCmp)
Chad Rosierdfd1de62017-08-01 20:18:54 +00004686 return isImpliedCondICmps(LHSCmp, RHSCmp, DL, LHSIsTrue, Depth);
Chad Rosier2f498032017-07-28 18:47:43 +00004687
Chad Rosierf73a10d2017-08-01 19:22:36 +00004688 // The LHS should be an 'or' or an 'and' instruction. We expect the RHS to be
4689 // an icmp. FIXME: Add support for and/or on the RHS.
4690 const BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHS);
4691 if (LHSBO && RHSCmp) {
4692 if ((LHSBO->getOpcode() == Instruction::And ||
4693 LHSBO->getOpcode() == Instruction::Or))
Chad Rosierdfd1de62017-08-01 20:18:54 +00004694 return isImpliedCondAndOr(LHSBO, RHSCmp, DL, LHSIsTrue, Depth);
Chad Rosier2f498032017-07-28 18:47:43 +00004695 }
Chad Rosierf73a10d2017-08-01 19:22:36 +00004696 return None;
Chad Rosier2f498032017-07-28 18:47:43 +00004697}