Bug Summary

File:build/source/llvm/lib/Analysis/ValueTracking.cpp
Warning:line 190, column 42
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ValueTracking.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Analysis -I /build/source/llvm/lib/Analysis -I include -I /build/source/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -source-date-epoch 1668078801 -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-11-10-135928-647445-1 -x c++ /build/source/llvm/lib/Analysis/ValueTracking.cpp
1//===- ValueTracking.cpp - Walk computations to compute properties --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains routines that help analyze properties that chains of
10// computations have.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Analysis/ValueTracking.h"
15#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/None.h"
19#include "llvm/ADT/Optional.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/StringRef.h"
25#include "llvm/ADT/iterator_range.h"
26#include "llvm/Analysis/AliasAnalysis.h"
27#include "llvm/Analysis/AssumeBundleQueries.h"
28#include "llvm/Analysis/AssumptionCache.h"
29#include "llvm/Analysis/ConstantFolding.h"
30#include "llvm/Analysis/EHPersonalities.h"
31#include "llvm/Analysis/GuardUtils.h"
32#include "llvm/Analysis/InstructionSimplify.h"
33#include "llvm/Analysis/Loads.h"
34#include "llvm/Analysis/LoopInfo.h"
35#include "llvm/Analysis/OptimizationRemarkEmitter.h"
36#include "llvm/Analysis/TargetLibraryInfo.h"
37#include "llvm/Analysis/VectorUtils.h"
38#include "llvm/IR/Argument.h"
39#include "llvm/IR/Attributes.h"
40#include "llvm/IR/BasicBlock.h"
41#include "llvm/IR/Constant.h"
42#include "llvm/IR/ConstantRange.h"
43#include "llvm/IR/Constants.h"
44#include "llvm/IR/DerivedTypes.h"
45#include "llvm/IR/DiagnosticInfo.h"
46#include "llvm/IR/Dominators.h"
47#include "llvm/IR/Function.h"
48#include "llvm/IR/GetElementPtrTypeIterator.h"
49#include "llvm/IR/GlobalAlias.h"
50#include "llvm/IR/GlobalValue.h"
51#include "llvm/IR/GlobalVariable.h"
52#include "llvm/IR/InstrTypes.h"
53#include "llvm/IR/Instruction.h"
54#include "llvm/IR/Instructions.h"
55#include "llvm/IR/IntrinsicInst.h"
56#include "llvm/IR/Intrinsics.h"
57#include "llvm/IR/IntrinsicsAArch64.h"
58#include "llvm/IR/IntrinsicsRISCV.h"
59#include "llvm/IR/IntrinsicsX86.h"
60#include "llvm/IR/LLVMContext.h"
61#include "llvm/IR/Metadata.h"
62#include "llvm/IR/Module.h"
63#include "llvm/IR/Operator.h"
64#include "llvm/IR/PatternMatch.h"
65#include "llvm/IR/Type.h"
66#include "llvm/IR/User.h"
67#include "llvm/IR/Value.h"
68#include "llvm/Support/Casting.h"
69#include "llvm/Support/CommandLine.h"
70#include "llvm/Support/Compiler.h"
71#include "llvm/Support/ErrorHandling.h"
72#include "llvm/Support/KnownBits.h"
73#include "llvm/Support/MathExtras.h"
74#include <algorithm>
75#include <cassert>
76#include <cstdint>
77#include <utility>
78
79using namespace llvm;
80using namespace llvm::PatternMatch;
81
82// Controls the number of uses of the value searched for possible
83// dominating comparisons.
84static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
85 cl::Hidden, cl::init(20));
86
87// According to the LangRef, branching on a poison condition is absolutely
88// immediate full UB. However, historically we haven't implemented that
89// consistently as we had an important transformation (non-trivial unswitch)
90// which introduced instances of branch on poison/undef to otherwise well
91// defined programs. This issue has since been fixed, but the flag is
92// temporarily retained to easily diagnose potential regressions.
93static cl::opt<bool> BranchOnPoisonAsUB("branch-on-poison-as-ub",
94 cl::Hidden, cl::init(true));
95
96
97/// Returns the bitwidth of the given scalar or pointer type. For vector types,
98/// returns the element type's bitwidth.
99static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
100 if (unsigned BitWidth = Ty->getScalarSizeInBits())
101 return BitWidth;
102
103 return DL.getPointerTypeSizeInBits(Ty);
104}
105
106namespace {
107
108// Simplifying using an assume can only be done in a particular control-flow
109// context (the context instruction provides that context). If an assume and
110// the context instruction are not in the same block then the DT helps in
111// figuring out if we can use it.
112struct Query {
113 const DataLayout &DL;
114 AssumptionCache *AC;
115 const Instruction *CxtI;
116 const DominatorTree *DT;
117
118 // Unlike the other analyses, this may be a nullptr because not all clients
119 // provide it currently.
120 OptimizationRemarkEmitter *ORE;
121
122 /// If true, it is safe to use metadata during simplification.
123 InstrInfoQuery IIQ;
124
125 Query(const DataLayout &DL, AssumptionCache *AC, const Instruction *CxtI,
126 const DominatorTree *DT, bool UseInstrInfo,
127 OptimizationRemarkEmitter *ORE = nullptr)
128 : DL(DL), AC(AC), CxtI(CxtI), DT(DT), ORE(ORE), IIQ(UseInstrInfo) {}
129};
130
131} // end anonymous namespace
132
133// Given the provided Value and, potentially, a context instruction, return
134// the preferred context instruction (if any).
135static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
136 // If we've been provided with a context instruction, then use that (provided
137 // it has been inserted).
138 if (CxtI && CxtI->getParent())
139 return CxtI;
140
141 // If the value is really an already-inserted instruction, then use that.
142 CxtI = dyn_cast<Instruction>(V);
143 if (CxtI && CxtI->getParent())
144 return CxtI;
145
146 return nullptr;
147}
148
149static const Instruction *safeCxtI(const Value *V1, const Value *V2, const Instruction *CxtI) {
150 // If we've been provided with a context instruction, then use that (provided
151 // it has been inserted).
152 if (CxtI && CxtI->getParent())
153 return CxtI;
154
155 // If the value is really an already-inserted instruction, then use that.
156 CxtI = dyn_cast<Instruction>(V1);
157 if (CxtI && CxtI->getParent())
158 return CxtI;
159
160 CxtI = dyn_cast<Instruction>(V2);
161 if (CxtI && CxtI->getParent())
162 return CxtI;
163
164 return nullptr;
165}
166
167static bool getShuffleDemandedElts(const ShuffleVectorInst *Shuf,
168 const APInt &DemandedElts,
169 APInt &DemandedLHS, APInt &DemandedRHS) {
170 if (isa<ScalableVectorType>(Shuf->getType())) {
171 assert(DemandedElts == APInt(1,1))(static_cast <bool> (DemandedElts == APInt(1,1)) ? void
(0) : __assert_fail ("DemandedElts == APInt(1,1)", "llvm/lib/Analysis/ValueTracking.cpp"
, 171, __extension__ __PRETTY_FUNCTION__))
;
172 DemandedLHS = DemandedRHS = DemandedElts;
173 return true;
174 }
175
176 int NumElts =
177 cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
178 return llvm::getShuffleDemandedElts(NumElts, Shuf->getShuffleMask(),
179 DemandedElts, DemandedLHS, DemandedRHS);
180}
181
182static void computeKnownBits(const Value *V, const APInt &DemandedElts,
183 KnownBits &Known, unsigned Depth, const Query &Q);
184
185static void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth,
186 const Query &Q) {
187 // Since the number of lanes in a scalable vector is unknown at compile time,
188 // we track one bit which is implicitly broadcast to all lanes. This means
189 // that all lanes in a scalable vector are considered demanded.
190 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
19
Called C++ object pointer is null
191 APInt DemandedElts =
192 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
193 computeKnownBits(V, DemandedElts, Known, Depth, Q);
194}
195
196void llvm::computeKnownBits(const Value *V, KnownBits &Known,
197 const DataLayout &DL, unsigned Depth,
198 AssumptionCache *AC, const Instruction *CxtI,
199 const DominatorTree *DT,
200 OptimizationRemarkEmitter *ORE, bool UseInstrInfo) {
201 ::computeKnownBits(V, Known, Depth,
202 Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
203}
204
205void llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
206 KnownBits &Known, const DataLayout &DL,
207 unsigned Depth, AssumptionCache *AC,
208 const Instruction *CxtI, const DominatorTree *DT,
209 OptimizationRemarkEmitter *ORE, bool UseInstrInfo) {
210 ::computeKnownBits(V, DemandedElts, Known, Depth,
211 Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
212}
213
214static KnownBits computeKnownBits(const Value *V, const APInt &DemandedElts,
215 unsigned Depth, const Query &Q);
216
217static KnownBits computeKnownBits(const Value *V, unsigned Depth,
218 const Query &Q);
219
220KnownBits llvm::computeKnownBits(const Value *V, const DataLayout &DL,
221 unsigned Depth, AssumptionCache *AC,
222 const Instruction *CxtI,
223 const DominatorTree *DT,
224 OptimizationRemarkEmitter *ORE,
225 bool UseInstrInfo) {
226 return ::computeKnownBits(
227 V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
228}
229
230KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
231 const DataLayout &DL, unsigned Depth,
232 AssumptionCache *AC, const Instruction *CxtI,
233 const DominatorTree *DT,
234 OptimizationRemarkEmitter *ORE,
235 bool UseInstrInfo) {
236 return ::computeKnownBits(
237 V, DemandedElts, Depth,
238 Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo, ORE));
239}
240
241bool llvm::haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
242 const DataLayout &DL, AssumptionCache *AC,
243 const Instruction *CxtI, const DominatorTree *DT,
244 bool UseInstrInfo) {
245 assert(LHS->getType() == RHS->getType() &&(static_cast <bool> (LHS->getType() == RHS->getType
() && "LHS and RHS should have the same type") ? void
(0) : __assert_fail ("LHS->getType() == RHS->getType() && \"LHS and RHS should have the same type\""
, "llvm/lib/Analysis/ValueTracking.cpp", 246, __extension__ __PRETTY_FUNCTION__
))
246 "LHS and RHS should have the same type")(static_cast <bool> (LHS->getType() == RHS->getType
() && "LHS and RHS should have the same type") ? void
(0) : __assert_fail ("LHS->getType() == RHS->getType() && \"LHS and RHS should have the same type\""
, "llvm/lib/Analysis/ValueTracking.cpp", 246, __extension__ __PRETTY_FUNCTION__
))
;
247 assert(LHS->getType()->isIntOrIntVectorTy() &&(static_cast <bool> (LHS->getType()->isIntOrIntVectorTy
() && "LHS and RHS should be integers") ? void (0) : __assert_fail
("LHS->getType()->isIntOrIntVectorTy() && \"LHS and RHS should be integers\""
, "llvm/lib/Analysis/ValueTracking.cpp", 248, __extension__ __PRETTY_FUNCTION__
))
248 "LHS and RHS should be integers")(static_cast <bool> (LHS->getType()->isIntOrIntVectorTy
() && "LHS and RHS should be integers") ? void (0) : __assert_fail
("LHS->getType()->isIntOrIntVectorTy() && \"LHS and RHS should be integers\""
, "llvm/lib/Analysis/ValueTracking.cpp", 248, __extension__ __PRETTY_FUNCTION__
))
;
249 // Look for an inverted mask: (X & ~M) op (Y & M).
250 {
251 Value *M;
252 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
253 match(RHS, m_c_And(m_Specific(M), m_Value())))
254 return true;
255 if (match(RHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
256 match(LHS, m_c_And(m_Specific(M), m_Value())))
257 return true;
258 }
259
260 // X op (Y & ~X)
261 if (match(RHS, m_c_And(m_Not(m_Specific(LHS)), m_Value())) ||
262 match(LHS, m_c_And(m_Not(m_Specific(RHS)), m_Value())))
263 return true;
264
265 // X op ((X & Y) ^ Y) -- this is the canonical form of the previous pattern
266 // for constant Y.
267 Value *Y;
268 if (match(RHS,
269 m_c_Xor(m_c_And(m_Specific(LHS), m_Value(Y)), m_Deferred(Y))) ||
270 match(LHS, m_c_Xor(m_c_And(m_Specific(RHS), m_Value(Y)), m_Deferred(Y))))
271 return true;
272
273 // Look for: (A & B) op ~(A | B)
274 {
275 Value *A, *B;
276 if (match(LHS, m_And(m_Value(A), m_Value(B))) &&
277 match(RHS, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
278 return true;
279 if (match(RHS, m_And(m_Value(A), m_Value(B))) &&
280 match(LHS, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
281 return true;
282 }
283 IntegerType *IT = cast<IntegerType>(LHS->getType()->getScalarType());
284 KnownBits LHSKnown(IT->getBitWidth());
285 KnownBits RHSKnown(IT->getBitWidth());
286 computeKnownBits(LHS, LHSKnown, DL, 0, AC, CxtI, DT, nullptr, UseInstrInfo);
287 computeKnownBits(RHS, RHSKnown, DL, 0, AC, CxtI, DT, nullptr, UseInstrInfo);
288 return KnownBits::haveNoCommonBitsSet(LHSKnown, RHSKnown);
289}
290
291bool llvm::isOnlyUsedInZeroEqualityComparison(const Instruction *I) {
292 return !I->user_empty() && all_of(I->users(), [](const User *U) {
293 ICmpInst::Predicate P;
294 return match(U, m_ICmp(P, m_Value(), m_Zero())) && ICmpInst::isEquality(P);
295 });
296}
297
298static bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
299 const Query &Q);
300
301bool llvm::isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
302 bool OrZero, unsigned Depth,
303 AssumptionCache *AC, const Instruction *CxtI,
304 const DominatorTree *DT, bool UseInstrInfo) {
305 return ::isKnownToBeAPowerOfTwo(
306 V, OrZero, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
307}
308
309static bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
310 unsigned Depth, const Query &Q);
311
312static bool isKnownNonZero(const Value *V, unsigned Depth, const Query &Q);
313
314bool llvm::isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth,
315 AssumptionCache *AC, const Instruction *CxtI,
316 const DominatorTree *DT, bool UseInstrInfo) {
317 return ::isKnownNonZero(V, Depth,
318 Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
319}
320
321bool llvm::isKnownNonNegative(const Value *V, const DataLayout &DL,
322 unsigned Depth, AssumptionCache *AC,
323 const Instruction *CxtI, const DominatorTree *DT,
324 bool UseInstrInfo) {
325 KnownBits Known =
326 computeKnownBits(V, DL, Depth, AC, CxtI, DT, nullptr, UseInstrInfo);
327 return Known.isNonNegative();
328}
329
330bool llvm::isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth,
331 AssumptionCache *AC, const Instruction *CxtI,
332 const DominatorTree *DT, bool UseInstrInfo) {
333 if (auto *CI = dyn_cast<ConstantInt>(V))
334 return CI->getValue().isStrictlyPositive();
335
336 // TODO: We'd doing two recursive queries here. We should factor this such
337 // that only a single query is needed.
338 return isKnownNonNegative(V, DL, Depth, AC, CxtI, DT, UseInstrInfo) &&
339 isKnownNonZero(V, DL, Depth, AC, CxtI, DT, UseInstrInfo);
340}
341
342bool llvm::isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth,
343 AssumptionCache *AC, const Instruction *CxtI,
344 const DominatorTree *DT, bool UseInstrInfo) {
345 KnownBits Known =
346 computeKnownBits(V, DL, Depth, AC, CxtI, DT, nullptr, UseInstrInfo);
347 return Known.isNegative();
348}
349
350static bool isKnownNonEqual(const Value *V1, const Value *V2, unsigned Depth,
351 const Query &Q);
352
353bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
354 const DataLayout &DL, AssumptionCache *AC,
355 const Instruction *CxtI, const DominatorTree *DT,
356 bool UseInstrInfo) {
357 return ::isKnownNonEqual(V1, V2, 0,
358 Query(DL, AC, safeCxtI(V2, V1, CxtI), DT,
359 UseInstrInfo, /*ORE=*/nullptr));
360}
361
362static bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
363 const Query &Q);
364
365bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
366 const DataLayout &DL, unsigned Depth,
367 AssumptionCache *AC, const Instruction *CxtI,
368 const DominatorTree *DT, bool UseInstrInfo) {
369 return ::MaskedValueIsZero(
370 V, Mask, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
371}
372
373static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
374 unsigned Depth, const Query &Q);
375
376static unsigned ComputeNumSignBits(const Value *V, unsigned Depth,
377 const Query &Q) {
378 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
379 APInt DemandedElts =
380 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
381 return ComputeNumSignBits(V, DemandedElts, Depth, Q);
382}
383
384unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
385 unsigned Depth, AssumptionCache *AC,
386 const Instruction *CxtI,
387 const DominatorTree *DT, bool UseInstrInfo) {
388 return ::ComputeNumSignBits(
389 V, Depth, Query(DL, AC, safeCxtI(V, CxtI), DT, UseInstrInfo));
390}
391
392unsigned llvm::ComputeMaxSignificantBits(const Value *V, const DataLayout &DL,
393 unsigned Depth, AssumptionCache *AC,
394 const Instruction *CxtI,
395 const DominatorTree *DT) {
396 unsigned SignBits = ComputeNumSignBits(V, DL, Depth, AC, CxtI, DT);
397 return V->getType()->getScalarSizeInBits() - SignBits + 1;
398}
399
400static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
401 bool NSW, const APInt &DemandedElts,
402 KnownBits &KnownOut, KnownBits &Known2,
403 unsigned Depth, const Query &Q) {
404 computeKnownBits(Op1, DemandedElts, KnownOut, Depth + 1, Q);
405
406 // If one operand is unknown and we have no nowrap information,
407 // the result will be unknown independently of the second operand.
408 if (KnownOut.isUnknown() && !NSW)
409 return;
410
411 computeKnownBits(Op0, DemandedElts, Known2, Depth + 1, Q);
412 KnownOut = KnownBits::computeForAddSub(Add, NSW, Known2, KnownOut);
413}
414
415static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
416 const APInt &DemandedElts, KnownBits &Known,
417 KnownBits &Known2, unsigned Depth,
418 const Query &Q) {
419 computeKnownBits(Op1, DemandedElts, Known, Depth + 1, Q);
420 computeKnownBits(Op0, DemandedElts, Known2, Depth + 1, Q);
421
422 bool isKnownNegative = false;
423 bool isKnownNonNegative = false;
424 // If the multiplication is known not to overflow, compute the sign bit.
425 if (NSW) {
426 if (Op0 == Op1) {
427 // The product of a number with itself is non-negative.
428 isKnownNonNegative = true;
429 } else {
430 bool isKnownNonNegativeOp1 = Known.isNonNegative();
431 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
432 bool isKnownNegativeOp1 = Known.isNegative();
433 bool isKnownNegativeOp0 = Known2.isNegative();
434 // The product of two numbers with the same sign is non-negative.
435 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
436 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
437 // The product of a negative number and a non-negative number is either
438 // negative or zero.
439 if (!isKnownNonNegative)
440 isKnownNegative =
441 (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
442 Known2.isNonZero()) ||
443 (isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.isNonZero());
444 }
445 }
446
447 bool SelfMultiply = Op0 == Op1;
448 // TODO: SelfMultiply can be poison, but not undef.
449 if (SelfMultiply)
450 SelfMultiply &=
451 isGuaranteedNotToBeUndefOrPoison(Op0, Q.AC, Q.CxtI, Q.DT, Depth + 1);
452 Known = KnownBits::mul(Known, Known2, SelfMultiply);
453
454 // Only make use of no-wrap flags if we failed to compute the sign bit
455 // directly. This matters if the multiplication always overflows, in
456 // which case we prefer to follow the result of the direct computation,
457 // though as the program is invoking undefined behaviour we can choose
458 // whatever we like here.
459 if (isKnownNonNegative && !Known.isNegative())
460 Known.makeNonNegative();
461 else if (isKnownNegative && !Known.isNonNegative())
462 Known.makeNegative();
463}
464
465void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
466 KnownBits &Known) {
467 unsigned BitWidth = Known.getBitWidth();
468 unsigned NumRanges = Ranges.getNumOperands() / 2;
469 assert(NumRanges >= 1)(static_cast <bool> (NumRanges >= 1) ? void (0) : __assert_fail
("NumRanges >= 1", "llvm/lib/Analysis/ValueTracking.cpp",
469, __extension__ __PRETTY_FUNCTION__))
;
470
471 Known.Zero.setAllBits();
472 Known.One.setAllBits();
473
474 for (unsigned i = 0; i < NumRanges; ++i) {
475 ConstantInt *Lower =
476 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
477 ConstantInt *Upper =
478 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
479 ConstantRange Range(Lower->getValue(), Upper->getValue());
480
481 // The first CommonPrefixBits of all values in Range are equal.
482 unsigned CommonPrefixBits =
483 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countLeadingZeros();
484 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
485 APInt UnsignedMax = Range.getUnsignedMax().zextOrTrunc(BitWidth);
486 Known.One &= UnsignedMax & Mask;
487 Known.Zero &= ~UnsignedMax & Mask;
488 }
489}
490
491static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
492 SmallVector<const Value *, 16> WorkSet(1, I);
493 SmallPtrSet<const Value *, 32> Visited;
494 SmallPtrSet<const Value *, 16> EphValues;
495
496 // The instruction defining an assumption's condition itself is always
497 // considered ephemeral to that assumption (even if it has other
498 // non-ephemeral users). See r246696's test case for an example.
499 if (is_contained(I->operands(), E))
500 return true;
501
502 while (!WorkSet.empty()) {
503 const Value *V = WorkSet.pop_back_val();
504 if (!Visited.insert(V).second)
505 continue;
506
507 // If all uses of this value are ephemeral, then so is this value.
508 if (llvm::all_of(V->users(), [&](const User *U) {
509 return EphValues.count(U);
510 })) {
511 if (V == E)
512 return true;
513
514 if (V == I || (isa<Instruction>(V) &&
515 !cast<Instruction>(V)->mayHaveSideEffects() &&
516 !cast<Instruction>(V)->isTerminator())) {
517 EphValues.insert(V);
518 if (const User *U = dyn_cast<User>(V))
519 append_range(WorkSet, U->operands());
520 }
521 }
522 }
523
524 return false;
525}
526
527// Is this an intrinsic that cannot be speculated but also cannot trap?
528bool llvm::isAssumeLikeIntrinsic(const Instruction *I) {
529 if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(I))
530 return CI->isAssumeLikeIntrinsic();
531
532 return false;
533}
534
535bool llvm::isValidAssumeForContext(const Instruction *Inv,
536 const Instruction *CxtI,
537 const DominatorTree *DT) {
538 // There are two restrictions on the use of an assume:
539 // 1. The assume must dominate the context (or the control flow must
540 // reach the assume whenever it reaches the context).
541 // 2. The context must not be in the assume's set of ephemeral values
542 // (otherwise we will use the assume to prove that the condition
543 // feeding the assume is trivially true, thus causing the removal of
544 // the assume).
545
546 if (Inv->getParent() == CxtI->getParent()) {
547 // If Inv and CtxI are in the same block, check if the assume (Inv) is first
548 // in the BB.
549 if (Inv->comesBefore(CxtI))
550 return true;
551
552 // Don't let an assume affect itself - this would cause the problems
553 // `isEphemeralValueOf` is trying to prevent, and it would also make
554 // the loop below go out of bounds.
555 if (Inv == CxtI)
556 return false;
557
558 // The context comes first, but they're both in the same block.
559 // Make sure there is nothing in between that might interrupt
560 // the control flow, not even CxtI itself.
561 // We limit the scan distance between the assume and its context instruction
562 // to avoid a compile-time explosion. This limit is chosen arbitrarily, so
563 // it can be adjusted if needed (could be turned into a cl::opt).
564 auto Range = make_range(CxtI->getIterator(), Inv->getIterator());
565 if (!isGuaranteedToTransferExecutionToSuccessor(Range, 15))
566 return false;
567
568 return !isEphemeralValueOf(Inv, CxtI);
569 }
570
571 // Inv and CxtI are in different blocks.
572 if (DT) {
573 if (DT->dominates(Inv, CxtI))
574 return true;
575 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor()) {
576 // We don't have a DT, but this trivially dominates.
577 return true;
578 }
579
580 return false;
581}
582
583static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS) {
584 // v u> y implies v != 0.
585 if (Pred == ICmpInst::ICMP_UGT)
586 return true;
587
588 // Special-case v != 0 to also handle v != null.
589 if (Pred == ICmpInst::ICMP_NE)
590 return match(RHS, m_Zero());
591
592 // All other predicates - rely on generic ConstantRange handling.
593 const APInt *C;
594 if (!match(RHS, m_APInt(C)))
595 return false;
596
597 ConstantRange TrueValues = ConstantRange::makeExactICmpRegion(Pred, *C);
598 return !TrueValues.contains(APInt::getZero(C->getBitWidth()));
599}
600
601static bool isKnownNonZeroFromAssume(const Value *V, const Query &Q) {
602 // Use of assumptions is context-sensitive. If we don't have a context, we
603 // cannot use them!
604 if (!Q.AC || !Q.CxtI)
605 return false;
606
607 if (Q.CxtI && V->getType()->isPointerTy()) {
608 SmallVector<Attribute::AttrKind, 2> AttrKinds{Attribute::NonNull};
609 if (!NullPointerIsDefined(Q.CxtI->getFunction(),
610 V->getType()->getPointerAddressSpace()))
611 AttrKinds.push_back(Attribute::Dereferenceable);
612
613 if (getKnowledgeValidInContext(V, AttrKinds, Q.CxtI, Q.DT, Q.AC))
614 return true;
615 }
616
617 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
618 if (!AssumeVH)
619 continue;
620 CallInst *I = cast<CallInst>(AssumeVH);
621 assert(I->getFunction() == Q.CxtI->getFunction() &&(static_cast <bool> (I->getFunction() == Q.CxtI->
getFunction() && "Got assumption for the wrong function!"
) ? void (0) : __assert_fail ("I->getFunction() == Q.CxtI->getFunction() && \"Got assumption for the wrong function!\""
, "llvm/lib/Analysis/ValueTracking.cpp", 622, __extension__ __PRETTY_FUNCTION__
))
622 "Got assumption for the wrong function!")(static_cast <bool> (I->getFunction() == Q.CxtI->
getFunction() && "Got assumption for the wrong function!"
) ? void (0) : __assert_fail ("I->getFunction() == Q.CxtI->getFunction() && \"Got assumption for the wrong function!\""
, "llvm/lib/Analysis/ValueTracking.cpp", 622, __extension__ __PRETTY_FUNCTION__
))
;
623
624 // Warning: This loop can end up being somewhat performance sensitive.
625 // We're running this loop for once for each value queried resulting in a
626 // runtime of ~O(#assumes * #values).
627
628 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&(static_cast <bool> (I->getCalledFunction()->getIntrinsicID
() == Intrinsic::assume && "must be an assume intrinsic"
) ? void (0) : __assert_fail ("I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume && \"must be an assume intrinsic\""
, "llvm/lib/Analysis/ValueTracking.cpp", 629, __extension__ __PRETTY_FUNCTION__
))
629 "must be an assume intrinsic")(static_cast <bool> (I->getCalledFunction()->getIntrinsicID
() == Intrinsic::assume && "must be an assume intrinsic"
) ? void (0) : __assert_fail ("I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume && \"must be an assume intrinsic\""
, "llvm/lib/Analysis/ValueTracking.cpp", 629, __extension__ __PRETTY_FUNCTION__
))
;
630
631 Value *RHS;
632 CmpInst::Predicate Pred;
633 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
634 if (!match(I->getArgOperand(0), m_c_ICmp(Pred, m_V, m_Value(RHS))))
635 return false;
636
637 if (cmpExcludesZero(Pred, RHS) && isValidAssumeForContext(I, Q.CxtI, Q.DT))
638 return true;
639 }
640
641 return false;
642}
643
644static void computeKnownBitsFromAssume(const Value *V, KnownBits &Known,
645 unsigned Depth, const Query &Q) {
646 // Use of assumptions is context-sensitive. If we don't have a context, we
647 // cannot use them!
648 if (!Q.AC || !Q.CxtI)
649 return;
650
651 unsigned BitWidth = Known.getBitWidth();
652
653 // Refine Known set if the pointer alignment is set by assume bundles.
654 if (V->getType()->isPointerTy()) {
655 if (RetainedKnowledge RK = getKnowledgeValidInContext(
656 V, {Attribute::Alignment}, Q.CxtI, Q.DT, Q.AC)) {
657 if (isPowerOf2_64(RK.ArgValue))
658 Known.Zero.setLowBits(Log2_64(RK.ArgValue));
659 }
660 }
661
662 // Note that the patterns below need to be kept in sync with the code
663 // in AssumptionCache::updateAffectedValues.
664
665 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
666 if (!AssumeVH)
667 continue;
668 CallInst *I = cast<CallInst>(AssumeVH);
669 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&(static_cast <bool> (I->getParent()->getParent() ==
Q.CxtI->getParent()->getParent() && "Got assumption for the wrong function!"
) ? void (0) : __assert_fail ("I->getParent()->getParent() == Q.CxtI->getParent()->getParent() && \"Got assumption for the wrong function!\""
, "llvm/lib/Analysis/ValueTracking.cpp", 670, __extension__ __PRETTY_FUNCTION__
))
670 "Got assumption for the wrong function!")(static_cast <bool> (I->getParent()->getParent() ==
Q.CxtI->getParent()->getParent() && "Got assumption for the wrong function!"
) ? void (0) : __assert_fail ("I->getParent()->getParent() == Q.CxtI->getParent()->getParent() && \"Got assumption for the wrong function!\""
, "llvm/lib/Analysis/ValueTracking.cpp", 670, __extension__ __PRETTY_FUNCTION__
))
;
671
672 // Warning: This loop can end up being somewhat performance sensitive.
673 // We're running this loop for once for each value queried resulting in a
674 // runtime of ~O(#assumes * #values).
675
676 assert(I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume &&(static_cast <bool> (I->getCalledFunction()->getIntrinsicID
() == Intrinsic::assume && "must be an assume intrinsic"
) ? void (0) : __assert_fail ("I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume && \"must be an assume intrinsic\""
, "llvm/lib/Analysis/ValueTracking.cpp", 677, __extension__ __PRETTY_FUNCTION__
))
677 "must be an assume intrinsic")(static_cast <bool> (I->getCalledFunction()->getIntrinsicID
() == Intrinsic::assume && "must be an assume intrinsic"
) ? void (0) : __assert_fail ("I->getCalledFunction()->getIntrinsicID() == Intrinsic::assume && \"must be an assume intrinsic\""
, "llvm/lib/Analysis/ValueTracking.cpp", 677, __extension__ __PRETTY_FUNCTION__
))
;
678
679 Value *Arg = I->getArgOperand(0);
680
681 if (Arg == V && isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
682 assert(BitWidth == 1 && "assume operand is not i1?")(static_cast <bool> (BitWidth == 1 && "assume operand is not i1?"
) ? void (0) : __assert_fail ("BitWidth == 1 && \"assume operand is not i1?\""
, "llvm/lib/Analysis/ValueTracking.cpp", 682, __extension__ __PRETTY_FUNCTION__
))
;
683 Known.setAllOnes();
684 return;
685 }
686 if (match(Arg, m_Not(m_Specific(V))) &&
687 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
688 assert(BitWidth == 1 && "assume operand is not i1?")(static_cast <bool> (BitWidth == 1 && "assume operand is not i1?"
) ? void (0) : __assert_fail ("BitWidth == 1 && \"assume operand is not i1?\""
, "llvm/lib/Analysis/ValueTracking.cpp", 688, __extension__ __PRETTY_FUNCTION__
))
;
689 Known.setAllZero();
690 return;
691 }
692
693 // The remaining tests are all recursive, so bail out if we hit the limit.
694 if (Depth == MaxAnalysisRecursionDepth)
695 continue;
696
697 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
698 if (!Cmp)
699 continue;
700
701 // We are attempting to compute known bits for the operands of an assume.
702 // Do not try to use other assumptions for those recursive calls because
703 // that can lead to mutual recursion and a compile-time explosion.
704 // An example of the mutual recursion: computeKnownBits can call
705 // isKnownNonZero which calls computeKnownBitsFromAssume (this function)
706 // and so on.
707 Query QueryNoAC = Q;
708 QueryNoAC.AC = nullptr;
709
710 // Note that ptrtoint may change the bitwidth.
711 Value *A, *B;
712 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
713
714 CmpInst::Predicate Pred;
715 uint64_t C;
716 switch (Cmp->getPredicate()) {
717 default:
718 break;
719 case ICmpInst::ICMP_EQ:
720 // assume(v = a)
721 if (match(Cmp, m_c_ICmp(Pred, m_V, m_Value(A))) &&
722 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
723 KnownBits RHSKnown =
724 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
725 Known.Zero |= RHSKnown.Zero;
726 Known.One |= RHSKnown.One;
727 // assume(v & b = a)
728 } else if (match(Cmp,
729 m_c_ICmp(Pred, m_c_And(m_V, m_Value(B)), m_Value(A))) &&
730 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
731 KnownBits RHSKnown =
732 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
733 KnownBits MaskKnown =
734 computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
735
736 // For those bits in the mask that are known to be one, we can propagate
737 // known bits from the RHS to V.
738 Known.Zero |= RHSKnown.Zero & MaskKnown.One;
739 Known.One |= RHSKnown.One & MaskKnown.One;
740 // assume(~(v & b) = a)
741 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_And(m_V, m_Value(B))),
742 m_Value(A))) &&
743 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
744 KnownBits RHSKnown =
745 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
746 KnownBits MaskKnown =
747 computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
748
749 // For those bits in the mask that are known to be one, we can propagate
750 // inverted known bits from the RHS to V.
751 Known.Zero |= RHSKnown.One & MaskKnown.One;
752 Known.One |= RHSKnown.Zero & MaskKnown.One;
753 // assume(v | b = a)
754 } else if (match(Cmp,
755 m_c_ICmp(Pred, m_c_Or(m_V, m_Value(B)), m_Value(A))) &&
756 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
757 KnownBits RHSKnown =
758 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
759 KnownBits BKnown =
760 computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
761
762 // For those bits in B that are known to be zero, we can propagate known
763 // bits from the RHS to V.
764 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
765 Known.One |= RHSKnown.One & BKnown.Zero;
766 // assume(~(v | b) = a)
767 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_Or(m_V, m_Value(B))),
768 m_Value(A))) &&
769 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
770 KnownBits RHSKnown =
771 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
772 KnownBits BKnown =
773 computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
774
775 // For those bits in B that are known to be zero, we can propagate
776 // inverted known bits from the RHS to V.
777 Known.Zero |= RHSKnown.One & BKnown.Zero;
778 Known.One |= RHSKnown.Zero & BKnown.Zero;
779 // assume(v ^ b = a)
780 } else if (match(Cmp,
781 m_c_ICmp(Pred, m_c_Xor(m_V, m_Value(B)), m_Value(A))) &&
782 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
783 KnownBits RHSKnown =
784 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
785 KnownBits BKnown =
786 computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
787
788 // For those bits in B that are known to be zero, we can propagate known
789 // bits from the RHS to V. For those bits in B that are known to be one,
790 // we can propagate inverted known bits from the RHS to V.
791 Known.Zero |= RHSKnown.Zero & BKnown.Zero;
792 Known.One |= RHSKnown.One & BKnown.Zero;
793 Known.Zero |= RHSKnown.One & BKnown.One;
794 Known.One |= RHSKnown.Zero & BKnown.One;
795 // assume(~(v ^ b) = a)
796 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_c_Xor(m_V, m_Value(B))),
797 m_Value(A))) &&
798 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
799 KnownBits RHSKnown =
800 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
801 KnownBits BKnown =
802 computeKnownBits(B, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
803
804 // For those bits in B that are known to be zero, we can propagate
805 // inverted known bits from the RHS to V. For those bits in B that are
806 // known to be one, we can propagate known bits from the RHS to V.
807 Known.Zero |= RHSKnown.One & BKnown.Zero;
808 Known.One |= RHSKnown.Zero & BKnown.Zero;
809 Known.Zero |= RHSKnown.Zero & BKnown.One;
810 Known.One |= RHSKnown.One & BKnown.One;
811 // assume(v << c = a)
812 } else if (match(Cmp, m_c_ICmp(Pred, m_Shl(m_V, m_ConstantInt(C)),
813 m_Value(A))) &&
814 isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
815 KnownBits RHSKnown =
816 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
817
818 // For those bits in RHS that are known, we can propagate them to known
819 // bits in V shifted to the right by C.
820 RHSKnown.Zero.lshrInPlace(C);
821 Known.Zero |= RHSKnown.Zero;
822 RHSKnown.One.lshrInPlace(C);
823 Known.One |= RHSKnown.One;
824 // assume(~(v << c) = a)
825 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_Shl(m_V, m_ConstantInt(C))),
826 m_Value(A))) &&
827 isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
828 KnownBits RHSKnown =
829 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
830 // For those bits in RHS that are known, we can propagate them inverted
831 // to known bits in V shifted to the right by C.
832 RHSKnown.One.lshrInPlace(C);
833 Known.Zero |= RHSKnown.One;
834 RHSKnown.Zero.lshrInPlace(C);
835 Known.One |= RHSKnown.Zero;
836 // assume(v >> c = a)
837 } else if (match(Cmp, m_c_ICmp(Pred, m_Shr(m_V, m_ConstantInt(C)),
838 m_Value(A))) &&
839 isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
840 KnownBits RHSKnown =
841 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
842 // For those bits in RHS that are known, we can propagate them to known
843 // bits in V shifted to the right by C.
844 Known.Zero |= RHSKnown.Zero << C;
845 Known.One |= RHSKnown.One << C;
846 // assume(~(v >> c) = a)
847 } else if (match(Cmp, m_c_ICmp(Pred, m_Not(m_Shr(m_V, m_ConstantInt(C))),
848 m_Value(A))) &&
849 isValidAssumeForContext(I, Q.CxtI, Q.DT) && C < BitWidth) {
850 KnownBits RHSKnown =
851 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
852 // For those bits in RHS that are known, we can propagate them inverted
853 // to known bits in V shifted to the right by C.
854 Known.Zero |= RHSKnown.One << C;
855 Known.One |= RHSKnown.Zero << C;
856 }
857 break;
858 case ICmpInst::ICMP_SGE:
859 // assume(v >=_s c) where c is non-negative
860 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
861 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
862 KnownBits RHSKnown =
863 computeKnownBits(A, Depth + 1, QueryNoAC).anyextOrTrunc(BitWidth);
864
865 if (RHSKnown.isNonNegative()) {
866 // We know that the sign bit is zero.
867 Known.makeNonNegative();
868 }
869 }
870 break;
871 case ICmpInst::ICMP_SGT:
872 // assume(v >_s c) where c is at least -1.
873 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
874 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
875 KnownBits RHSKnown =
876 computeKnownBits(A, Depth + 1, QueryNoAC).anyextOrTrunc(BitWidth);
877
878 if (RHSKnown.isAllOnes() || RHSKnown.isNonNegative()) {
879 // We know that the sign bit is zero.
880 Known.makeNonNegative();
881 }
882 }
883 break;
884 case ICmpInst::ICMP_SLE:
885 // assume(v <=_s c) where c is negative
886 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
887 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
888 KnownBits RHSKnown =
889 computeKnownBits(A, Depth + 1, QueryNoAC).anyextOrTrunc(BitWidth);
890
891 if (RHSKnown.isNegative()) {
892 // We know that the sign bit is one.
893 Known.makeNegative();
894 }
895 }
896 break;
897 case ICmpInst::ICMP_SLT:
898 // assume(v <_s c) where c is non-positive
899 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
900 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
901 KnownBits RHSKnown =
902 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
903
904 if (RHSKnown.isZero() || RHSKnown.isNegative()) {
905 // We know that the sign bit is one.
906 Known.makeNegative();
907 }
908 }
909 break;
910 case ICmpInst::ICMP_ULE:
911 // assume(v <=_u c)
912 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
913 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
914 KnownBits RHSKnown =
915 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
916
917 // Whatever high bits in c are zero are known to be zero.
918 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
919 }
920 break;
921 case ICmpInst::ICMP_ULT:
922 // assume(v <_u c)
923 if (match(Cmp, m_ICmp(Pred, m_V, m_Value(A))) &&
924 isValidAssumeForContext(I, Q.CxtI, Q.DT)) {
925 KnownBits RHSKnown =
926 computeKnownBits(A, Depth+1, QueryNoAC).anyextOrTrunc(BitWidth);
927
928 // If the RHS is known zero, then this assumption must be wrong (nothing
929 // is unsigned less than zero). Signal a conflict and get out of here.
930 if (RHSKnown.isZero()) {
931 Known.Zero.setAllBits();
932 Known.One.setAllBits();
933 break;
934 }
935
936 // Whatever high bits in c are zero are known to be zero (if c is a power
937 // of 2, then one more).
938 if (isKnownToBeAPowerOfTwo(A, false, Depth + 1, QueryNoAC))
939 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros() + 1);
940 else
941 Known.Zero.setHighBits(RHSKnown.countMinLeadingZeros());
942 }
943 break;
944 }
945 }
946
947 // If assumptions conflict with each other or previous known bits, then we
948 // have a logical fallacy. It's possible that the assumption is not reachable,
949 // so this isn't a real bug. On the other hand, the program may have undefined
950 // behavior, or we might have a bug in the compiler. We can't assert/crash, so
951 // clear out the known bits, try to warn the user, and hope for the best.
952 if (Known.Zero.intersects(Known.One)) {
953 Known.resetAll();
954
955 if (Q.ORE)
956 Q.ORE->emit([&]() {
957 auto *CxtI = const_cast<Instruction *>(Q.CxtI);
958 return OptimizationRemarkAnalysis("value-tracking", "BadAssumption",
959 CxtI)
960 << "Detected conflicting code assumptions. Program may "
961 "have undefined behavior, or compiler may have "
962 "internal error.";
963 });
964 }
965}
966
967/// Compute known bits from a shift operator, including those with a
968/// non-constant shift amount. Known is the output of this function. Known2 is a
969/// pre-allocated temporary with the same bit width as Known and on return
970/// contains the known bit of the shift value source. KF is an
971/// operator-specific function that, given the known-bits and a shift amount,
972/// compute the implied known-bits of the shift operator's result respectively
973/// for that shift amount. The results from calling KF are conservatively
974/// combined for all permitted shift amounts.
975static void computeKnownBitsFromShiftOperator(
976 const Operator *I, const APInt &DemandedElts, KnownBits &Known,
977 KnownBits &Known2, unsigned Depth, const Query &Q,
978 function_ref<KnownBits(const KnownBits &, const KnownBits &)> KF) {
979 unsigned BitWidth = Known.getBitWidth();
980 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
981 computeKnownBits(I->getOperand(1), DemandedElts, Known, Depth + 1, Q);
982
983 // Note: We cannot use Known.Zero.getLimitedValue() here, because if
984 // BitWidth > 64 and any upper bits are known, we'll end up returning the
985 // limit value (which implies all bits are known).
986 uint64_t ShiftAmtKZ = Known.Zero.zextOrTrunc(64).getZExtValue();
987 uint64_t ShiftAmtKO = Known.One.zextOrTrunc(64).getZExtValue();
988 bool ShiftAmtIsConstant = Known.isConstant();
989 bool MaxShiftAmtIsOutOfRange = Known.getMaxValue().uge(BitWidth);
990
991 if (ShiftAmtIsConstant) {
992 Known = KF(Known2, Known);
993
994 // If the known bits conflict, this must be an overflowing left shift, so
995 // the shift result is poison. We can return anything we want. Choose 0 for
996 // the best folding opportunity.
997 if (Known.hasConflict())
998 Known.setAllZero();
999
1000 return;
1001 }
1002
1003 // If the shift amount could be greater than or equal to the bit-width of the
1004 // LHS, the value could be poison, but bail out because the check below is
1005 // expensive.
1006 // TODO: Should we just carry on?
1007 if (MaxShiftAmtIsOutOfRange) {
1008 Known.resetAll();
1009 return;
1010 }
1011
1012 // It would be more-clearly correct to use the two temporaries for this
1013 // calculation. Reusing the APInts here to prevent unnecessary allocations.
1014 Known.resetAll();
1015
1016 // If we know the shifter operand is nonzero, we can sometimes infer more
1017 // known bits. However this is expensive to compute, so be lazy about it and
1018 // only compute it when absolutely necessary.
1019 Optional<bool> ShifterOperandIsNonZero;
1020
1021 // Early exit if we can't constrain any well-defined shift amount.
1022 if (!(ShiftAmtKZ & (PowerOf2Ceil(BitWidth) - 1)) &&
1023 !(ShiftAmtKO & (PowerOf2Ceil(BitWidth) - 1))) {
1024 ShifterOperandIsNonZero =
1025 isKnownNonZero(I->getOperand(1), DemandedElts, Depth + 1, Q);
1026 if (!*ShifterOperandIsNonZero)
1027 return;
1028 }
1029
1030 Known.Zero.setAllBits();
1031 Known.One.setAllBits();
1032 for (unsigned ShiftAmt = 0; ShiftAmt < BitWidth; ++ShiftAmt) {
1033 // Combine the shifted known input bits only for those shift amounts
1034 // compatible with its known constraints.
1035 if ((ShiftAmt & ~ShiftAmtKZ) != ShiftAmt)
1036 continue;
1037 if ((ShiftAmt | ShiftAmtKO) != ShiftAmt)
1038 continue;
1039 // If we know the shifter is nonzero, we may be able to infer more known
1040 // bits. This check is sunk down as far as possible to avoid the expensive
1041 // call to isKnownNonZero if the cheaper checks above fail.
1042 if (ShiftAmt == 0) {
1043 if (!ShifterOperandIsNonZero)
1044 ShifterOperandIsNonZero =
1045 isKnownNonZero(I->getOperand(1), DemandedElts, Depth + 1, Q);
1046 if (*ShifterOperandIsNonZero)
1047 continue;
1048 }
1049
1050 Known = KnownBits::commonBits(
1051 Known, KF(Known2, KnownBits::makeConstant(APInt(32, ShiftAmt))));
1052 }
1053
1054 // If the known bits conflict, the result is poison. Return a 0 and hope the
1055 // caller can further optimize that.
1056 if (Known.hasConflict())
1057 Known.setAllZero();
1058}
1059
1060static void computeKnownBitsFromOperator(const Operator *I,
1061 const APInt &DemandedElts,
1062 KnownBits &Known, unsigned Depth,
1063 const Query &Q) {
1064 unsigned BitWidth = Known.getBitWidth();
1065
1066 KnownBits Known2(BitWidth);
1067 switch (I->getOpcode()) {
1
Control jumps to 'case PHI:' at line 1408
1068 default: break;
1069 case Instruction::Load:
1070 if (MDNode *MD =
1071 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
1072 computeKnownBitsFromRangeMetadata(*MD, Known);
1073 break;
1074 case Instruction::And: {
1075 // If either the LHS or the RHS are Zero, the result is zero.
1076 computeKnownBits(I->getOperand(1), DemandedElts, Known, Depth + 1, Q);
1077 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
1078
1079 Known &= Known2;
1080
1081 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
1082 // here we handle the more general case of adding any odd number by
1083 // matching the form add(x, add(x, y)) where y is odd.
1084 // TODO: This could be generalized to clearing any bit set in y where the
1085 // following bit is known to be unset in y.
1086 Value *X = nullptr, *Y = nullptr;
1087 if (!Known.Zero[0] && !Known.One[0] &&
1088 match(I, m_c_BinOp(m_Value(X), m_Add(m_Deferred(X), m_Value(Y))))) {
1089 Known2.resetAll();
1090 computeKnownBits(Y, DemandedElts, Known2, Depth + 1, Q);
1091 if (Known2.countMinTrailingOnes() > 0)
1092 Known.Zero.setBit(0);
1093 }
1094 break;
1095 }
1096 case Instruction::Or:
1097 computeKnownBits(I->getOperand(1), DemandedElts, Known, Depth + 1, Q);
1098 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
1099
1100 Known |= Known2;
1101 break;
1102 case Instruction::Xor:
1103 computeKnownBits(I->getOperand(1), DemandedElts, Known, Depth + 1, Q);
1104 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
1105
1106 Known ^= Known2;
1107 break;
1108 case Instruction::Mul: {
1109 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
1110 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, DemandedElts,
1111 Known, Known2, Depth, Q);
1112 break;
1113 }
1114 case Instruction::UDiv: {
1115 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1116 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1117 Known = KnownBits::udiv(Known, Known2);
1118 break;
1119 }
1120 case Instruction::Select: {
1121 const Value *LHS = nullptr, *RHS = nullptr;
1122 SelectPatternFlavor SPF = matchSelectPattern(I, LHS, RHS).Flavor;
1123 if (SelectPatternResult::isMinOrMax(SPF)) {
1124 computeKnownBits(RHS, Known, Depth + 1, Q);
1125 computeKnownBits(LHS, Known2, Depth + 1, Q);
1126 switch (SPF) {
1127 default:
1128 llvm_unreachable("Unhandled select pattern flavor!")::llvm::llvm_unreachable_internal("Unhandled select pattern flavor!"
, "llvm/lib/Analysis/ValueTracking.cpp", 1128)
;
1129 case SPF_SMAX:
1130 Known = KnownBits::smax(Known, Known2);
1131 break;
1132 case SPF_SMIN:
1133 Known = KnownBits::smin(Known, Known2);
1134 break;
1135 case SPF_UMAX:
1136 Known = KnownBits::umax(Known, Known2);
1137 break;
1138 case SPF_UMIN:
1139 Known = KnownBits::umin(Known, Known2);
1140 break;
1141 }
1142 break;
1143 }
1144
1145 computeKnownBits(I->getOperand(2), Known, Depth + 1, Q);
1146 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1147
1148 // Only known if known in both the LHS and RHS.
1149 Known = KnownBits::commonBits(Known, Known2);
1150
1151 if (SPF == SPF_ABS) {
1152 // RHS from matchSelectPattern returns the negation part of abs pattern.
1153 // If the negate has an NSW flag we can assume the sign bit of the result
1154 // will be 0 because that makes abs(INT_MIN) undefined.
1155 if (match(RHS, m_Neg(m_Specific(LHS))) &&
1156 Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RHS)))
1157 Known.Zero.setSignBit();
1158 }
1159
1160 break;
1161 }
1162 case Instruction::FPTrunc:
1163 case Instruction::FPExt:
1164 case Instruction::FPToUI:
1165 case Instruction::FPToSI:
1166 case Instruction::SIToFP:
1167 case Instruction::UIToFP:
1168 break; // Can't work with floating point.
1169 case Instruction::PtrToInt:
1170 case Instruction::IntToPtr:
1171 // Fall through and handle them the same as zext/trunc.
1172 [[fallthrough]];
1173 case Instruction::ZExt:
1174 case Instruction::Trunc: {
1175 Type *SrcTy = I->getOperand(0)->getType();
1176
1177 unsigned SrcBitWidth;
1178 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1179 // which fall through here.
1180 Type *ScalarTy = SrcTy->getScalarType();
1181 SrcBitWidth = ScalarTy->isPointerTy() ?
1182 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
1183 Q.DL.getTypeSizeInBits(ScalarTy);
1184
1185 assert(SrcBitWidth && "SrcBitWidth can't be zero")(static_cast <bool> (SrcBitWidth && "SrcBitWidth can't be zero"
) ? void (0) : __assert_fail ("SrcBitWidth && \"SrcBitWidth can't be zero\""
, "llvm/lib/Analysis/ValueTracking.cpp", 1185, __extension__ __PRETTY_FUNCTION__
))
;
1186 Known = Known.anyextOrTrunc(SrcBitWidth);
1187 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1188 Known = Known.zextOrTrunc(BitWidth);
1189 break;
1190 }
1191 case Instruction::BitCast: {
1192 Type *SrcTy = I->getOperand(0)->getType();
1193 if (SrcTy->isIntOrPtrTy() &&
1194 // TODO: For now, not handling conversions like:
1195 // (bitcast i64 %x to <2 x i32>)
1196 !I->getType()->isVectorTy()) {
1197 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1198 break;
1199 }
1200
1201 // Handle cast from vector integer type to scalar or vector integer.
1202 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcTy);
1203 if (!SrcVecTy || !SrcVecTy->getElementType()->isIntegerTy() ||
1204 !I->getType()->isIntOrIntVectorTy() ||
1205 isa<ScalableVectorType>(I->getType()))
1206 break;
1207
1208 // Look through a cast from narrow vector elements to wider type.
1209 // Examples: v4i32 -> v2i64, v3i8 -> v24
1210 unsigned SubBitWidth = SrcVecTy->getScalarSizeInBits();
1211 if (BitWidth % SubBitWidth == 0) {
1212 // Known bits are automatically intersected across demanded elements of a
1213 // vector. So for example, if a bit is computed as known zero, it must be
1214 // zero across all demanded elements of the vector.
1215 //
1216 // For this bitcast, each demanded element of the output is sub-divided
1217 // across a set of smaller vector elements in the source vector. To get
1218 // the known bits for an entire element of the output, compute the known
1219 // bits for each sub-element sequentially. This is done by shifting the
1220 // one-set-bit demanded elements parameter across the sub-elements for
1221 // consecutive calls to computeKnownBits. We are using the demanded
1222 // elements parameter as a mask operator.
1223 //
1224 // The known bits of each sub-element are then inserted into place
1225 // (dependent on endian) to form the full result of known bits.
1226 unsigned NumElts = DemandedElts.getBitWidth();
1227 unsigned SubScale = BitWidth / SubBitWidth;
1228 APInt SubDemandedElts = APInt::getZero(NumElts * SubScale);
1229 for (unsigned i = 0; i != NumElts; ++i) {
1230 if (DemandedElts[i])
1231 SubDemandedElts.setBit(i * SubScale);
1232 }
1233
1234 KnownBits KnownSrc(SubBitWidth);
1235 for (unsigned i = 0; i != SubScale; ++i) {
1236 computeKnownBits(I->getOperand(0), SubDemandedElts.shl(i), KnownSrc,
1237 Depth + 1, Q);
1238 unsigned ShiftElt = Q.DL.isLittleEndian() ? i : SubScale - 1 - i;
1239 Known.insertBits(KnownSrc, ShiftElt * SubBitWidth);
1240 }
1241 }
1242 break;
1243 }
1244 case Instruction::SExt: {
1245 // Compute the bits in the result that are not present in the input.
1246 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1247
1248 Known = Known.trunc(SrcBitWidth);
1249 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1250 // If the sign bit of the input is known set or clear, then we know the
1251 // top bits of the result.
1252 Known = Known.sext(BitWidth);
1253 break;
1254 }
1255 case Instruction::Shl: {
1256 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
1257 auto KF = [NSW](const KnownBits &KnownVal, const KnownBits &KnownAmt) {
1258 KnownBits Result = KnownBits::shl(KnownVal, KnownAmt);
1259 // If this shift has "nsw" keyword, then the result is either a poison
1260 // value or has the same sign bit as the first operand.
1261 if (NSW) {
1262 if (KnownVal.Zero.isSignBitSet())
1263 Result.Zero.setSignBit();
1264 if (KnownVal.One.isSignBitSet())
1265 Result.One.setSignBit();
1266 }
1267 return Result;
1268 };
1269 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Depth, Q,
1270 KF);
1271 // Trailing zeros of a right-shifted constant never decrease.
1272 const APInt *C;
1273 if (match(I->getOperand(0), m_APInt(C)))
1274 Known.Zero.setLowBits(C->countTrailingZeros());
1275 break;
1276 }
1277 case Instruction::LShr: {
1278 auto KF = [](const KnownBits &KnownVal, const KnownBits &KnownAmt) {
1279 return KnownBits::lshr(KnownVal, KnownAmt);
1280 };
1281 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Depth, Q,
1282 KF);
1283 // Leading zeros of a left-shifted constant never decrease.
1284 const APInt *C;
1285 if (match(I->getOperand(0), m_APInt(C)))
1286 Known.Zero.setHighBits(C->countLeadingZeros());
1287 break;
1288 }
1289 case Instruction::AShr: {
1290 auto KF = [](const KnownBits &KnownVal, const KnownBits &KnownAmt) {
1291 return KnownBits::ashr(KnownVal, KnownAmt);
1292 };
1293 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Depth, Q,
1294 KF);
1295 break;
1296 }
1297 case Instruction::Sub: {
1298 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
1299 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW,
1300 DemandedElts, Known, Known2, Depth, Q);
1301 break;
1302 }
1303 case Instruction::Add: {
1304 bool NSW = Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(I));
1305 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW,
1306 DemandedElts, Known, Known2, Depth, Q);
1307 break;
1308 }
1309 case Instruction::SRem:
1310 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1311 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1312 Known = KnownBits::srem(Known, Known2);
1313 break;
1314
1315 case Instruction::URem:
1316 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1317 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1318 Known = KnownBits::urem(Known, Known2);
1319 break;
1320 case Instruction::Alloca:
1321 Known.Zero.setLowBits(Log2(cast<AllocaInst>(I)->getAlign()));
1322 break;
1323 case Instruction::GetElementPtr: {
1324 // Analyze all of the subscripts of this getelementptr instruction
1325 // to determine if we can prove known low zero bits.
1326 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1327 // Accumulate the constant indices in a separate variable
1328 // to minimize the number of calls to computeForAddSub.
1329 APInt AccConstIndices(BitWidth, 0, /*IsSigned*/ true);
1330
1331 gep_type_iterator GTI = gep_type_begin(I);
1332 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1333 // TrailZ can only become smaller, short-circuit if we hit zero.
1334 if (Known.isUnknown())
1335 break;
1336
1337 Value *Index = I->getOperand(i);
1338
1339 // Handle case when index is zero.
1340 Constant *CIndex = dyn_cast<Constant>(Index);
1341 if (CIndex && CIndex->isZeroValue())
1342 continue;
1343
1344 if (StructType *STy = GTI.getStructTypeOrNull()) {
1345 // Handle struct member offset arithmetic.
1346
1347 assert(CIndex &&(static_cast <bool> (CIndex && "Access to structure field must be known at compile time"
) ? void (0) : __assert_fail ("CIndex && \"Access to structure field must be known at compile time\""
, "llvm/lib/Analysis/ValueTracking.cpp", 1348, __extension__ __PRETTY_FUNCTION__
))
1348 "Access to structure field must be known at compile time")(static_cast <bool> (CIndex && "Access to structure field must be known at compile time"
) ? void (0) : __assert_fail ("CIndex && \"Access to structure field must be known at compile time\""
, "llvm/lib/Analysis/ValueTracking.cpp", 1348, __extension__ __PRETTY_FUNCTION__
))
;
1349
1350 if (CIndex->getType()->isVectorTy())
1351 Index = CIndex->getSplatValue();
1352
1353 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1354 const StructLayout *SL = Q.DL.getStructLayout(STy);
1355 uint64_t Offset = SL->getElementOffset(Idx);
1356 AccConstIndices += Offset;
1357 continue;
1358 }
1359
1360 // Handle array index arithmetic.
1361 Type *IndexedTy = GTI.getIndexedType();
1362 if (!IndexedTy->isSized()) {
1363 Known.resetAll();
1364 break;
1365 }
1366
1367 unsigned IndexBitWidth = Index->getType()->getScalarSizeInBits();
1368 KnownBits IndexBits(IndexBitWidth);
1369 computeKnownBits(Index, IndexBits, Depth + 1, Q);
1370 TypeSize IndexTypeSize = Q.DL.getTypeAllocSize(IndexedTy);
1371 uint64_t TypeSizeInBytes = IndexTypeSize.getKnownMinSize();
1372 KnownBits ScalingFactor(IndexBitWidth);
1373 // Multiply by current sizeof type.
1374 // &A[i] == A + i * sizeof(*A[i]).
1375 if (IndexTypeSize.isScalable()) {
1376 // For scalable types the only thing we know about sizeof is
1377 // that this is a multiple of the minimum size.
1378 ScalingFactor.Zero.setLowBits(countTrailingZeros(TypeSizeInBytes));
1379 } else if (IndexBits.isConstant()) {
1380 APInt IndexConst = IndexBits.getConstant();
1381 APInt ScalingFactor(IndexBitWidth, TypeSizeInBytes);
1382 IndexConst *= ScalingFactor;
1383 AccConstIndices += IndexConst.sextOrTrunc(BitWidth);
1384 continue;
1385 } else {
1386 ScalingFactor =
1387 KnownBits::makeConstant(APInt(IndexBitWidth, TypeSizeInBytes));
1388 }
1389 IndexBits = KnownBits::mul(IndexBits, ScalingFactor);
1390
1391 // If the offsets have a different width from the pointer, according
1392 // to the language reference we need to sign-extend or truncate them
1393 // to the width of the pointer.
1394 IndexBits = IndexBits.sextOrTrunc(BitWidth);
1395
1396 // Note that inbounds does *not* guarantee nsw for the addition, as only
1397 // the offset is signed, while the base address is unsigned.
1398 Known = KnownBits::computeForAddSub(
1399 /*Add=*/true, /*NSW=*/false, Known, IndexBits);
1400 }
1401 if (!Known.isUnknown() && !AccConstIndices.isZero()) {
1402 KnownBits Index = KnownBits::makeConstant(AccConstIndices);
1403 Known = KnownBits::computeForAddSub(
1404 /*Add=*/true, /*NSW=*/false, Known, Index);
1405 }
1406 break;
1407 }
1408 case Instruction::PHI: {
1409 const PHINode *P = cast<PHINode>(I);
2
'I' is a 'CastReturnType'
1410 BinaryOperator *BO = nullptr;
1411 Value *R = nullptr, *L = nullptr;
1412 if (matchSimpleRecurrence(P, BO, R, L)) {
3
Value assigned to 'R'
4
Assuming the condition is true
5
Taking true branch
1413 // Handle the case of a simple two-predecessor recurrence PHI.
1414 // There's a lot more that could theoretically be done here, but
1415 // this is sufficient to catch some interesting cases.
1416 unsigned Opcode = BO->getOpcode();
1417
1418 // If this is a shift recurrence, we know the bits being shifted in.
1419 // We can combine that with information about the start value of the
1420 // recurrence to conclude facts about the result.
1421 if ((Opcode == Instruction::LShr || Opcode == Instruction::AShr ||
6
Assuming 'Opcode' is not equal to LShr
7
Assuming 'Opcode' is not equal to AShr
1422 Opcode == Instruction::Shl) &&
8
Assuming 'Opcode' is not equal to Shl
1423 BO->getOperand(0) == I) {
1424
1425 // We have matched a recurrence of the form:
1426 // %iv = [R, %entry], [%iv.next, %backedge]
1427 // %iv.next = shift_op %iv, L
1428
1429 // Recurse with the phi context to avoid concern about whether facts
1430 // inferred hold at original context instruction. TODO: It may be
1431 // correct to use the original context. IF warranted, explore and
1432 // add sufficient tests to cover.
1433 Query RecQ = Q;
1434 RecQ.CxtI = P;
1435 computeKnownBits(R, DemandedElts, Known2, Depth + 1, RecQ);
1436 switch (Opcode) {
1437 case Instruction::Shl:
1438 // A shl recurrence will only increase the tailing zeros
1439 Known.Zero.setLowBits(Known2.countMinTrailingZeros());
1440 break;
1441 case Instruction::LShr:
1442 // A lshr recurrence will preserve the leading zeros of the
1443 // start value
1444 Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1445 break;
1446 case Instruction::AShr:
1447 // An ashr recurrence will extend the initial sign bit
1448 Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1449 Known.One.setHighBits(Known2.countMinLeadingOnes());
1450 break;
1451 };
1452 }
1453
1454 // Check for operations that have the property that if
1455 // both their operands have low zero bits, the result
1456 // will have low zero bits.
1457 if (Opcode == Instruction::Add ||
9
Assuming 'Opcode' is not equal to Add
14
Taking true branch
1458 Opcode == Instruction::Sub ||
10
Assuming 'Opcode' is not equal to Sub
1459 Opcode == Instruction::And ||
11
Assuming 'Opcode' is not equal to And
1460 Opcode == Instruction::Or ||
12
Assuming 'Opcode' is not equal to Or
1461 Opcode == Instruction::Mul) {
13
Assuming 'Opcode' is equal to Mul
1462 // Change the context instruction to the "edge" that flows into the
1463 // phi. This is important because that is where the value is actually
1464 // "evaluated" even though it is used later somewhere else. (see also
1465 // D69571).
1466 Query RecQ = Q;
1467
1468 unsigned OpNum = P->getOperand(0) == R ? 0 : 1;
15
Assuming pointer value is null
16
'?' condition is true
1469 Instruction *RInst = P->getIncomingBlock(OpNum)->getTerminator();
1470 Instruction *LInst = P->getIncomingBlock(1-OpNum)->getTerminator();
1471
1472 // Ok, we have a PHI of the form L op= R. Check for low
1473 // zero bits.
1474 RecQ.CxtI = RInst;
1475 computeKnownBits(R, Known2, Depth + 1, RecQ);
17
Passing null pointer value via 1st parameter 'V'
18
Calling 'computeKnownBits'
1476
1477 // We need to take the minimum number of known bits
1478 KnownBits Known3(BitWidth);
1479 RecQ.CxtI = LInst;
1480 computeKnownBits(L, Known3, Depth + 1, RecQ);
1481
1482 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1483 Known3.countMinTrailingZeros()));
1484
1485 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO);
1486 if (OverflowOp && Q.IIQ.hasNoSignedWrap(OverflowOp)) {
1487 // If initial value of recurrence is nonnegative, and we are adding
1488 // a nonnegative number with nsw, the result can only be nonnegative
1489 // or poison value regardless of the number of times we execute the
1490 // add in phi recurrence. If initial value is negative and we are
1491 // adding a negative number with nsw, the result can only be
1492 // negative or poison value. Similar arguments apply to sub and mul.
1493 //
1494 // (add non-negative, non-negative) --> non-negative
1495 // (add negative, negative) --> negative
1496 if (Opcode == Instruction::Add) {
1497 if (Known2.isNonNegative() && Known3.isNonNegative())
1498 Known.makeNonNegative();
1499 else if (Known2.isNegative() && Known3.isNegative())
1500 Known.makeNegative();
1501 }
1502
1503 // (sub nsw non-negative, negative) --> non-negative
1504 // (sub nsw negative, non-negative) --> negative
1505 else if (Opcode == Instruction::Sub && BO->getOperand(0) == I) {
1506 if (Known2.isNonNegative() && Known3.isNegative())
1507 Known.makeNonNegative();
1508 else if (Known2.isNegative() && Known3.isNonNegative())
1509 Known.makeNegative();
1510 }
1511
1512 // (mul nsw non-negative, non-negative) --> non-negative
1513 else if (Opcode == Instruction::Mul && Known2.isNonNegative() &&
1514 Known3.isNonNegative())
1515 Known.makeNonNegative();
1516 }
1517
1518 break;
1519 }
1520 }
1521
1522 // Unreachable blocks may have zero-operand PHI nodes.
1523 if (P->getNumIncomingValues() == 0)
1524 break;
1525
1526 // Otherwise take the unions of the known bit sets of the operands,
1527 // taking conservative care to avoid excessive recursion.
1528 if (Depth < MaxAnalysisRecursionDepth - 1 && !Known.Zero && !Known.One) {
1529 // Skip if every incoming value references to ourself.
1530 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
1531 break;
1532
1533 Known.Zero.setAllBits();
1534 Known.One.setAllBits();
1535 for (unsigned u = 0, e = P->getNumIncomingValues(); u < e; ++u) {
1536 Value *IncValue = P->getIncomingValue(u);
1537 // Skip direct self references.
1538 if (IncValue == P) continue;
1539
1540 // Change the context instruction to the "edge" that flows into the
1541 // phi. This is important because that is where the value is actually
1542 // "evaluated" even though it is used later somewhere else. (see also
1543 // D69571).
1544 Query RecQ = Q;
1545 RecQ.CxtI = P->getIncomingBlock(u)->getTerminator();
1546
1547 Known2 = KnownBits(BitWidth);
1548
1549 // Recurse, but cap the recursion to one level, because we don't
1550 // want to waste time spinning around in loops.
1551 computeKnownBits(IncValue, Known2, MaxAnalysisRecursionDepth - 1, RecQ);
1552
1553 // If this failed, see if we can use a conditional branch into the phi
1554 // to help us determine the range of the value.
1555 if (Known2.isUnknown()) {
1556 ICmpInst::Predicate Pred;
1557 const APInt *RHSC;
1558 BasicBlock *TrueSucc, *FalseSucc;
1559 // TODO: Use RHS Value and compute range from its known bits.
1560 if (match(RecQ.CxtI,
1561 m_Br(m_c_ICmp(Pred, m_Specific(IncValue), m_APInt(RHSC)),
1562 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
1563 // Check for cases of duplicate successors.
1564 if ((TrueSucc == P->getParent()) != (FalseSucc == P->getParent())) {
1565 // If we're using the false successor, invert the predicate.
1566 if (FalseSucc == P->getParent())
1567 Pred = CmpInst::getInversePredicate(Pred);
1568
1569 switch (Pred) {
1570 case CmpInst::Predicate::ICMP_EQ:
1571 Known2 = KnownBits::makeConstant(*RHSC);
1572 break;
1573 case CmpInst::Predicate::ICMP_ULE:
1574 Known2.Zero.setHighBits(RHSC->countLeadingZeros());
1575 break;
1576 case CmpInst::Predicate::ICMP_ULT:
1577 Known2.Zero.setHighBits((*RHSC - 1).countLeadingZeros());
1578 break;
1579 default:
1580 // TODO - add additional integer predicate handling.
1581 break;
1582 }
1583 }
1584 }
1585 }
1586
1587 Known = KnownBits::commonBits(Known, Known2);
1588 // If all bits have been ruled out, there's no need to check
1589 // more operands.
1590 if (Known.isUnknown())
1591 break;
1592 }
1593 }
1594 break;
1595 }
1596 case Instruction::Call:
1597 case Instruction::Invoke:
1598 // If range metadata is attached to this call, set known bits from that,
1599 // and then intersect with known bits based on other properties of the
1600 // function.
1601 if (MDNode *MD =
1602 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
1603 computeKnownBitsFromRangeMetadata(*MD, Known);
1604 if (const Value *RV = cast<CallBase>(I)->getReturnedArgOperand()) {
1605 computeKnownBits(RV, Known2, Depth + 1, Q);
1606 Known.Zero |= Known2.Zero;
1607 Known.One |= Known2.One;
1608 }
1609 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1610 switch (II->getIntrinsicID()) {
1611 default: break;
1612 case Intrinsic::abs: {
1613 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1614 bool IntMinIsPoison = match(II->getArgOperand(1), m_One());
1615 Known = Known2.abs(IntMinIsPoison);
1616 break;
1617 }
1618 case Intrinsic::bitreverse:
1619 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
1620 Known.Zero |= Known2.Zero.reverseBits();
1621 Known.One |= Known2.One.reverseBits();
1622 break;
1623 case Intrinsic::bswap:
1624 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Depth + 1, Q);
1625 Known.Zero |= Known2.Zero.byteSwap();
1626 Known.One |= Known2.One.byteSwap();
1627 break;
1628 case Intrinsic::ctlz: {
1629 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1630 // If we have a known 1, its position is our upper bound.
1631 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
1632 // If this call is poison for 0 input, the result will be less than 2^n.
1633 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1634 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
1635 unsigned LowBits = Log2_32(PossibleLZ)+1;
1636 Known.Zero.setBitsFrom(LowBits);
1637 break;
1638 }
1639 case Intrinsic::cttz: {
1640 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1641 // If we have a known 1, its position is our upper bound.
1642 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
1643 // If this call is poison for 0 input, the result will be less than 2^n.
1644 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
1645 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
1646 unsigned LowBits = Log2_32(PossibleTZ)+1;
1647 Known.Zero.setBitsFrom(LowBits);
1648 break;
1649 }
1650 case Intrinsic::ctpop: {
1651 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1652 // We can bound the space the count needs. Also, bits known to be zero
1653 // can't contribute to the population.
1654 unsigned BitsPossiblySet = Known2.countMaxPopulation();
1655 unsigned LowBits = Log2_32(BitsPossiblySet)+1;
1656 Known.Zero.setBitsFrom(LowBits);
1657 // TODO: we could bound KnownOne using the lower bound on the number
1658 // of bits which might be set provided by popcnt KnownOne2.
1659 break;
1660 }
1661 case Intrinsic::fshr:
1662 case Intrinsic::fshl: {
1663 const APInt *SA;
1664 if (!match(I->getOperand(2), m_APInt(SA)))
1665 break;
1666
1667 // Normalize to funnel shift left.
1668 uint64_t ShiftAmt = SA->urem(BitWidth);
1669 if (II->getIntrinsicID() == Intrinsic::fshr)
1670 ShiftAmt = BitWidth - ShiftAmt;
1671
1672 KnownBits Known3(BitWidth);
1673 computeKnownBits(I->getOperand(0), Known2, Depth + 1, Q);
1674 computeKnownBits(I->getOperand(1), Known3, Depth + 1, Q);
1675
1676 Known.Zero =
1677 Known2.Zero.shl(ShiftAmt) | Known3.Zero.lshr(BitWidth - ShiftAmt);
1678 Known.One =
1679 Known2.One.shl(ShiftAmt) | Known3.One.lshr(BitWidth - ShiftAmt);
1680 break;
1681 }
1682 case Intrinsic::uadd_sat:
1683 case Intrinsic::usub_sat: {
1684 bool IsAdd = II->getIntrinsicID() == Intrinsic::uadd_sat;
1685 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1686 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1687
1688 // Add: Leading ones of either operand are preserved.
1689 // Sub: Leading zeros of LHS and leading ones of RHS are preserved
1690 // as leading zeros in the result.
1691 unsigned LeadingKnown;
1692 if (IsAdd)
1693 LeadingKnown = std::max(Known.countMinLeadingOnes(),
1694 Known2.countMinLeadingOnes());
1695 else
1696 LeadingKnown = std::max(Known.countMinLeadingZeros(),
1697 Known2.countMinLeadingOnes());
1698
1699 Known = KnownBits::computeForAddSub(
1700 IsAdd, /* NSW */ false, Known, Known2);
1701
1702 // We select between the operation result and all-ones/zero
1703 // respectively, so we can preserve known ones/zeros.
1704 if (IsAdd) {
1705 Known.One.setHighBits(LeadingKnown);
1706 Known.Zero.clearAllBits();
1707 } else {
1708 Known.Zero.setHighBits(LeadingKnown);
1709 Known.One.clearAllBits();
1710 }
1711 break;
1712 }
1713 case Intrinsic::umin:
1714 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1715 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1716 Known = KnownBits::umin(Known, Known2);
1717 break;
1718 case Intrinsic::umax:
1719 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1720 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1721 Known = KnownBits::umax(Known, Known2);
1722 break;
1723 case Intrinsic::smin:
1724 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1725 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1726 Known = KnownBits::smin(Known, Known2);
1727 break;
1728 case Intrinsic::smax:
1729 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1730 computeKnownBits(I->getOperand(1), Known2, Depth + 1, Q);
1731 Known = KnownBits::smax(Known, Known2);
1732 break;
1733 case Intrinsic::x86_sse42_crc32_64_64:
1734 Known.Zero.setBitsFrom(32);
1735 break;
1736 case Intrinsic::riscv_vsetvli:
1737 case Intrinsic::riscv_vsetvlimax:
1738 // Assume that VL output is positive and would fit in an int32_t.
1739 // TODO: VLEN might be capped at 16 bits in a future V spec update.
1740 if (BitWidth >= 32)
1741 Known.Zero.setBitsFrom(31);
1742 break;
1743 case Intrinsic::vscale: {
1744 if (!II->getParent() || !II->getFunction() ||
1745 !II->getFunction()->hasFnAttribute(Attribute::VScaleRange))
1746 break;
1747
1748 auto Attr = II->getFunction()->getFnAttribute(Attribute::VScaleRange);
1749 Optional<unsigned> VScaleMax = Attr.getVScaleRangeMax();
1750
1751 if (!VScaleMax)
1752 break;
1753
1754 unsigned VScaleMin = Attr.getVScaleRangeMin();
1755
1756 // If vscale min = max then we know the exact value at compile time
1757 // and hence we know the exact bits.
1758 if (VScaleMin == VScaleMax) {
1759 Known.One = VScaleMin;
1760 Known.Zero = VScaleMin;
1761 Known.Zero.flipAllBits();
1762 break;
1763 }
1764
1765 unsigned FirstZeroHighBit = 32 - countLeadingZeros(*VScaleMax);
1766 if (FirstZeroHighBit < BitWidth)
1767 Known.Zero.setBitsFrom(FirstZeroHighBit);
1768
1769 break;
1770 }
1771 }
1772 }
1773 break;
1774 case Instruction::ShuffleVector: {
1775 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
1776 // FIXME: Do we need to handle ConstantExpr involving shufflevectors?
1777 if (!Shuf) {
1778 Known.resetAll();
1779 return;
1780 }
1781 // For undef elements, we don't know anything about the common state of
1782 // the shuffle result.
1783 APInt DemandedLHS, DemandedRHS;
1784 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) {
1785 Known.resetAll();
1786 return;
1787 }
1788 Known.One.setAllBits();
1789 Known.Zero.setAllBits();
1790 if (!!DemandedLHS) {
1791 const Value *LHS = Shuf->getOperand(0);
1792 computeKnownBits(LHS, DemandedLHS, Known, Depth + 1, Q);
1793 // If we don't know any bits, early out.
1794 if (Known.isUnknown())
1795 break;
1796 }
1797 if (!!DemandedRHS) {
1798 const Value *RHS = Shuf->getOperand(1);
1799 computeKnownBits(RHS, DemandedRHS, Known2, Depth + 1, Q);
1800 Known = KnownBits::commonBits(Known, Known2);
1801 }
1802 break;
1803 }
1804 case Instruction::InsertElement: {
1805 if (isa<ScalableVectorType>(I->getType())) {
1806 Known.resetAll();
1807 return;
1808 }
1809 const Value *Vec = I->getOperand(0);
1810 const Value *Elt = I->getOperand(1);
1811 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
1812 // Early out if the index is non-constant or out-of-range.
1813 unsigned NumElts = DemandedElts.getBitWidth();
1814 if (!CIdx || CIdx->getValue().uge(NumElts)) {
1815 Known.resetAll();
1816 return;
1817 }
1818 Known.One.setAllBits();
1819 Known.Zero.setAllBits();
1820 unsigned EltIdx = CIdx->getZExtValue();
1821 // Do we demand the inserted element?
1822 if (DemandedElts[EltIdx]) {
1823 computeKnownBits(Elt, Known, Depth + 1, Q);
1824 // If we don't know any bits, early out.
1825 if (Known.isUnknown())
1826 break;
1827 }
1828 // We don't need the base vector element that has been inserted.
1829 APInt DemandedVecElts = DemandedElts;
1830 DemandedVecElts.clearBit(EltIdx);
1831 if (!!DemandedVecElts) {
1832 computeKnownBits(Vec, DemandedVecElts, Known2, Depth + 1, Q);
1833 Known = KnownBits::commonBits(Known, Known2);
1834 }
1835 break;
1836 }
1837 case Instruction::ExtractElement: {
1838 // Look through extract element. If the index is non-constant or
1839 // out-of-range demand all elements, otherwise just the extracted element.
1840 const Value *Vec = I->getOperand(0);
1841 const Value *Idx = I->getOperand(1);
1842 auto *CIdx = dyn_cast<ConstantInt>(Idx);
1843 if (isa<ScalableVectorType>(Vec->getType())) {
1844 // FIXME: there's probably *something* we can do with scalable vectors
1845 Known.resetAll();
1846 break;
1847 }
1848 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
1849 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
1850 if (CIdx && CIdx->getValue().ult(NumElts))
1851 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
1852 computeKnownBits(Vec, DemandedVecElts, Known, Depth + 1, Q);
1853 break;
1854 }
1855 case Instruction::ExtractValue:
1856 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
1857 const ExtractValueInst *EVI = cast<ExtractValueInst>(I);
1858 if (EVI->getNumIndices() != 1) break;
1859 if (EVI->getIndices()[0] == 0) {
1860 switch (II->getIntrinsicID()) {
1861 default: break;
1862 case Intrinsic::uadd_with_overflow:
1863 case Intrinsic::sadd_with_overflow:
1864 computeKnownBitsAddSub(true, II->getArgOperand(0),
1865 II->getArgOperand(1), false, DemandedElts,
1866 Known, Known2, Depth, Q);
1867 break;
1868 case Intrinsic::usub_with_overflow:
1869 case Intrinsic::ssub_with_overflow:
1870 computeKnownBitsAddSub(false, II->getArgOperand(0),
1871 II->getArgOperand(1), false, DemandedElts,
1872 Known, Known2, Depth, Q);
1873 break;
1874 case Intrinsic::umul_with_overflow:
1875 case Intrinsic::smul_with_overflow:
1876 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
1877 DemandedElts, Known, Known2, Depth, Q);
1878 break;
1879 }
1880 }
1881 }
1882 break;
1883 case Instruction::Freeze:
1884 if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
1885 Depth + 1))
1886 computeKnownBits(I->getOperand(0), Known, Depth + 1, Q);
1887 break;
1888 }
1889}
1890
1891/// Determine which bits of V are known to be either zero or one and return
1892/// them.
1893KnownBits computeKnownBits(const Value *V, const APInt &DemandedElts,
1894 unsigned Depth, const Query &Q) {
1895 KnownBits Known(getBitWidth(V->getType(), Q.DL));
1896 computeKnownBits(V, DemandedElts, Known, Depth, Q);
1897 return Known;
1898}
1899
1900/// Determine which bits of V are known to be either zero or one and return
1901/// them.
1902KnownBits computeKnownBits(const Value *V, unsigned Depth, const Query &Q) {
1903 KnownBits Known(getBitWidth(V->getType(), Q.DL));
1904 computeKnownBits(V, Known, Depth, Q);
1905 return Known;
1906}
1907
1908/// Determine which bits of V are known to be either zero or one and return
1909/// them in the Known bit set.
1910///
1911/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
1912/// we cannot optimize based on the assumption that it is zero without changing
1913/// it to be an explicit zero. If we don't change it to zero, other code could
1914/// optimized based on the contradictory assumption that it is non-zero.
1915/// Because instcombine aggressively folds operations with undef args anyway,
1916/// this won't lose us code quality.
1917///
1918/// This function is defined on values with integer type, values with pointer
1919/// type, and vectors of integers. In the case
1920/// where V is a vector, known zero, and known one values are the
1921/// same width as the vector element, and the bit is set only if it is true
1922/// for all of the demanded elements in the vector specified by DemandedElts.
1923void computeKnownBits(const Value *V, const APInt &DemandedElts,
1924 KnownBits &Known, unsigned Depth, const Query &Q) {
1925 if (!DemandedElts) {
1926 // No demanded elts, better to assume we don't know anything.
1927 Known.resetAll();
1928 return;
1929 }
1930
1931 assert(V && "No Value?")(static_cast <bool> (V && "No Value?") ? void (
0) : __assert_fail ("V && \"No Value?\"", "llvm/lib/Analysis/ValueTracking.cpp"
, 1931, __extension__ __PRETTY_FUNCTION__))
;
1932 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth")(static_cast <bool> (Depth <= MaxAnalysisRecursionDepth
&& "Limit Search Depth") ? void (0) : __assert_fail (
"Depth <= MaxAnalysisRecursionDepth && \"Limit Search Depth\""
, "llvm/lib/Analysis/ValueTracking.cpp", 1932, __extension__ __PRETTY_FUNCTION__
))
;
1933
1934#ifndef NDEBUG
1935 Type *Ty = V->getType();
1936 unsigned BitWidth = Known.getBitWidth();
1937
1938 assert((Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) &&(static_cast <bool> ((Ty->isIntOrIntVectorTy(BitWidth
) || Ty->isPtrOrPtrVectorTy()) && "Not integer or pointer type!"
) ? void (0) : __assert_fail ("(Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) && \"Not integer or pointer type!\""
, "llvm/lib/Analysis/ValueTracking.cpp", 1939, __extension__ __PRETTY_FUNCTION__
))
1939 "Not integer or pointer type!")(static_cast <bool> ((Ty->isIntOrIntVectorTy(BitWidth
) || Ty->isPtrOrPtrVectorTy()) && "Not integer or pointer type!"
) ? void (0) : __assert_fail ("(Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) && \"Not integer or pointer type!\""
, "llvm/lib/Analysis/ValueTracking.cpp", 1939, __extension__ __PRETTY_FUNCTION__
))
;
1940
1941 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
1942 assert((static_cast <bool> (FVTy->getNumElements() == DemandedElts
.getBitWidth() && "DemandedElt width should equal the fixed vector number of elements"
) ? void (0) : __assert_fail ("FVTy->getNumElements() == DemandedElts.getBitWidth() && \"DemandedElt width should equal the fixed vector number of elements\""
, "llvm/lib/Analysis/ValueTracking.cpp", 1944, __extension__ __PRETTY_FUNCTION__
))
1943 FVTy->getNumElements() == DemandedElts.getBitWidth() &&(static_cast <bool> (FVTy->getNumElements() == DemandedElts
.getBitWidth() && "DemandedElt width should equal the fixed vector number of elements"
) ? void (0) : __assert_fail ("FVTy->getNumElements() == DemandedElts.getBitWidth() && \"DemandedElt width should equal the fixed vector number of elements\""
, "llvm/lib/Analysis/ValueTracking.cpp", 1944, __extension__ __PRETTY_FUNCTION__
))
1944 "DemandedElt width should equal the fixed vector number of elements")(static_cast <bool> (FVTy->getNumElements() == DemandedElts
.getBitWidth() && "DemandedElt width should equal the fixed vector number of elements"
) ? void (0) : __assert_fail ("FVTy->getNumElements() == DemandedElts.getBitWidth() && \"DemandedElt width should equal the fixed vector number of elements\""
, "llvm/lib/Analysis/ValueTracking.cpp", 1944, __extension__ __PRETTY_FUNCTION__
))
;
1945 } else {
1946 assert(DemandedElts == APInt(1, 1) &&(static_cast <bool> (DemandedElts == APInt(1, 1) &&
"DemandedElt width should be 1 for scalars or scalable vectors"
) ? void (0) : __assert_fail ("DemandedElts == APInt(1, 1) && \"DemandedElt width should be 1 for scalars or scalable vectors\""
, "llvm/lib/Analysis/ValueTracking.cpp", 1947, __extension__ __PRETTY_FUNCTION__
))
1947 "DemandedElt width should be 1 for scalars or scalable vectors")(static_cast <bool> (DemandedElts == APInt(1, 1) &&
"DemandedElt width should be 1 for scalars or scalable vectors"
) ? void (0) : __assert_fail ("DemandedElts == APInt(1, 1) && \"DemandedElt width should be 1 for scalars or scalable vectors\""
, "llvm/lib/Analysis/ValueTracking.cpp", 1947, __extension__ __PRETTY_FUNCTION__
))
;
1948 }
1949
1950 Type *ScalarTy = Ty->getScalarType();
1951 if (ScalarTy->isPointerTy()) {
1952 assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) &&(static_cast <bool> (BitWidth == Q.DL.getPointerTypeSizeInBits
(ScalarTy) && "V and Known should have same BitWidth"
) ? void (0) : __assert_fail ("BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) && \"V and Known should have same BitWidth\""
, "llvm/lib/Analysis/ValueTracking.cpp", 1953, __extension__ __PRETTY_FUNCTION__
))
1953 "V and Known should have same BitWidth")(static_cast <bool> (BitWidth == Q.DL.getPointerTypeSizeInBits
(ScalarTy) && "V and Known should have same BitWidth"
) ? void (0) : __assert_fail ("BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) && \"V and Known should have same BitWidth\""
, "llvm/lib/Analysis/ValueTracking.cpp", 1953, __extension__ __PRETTY_FUNCTION__
))
;
1954 } else {
1955 assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) &&(static_cast <bool> (BitWidth == Q.DL.getTypeSizeInBits
(ScalarTy) && "V and Known should have same BitWidth"
) ? void (0) : __assert_fail ("BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) && \"V and Known should have same BitWidth\""
, "llvm/lib/Analysis/ValueTracking.cpp", 1956, __extension__ __PRETTY_FUNCTION__
))
1956 "V and Known should have same BitWidth")(static_cast <bool> (BitWidth == Q.DL.getTypeSizeInBits
(ScalarTy) && "V and Known should have same BitWidth"
) ? void (0) : __assert_fail ("BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) && \"V and Known should have same BitWidth\""
, "llvm/lib/Analysis/ValueTracking.cpp", 1956, __extension__ __PRETTY_FUNCTION__
))
;
1957 }
1958#endif
1959
1960 const APInt *C;
1961 if (match(V, m_APInt(C))) {
1962 // We know all of the bits for a scalar constant or a splat vector constant!
1963 Known = KnownBits::makeConstant(*C);
1964 return;
1965 }
1966 // Null and aggregate-zero are all-zeros.
1967 if (isa<ConstantPointerNull>(V) || isa<ConstantAggregateZero>(V)) {
1968 Known.setAllZero();
1969 return;
1970 }
1971 // Handle a constant vector by taking the intersection of the known bits of
1972 // each element.
1973 if (const ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(V)) {
1974 assert(!isa<ScalableVectorType>(V->getType()))(static_cast <bool> (!isa<ScalableVectorType>(V->
getType())) ? void (0) : __assert_fail ("!isa<ScalableVectorType>(V->getType())"
, "llvm/lib/Analysis/ValueTracking.cpp", 1974, __extension__ __PRETTY_FUNCTION__
))
;
1975 // We know that CDV must be a vector of integers. Take the intersection of
1976 // each element.
1977 Known.Zero.setAllBits(); Known.One.setAllBits();
1978 for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
1979 if (!DemandedElts[i])
1980 continue;
1981 APInt Elt = CDV->getElementAsAPInt(i);
1982 Known.Zero &= ~Elt;
1983 Known.One &= Elt;
1984 }
1985 return;
1986 }
1987
1988 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
1989 assert(!isa<ScalableVectorType>(V->getType()))(static_cast <bool> (!isa<ScalableVectorType>(V->
getType())) ? void (0) : __assert_fail ("!isa<ScalableVectorType>(V->getType())"
, "llvm/lib/Analysis/ValueTracking.cpp", 1989, __extension__ __PRETTY_FUNCTION__
))
;
1990 // We know that CV must be a vector of integers. Take the intersection of
1991 // each element.
1992 Known.Zero.setAllBits(); Known.One.setAllBits();
1993 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
1994 if (!DemandedElts[i])
1995 continue;
1996 Constant *Element = CV->getAggregateElement(i);
1997 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
1998 if (!ElementCI) {
1999 Known.resetAll();
2000 return;
2001 }
2002 const APInt &Elt = ElementCI->getValue();
2003 Known.Zero &= ~Elt;
2004 Known.One &= Elt;
2005 }
2006 return;
2007 }
2008
2009 // Start out not knowing anything.
2010 Known.resetAll();
2011
2012 // We can't imply anything about undefs.
2013 if (isa<UndefValue>(V))
2014 return;
2015
2016 // There's no point in looking through other users of ConstantData for
2017 // assumptions. Confirm that we've handled them all.
2018 assert(!isa<ConstantData>(V) && "Unhandled constant data!")(static_cast <bool> (!isa<ConstantData>(V) &&
"Unhandled constant data!") ? void (0) : __assert_fail ("!isa<ConstantData>(V) && \"Unhandled constant data!\""
, "llvm/lib/Analysis/ValueTracking.cpp", 2018, __extension__ __PRETTY_FUNCTION__
))
;
2019
2020 // All recursive calls that increase depth must come after this.
2021 if (Depth == MaxAnalysisRecursionDepth)
2022 return;
2023
2024 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
2025 // the bits of its aliasee.
2026 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2027 if (!GA->isInterposable())
2028 computeKnownBits(GA->getAliasee(), Known, Depth + 1, Q);
2029 return;
2030 }
2031
2032 if (const Operator *I = dyn_cast<Operator>(V))
2033 computeKnownBitsFromOperator(I, DemandedElts, Known, Depth, Q);
2034
2035 // Aligned pointers have trailing zeros - refine Known.Zero set
2036 if (isa<PointerType>(V->getType())) {
2037 Align Alignment = V->getPointerAlignment(Q.DL);
2038 Known.Zero.setLowBits(Log2(Alignment));
2039 }
2040
2041 // computeKnownBitsFromAssume strictly refines Known.
2042 // Therefore, we run them after computeKnownBitsFromOperator.
2043
2044 // Check whether a nearby assume intrinsic can determine some known bits.
2045 computeKnownBitsFromAssume(V, Known, Depth, Q);
2046
2047 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?")(static_cast <bool> ((Known.Zero & Known.One) == 0 &&
"Bits known to be one AND zero?") ? void (0) : __assert_fail
("(Known.Zero & Known.One) == 0 && \"Bits known to be one AND zero?\""
, "llvm/lib/Analysis/ValueTracking.cpp", 2047, __extension__ __PRETTY_FUNCTION__
))
;
2048}
2049
2050/// Try to detect a recurrence that the value of the induction variable is
2051/// always a power of two (or zero).
2052static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero,
2053 unsigned Depth, Query &Q) {
2054 BinaryOperator *BO = nullptr;
2055 Value *Start = nullptr, *Step = nullptr;
2056 if (!matchSimpleRecurrence(PN, BO, Start, Step))
2057 return false;
2058
2059 // Initial value must be a power of two.
2060 for (const Use &U : PN->operands()) {
2061 if (U.get() == Start) {
2062 // Initial value comes from a different BB, need to adjust context
2063 // instruction for analysis.
2064 Q.CxtI = PN->getIncomingBlock(U)->getTerminator();
2065 if (!isKnownToBeAPowerOfTwo(Start, OrZero, Depth, Q))
2066 return false;
2067 }
2068 }
2069
2070 // Except for Mul, the induction variable must be on the left side of the
2071 // increment expression, otherwise its value can be arbitrary.
2072 if (BO->getOpcode() != Instruction::Mul && BO->getOperand(1) != Step)
2073 return false;
2074
2075 Q.CxtI = BO->getParent()->getTerminator();
2076 switch (BO->getOpcode()) {
2077 case Instruction::Mul:
2078 // Power of two is closed under multiplication.
2079 return (OrZero || Q.IIQ.hasNoUnsignedWrap(BO) ||
2080 Q.IIQ.hasNoSignedWrap(BO)) &&
2081 isKnownToBeAPowerOfTwo(Step, OrZero, Depth, Q);
2082 case Instruction::SDiv:
2083 // Start value must not be signmask for signed division, so simply being a
2084 // power of two is not sufficient, and it has to be a constant.
2085 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2086 return false;
2087 [[fallthrough]];
2088 case Instruction::UDiv:
2089 // Divisor must be a power of two.
2090 // If OrZero is false, cannot guarantee induction variable is non-zero after
2091 // division, same for Shr, unless it is exact division.
2092 return (OrZero || Q.IIQ.isExact(BO)) &&
2093 isKnownToBeAPowerOfTwo(Step, false, Depth, Q);
2094 case Instruction::Shl:
2095 return OrZero || Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO);
2096 case Instruction::AShr:
2097 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2098 return false;
2099 [[fallthrough]];
2100 case Instruction::LShr:
2101 return OrZero || Q.IIQ.isExact(BO);
2102 default:
2103 return false;
2104 }
2105}
2106
2107/// Return true if the given value is known to have exactly one
2108/// bit set when defined. For vectors return true if every element is known to
2109/// be a power of two when defined. Supports values with integer or pointer
2110/// types and vectors of integers.
2111bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero, unsigned Depth,
2112 const Query &Q) {
2113 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth")(static_cast <bool> (Depth <= MaxAnalysisRecursionDepth
&& "Limit Search Depth") ? void (0) : __assert_fail (
"Depth <= MaxAnalysisRecursionDepth && \"Limit Search Depth\""
, "llvm/lib/Analysis/ValueTracking.cpp", 2113, __extension__ __PRETTY_FUNCTION__
))
;
2114
2115 // Attempt to match against constants.
2116 if (OrZero && match(V, m_Power2OrZero()))
2117 return true;
2118 if (match(V, m_Power2()))
2119 return true;
2120
2121 // 1 << X is clearly a power of two if the one is not shifted off the end. If
2122 // it is shifted off the end then the result is undefined.
2123 if (match(V, m_Shl(m_One(), m_Value())))
2124 return true;
2125
2126 // (signmask) >>l X is clearly a power of two if the one is not shifted off
2127 // the bottom. If it is shifted off the bottom then the result is undefined.
2128 if (match(V, m_LShr(m_SignMask(), m_Value())))
2129 return true;
2130
2131 // The remaining tests are all recursive, so bail out if we hit the limit.
2132 if (Depth++ == MaxAnalysisRecursionDepth)
2133 return false;
2134
2135 Value *X = nullptr, *Y = nullptr;
2136 // A shift left or a logical shift right of a power of two is a power of two
2137 // or zero.
2138 if (OrZero && (match(V, m_Shl(m_Value(X), m_Value())) ||
2139 match(V, m_LShr(m_Value(X), m_Value()))))
2140 return isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q);
2141
2142 if (const ZExtInst *ZI = dyn_cast<ZExtInst>(V))
2143 return isKnownToBeAPowerOfTwo(ZI->getOperand(0), OrZero, Depth, Q);
2144
2145 if (const SelectInst *SI = dyn_cast<SelectInst>(V))
2146 return isKnownToBeAPowerOfTwo(SI->getTrueValue(), OrZero, Depth, Q) &&
2147 isKnownToBeAPowerOfTwo(SI->getFalseValue(), OrZero, Depth, Q);
2148
2149 // Peek through min/max.
2150 if (match(V, m_MaxOrMin(m_Value(X), m_Value(Y)))) {
2151 return isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q) &&
2152 isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q);
2153 }
2154
2155 if (OrZero && match(V, m_And(m_Value(X), m_Value(Y)))) {
2156 // A power of two and'd with anything is a power of two or zero.
2157 if (isKnownToBeAPowerOfTwo(X, /*OrZero*/ true, Depth, Q) ||
2158 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, Depth, Q))
2159 return true;
2160 // X & (-X) is always a power of two or zero.
2161 if (match(X, m_Neg(m_Specific(Y))) || match(Y, m_Neg(m_Specific(X))))
2162 return true;
2163 return false;
2164 }
2165
2166 // Adding a power-of-two or zero to the same power-of-two or zero yields
2167 // either the original power-of-two, a larger power-of-two or zero.
2168 if (match(V, m_Add(m_Value(X), m_Value(Y)))) {
2169 const OverflowingBinaryOperator *VOBO = cast<OverflowingBinaryOperator>(V);
2170 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
2171 Q.IIQ.hasNoSignedWrap(VOBO)) {
2172 if (match(X, m_And(m_Specific(Y), m_Value())) ||
2173 match(X, m_And(m_Value(), m_Specific(Y))))
2174 if (isKnownToBeAPowerOfTwo(Y, OrZero, Depth, Q))
2175 return true;
2176 if (match(Y, m_And(m_Specific(X), m_Value())) ||
2177 match(Y, m_And(m_Value(), m_Specific(X))))
2178 if (isKnownToBeAPowerOfTwo(X, OrZero, Depth, Q))
2179 return true;
2180
2181 unsigned BitWidth = V->getType()->getScalarSizeInBits();
2182 KnownBits LHSBits(BitWidth);
2183 computeKnownBits(X, LHSBits, Depth, Q);
2184
2185 KnownBits RHSBits(BitWidth);
2186 computeKnownBits(Y, RHSBits, Depth, Q);
2187 // If i8 V is a power of two or zero:
2188 // ZeroBits: 1 1 1 0 1 1 1 1
2189 // ~ZeroBits: 0 0 0 1 0 0 0 0
2190 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
2191 // If OrZero isn't set, we cannot give back a zero result.
2192 // Make sure either the LHS or RHS has a bit set.
2193 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
2194 return true;
2195 }
2196 }
2197
2198 // A PHI node is power of two if all incoming values are power of two, or if
2199 // it is an induction variable where in each step its value is a power of two.
2200 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
2201 Query RecQ = Q;
2202
2203 // Check if it is an induction variable and always power of two.
2204 if (isPowerOfTwoRecurrence(PN, OrZero, Depth, RecQ))
2205 return true;
2206
2207 // Recursively check all incoming values. Limit recursion to 2 levels, so
2208 // that search complexity is limited to number of operands^2.
2209 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
2210 return llvm::all_of(PN->operands(), [&](const Use &U) {
2211 // Value is power of 2 if it is coming from PHI node itself by induction.
2212 if (U.get() == PN)
2213 return true;
2214
2215 // Change the context instruction to the incoming block where it is
2216 // evaluated.
2217 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
2218 return isKnownToBeAPowerOfTwo(U.get(), OrZero, NewDepth, RecQ);
2219 });
2220 }
2221
2222 // An exact divide or right shift can only shift off zero bits, so the result
2223 // is a power of two only if the first operand is a power of two and not
2224 // copying a sign bit (sdiv int_min, 2).
2225 if (match(V, m_Exact(m_LShr(m_Value(), m_Value()))) ||
2226 match(V, m_Exact(m_UDiv(m_Value(), m_Value())))) {
2227 return isKnownToBeAPowerOfTwo(cast<Operator>(V)->getOperand(0), OrZero,
2228 Depth, Q);
2229 }
2230
2231 return false;
2232}
2233
2234/// Test whether a GEP's result is known to be non-null.
2235///
2236/// Uses properties inherent in a GEP to try to determine whether it is known
2237/// to be non-null.
2238///
2239/// Currently this routine does not support vector GEPs.
2240static bool isGEPKnownNonNull(const GEPOperator *GEP, unsigned Depth,
2241 const Query &Q) {
2242 const Function *F = nullptr;
2243 if (const Instruction *I = dyn_cast<Instruction>(GEP))
2244 F = I->getFunction();
2245
2246 if (!GEP->isInBounds() ||
2247 NullPointerIsDefined(F, GEP->getPointerAddressSpace()))
2248 return false;
2249
2250 // FIXME: Support vector-GEPs.
2251 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP")(static_cast <bool> (GEP->getType()->isPointerTy(
) && "We only support plain pointer GEP") ? void (0) :
__assert_fail ("GEP->getType()->isPointerTy() && \"We only support plain pointer GEP\""
, "llvm/lib/Analysis/ValueTracking.cpp", 2251, __extension__ __PRETTY_FUNCTION__
))
;
2252
2253 // If the base pointer is non-null, we cannot walk to a null address with an
2254 // inbounds GEP in address space zero.
2255 if (isKnownNonZero(GEP->getPointerOperand(), Depth, Q))
2256 return true;
2257
2258 // Walk the GEP operands and see if any operand introduces a non-zero offset.
2259 // If so, then the GEP cannot produce a null pointer, as doing so would
2260 // inherently violate the inbounds contract within address space zero.
2261 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
2262 GTI != GTE; ++GTI) {
2263 // Struct types are easy -- they must always be indexed by a constant.
2264 if (StructType *STy = GTI.getStructTypeOrNull()) {
2265 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
2266 unsigned ElementIdx = OpC->getZExtValue();
2267 const StructLayout *SL = Q.DL.getStructLayout(STy);
2268 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
2269 if (ElementOffset > 0)
2270 return true;
2271 continue;
2272 }
2273
2274 // If we have a zero-sized type, the index doesn't matter. Keep looping.
2275 if (Q.DL.getTypeAllocSize(GTI.getIndexedType()).isZero())
2276 continue;
2277
2278 // Fast path the constant operand case both for efficiency and so we don't
2279 // increment Depth when just zipping down an all-constant GEP.
2280 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
2281 if (!OpC->isZero())
2282 return true;
2283 continue;
2284 }
2285
2286 // We post-increment Depth here because while isKnownNonZero increments it
2287 // as well, when we pop back up that increment won't persist. We don't want
2288 // to recurse 10k times just because we have 10k GEP operands. We don't
2289 // bail completely out because we want to handle constant GEPs regardless
2290 // of depth.
2291 if (Depth++ >= MaxAnalysisRecursionDepth)
2292 continue;
2293
2294 if (isKnownNonZero(GTI.getOperand(), Depth, Q))
2295 return true;
2296 }
2297
2298 return false;
2299}
2300
2301static bool isKnownNonNullFromDominatingCondition(const Value *V,
2302 const Instruction *CtxI,
2303 const DominatorTree *DT) {
2304 if (isa<Constant>(V))
2305 return false;
2306
2307 if (!CtxI || !DT)
2308 return false;
2309
2310 unsigned NumUsesExplored = 0;
2311 for (const auto *U : V->users()) {
2312 // Avoid massive lists
2313 if (NumUsesExplored >= DomConditionsMaxUses)
2314 break;
2315 NumUsesExplored++;
2316
2317 // If the value is used as an argument to a call or invoke, then argument
2318 // attributes may provide an answer about null-ness.
2319 if (const auto *CB = dyn_cast<CallBase>(U))
2320 if (auto *CalledFunc = CB->getCalledFunction())
2321 for (const Argument &Arg : CalledFunc->args())
2322 if (CB->getArgOperand(Arg.getArgNo()) == V &&
2323 Arg.hasNonNullAttr(/* AllowUndefOrPoison */ false) &&
2324 DT->dominates(CB, CtxI))
2325 return true;
2326
2327 // If the value is used as a load/store, then the pointer must be non null.
2328 if (V == getLoadStorePointerOperand(U)) {
2329 const Instruction *I = cast<Instruction>(U);
2330 if (!NullPointerIsDefined(I->getFunction(),
2331 V->getType()->getPointerAddressSpace()) &&
2332 DT->dominates(I, CtxI))
2333 return true;
2334 }
2335
2336 // Consider only compare instructions uniquely controlling a branch
2337 Value *RHS;
2338 CmpInst::Predicate Pred;
2339 if (!match(U, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS))))
2340 continue;
2341
2342 bool NonNullIfTrue;
2343 if (cmpExcludesZero(Pred, RHS))
2344 NonNullIfTrue = true;
2345 else if (cmpExcludesZero(CmpInst::getInversePredicate(Pred), RHS))
2346 NonNullIfTrue = false;
2347 else
2348 continue;
2349
2350 SmallVector<const User *, 4> WorkList;
2351 SmallPtrSet<const User *, 4> Visited;
2352 for (const auto *CmpU : U->users()) {
2353 assert(WorkList.empty() && "Should be!")(static_cast <bool> (WorkList.empty() && "Should be!"
) ? void (0) : __assert_fail ("WorkList.empty() && \"Should be!\""
, "llvm/lib/Analysis/ValueTracking.cpp", 2353, __extension__ __PRETTY_FUNCTION__
))
;
2354 if (Visited.insert(CmpU).second)
2355 WorkList.push_back(CmpU);
2356
2357 while (!WorkList.empty()) {
2358 auto *Curr = WorkList.pop_back_val();
2359
2360 // If a user is an AND, add all its users to the work list. We only
2361 // propagate "pred != null" condition through AND because it is only
2362 // correct to assume that all conditions of AND are met in true branch.
2363 // TODO: Support similar logic of OR and EQ predicate?
2364 if (NonNullIfTrue)
2365 if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) {
2366 for (const auto *CurrU : Curr->users())
2367 if (Visited.insert(CurrU).second)
2368 WorkList.push_back(CurrU);
2369 continue;
2370 }
2371
2372 if (const BranchInst *BI = dyn_cast<BranchInst>(Curr)) {
2373 assert(BI->isConditional() && "uses a comparison!")(static_cast <bool> (BI->isConditional() && "uses a comparison!"
) ? void (0) : __assert_fail ("BI->isConditional() && \"uses a comparison!\""
, "llvm/lib/Analysis/ValueTracking.cpp", 2373, __extension__ __PRETTY_FUNCTION__
))
;
2374
2375 BasicBlock *NonNullSuccessor =
2376 BI->getSuccessor(NonNullIfTrue ? 0 : 1);
2377 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
2378 if (Edge.isSingleEdge() && DT->dominates(Edge, CtxI->getParent()))
2379 return true;
2380 } else if (NonNullIfTrue && isGuard(Curr) &&
2381 DT->dominates(cast<Instruction>(Curr), CtxI)) {
2382 return true;
2383 }
2384 }
2385 }
2386 }
2387
2388 return false;
2389}
2390
2391/// Does the 'Range' metadata (which must be a valid MD_range operand list)
2392/// ensure that the value it's attached to is never Value? 'RangeType' is
2393/// is the type of the value described by the range.
2394static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
2395 const unsigned NumRanges = Ranges->getNumOperands() / 2;
2396 assert(NumRanges >= 1)(static_cast <bool> (NumRanges >= 1) ? void (0) : __assert_fail
("NumRanges >= 1", "llvm/lib/Analysis/ValueTracking.cpp",
2396, __extension__ __PRETTY_FUNCTION__))
;
2397 for (unsigned i = 0; i < NumRanges; ++i) {
2398 ConstantInt *Lower =
2399 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
2400 ConstantInt *Upper =
2401 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
2402 ConstantRange Range(Lower->getValue(), Upper->getValue());
2403 if (Range.contains(Value))
2404 return false;
2405 }
2406 return true;
2407}
2408
2409/// Try to detect a recurrence that monotonically increases/decreases from a
2410/// non-zero starting value. These are common as induction variables.
2411static bool isNonZeroRecurrence(const PHINode *PN) {
2412 BinaryOperator *BO = nullptr;
2413 Value *Start = nullptr, *Step = nullptr;
2414 const APInt *StartC, *StepC;
2415 if (!matchSimpleRecurrence(PN, BO, Start, Step) ||
2416 !match(Start, m_APInt(StartC)) || StartC->isZero())
2417 return false;
2418
2419 switch (BO->getOpcode()) {
2420 case Instruction::Add:
2421 // Starting from non-zero and stepping away from zero can never wrap back
2422 // to zero.
2423 return BO->hasNoUnsignedWrap() ||
2424 (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) &&
2425 StartC->isNegative() == StepC->isNegative());
2426 case Instruction::Mul:
2427 return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) &&
2428 match(Step, m_APInt(StepC)) && !StepC->isZero();
2429 case Instruction::Shl:
2430 return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap();
2431 case Instruction::AShr:
2432 case Instruction::LShr:
2433 return BO->isExact();
2434 default:
2435 return false;
2436 }
2437}
2438
2439/// Return true if the given value is known to be non-zero when defined. For
2440/// vectors, return true if every demanded element is known to be non-zero when
2441/// defined. For pointers, if the context instruction and dominator tree are
2442/// specified, perform context-sensitive analysis and return true if the
2443/// pointer couldn't possibly be null at the specified instruction.
2444/// Supports values with integer or pointer type and vectors of integers.
2445bool isKnownNonZero(const Value *V, const APInt &DemandedElts, unsigned Depth,
2446 const Query &Q) {
2447
2448#ifndef NDEBUG
2449 Type *Ty = V->getType();
2450 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth")(static_cast <bool> (Depth <= MaxAnalysisRecursionDepth
&& "Limit Search Depth") ? void (0) : __assert_fail (
"Depth <= MaxAnalysisRecursionDepth && \"Limit Search Depth\""
, "llvm/lib/Analysis/ValueTracking.cpp", 2450, __extension__ __PRETTY_FUNCTION__
))
;
2451
2452 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2453 assert((static_cast <bool> (FVTy->getNumElements() == DemandedElts
.getBitWidth() && "DemandedElt width should equal the fixed vector number of elements"
) ? void (0) : __assert_fail ("FVTy->getNumElements() == DemandedElts.getBitWidth() && \"DemandedElt width should equal the fixed vector number of elements\""
, "llvm/lib/Analysis/ValueTracking.cpp", 2455, __extension__ __PRETTY_FUNCTION__
))
2454 FVTy->getNumElements() == DemandedElts.getBitWidth() &&(static_cast <bool> (FVTy->getNumElements() == DemandedElts
.getBitWidth() && "DemandedElt width should equal the fixed vector number of elements"
) ? void (0) : __assert_fail ("FVTy->getNumElements() == DemandedElts.getBitWidth() && \"DemandedElt width should equal the fixed vector number of elements\""
, "llvm/lib/Analysis/ValueTracking.cpp", 2455, __extension__ __PRETTY_FUNCTION__
))
2455 "DemandedElt width should equal the fixed vector number of elements")(static_cast <bool> (FVTy->getNumElements() == DemandedElts
.getBitWidth() && "DemandedElt width should equal the fixed vector number of elements"
) ? void (0) : __assert_fail ("FVTy->getNumElements() == DemandedElts.getBitWidth() && \"DemandedElt width should equal the fixed vector number of elements\""
, "llvm/lib/Analysis/ValueTracking.cpp", 2455, __extension__ __PRETTY_FUNCTION__
))
;
2456 } else {
2457 assert(DemandedElts == APInt(1, 1) &&(static_cast <bool> (DemandedElts == APInt(1, 1) &&
"DemandedElt width should be 1 for scalars") ? void (0) : __assert_fail
("DemandedElts == APInt(1, 1) && \"DemandedElt width should be 1 for scalars\""
, "llvm/lib/Analysis/ValueTracking.cpp", 2458, __extension__ __PRETTY_FUNCTION__
))
2458 "DemandedElt width should be 1 for scalars")(static_cast <bool> (DemandedElts == APInt(1, 1) &&
"DemandedElt width should be 1 for scalars") ? void (0) : __assert_fail
("DemandedElts == APInt(1, 1) && \"DemandedElt width should be 1 for scalars\""
, "llvm/lib/Analysis/ValueTracking.cpp", 2458, __extension__ __PRETTY_FUNCTION__
))
;
2459 }
2460#endif
2461
2462 if (auto *C = dyn_cast<Constant>(V)) {
2463 if (C->isNullValue())
2464 return false;
2465 if (isa<ConstantInt>(C))
2466 // Must be non-zero due to null test above.
2467 return true;
2468
2469 // For constant vectors, check that all elements are undefined or known
2470 // non-zero to determine that the whole vector is known non-zero.
2471 if (auto *VecTy = dyn_cast<FixedVectorType>(C->getType())) {
2472 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
2473 if (!DemandedElts[i])
2474 continue;
2475 Constant *Elt = C->getAggregateElement(i);
2476 if (!Elt || Elt->isNullValue())
2477 return false;
2478 if (!isa<UndefValue>(Elt) && !isa<ConstantInt>(Elt))
2479 return false;
2480 }
2481 return true;
2482 }
2483
2484 // A global variable in address space 0 is non null unless extern weak
2485 // or an absolute symbol reference. Other address spaces may have null as a
2486 // valid address for a global, so we can't assume anything.
2487 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2488 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
2489 GV->getType()->getAddressSpace() == 0)
2490 return true;
2491 }
2492
2493 // For constant expressions, fall through to the Operator code below.
2494 if (!isa<ConstantExpr>(V))
2495 return false;
2496 }
2497
2498 if (auto *I = dyn_cast<Instruction>(V)) {
2499 if (MDNode *Ranges = Q.IIQ.getMetadata(I, LLVMContext::MD_range)) {
2500 // If the possible ranges don't contain zero, then the value is
2501 // definitely non-zero.
2502 if (auto *Ty = dyn_cast<IntegerType>(V->getType())) {
2503 const APInt ZeroValue(Ty->getBitWidth(), 0);
2504 if (rangeMetadataExcludesValue(Ranges, ZeroValue))
2505 return true;
2506 }
2507 }
2508 }
2509
2510 if (!isa<Constant>(V) && isKnownNonZeroFromAssume(V, Q))
2511 return true;
2512
2513 // Some of the tests below are recursive, so bail out if we hit the limit.
2514 if (Depth++ >= MaxAnalysisRecursionDepth)
2515 return false;
2516
2517 // Check for pointer simplifications.
2518
2519 if (PointerType *PtrTy = dyn_cast<PointerType>(V->getType())) {
2520 // Alloca never returns null, malloc might.
2521 if (isa<AllocaInst>(V) && Q.DL.getAllocaAddrSpace() == 0)
2522 return true;
2523
2524 // A byval, inalloca may not be null in a non-default addres space. A
2525 // nonnull argument is assumed never 0.
2526 if (const Argument *A = dyn_cast<Argument>(V)) {
2527 if (((A->hasPassPointeeByValueCopyAttr() &&
2528 !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
2529 A->hasNonNullAttr()))
2530 return true;
2531 }
2532
2533 // A Load tagged with nonnull metadata is never null.
2534 if (const LoadInst *LI = dyn_cast<LoadInst>(V))
2535 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull))
2536 return true;
2537
2538 if (const auto *Call = dyn_cast<CallBase>(V)) {
2539 if (Call->isReturnNonNull())
2540 return true;
2541 if (const auto *RP = getArgumentAliasingToReturnedPointer(Call, true))
2542 return isKnownNonZero(RP, Depth, Q);
2543 }
2544 }
2545
2546 if (!isa<Constant>(V) &&
2547 isKnownNonNullFromDominatingCondition(V, Q.CxtI, Q.DT))
2548 return true;
2549
2550 const Operator *I = dyn_cast<Operator>(V);
2551 if (!I)
2552 return false;
2553
2554 unsigned BitWidth = getBitWidth(V->getType()->getScalarType(), Q.DL);
2555 switch (I->getOpcode()) {
2556 case Instruction::GetElementPtr:
2557 if (I->getType()->isPointerTy())
2558 return isGEPKnownNonNull(cast<GEPOperator>(I), Depth, Q);
2559 break;
2560 case Instruction::BitCast:
2561 if (I->getType()->isPointerTy())
2562 return isKnownNonZero(I->getOperand(0), Depth, Q);
2563 break;
2564 case Instruction::IntToPtr:
2565 // Note that we have to take special care to avoid looking through
2566 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
2567 // as casts that can alter the value, e.g., AddrSpaceCasts.
2568 if (!isa<ScalableVectorType>(I->getType()) &&
2569 Q.DL.getTypeSizeInBits(I->getOperand(0)->getType()).getFixedSize() <=
2570 Q.DL.getTypeSizeInBits(I->getType()).getFixedSize())
2571 return isKnownNonZero(I->getOperand(0), Depth, Q);
2572 break;
2573 case Instruction::PtrToInt:
2574 // Similar to int2ptr above, we can look through ptr2int here if the cast
2575 // is a no-op or an extend and not a truncate.
2576 if (!isa<ScalableVectorType>(I->getType()) &&
2577 Q.DL.getTypeSizeInBits(I->getOperand(0)->getType()).getFixedSize() <=
2578 Q.DL.getTypeSizeInBits(I->getType()).getFixedSize())
2579 return isKnownNonZero(I->getOperand(0), Depth, Q);
2580 break;
2581 case Instruction::Or:
2582 // X | Y != 0 if X != 0 or Y != 0.
2583 return isKnownNonZero(I->getOperand(0), DemandedElts, Depth, Q) ||
2584 isKnownNonZero(I->getOperand(1), DemandedElts, Depth, Q);
2585 case Instruction::SExt:
2586 case Instruction::ZExt:
2587 // ext X != 0 if X != 0.
2588 return isKnownNonZero(I->getOperand(0), Depth, Q);
2589
2590 case Instruction::Shl: {
2591 // shl nuw can't remove any non-zero bits.
2592 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
2593 if (Q.IIQ.hasNoUnsignedWrap(BO))
2594 return isKnownNonZero(I->getOperand(0), Depth, Q);
2595
2596 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
2597 // if the lowest bit is shifted off the end.
2598 KnownBits Known(BitWidth);
2599 computeKnownBits(I->getOperand(0), DemandedElts, Known, Depth, Q);
2600 if (Known.One[0])
2601 return true;
2602 break;
2603 }
2604 case Instruction::LShr:
2605 case Instruction::AShr: {
2606 // shr exact can only shift out zero bits.
2607 const PossiblyExactOperator *BO = cast<PossiblyExactOperator>(V);
2608 if (BO->isExact())
2609 return isKnownNonZero(I->getOperand(0), Depth, Q);
2610
2611 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
2612 // defined if the sign bit is shifted off the end.
2613 KnownBits Known =
2614 computeKnownBits(I->getOperand(0), DemandedElts, Depth, Q);
2615 if (Known.isNegative())
2616 return true;
2617
2618 // If the shifter operand is a constant, and all of the bits shifted
2619 // out are known to be zero, and X is known non-zero then at least one
2620 // non-zero bit must remain.
2621 if (ConstantInt *Shift = dyn_cast<ConstantInt>(I->getOperand(1))) {
2622 auto ShiftVal = Shift->getLimitedValue(BitWidth - 1);
2623 // Is there a known one in the portion not shifted out?
2624 if (Known.countMaxLeadingZeros() < BitWidth - ShiftVal)
2625 return true;
2626 // Are all the bits to be shifted out known zero?
2627 if (Known.countMinTrailingZeros() >= ShiftVal)
2628 return isKnownNonZero(I->getOperand(0), DemandedElts, Depth, Q);
2629 }
2630 break;
2631 }
2632 case Instruction::UDiv:
2633 case Instruction::SDiv:
2634 // div exact can only produce a zero if the dividend is zero.
2635 if (cast<PossiblyExactOperator>(I)->isExact())
2636 return isKnownNonZero(I->getOperand(0), DemandedElts, Depth, Q);
2637 break;
2638 case Instruction::Add: {
2639 // X + Y.
2640 KnownBits XKnown =
2641 computeKnownBits(I->getOperand(0), DemandedElts, Depth, Q);
2642 KnownBits YKnown =
2643 computeKnownBits(I->getOperand(1), DemandedElts, Depth, Q);
2644
2645 // If X and Y are both non-negative (as signed values) then their sum is not
2646 // zero unless both X and Y are zero.
2647 if (XKnown.isNonNegative() && YKnown.isNonNegative())
2648 if (isKnownNonZero(I->getOperand(0), DemandedElts, Depth, Q) ||
2649 isKnownNonZero(I->getOperand(1), DemandedElts, Depth, Q))
2650 return true;
2651
2652 // If X and Y are both negative (as signed values) then their sum is not
2653 // zero unless both X and Y equal INT_MIN.
2654 if (XKnown.isNegative() && YKnown.isNegative()) {
2655 APInt Mask = APInt::getSignedMaxValue(BitWidth);
2656 // The sign bit of X is set. If some other bit is set then X is not equal
2657 // to INT_MIN.
2658 if (XKnown.One.intersects(Mask))
2659 return true;
2660 // The sign bit of Y is set. If some other bit is set then Y is not equal
2661 // to INT_MIN.
2662 if (YKnown.One.intersects(Mask))
2663 return true;
2664 }
2665
2666 // The sum of a non-negative number and a power of two is not zero.
2667 if (XKnown.isNonNegative() &&
2668 isKnownToBeAPowerOfTwo(I->getOperand(1), /*OrZero*/ false, Depth, Q))
2669 return true;
2670 if (YKnown.isNonNegative() &&
2671 isKnownToBeAPowerOfTwo(I->getOperand(0), /*OrZero*/ false, Depth, Q))
2672 return true;
2673 break;
2674 }
2675 case Instruction::Mul: {
2676 // If X and Y are non-zero then so is X * Y as long as the multiplication
2677 // does not overflow.
2678 const OverflowingBinaryOperator *BO = cast<OverflowingBinaryOperator>(V);
2679 if ((Q.IIQ.hasNoSignedWrap(BO) || Q.IIQ.hasNoUnsignedWrap(BO)) &&
2680 isKnownNonZero(I->getOperand(0), DemandedElts, Depth, Q) &&
2681 isKnownNonZero(I->getOperand(1), DemandedElts, Depth, Q))
2682 return true;
2683 break;
2684 }
2685 case Instruction::Select:
2686 // (C ? X : Y) != 0 if X != 0 and Y != 0.
2687 if (isKnownNonZero(I->getOperand(1), DemandedElts, Depth, Q) &&
2688 isKnownNonZero(I->getOperand(2), DemandedElts, Depth, Q))
2689 return true;
2690 break;
2691 case Instruction::PHI: {
2692 auto *PN = cast<PHINode>(I);
2693 if (Q.IIQ.UseInstrInfo && isNonZeroRecurrence(PN))
2694 return true;
2695
2696 // Check if all incoming values are non-zero using recursion.
2697 Query RecQ = Q;
2698 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
2699 return llvm::all_of(PN->operands(), [&](const Use &U) {
2700 if (U.get() == PN)
2701 return true;
2702 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
2703 return isKnownNonZero(U.get(), DemandedElts, NewDepth, RecQ);
2704 });
2705 }
2706 case Instruction::ExtractElement:
2707 if (const auto *EEI = dyn_cast<ExtractElementInst>(V)) {
2708 const Value *Vec = EEI->getVectorOperand();
2709 const Value *Idx = EEI->getIndexOperand();
2710 auto *CIdx = dyn_cast<ConstantInt>(Idx);
2711 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
2712 unsigned NumElts = VecTy->getNumElements();
2713 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
2714 if (CIdx && CIdx->getValue().ult(NumElts))
2715 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2716 return isKnownNonZero(Vec, DemandedVecElts, Depth, Q);
2717 }
2718 }
2719 break;
2720 case Instruction::Freeze:
2721 return isKnownNonZero(I->getOperand(0), Depth, Q) &&
2722 isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
2723 Depth);
2724 case Instruction::Call:
2725 if (cast<CallInst>(I)->getIntrinsicID() == Intrinsic::vscale)
2726 return true;
2727 break;
2728 }
2729
2730 KnownBits Known(BitWidth);
2731 computeKnownBits(V, DemandedElts, Known, Depth, Q);
2732 return Known.One != 0;
2733}
2734
2735bool isKnownNonZero(const Value* V, unsigned Depth, const Query& Q) {
2736 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
2737 APInt DemandedElts =
2738 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
2739 return isKnownNonZero(V, DemandedElts, Depth, Q);
2740}
2741
2742/// If the pair of operators are the same invertible function, return the
2743/// the operands of the function corresponding to each input. Otherwise,
2744/// return None. An invertible function is one that is 1-to-1 and maps
2745/// every input value to exactly one output value. This is equivalent to
2746/// saying that Op1 and Op2 are equal exactly when the specified pair of
2747/// operands are equal, (except that Op1 and Op2 may be poison more often.)
2748static Optional<std::pair<Value*, Value*>>
2749getInvertibleOperands(const Operator *Op1,
2750 const Operator *Op2) {
2751 if (Op1->getOpcode() != Op2->getOpcode())
2752 return None;
2753
2754 auto getOperands = [&](unsigned OpNum) -> auto {
2755 return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
2756 };
2757
2758 switch (Op1->getOpcode()) {
2759 default:
2760 break;
2761 case Instruction::Add:
2762 case Instruction::Sub:
2763 if (Op1->getOperand(0) == Op2->getOperand(0))
2764 return getOperands(1);
2765 if (Op1->getOperand(1) == Op2->getOperand(1))
2766 return getOperands(0);
2767 break;
2768 case Instruction::Mul: {
2769 // invertible if A * B == (A * B) mod 2^N where A, and B are integers
2770 // and N is the bitwdith. The nsw case is non-obvious, but proven by
2771 // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
2772 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
2773 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
2774 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
2775 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
2776 break;
2777
2778 // Assume operand order has been canonicalized
2779 if (Op1->getOperand(1) == Op2->getOperand(1) &&
2780 isa<ConstantInt>(Op1->getOperand(1)) &&
2781 !cast<ConstantInt>(Op1->getOperand(1))->isZero())
2782 return getOperands(0);
2783 break;
2784 }
2785 case Instruction::Shl: {
2786 // Same as multiplies, with the difference that we don't need to check
2787 // for a non-zero multiply. Shifts always multiply by non-zero.
2788 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
2789 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
2790 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
2791 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
2792 break;
2793
2794 if (Op1->getOperand(1) == Op2->getOperand(1))
2795 return getOperands(0);
2796 break;
2797 }
2798 case Instruction::AShr:
2799 case Instruction::LShr: {
2800 auto *PEO1 = cast<PossiblyExactOperator>(Op1);
2801 auto *PEO2 = cast<PossiblyExactOperator>(Op2);
2802 if (!PEO1->isExact() || !PEO2->isExact())
2803 break;
2804
2805 if (Op1->getOperand(1) == Op2->getOperand(1))
2806 return getOperands(0);
2807 break;
2808 }
2809 case Instruction::SExt:
2810 case Instruction::ZExt:
2811 if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
2812 return getOperands(0);
2813 break;
2814 case Instruction::PHI: {
2815 const PHINode *PN1 = cast<PHINode>(Op1);
2816 const PHINode *PN2 = cast<PHINode>(Op2);
2817
2818 // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
2819 // are a single invertible function of the start values? Note that repeated
2820 // application of an invertible function is also invertible
2821 BinaryOperator *BO1 = nullptr;
2822 Value *Start1 = nullptr, *Step1 = nullptr;
2823 BinaryOperator *BO2 = nullptr;
2824 Value *Start2 = nullptr, *Step2 = nullptr;
2825 if (PN1->getParent() != PN2->getParent() ||
2826 !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
2827 !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
2828 break;
2829
2830 auto Values = getInvertibleOperands(cast<Operator>(BO1),
2831 cast<Operator>(BO2));
2832 if (!Values)
2833 break;
2834
2835 // We have to be careful of mutually defined recurrences here. Ex:
2836 // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
2837 // * X_i = Y_i = X_(i-1) OP Y_(i-1)
2838 // The invertibility of these is complicated, and not worth reasoning
2839 // about (yet?).
2840 if (Values->first != PN1 || Values->second != PN2)
2841 break;
2842
2843 return std::make_pair(Start1, Start2);
2844 }
2845 }
2846 return None;
2847}
2848
2849/// Return true if V2 == V1 + X, where X is known non-zero.
2850static bool isAddOfNonZero(const Value *V1, const Value *V2, unsigned Depth,
2851 const Query &Q) {
2852 const BinaryOperator *BO = dyn_cast<BinaryOperator>(V1);
2853 if (!BO || BO->getOpcode() != Instruction::Add)
2854 return false;
2855 Value *Op = nullptr;
2856 if (V2 == BO->getOperand(0))
2857 Op = BO->getOperand(1);
2858 else if (V2 == BO->getOperand(1))
2859 Op = BO->getOperand(0);
2860 else
2861 return false;
2862 return isKnownNonZero(Op, Depth + 1, Q);
2863}
2864
2865/// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
2866/// the multiplication is nuw or nsw.
2867static bool isNonEqualMul(const Value *V1, const Value *V2, unsigned Depth,
2868 const Query &Q) {
2869 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
2870 const APInt *C;
2871 return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
2872 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
2873 !C->isZero() && !C->isOne() && isKnownNonZero(V1, Depth + 1, Q);
2874 }
2875 return false;
2876}
2877
2878/// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
2879/// the shift is nuw or nsw.
2880static bool isNonEqualShl(const Value *V1, const Value *V2, unsigned Depth,
2881 const Query &Q) {
2882 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
2883 const APInt *C;
2884 return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
2885 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
2886 !C->isZero() && isKnownNonZero(V1, Depth + 1, Q);
2887 }
2888 return false;
2889}
2890
2891static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
2892 unsigned Depth, const Query &Q) {
2893 // Check two PHIs are in same block.
2894 if (PN1->getParent() != PN2->getParent())
2895 return false;
2896
2897 SmallPtrSet<const BasicBlock *, 8> VisitedBBs;
2898 bool UsedFullRecursion = false;
2899 for (const BasicBlock *IncomBB : PN1->blocks()) {
2900 if (!VisitedBBs.insert(IncomBB).second)
2901 continue; // Don't reprocess blocks that we have dealt with already.
2902 const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
2903 const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
2904 const APInt *C1, *C2;
2905 if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
2906 continue;
2907
2908 // Only one pair of phi operands is allowed for full recursion.
2909 if (UsedFullRecursion)
2910 return false;
2911
2912 Query RecQ = Q;
2913 RecQ.CxtI = IncomBB->getTerminator();
2914 if (!isKnownNonEqual(IV1, IV2, Depth + 1, RecQ))
2915 return false;
2916 UsedFullRecursion = true;
2917 }
2918 return true;
2919}
2920
2921/// Return true if it is known that V1 != V2.
2922static bool isKnownNonEqual(const Value *V1, const Value *V2, unsigned Depth,
2923 const Query &Q) {
2924 if (V1 == V2)
2925 return false;
2926 if (V1->getType() != V2->getType())
2927 // We can't look through casts yet.
2928 return false;
2929
2930 if (Depth >= MaxAnalysisRecursionDepth)
2931 return false;
2932
2933 // See if we can recurse through (exactly one of) our operands. This
2934 // requires our operation be 1-to-1 and map every input value to exactly
2935 // one output value. Such an operation is invertible.
2936 auto *O1 = dyn_cast<Operator>(V1);
2937 auto *O2 = dyn_cast<Operator>(V2);
2938 if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
2939 if (auto Values = getInvertibleOperands(O1, O2))
2940 return isKnownNonEqual(Values->first, Values->second, Depth + 1, Q);
2941
2942 if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
2943 const PHINode *PN2 = cast<PHINode>(V2);
2944 // FIXME: This is missing a generalization to handle the case where one is
2945 // a PHI and another one isn't.
2946 if (isNonEqualPHIs(PN1, PN2, Depth, Q))
2947 return true;
2948 };
2949 }
2950
2951 if (isAddOfNonZero(V1, V2, Depth, Q) || isAddOfNonZero(V2, V1, Depth, Q))
2952 return true;
2953
2954 if (isNonEqualMul(V1, V2, Depth, Q) || isNonEqualMul(V2, V1, Depth, Q))
2955 return true;
2956
2957 if (isNonEqualShl(V1, V2, Depth, Q) || isNonEqualShl(V2, V1, Depth, Q))
2958 return true;
2959
2960 if (V1->getType()->isIntOrIntVectorTy()) {
2961 // Are any known bits in V1 contradictory to known bits in V2? If V1
2962 // has a known zero where V2 has a known one, they must not be equal.
2963 KnownBits Known1 = computeKnownBits(V1, Depth, Q);
2964 KnownBits Known2 = computeKnownBits(V2, Depth, Q);
2965
2966 if (Known1.Zero.intersects(Known2.One) ||
2967 Known2.Zero.intersects(Known1.One))
2968 return true;
2969 }
2970 return false;
2971}
2972
2973/// Return true if 'V & Mask' is known to be zero. We use this predicate to
2974/// simplify operations downstream. Mask is known to be zero for bits that V
2975/// cannot have.
2976///
2977/// This function is defined on values with integer type, values with pointer
2978/// type, and vectors of integers. In the case
2979/// where V is a vector, the mask, known zero, and known one values are the
2980/// same width as the vector element, and the bit is set only if it is true
2981/// for all of the elements in the vector.
2982bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth,
2983 const Query &Q) {
2984 KnownBits Known(Mask.getBitWidth());
2985 computeKnownBits(V, Known, Depth, Q);
2986 return Mask.isSubsetOf(Known.Zero);
2987}
2988
2989// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
2990// Returns the input and lower/upper bounds.
2991static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
2992 const APInt *&CLow, const APInt *&CHigh) {
2993 assert(isa<Operator>(Select) &&(static_cast <bool> (isa<Operator>(Select) &&
cast<Operator>(Select)->getOpcode() == Instruction::
Select && "Input should be a Select!") ? void (0) : __assert_fail
("isa<Operator>(Select) && cast<Operator>(Select)->getOpcode() == Instruction::Select && \"Input should be a Select!\""
, "llvm/lib/Analysis/ValueTracking.cpp", 2995, __extension__ __PRETTY_FUNCTION__
))
2994 cast<Operator>(Select)->getOpcode() == Instruction::Select &&(static_cast <bool> (isa<Operator>(Select) &&
cast<Operator>(Select)->getOpcode() == Instruction::
Select && "Input should be a Select!") ? void (0) : __assert_fail
("isa<Operator>(Select) && cast<Operator>(Select)->getOpcode() == Instruction::Select && \"Input should be a Select!\""
, "llvm/lib/Analysis/ValueTracking.cpp", 2995, __extension__ __PRETTY_FUNCTION__
))
2995 "Input should be a Select!")(static_cast <bool> (isa<Operator>(Select) &&
cast<Operator>(Select)->getOpcode() == Instruction::
Select && "Input should be a Select!") ? void (0) : __assert_fail
("isa<Operator>(Select) && cast<Operator>(Select)->getOpcode() == Instruction::Select && \"Input should be a Select!\""
, "llvm/lib/Analysis/ValueTracking.cpp", 2995, __extension__ __PRETTY_FUNCTION__
))
;
2996
2997 const Value *LHS = nullptr, *RHS = nullptr;
2998 SelectPatternFlavor SPF = matchSelectPattern(Select, LHS, RHS).Flavor;
2999 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
3000 return false;
3001
3002 if (!match(RHS, m_APInt(CLow)))
3003 return false;
3004
3005 const Value *LHS2 = nullptr, *RHS2 = nullptr;
3006 SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor;
3007 if (getInverseMinMaxFlavor(SPF) != SPF2)
3008 return false;
3009
3010 if (!match(RHS2, m_APInt(CHigh)))
3011 return false;
3012
3013 if (SPF == SPF_SMIN)
3014 std::swap(CLow, CHigh);
3015
3016 In = LHS2;
3017 return CLow->sle(*CHigh);
3018}
3019
3020static bool isSignedMinMaxIntrinsicClamp(const IntrinsicInst *II,
3021 const APInt *&CLow,
3022 const APInt *&CHigh) {
3023 assert((II->getIntrinsicID() == Intrinsic::smin ||(static_cast <bool> ((II->getIntrinsicID() == Intrinsic
::smin || II->getIntrinsicID() == Intrinsic::smax) &&
"Must be smin/smax") ? void (0) : __assert_fail ("(II->getIntrinsicID() == Intrinsic::smin || II->getIntrinsicID() == Intrinsic::smax) && \"Must be smin/smax\""
, "llvm/lib/Analysis/ValueTracking.cpp", 3024, __extension__ __PRETTY_FUNCTION__
))
3024 II->getIntrinsicID() == Intrinsic::smax) && "Must be smin/smax")(static_cast <bool> ((II->getIntrinsicID() == Intrinsic
::smin || II->getIntrinsicID() == Intrinsic::smax) &&
"Must be smin/smax") ? void (0) : __assert_fail ("(II->getIntrinsicID() == Intrinsic::smin || II->getIntrinsicID() == Intrinsic::smax) && \"Must be smin/smax\""
, "llvm/lib/Analysis/ValueTracking.cpp", 3024, __extension__ __PRETTY_FUNCTION__
))
;
3025
3026 Intrinsic::ID InverseID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
3027 auto *InnerII = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
3028 if (!InnerII || InnerII->getIntrinsicID() != InverseID ||
3029 !match(II->getArgOperand(1), m_APInt(CLow)) ||
3030 !match(InnerII->getArgOperand(1), m_APInt(CHigh)))
3031 return false;
3032
3033 if (II->getIntrinsicID() == Intrinsic::smin)
3034 std::swap(CLow, CHigh);
3035 return CLow->sle(*CHigh);
3036}
3037
3038/// For vector constants, loop over the elements and find the constant with the
3039/// minimum number of sign bits. Return 0 if the value is not a vector constant
3040/// or if any element was not analyzed; otherwise, return the count for the
3041/// element with the minimum number of sign bits.
3042static unsigned computeNumSignBitsVectorConstant(const Value *V,
3043 const APInt &DemandedElts,
3044 unsigned TyBits) {
3045 const auto *CV = dyn_cast<Constant>(V);
3046 if (!CV || !isa<FixedVectorType>(CV->getType()))
3047 return 0;
3048
3049 unsigned MinSignBits = TyBits;
3050 unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
3051 for (unsigned i = 0; i != NumElts; ++i) {
3052 if (!DemandedElts[i])
3053 continue;
3054 // If we find a non-ConstantInt, bail out.
3055 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
3056 if (!Elt)
3057 return 0;
3058
3059 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
3060 }
3061
3062 return MinSignBits;
3063}
3064
3065static unsigned ComputeNumSignBitsImpl(const Value *V,
3066 const APInt &DemandedElts,
3067 unsigned Depth, const Query &Q);
3068
3069static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
3070 unsigned Depth, const Query &Q) {
3071 unsigned Result = ComputeNumSignBitsImpl(V, DemandedElts, Depth, Q);
3072 assert(Result > 0 && "At least one sign bit needs to be present!")(static_cast <bool> (Result > 0 && "At least one sign bit needs to be present!"
) ? void (0) : __assert_fail ("Result > 0 && \"At least one sign bit needs to be present!\""
, "llvm/lib/Analysis/ValueTracking.cpp", 3072, __extension__ __PRETTY_FUNCTION__
))
;
3073 return Result;
3074}
3075
3076/// Return the number of times the sign bit of the register is replicated into
3077/// the other bits. We know that at least 1 bit is always equal to the sign bit
3078/// (itself), but other cases can give us information. For example, immediately
3079/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
3080/// other, so we return 3. For vectors, return the number of sign bits for the
3081/// vector element with the minimum number of known sign bits of the demanded
3082/// elements in the vector specified by DemandedElts.
3083static unsigned ComputeNumSignBitsImpl(const Value *V,
3084 const APInt &DemandedElts,
3085 unsigned Depth, const Query &Q) {
3086 Type *Ty = V->getType();
3087#ifndef NDEBUG
3088 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth")(static_cast <bool> (Depth <= MaxAnalysisRecursionDepth
&& "Limit Search Depth") ? void (0) : __assert_fail (
"Depth <= MaxAnalysisRecursionDepth && \"Limit Search Depth\""
, "llvm/lib/Analysis/ValueTracking.cpp", 3088, __extension__ __PRETTY_FUNCTION__
))
;
3089
3090 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
3091 assert((static_cast <bool> (FVTy->getNumElements() == DemandedElts
.getBitWidth() && "DemandedElt width should equal the fixed vector number of elements"
) ? void (0) : __assert_fail ("FVTy->getNumElements() == DemandedElts.getBitWidth() && \"DemandedElt width should equal the fixed vector number of elements\""
, "llvm/lib/Analysis/ValueTracking.cpp", 3093, __extension__ __PRETTY_FUNCTION__
))
3092 FVTy->getNumElements() == DemandedElts.getBitWidth() &&(static_cast <bool> (FVTy->getNumElements() == DemandedElts
.getBitWidth() && "DemandedElt width should equal the fixed vector number of elements"
) ? void (0) : __assert_fail ("FVTy->getNumElements() == DemandedElts.getBitWidth() && \"DemandedElt width should equal the fixed vector number of elements\""
, "llvm/lib/Analysis/ValueTracking.cpp", 3093, __extension__ __PRETTY_FUNCTION__
))
3093 "DemandedElt width should equal the fixed vector number of elements")(static_cast <bool> (FVTy->getNumElements() == DemandedElts
.getBitWidth() && "DemandedElt width should equal the fixed vector number of elements"
) ? void (0) : __assert_fail ("FVTy->getNumElements() == DemandedElts.getBitWidth() && \"DemandedElt width should equal the fixed vector number of elements\""
, "llvm/lib/Analysis/ValueTracking.cpp", 3093, __extension__ __PRETTY_FUNCTION__
))
;
3094 } else {
3095 assert(DemandedElts == APInt(1, 1) &&(static_cast <bool> (DemandedElts == APInt(1, 1) &&
"DemandedElt width should be 1 for scalars") ? void (0) : __assert_fail
("DemandedElts == APInt(1, 1) && \"DemandedElt width should be 1 for scalars\""
, "llvm/lib/Analysis/ValueTracking.cpp", 3096, __extension__ __PRETTY_FUNCTION__
))
3096 "DemandedElt width should be 1 for scalars")(static_cast <bool> (DemandedElts == APInt(1, 1) &&
"DemandedElt width should be 1 for scalars") ? void (0) : __assert_fail
("DemandedElts == APInt(1, 1) && \"DemandedElt width should be 1 for scalars\""
, "llvm/lib/Analysis/ValueTracking.cpp", 3096, __extension__ __PRETTY_FUNCTION__
))
;
3097 }
3098#endif
3099
3100 // We return the minimum number of sign bits that are guaranteed to be present
3101 // in V, so for undef we have to conservatively return 1. We don't have the
3102 // same behavior for poison though -- that's a FIXME today.
3103
3104 Type *ScalarTy = Ty->getScalarType();
3105 unsigned TyBits = ScalarTy->isPointerTy() ?
3106 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
3107 Q.DL.getTypeSizeInBits(ScalarTy);
3108
3109 unsigned Tmp, Tmp2;
3110 unsigned FirstAnswer = 1;
3111
3112 // Note that ConstantInt is handled by the general computeKnownBits case
3113 // below.
3114
3115 if (Depth == MaxAnalysisRecursionDepth)
3116 return 1;
3117
3118 if (auto *U = dyn_cast<Operator>(V)) {
3119 switch (Operator::getOpcode(V)) {
3120 default: break;
3121 case Instruction::SExt:
3122 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
3123 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q) + Tmp;
3124
3125 case Instruction::SDiv: {
3126 const APInt *Denominator;
3127 // sdiv X, C -> adds log(C) sign bits.
3128 if (match(U->getOperand(1), m_APInt(Denominator))) {
3129
3130 // Ignore non-positive denominator.
3131 if (!Denominator->isStrictlyPositive())
3132 break;
3133
3134 // Calculate the incoming numerator bits.
3135 unsigned NumBits = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3136
3137 // Add floor(log(C)) bits to the numerator bits.
3138 return std::min(TyBits, NumBits + Denominator->logBase2());
3139 }
3140 break;
3141 }
3142
3143 case Instruction::SRem: {
3144 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3145
3146 const APInt *Denominator;
3147 // srem X, C -> we know that the result is within [-C+1,C) when C is a
3148 // positive constant. This let us put a lower bound on the number of sign
3149 // bits.
3150 if (match(U->getOperand(1), m_APInt(Denominator))) {
3151
3152 // Ignore non-positive denominator.
3153 if (Denominator->isStrictlyPositive()) {
3154 // Calculate the leading sign bit constraints by examining the
3155 // denominator. Given that the denominator is positive, there are two
3156 // cases:
3157 //
3158 // 1. The numerator is positive. The result range is [0,C) and
3159 // [0,C) u< (1 << ceilLogBase2(C)).
3160 //
3161 // 2. The numerator is negative. Then the result range is (-C,0] and
3162 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
3163 //
3164 // Thus a lower bound on the number of sign bits is `TyBits -
3165 // ceilLogBase2(C)`.
3166
3167 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
3168 Tmp = std::max(Tmp, ResBits);
3169 }
3170 }
3171 return Tmp;
3172 }
3173
3174 case Instruction::AShr: {
3175 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3176 // ashr X, C -> adds C sign bits. Vectors too.
3177 const APInt *ShAmt;
3178 if (match(U->getOperand(1), m_APInt(ShAmt))) {
3179 if (ShAmt->uge(TyBits))
3180 break; // Bad shift.
3181 unsigned ShAmtLimited = ShAmt->getZExtValue();
3182 Tmp += ShAmtLimited;
3183 if (Tmp > TyBits) Tmp = TyBits;
3184 }
3185 return Tmp;
3186 }
3187 case Instruction::Shl: {
3188 const APInt *ShAmt;
3189 if (match(U->getOperand(1), m_APInt(ShAmt))) {
3190 // shl destroys sign bits.
3191 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3192 if (ShAmt->uge(TyBits) || // Bad shift.
3193 ShAmt->uge(Tmp)) break; // Shifted all sign bits out.
3194 Tmp2 = ShAmt->getZExtValue();
3195 return Tmp - Tmp2;
3196 }
3197 break;
3198 }
3199 case Instruction::And:
3200 case Instruction::Or:
3201 case Instruction::Xor: // NOT is handled here.
3202 // Logical binary ops preserve the number of sign bits at the worst.
3203 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3204 if (Tmp != 1) {
3205 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
3206 FirstAnswer = std::min(Tmp, Tmp2);
3207 // We computed what we know about the sign bits as our first
3208 // answer. Now proceed to the generic code that uses
3209 // computeKnownBits, and pick whichever answer is better.
3210 }
3211 break;
3212
3213 case Instruction::Select: {
3214 // If we have a clamp pattern, we know that the number of sign bits will
3215 // be the minimum of the clamp min/max range.
3216 const Value *X;
3217 const APInt *CLow, *CHigh;
3218 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
3219 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
3220
3221 Tmp = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
3222 if (Tmp == 1) break;
3223 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth + 1, Q);
3224 return std::min(Tmp, Tmp2);
3225 }
3226
3227 case Instruction::Add:
3228 // Add can have at most one carry bit. Thus we know that the output
3229 // is, at worst, one more bit than the inputs.
3230 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3231 if (Tmp == 1) break;
3232
3233 // Special case decrementing a value (ADD X, -1):
3234 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
3235 if (CRHS->isAllOnesValue()) {
3236 KnownBits Known(TyBits);
3237 computeKnownBits(U->getOperand(0), Known, Depth + 1, Q);
3238
3239 // If the input is known to be 0 or 1, the output is 0/-1, which is
3240 // all sign bits set.
3241 if ((Known.Zero | 1).isAllOnes())
3242 return TyBits;
3243
3244 // If we are subtracting one from a positive number, there is no carry
3245 // out of the result.
3246 if (Known.isNonNegative())
3247 return Tmp;
3248 }
3249
3250 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
3251 if (Tmp2 == 1) break;
3252 return std::min(Tmp, Tmp2) - 1;
3253
3254 case Instruction::Sub:
3255 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
3256 if (Tmp2 == 1) break;
3257
3258 // Handle NEG.
3259 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
3260 if (CLHS->isNullValue()) {
3261 KnownBits Known(TyBits);
3262 computeKnownBits(U->getOperand(1), Known, Depth + 1, Q);
3263 // If the input is known to be 0 or 1, the output is 0/-1, which is
3264 // all sign bits set.
3265 if ((Known.Zero | 1).isAllOnes())
3266 return TyBits;
3267
3268 // If the input is known to be positive (the sign bit is known clear),
3269 // the output of the NEG has the same number of sign bits as the
3270 // input.
3271 if (Known.isNonNegative())
3272 return Tmp2;
3273
3274 // Otherwise, we treat this like a SUB.
3275 }
3276
3277 // Sub can have at most one carry bit. Thus we know that the output
3278 // is, at worst, one more bit than the inputs.
3279 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3280 if (Tmp == 1) break;
3281 return std::min(Tmp, Tmp2) - 1;
3282
3283 case Instruction::Mul: {
3284 // The output of the Mul can be at most twice the valid bits in the
3285 // inputs.
3286 unsigned SignBitsOp0 = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3287 if (SignBitsOp0 == 1) break;
3288 unsigned SignBitsOp1 = ComputeNumSignBits(U->getOperand(1), Depth + 1, Q);
3289 if (SignBitsOp1 == 1) break;
3290 unsigned OutValidBits =
3291 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
3292 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
3293 }
3294
3295 case Instruction::PHI: {
3296 const PHINode *PN = cast<PHINode>(U);
3297 unsigned NumIncomingValues = PN->getNumIncomingValues();
3298 // Don't analyze large in-degree PHIs.
3299 if (NumIncomingValues > 4) break;
3300 // Unreachable blocks may have zero-operand PHI nodes.
3301 if (NumIncomingValues == 0) break;
3302
3303 // Take the minimum of all incoming values. This can't infinitely loop
3304 // because of our depth threshold.
3305 Query RecQ = Q;
3306 Tmp = TyBits;
3307 for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
3308 if (Tmp == 1) return Tmp;
3309 RecQ.CxtI = PN->getIncomingBlock(i)->getTerminator();
3310 Tmp = std::min(
3311 Tmp, ComputeNumSignBits(PN->getIncomingValue(i), Depth + 1, RecQ));
3312 }
3313 return Tmp;
3314 }
3315
3316 case Instruction::Trunc:
3317 // FIXME: it's tricky to do anything useful for this, but it is an
3318 // important case for targets like X86.
3319 break;
3320
3321 case Instruction::ExtractElement:
3322 // Look through extract element. At the moment we keep this simple and
3323 // skip tracking the specific element. But at least we might find
3324 // information valid for all elements of the vector (for example if vector
3325 // is sign extended, shifted, etc).
3326 return ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3327
3328 case Instruction::ShuffleVector: {
3329 // Collect the minimum number of sign bits that are shared by every vector
3330 // element referenced by the shuffle.
3331 auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
3332 if (!Shuf) {
3333 // FIXME: Add support for shufflevector constant expressions.
3334 return 1;
3335 }
3336 APInt DemandedLHS, DemandedRHS;
3337 // For undef elements, we don't know anything about the common state of
3338 // the shuffle result.
3339 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
3340 return 1;
3341 Tmp = std::numeric_limits<unsigned>::max();
3342 if (!!DemandedLHS) {
3343 const Value *LHS = Shuf->getOperand(0);
3344 Tmp = ComputeNumSignBits(LHS, DemandedLHS, Depth + 1, Q);
3345 }
3346 // If we don't know anything, early out and try computeKnownBits
3347 // fall-back.
3348 if (Tmp == 1)
3349 break;
3350 if (!!DemandedRHS) {
3351 const Value *RHS = Shuf->getOperand(1);
3352 Tmp2 = ComputeNumSignBits(RHS, DemandedRHS, Depth + 1, Q);
3353 Tmp = std::min(Tmp, Tmp2);
3354 }
3355 // If we don't know anything, early out and try computeKnownBits
3356 // fall-back.
3357 if (Tmp == 1)
3358 break;
3359 assert(Tmp <= TyBits && "Failed to determine minimum sign bits")(static_cast <bool> (Tmp <= TyBits && "Failed to determine minimum sign bits"
) ? void (0) : __assert_fail ("Tmp <= TyBits && \"Failed to determine minimum sign bits\""
, "llvm/lib/Analysis/ValueTracking.cpp", 3359, __extension__ __PRETTY_FUNCTION__
))
;
3360 return Tmp;
3361 }
3362 case Instruction::Call: {
3363 if (const auto *II = dyn_cast<IntrinsicInst>(U)) {
3364 switch (II->getIntrinsicID()) {
3365 default: break;
3366 case Intrinsic::abs:
3367 Tmp = ComputeNumSignBits(U->getOperand(0), Depth + 1, Q);
3368 if (Tmp == 1) break;
3369
3370 // Absolute value reduces number of sign bits by at most 1.
3371 return Tmp - 1;
3372 case Intrinsic::smin:
3373 case Intrinsic::smax: {
3374 const APInt *CLow, *CHigh;
3375 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
3376 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
3377 }
3378 }
3379 }
3380 }
3381 }
3382 }
3383
3384 // Finally, if we can prove that the top bits of the result are 0's or 1's,
3385 // use this information.
3386
3387 // If we can examine all elements of a vector constant successfully, we're
3388 // done (we can't do any better than that). If not, keep trying.
3389 if (unsigned VecSignBits =
3390 computeNumSignBitsVectorConstant(V, DemandedElts, TyBits))
3391 return VecSignBits;
3392
3393 KnownBits Known(TyBits);
3394 computeKnownBits(V, DemandedElts, Known, Depth, Q);
3395
3396 // If we know that the sign bit is either zero or one, determine the number of
3397 // identical bits in the top of the input value.
3398 return std::max(FirstAnswer, Known.countMinSignBits());
3399}
3400
3401Intrinsic::ID llvm::getIntrinsicForCallSite(const CallBase &CB,
3402 const TargetLibraryInfo *TLI) {
3403 const Function *F = CB.getCalledFunction();
3404 if (!F)
3405 return Intrinsic::not_intrinsic;
3406
3407 if (F->isIntrinsic())
3408 return F->getIntrinsicID();
3409
3410 // We are going to infer semantics of a library function based on mapping it
3411 // to an LLVM intrinsic. Check that the library function is available from
3412 // this callbase and in this environment.
3413 LibFunc Func;
3414 if (F->hasLocalLinkage() || !TLI || !TLI->getLibFunc(CB, Func) ||
3415 !CB.onlyReadsMemory())
3416 return Intrinsic::not_intrinsic;
3417
3418 switch (Func) {
3419 default:
3420 break;
3421 case LibFunc_sin:
3422 case LibFunc_sinf:
3423 case LibFunc_sinl:
3424 return Intrinsic::sin;
3425 case LibFunc_cos:
3426 case LibFunc_cosf:
3427 case LibFunc_cosl:
3428 return Intrinsic::cos;
3429 case LibFunc_exp:
3430 case LibFunc_expf:
3431 case LibFunc_expl:
3432 return Intrinsic::exp;
3433 case LibFunc_exp2:
3434 case LibFunc_exp2f:
3435 case LibFunc_exp2l:
3436 return Intrinsic::exp2;
3437 case LibFunc_log:
3438 case LibFunc_logf:
3439 case LibFunc_logl:
3440 return Intrinsic::log;
3441 case LibFunc_log10:
3442 case LibFunc_log10f:
3443 case LibFunc_log10l:
3444 return Intrinsic::log10;
3445 case LibFunc_log2:
3446 case LibFunc_log2f:
3447 case LibFunc_log2l:
3448 return Intrinsic::log2;
3449 case LibFunc_fabs:
3450 case LibFunc_fabsf:
3451 case LibFunc_fabsl:
3452 return Intrinsic::fabs;
3453 case LibFunc_fmin:
3454 case LibFunc_fminf:
3455 case LibFunc_fminl:
3456 return Intrinsic::minnum;
3457 case LibFunc_fmax:
3458 case LibFunc_fmaxf:
3459 case LibFunc_fmaxl:
3460 return Intrinsic::maxnum;
3461 case LibFunc_copysign:
3462 case LibFunc_copysignf:
3463 case LibFunc_copysignl:
3464 return Intrinsic::copysign;
3465 case LibFunc_floor:
3466 case LibFunc_floorf:
3467 case LibFunc_floorl:
3468 return Intrinsic::floor;
3469 case LibFunc_ceil:
3470 case LibFunc_ceilf:
3471 case LibFunc_ceill:
3472 return Intrinsic::ceil;
3473 case LibFunc_trunc:
3474 case LibFunc_truncf:
3475 case LibFunc_truncl:
3476 return Intrinsic::trunc;
3477 case LibFunc_rint:
3478 case LibFunc_rintf:
3479 case LibFunc_rintl:
3480 return Intrinsic::rint;
3481 case LibFunc_nearbyint:
3482 case LibFunc_nearbyintf:
3483 case LibFunc_nearbyintl:
3484 return Intrinsic::nearbyint;
3485 case LibFunc_round:
3486 case LibFunc_roundf:
3487 case LibFunc_roundl:
3488 return Intrinsic::round;
3489 case LibFunc_roundeven:
3490 case LibFunc_roundevenf:
3491 case LibFunc_roundevenl:
3492 return Intrinsic::roundeven;
3493 case LibFunc_pow:
3494 case LibFunc_powf:
3495 case LibFunc_powl:
3496 return Intrinsic::pow;
3497 case LibFunc_sqrt:
3498 case LibFunc_sqrtf:
3499 case LibFunc_sqrtl:
3500 return Intrinsic::sqrt;
3501 }
3502
3503 return Intrinsic::not_intrinsic;
3504}
3505
3506/// Return true if we can prove that the specified FP value is never equal to
3507/// -0.0.
3508/// NOTE: Do not check 'nsz' here because that fast-math-flag does not guarantee
3509/// that a value is not -0.0. It only guarantees that -0.0 may be treated
3510/// the same as +0.0 in floating-point ops.
3511bool llvm::CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
3512 unsigned Depth) {
3513 if (auto *CFP = dyn_cast<ConstantFP>(V))
3514 return !CFP->getValueAPF().isNegZero();
3515
3516 if (Depth == MaxAnalysisRecursionDepth)
3517 return false;
3518
3519 auto *Op = dyn_cast<Operator>(V);
3520 if (!Op)
3521 return false;
3522
3523 // (fadd x, 0.0) is guaranteed to return +0.0, not -0.0.
3524 if (match(Op, m_FAdd(m_Value(), m_PosZeroFP())))
3525 return true;
3526
3527 // sitofp and uitofp turn into +0.0 for zero.
3528 if (isa<SIToFPInst>(Op) || isa<UIToFPInst>(Op))
3529 return true;
3530
3531 if (auto *Call = dyn_cast<CallInst>(Op)) {
3532 Intrinsic::ID IID = getIntrinsicForCallSite(*Call, TLI);
3533 switch (IID) {
3534 default:
3535 break;
3536 // sqrt(-0.0) = -0.0, no other negative results are possible.
3537 case Intrinsic::sqrt:
3538 case Intrinsic::canonicalize:
3539 return CannotBeNegativeZero(Call->getArgOperand(0), TLI, Depth + 1);
3540 case Intrinsic::experimental_constrained_sqrt: {
3541 // NOTE: This rounding mode restriction may be too strict.
3542 const auto *CI = cast<ConstrainedFPIntrinsic>(Call);
3543 if (CI->getRoundingMode() == RoundingMode::NearestTiesToEven)
3544 return CannotBeNegativeZero(Call->getArgOperand(0), TLI, Depth + 1);
3545 else
3546 return false;
3547 }
3548 // fabs(x) != -0.0
3549 case Intrinsic::fabs:
3550 return true;
3551 // sitofp and uitofp turn into +0.0 for zero.
3552 case Intrinsic::experimental_constrained_sitofp:
3553 case Intrinsic::experimental_constrained_uitofp:
3554 return true;
3555 }
3556 }
3557
3558 return false;
3559}
3560
3561/// If \p SignBitOnly is true, test for a known 0 sign bit rather than a
3562/// standard ordered compare. e.g. make -0.0 olt 0.0 be true because of the sign
3563/// bit despite comparing equal.
3564static bool cannotBeOrderedLessThanZeroImpl(const Value *V,
3565 const TargetLibraryInfo *TLI,
3566 bool SignBitOnly,
3567 unsigned Depth) {
3568 // TODO: This function does not do the right thing when SignBitOnly is true
3569 // and we're lowering to a hypothetical IEEE 754-compliant-but-evil platform
3570 // which flips the sign bits of NaNs. See
3571 // https://llvm.org/bugs/show_bug.cgi?id=31702.
3572
3573 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
3574 return !CFP->getValueAPF().isNegative() ||
3575 (!SignBitOnly && CFP->getValueAPF().isZero());
3576 }
3577
3578 // Handle vector of constants.
3579 if (auto *CV = dyn_cast<Constant>(V)) {
3580 if (auto *CVFVTy = dyn_cast<FixedVectorType>(CV->getType())) {
3581 unsigned NumElts = CVFVTy->getNumElements();
3582 for (unsigned i = 0; i != NumElts; ++i) {
3583 auto *CFP = dyn_cast_or_null<ConstantFP>(CV->getAggregateElement(i));
3584 if (!CFP)
3585 return false;
3586 if (CFP->getValueAPF().isNegative() &&
3587 (SignBitOnly || !CFP->getValueAPF().isZero()))
3588 return false;
3589 }
3590
3591 // All non-negative ConstantFPs.
3592 return true;
3593 }
3594 }
3595
3596 if (Depth == MaxAnalysisRecursionDepth)
3597 return false;
3598
3599 const Operator *I = dyn_cast<Operator>(V);
3600 if (!I)
3601 return false;
3602
3603 switch (I->getOpcode()) {
3604 default:
3605 break;
3606 // Unsigned integers are always nonnegative.
3607 case Instruction::UIToFP:
3608 return true;
3609 case Instruction::FDiv:
3610 // X / X is always exactly 1.0 or a NaN.
3611 if (I->getOperand(0) == I->getOperand(1) &&
3612 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
3613 return true;
3614
3615 // Set SignBitOnly for RHS, because X / -0.0 is -Inf (or NaN).
3616 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3617 Depth + 1) &&
3618 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI,
3619 /*SignBitOnly*/ true, Depth + 1);
3620 case Instruction::FMul:
3621 // X * X is always non-negative or a NaN.
3622 if (I->getOperand(0) == I->getOperand(1) &&
3623 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()))
3624 return true;
3625
3626 [[fallthrough]];
3627 case Instruction::FAdd:
3628 case Instruction::FRem:
3629 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3630 Depth + 1) &&
3631 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
3632 Depth + 1);
3633 case Instruction::Select:
3634 return cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
3635 Depth + 1) &&
3636 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
3637 Depth + 1);
3638 case Instruction::FPExt:
3639 case Instruction::FPTrunc:
3640 // Widening/narrowing never change sign.
3641 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3642 Depth + 1);
3643 case Instruction::ExtractElement:
3644 // Look through extract element. At the moment we keep this simple and skip
3645 // tracking the specific element. But at least we might find information
3646 // valid for all elements of the vector.
3647 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3648 Depth + 1);
3649 case Instruction::Call:
3650 const auto *CI = cast<CallInst>(I);
3651 Intrinsic::ID IID = getIntrinsicForCallSite(*CI, TLI);
3652 switch (IID) {
3653 default:
3654 break;
3655 case Intrinsic::maxnum: {
3656 Value *V0 = I->getOperand(0), *V1 = I->getOperand(1);
3657 auto isPositiveNum = [&](Value *V) {
3658 if (SignBitOnly) {
3659 // With SignBitOnly, this is tricky because the result of
3660 // maxnum(+0.0, -0.0) is unspecified. Just check if the operand is
3661 // a constant strictly greater than 0.0.
3662 const APFloat *C;
3663 return match(V, m_APFloat(C)) &&
3664 *C > APFloat::getZero(C->getSemantics());
3665 }
3666
3667 // -0.0 compares equal to 0.0, so if this operand is at least -0.0,
3668 // maxnum can't be ordered-less-than-zero.
3669 return isKnownNeverNaN(V, TLI) &&
3670 cannotBeOrderedLessThanZeroImpl(V, TLI, false, Depth + 1);
3671 };
3672
3673 // TODO: This could be improved. We could also check that neither operand
3674 // has its sign bit set (and at least 1 is not-NAN?).
3675 return isPositiveNum(V0) || isPositiveNum(V1);
3676 }
3677
3678 case Intrinsic::maximum:
3679 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3680 Depth + 1) ||
3681 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
3682 Depth + 1);
3683 case Intrinsic::minnum:
3684 case Intrinsic::minimum:
3685 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3686 Depth + 1) &&
3687 cannotBeOrderedLessThanZeroImpl(I->getOperand(1), TLI, SignBitOnly,
3688 Depth + 1);
3689 case Intrinsic::exp:
3690 case Intrinsic::exp2:
3691 case Intrinsic::fabs:
3692 return true;
3693
3694 case Intrinsic::sqrt:
3695 // sqrt(x) is always >= -0 or NaN. Moreover, sqrt(x) == -0 iff x == -0.
3696 if (!SignBitOnly)
3697 return true;
3698 return CI->hasNoNaNs() && (CI->hasNoSignedZeros() ||
3699 CannotBeNegativeZero(CI->getOperand(0), TLI));
3700
3701 case Intrinsic::powi:
3702 if (ConstantInt *Exponent = dyn_cast<ConstantInt>(I->getOperand(1))) {
3703 // powi(x,n) is non-negative if n is even.
3704 if (Exponent->getBitWidth() <= 64 && Exponent->getSExtValue() % 2u == 0)
3705 return true;
3706 }
3707 // TODO: This is not correct. Given that exp is an integer, here are the
3708 // ways that pow can return a negative value:
3709 //
3710 // pow(x, exp) --> negative if exp is odd and x is negative.
3711 // pow(-0, exp) --> -inf if exp is negative odd.
3712 // pow(-0, exp) --> -0 if exp is positive odd.
3713 // pow(-inf, exp) --> -0 if exp is negative odd.
3714 // pow(-inf, exp) --> -inf if exp is positive odd.
3715 //
3716 // Therefore, if !SignBitOnly, we can return true if x >= +0 or x is NaN,
3717 // but we must return false if x == -0. Unfortunately we do not currently
3718 // have a way of expressing this constraint. See details in
3719 // https://llvm.org/bugs/show_bug.cgi?id=31702.
3720 return cannotBeOrderedLessThanZeroImpl(I->getOperand(0), TLI, SignBitOnly,
3721 Depth + 1);
3722
3723 case Intrinsic::fma:
3724 case Intrinsic::fmuladd:
3725 // x*x+y is non-negative if y is non-negative.
3726 return I->getOperand(0) == I->getOperand(1) &&
3727 (!SignBitOnly || cast<FPMathOperator>(I)->hasNoNaNs()) &&
3728 cannotBeOrderedLessThanZeroImpl(I->getOperand(2), TLI, SignBitOnly,
3729 Depth + 1);
3730 }
3731 break;
3732 }
3733 return false;
3734}
3735
3736bool llvm::CannotBeOrderedLessThanZero(const Value *V,
3737 const TargetLibraryInfo *TLI) {
3738 return cannotBeOrderedLessThanZeroImpl(V, TLI, false, 0);
3739}
3740
3741bool llvm::SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI) {
3742 return cannotBeOrderedLessThanZeroImpl(V, TLI, true, 0);
3743}
3744
3745bool llvm::isKnownNeverInfinity(const Value *V, const TargetLibraryInfo *TLI,
3746 unsigned Depth) {
3747 assert(V->getType()->isFPOrFPVectorTy() && "Querying for Inf on non-FP type")(static_cast <bool> (V->getType()->isFPOrFPVectorTy
() && "Querying for Inf on non-FP type") ? void (0) :
__assert_fail ("V->getType()->isFPOrFPVectorTy() && \"Querying for Inf on non-FP type\""
, "llvm/lib/Analysis/ValueTracking.cpp", 3747, __extension__ __PRETTY_FUNCTION__
))
;
3748
3749 // If we're told that infinities won't happen, assume they won't.
3750 if (auto *FPMathOp = dyn_cast<FPMathOperator>(V))
3751 if (FPMathOp->hasNoInfs())
3752 return true;
3753
3754 // Handle scalar constants.
3755 if (auto *CFP = dyn_cast<ConstantFP>(V))
3756 return !CFP->isInfinity();
3757
3758 if (Depth == MaxAnalysisRecursionDepth)
3759 return false;
3760
3761 if (auto *Inst = dyn_cast<Instruction>(V)) {
3762 switch (Inst->getOpcode()) {
3763 case Instruction::Select: {
3764 return isKnownNeverInfinity(Inst->getOperand(1), TLI, Depth + 1) &&
3765 isKnownNeverInfinity(Inst->getOperand(2), TLI, Depth + 1);
3766 }
3767 case Instruction::SIToFP:
3768 case Instruction::UIToFP: {
3769 // Get width of largest magnitude integer (remove a bit if signed).
3770 // This still works for a signed minimum value because the largest FP
3771 // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx).
3772 int IntSize = Inst->getOperand(0)->getType()->getScalarSizeInBits();
3773 if (Inst->getOpcode() == Instruction::SIToFP)
3774 --IntSize;
3775
3776 // If the exponent of the largest finite FP value can hold the largest
3777 // integer, the result of the cast must be finite.
3778 Type *FPTy = Inst->getType()->getScalarType();
3779 return ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize;
3780 }
3781 case Instruction::FPExt: {
3782 // Peek through to source op. If it is not infinity, this is not infinity.
3783 return isKnownNeverInfinity(Inst->getOperand(0), TLI, Depth + 1);
3784 }
3785 default:
3786 break;
3787 }
3788 }
3789
3790 // try to handle fixed width vector constants
3791 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
3792 if (VFVTy && isa<Constant>(V)) {
3793 // For vectors, verify that each element is not infinity.
3794 unsigned NumElts = VFVTy->getNumElements();
3795 for (unsigned i = 0; i != NumElts; ++i) {
3796 Constant *Elt = cast<Constant>(V)->getAggregateElement(i);
3797 if (!Elt)
3798 return false;
3799 if (isa<UndefValue>(Elt))
3800 continue;
3801 auto *CElt = dyn_cast<ConstantFP>(Elt);
3802 if (!CElt || CElt->isInfinity())
3803 return false;
3804 }
3805 // All elements were confirmed non-infinity or undefined.
3806 return true;
3807 }
3808
3809 // was not able to prove that V never contains infinity
3810 return false;
3811}
3812
3813bool llvm::isKnownNeverNaN(const Value *V, const TargetLibraryInfo *TLI,
3814 unsigned Depth) {
3815 assert(V->getType()->isFPOrFPVectorTy() && "Querying for NaN on non-FP type")(static_cast <bool> (V->getType()->isFPOrFPVectorTy
() && "Querying for NaN on non-FP type") ? void (0) :
__assert_fail ("V->getType()->isFPOrFPVectorTy() && \"Querying for NaN on non-FP type\""
, "llvm/lib/Analysis/ValueTracking.cpp", 3815, __extension__ __PRETTY_FUNCTION__
))
;
3816
3817 // If we're told that NaNs won't happen, assume they won't.
3818 if (auto *FPMathOp = dyn_cast<FPMathOperator>(V))
3819 if (FPMathOp->hasNoNaNs())
3820 return true;
3821
3822 // Handle scalar constants.
3823 if (auto *CFP = dyn_cast<ConstantFP>(V))
3824 return !CFP->isNaN();
3825
3826 if (Depth == MaxAnalysisRecursionDepth)
3827 return false;
3828
3829 if (auto *Inst = dyn_cast<Instruction>(V)) {
3830 switch (Inst->getOpcode()) {
3831 case Instruction::FAdd:
3832 case Instruction::FSub:
3833 // Adding positive and negative infinity produces NaN.
3834 return isKnownNeverNaN(Inst->getOperand(0), TLI, Depth + 1) &&
3835 isKnownNeverNaN(Inst->getOperand(1), TLI, Depth + 1) &&
3836 (isKnownNeverInfinity(Inst->getOperand(0), TLI, Depth + 1) ||
3837 isKnownNeverInfinity(Inst->getOperand(1), TLI, Depth + 1));
3838
3839 case Instruction::FMul:
3840 // Zero multiplied with infinity produces NaN.
3841 // FIXME: If neither side can be zero fmul never produces NaN.
3842 return isKnownNeverNaN(Inst->getOperand(0), TLI, Depth + 1) &&
3843 isKnownNeverInfinity(Inst->getOperand(0), TLI, Depth + 1) &&
3844 isKnownNeverNaN(Inst->getOperand(1), TLI, Depth + 1) &&
3845 isKnownNeverInfinity(Inst->getOperand(1), TLI, Depth + 1);
3846
3847 case Instruction::FDiv:
3848 case Instruction::FRem:
3849 // FIXME: Only 0/0, Inf/Inf, Inf REM x and x REM 0 produce NaN.
3850 return false;
3851
3852 case Instruction::Select: {
3853 return isKnownNeverNaN(Inst->getOperand(1), TLI, Depth + 1) &&
3854 isKnownNeverNaN(Inst->getOperand(2), TLI, Depth + 1);
3855 }
3856 case Instruction::SIToFP:
3857 case Instruction::UIToFP:
3858 return true;
3859 case Instruction::FPTrunc:
3860 case Instruction::FPExt:
3861 return isKnownNeverNaN(Inst->getOperand(0), TLI, Depth + 1);
3862 default:
3863 break;
3864 }
3865 }
3866
3867 if (const auto *II = dyn_cast<IntrinsicInst>(V)) {
3868 switch (II->getIntrinsicID()) {
3869 case Intrinsic::canonicalize:
3870 case Intrinsic::fabs:
3871 case Intrinsic::copysign:
3872 case Intrinsic::exp:
3873 case Intrinsic::exp2:
3874 case Intrinsic::floor:
3875 case Intrinsic::ceil:
3876 case Intrinsic::trunc:
3877 case Intrinsic::rint:
3878 case Intrinsic::nearbyint:
3879 case Intrinsic::round:
3880 case Intrinsic::roundeven:
3881 return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1);
3882 case Intrinsic::sqrt:
3883 return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1) &&
3884 CannotBeOrderedLessThanZero(II->getArgOperand(0), TLI);
3885 case Intrinsic::minnum:
3886 case Intrinsic::maxnum:
3887 // If either operand is not NaN, the result is not NaN.
3888 return isKnownNeverNaN(II->getArgOperand(0), TLI, Depth + 1) ||
3889 isKnownNeverNaN(II->getArgOperand(1), TLI, Depth + 1);
3890 default:
3891 return false;
3892 }
3893 }
3894
3895 // Try to handle fixed width vector constants
3896 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
3897 if (VFVTy && isa<Constant>(V)) {
3898 // For vectors, verify that each element is not NaN.
3899 unsigned NumElts = VFVTy->getNumElements();
3900 for (unsigned i = 0; i != NumElts; ++i) {
3901 Constant *Elt = cast<Constant>(V)->getAggregateElement(i);
3902 if (!Elt)
3903 return false;
3904 if (isa<UndefValue>(Elt))
3905 continue;
3906 auto *CElt = dyn_cast<ConstantFP>(Elt);
3907 if (!CElt || CElt->isNaN())
3908 return false;
3909 }
3910 // All elements were confirmed not-NaN or undefined.
3911 return true;
3912 }
3913
3914 // Was not able to prove that V never contains NaN
3915 return false;
3916}
3917
3918Value *llvm::isBytewiseValue(Value *V, const DataLayout &DL) {
3919
3920 // All byte-wide stores are splatable, even of arbitrary variables.
3921 if (V->getType()->isIntegerTy(8))
3922 return V;
3923
3924 LLVMContext &Ctx = V->getContext();
3925
3926 // Undef don't care.
3927 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
3928 if (isa<UndefValue>(V))
3929 return UndefInt8;
3930
3931 // Return Undef for zero-sized type.
3932 if (!DL.getTypeStoreSize(V->getType()).isNonZero())
3933 return UndefInt8;
3934
3935 Constant *C = dyn_cast<Constant>(V);
3936 if (!C) {
3937 // Conceptually, we could handle things like:
3938 // %a = zext i8 %X to i16
3939 // %b = shl i16 %a, 8
3940 // %c = or i16 %a, %b
3941 // but until there is an example that actually needs this, it doesn't seem
3942 // worth worrying about.
3943 return nullptr;
3944 }
3945
3946 // Handle 'null' ConstantArrayZero etc.
3947 if (C->isNullValue())
3948 return Constant::getNullValue(Type::getInt8Ty(Ctx));
3949
3950 // Constant floating-point values can be handled as integer values if the
3951 // corresponding integer value is "byteable". An important case is 0.0.
3952 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3953 Type *Ty = nullptr;
3954 if (CFP->getType()->isHalfTy())
3955 Ty = Type::getInt16Ty(Ctx);
3956 else if (CFP->getType()->isFloatTy())
3957 Ty = Type::getInt32Ty(Ctx);
3958 else if (CFP->getType()->isDoubleTy())
3959 Ty = Type::getInt64Ty(Ctx);
3960 // Don't handle long double formats, which have strange constraints.
3961 return Ty ? isBytewiseValue(ConstantExpr::getBitCast(CFP, Ty), DL)
3962 : nullptr;
3963 }
3964
3965 // We can handle constant integers that are multiple of 8 bits.
3966 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
3967 if (CI->getBitWidth() % 8 == 0) {
3968 assert(CI->getBitWidth() > 8 && "8 bits should be handled above!")(static_cast <bool> (CI->getBitWidth() > 8 &&
"8 bits should be handled above!") ? void (0) : __assert_fail
("CI->getBitWidth() > 8 && \"8 bits should be handled above!\""
, "llvm/lib/Analysis/ValueTracking.cpp", 3968, __extension__ __PRETTY_FUNCTION__
))
;
3969 if (!CI->getValue().isSplat(8))
3970 return nullptr;
3971 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
3972 }
3973 }
3974
3975 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
3976 if (CE->getOpcode() == Instruction::IntToPtr) {
3977 if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
3978 unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
3979 return isBytewiseValue(
3980 ConstantExpr::getIntegerCast(CE->getOperand(0),
3981 Type::getIntNTy(Ctx, BitWidth), false),
3982 DL);
3983 }
3984 }
3985 }
3986
3987 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
3988 if (LHS == RHS)
3989 return LHS;
3990 if (!LHS || !RHS)
3991 return nullptr;
3992 if (LHS == UndefInt8)
3993 return RHS;
3994 if (RHS == UndefInt8)
3995 return LHS;
3996 return nullptr;
3997 };
3998
3999 if (ConstantDataSequential *CA = dyn_cast<ConstantDataSequential>(C)) {
4000 Value *Val = UndefInt8;
4001 for (unsigned I = 0, E = CA->getNumElements(); I != E; ++I)
4002 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
4003 return nullptr;
4004 return Val;
4005 }
4006
4007 if (isa<ConstantAggregate>(C)) {
4008 Value *Val = UndefInt8;
4009 for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I)
4010 if (!(Val = Merge(Val, isBytewiseValue(C->getOperand(I), DL))))
4011 return nullptr;
4012 return Val;
4013 }
4014
4015 // Don't try to handle the handful of other constants.
4016 return nullptr;
4017}
4018
4019// This is the recursive version of BuildSubAggregate. It takes a few different
4020// arguments. Idxs is the index within the nested struct From that we are
4021// looking at now (which is of type IndexedType). IdxSkip is the number of
4022// indices from Idxs that should be left out when inserting into the resulting
4023// struct. To is the result struct built so far, new insertvalue instructions
4024// build on that.
4025static Value *BuildSubAggregate(Value *From, Value* To, Type *IndexedType,
4026 SmallVectorImpl<unsigned> &Idxs,
4027 unsigned IdxSkip,
4028 Instruction *InsertBefore) {
4029 StructType *STy = dyn_cast<StructType>(IndexedType);
4030 if (STy) {
4031 // Save the original To argument so we can modify it
4032 Value *OrigTo = To;
4033 // General case, the type indexed by Idxs is a struct
4034 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
4035 // Process each struct element recursively
4036 Idxs.push_back(i);
4037 Value *PrevTo = To;
4038 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
4039 InsertBefore);
4040 Idxs.pop_back();
4041 if (!To) {
4042 // Couldn't find any inserted value for this index? Cleanup
4043 while (PrevTo != OrigTo) {
4044 InsertValueInst* Del = cast<InsertValueInst>(PrevTo);
4045 PrevTo = Del->getAggregateOperand();
4046 Del->eraseFromParent();
4047 }
4048 // Stop processing elements
4049 break;
4050 }
4051 }
4052 // If we successfully found a value for each of our subaggregates
4053 if (To)
4054 return To;
4055 }
4056 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
4057 // the struct's elements had a value that was inserted directly. In the latter
4058 // case, perhaps we can't determine each of the subelements individually, but
4059 // we might be able to find the complete struct somewhere.
4060
4061 // Find the value that is at that particular spot
4062 Value *V = FindInsertedValue(From, Idxs);
4063
4064 if (!V)
4065 return nullptr;
4066
4067 // Insert the value in the new (sub) aggregate
4068 return InsertValueInst::Create(To, V, makeArrayRef(Idxs).slice(IdxSkip),
4069 "tmp", InsertBefore);
4070}
4071
4072// This helper takes a nested struct and extracts a part of it (which is again a
4073// struct) into a new value. For example, given the struct:
4074// { a, { b, { c, d }, e } }
4075// and the indices "1, 1" this returns
4076// { c, d }.
4077//
4078// It does this by inserting an insertvalue for each element in the resulting
4079// struct, as opposed to just inserting a single struct. This will only work if
4080// each of the elements of the substruct are known (ie, inserted into From by an
4081// insertvalue instruction somewhere).
4082//
4083// All inserted insertvalue instructions are inserted before InsertBefore
4084static Value *BuildSubAggregate(Value *From, ArrayRef<unsigned> idx_range,
4085 Instruction *InsertBefore) {
4086 assert(InsertBefore && "Must have someplace to insert!")(static_cast <bool> (InsertBefore && "Must have someplace to insert!"
) ? void (0) : __assert_fail ("InsertBefore && \"Must have someplace to insert!\""
, "llvm/lib/Analysis/ValueTracking.cpp", 4086, __extension__ __PRETTY_FUNCTION__
))
;
4087 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
4088 idx_range);
4089 Value *To = UndefValue::get(IndexedType);
4090 SmallVector<unsigned, 10> Idxs(idx_range.begin(), idx_range.end());
4091 unsigned IdxSkip = Idxs.size();
4092
4093 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
4094}
4095
4096/// Given an aggregate and a sequence of indices, see if the scalar value
4097/// indexed is already around as a register, for example if it was inserted
4098/// directly into the aggregate.
4099///
4100/// If InsertBefore is not null, this function will duplicate (modified)
4101/// insertvalues when a part of a nested struct is extracted.
4102Value *llvm::FindInsertedValue(Value *V, ArrayRef<unsigned> idx_range,
4103 Instruction *InsertBefore) {
4104 // Nothing to index? Just return V then (this is useful at the end of our
4105 // recursion).
4106 if (idx_range.empty())
4107 return V;
4108 // We have indices, so V should have an indexable type.
4109 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&(static_cast <bool> ((V->getType()->isStructTy() ||
V->getType()->isArrayTy()) && "Not looking at a struct or array?"
) ? void (0) : __assert_fail ("(V->getType()->isStructTy() || V->getType()->isArrayTy()) && \"Not looking at a struct or array?\""
, "llvm/lib/Analysis/ValueTracking.cpp", 4110, __extension__ __PRETTY_FUNCTION__
))
4110 "Not looking at a struct or array?")(static_cast <bool> ((V->getType()->isStructTy() ||
V->getType()->isArrayTy()) && "Not looking at a struct or array?"
) ? void (0) : __assert_fail ("(V->getType()->isStructTy() || V->getType()->isArrayTy()) && \"Not looking at a struct or array?\""
, "llvm/lib/Analysis/ValueTracking.cpp", 4110, __extension__ __PRETTY_FUNCTION__
))
;
4111 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&(static_cast <bool> (ExtractValueInst::getIndexedType(V
->getType(), idx_range) && "Invalid indices for type?"
) ? void (0) : __assert_fail ("ExtractValueInst::getIndexedType(V->getType(), idx_range) && \"Invalid indices for type?\""
, "llvm/lib/Analysis/ValueTracking.cpp", 4112, __extension__ __PRETTY_FUNCTION__
))
4112 "Invalid indices for type?")(static_cast <bool> (ExtractValueInst::getIndexedType(V
->getType(), idx_range) && "Invalid indices for type?"
) ? void (0) : __assert_fail ("ExtractValueInst::getIndexedType(V->getType(), idx_range) && \"Invalid indices for type?\""
, "llvm/lib/Analysis/ValueTracking.cpp", 4112, __extension__ __PRETTY_FUNCTION__
))
;
4113
4114 if (Constant *C = dyn_cast<Constant>(V)) {
4115 C = C->getAggregateElement(idx_range[0]);
4116 if (!C) return nullptr;
4117 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
4118 }
4119
4120 if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
4121 // Loop the indices for the insertvalue instruction in parallel with the
4122 // requested indices
4123 const unsigned *req_idx = idx_range.begin();
4124 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
4125 i != e; ++i, ++req_idx) {
4126 if (req_idx == idx_range.end()) {
4127 // We can't handle this without inserting insertvalues
4128 if (!InsertBefore)
4129 return nullptr;
4130
4131 // The requested index identifies a part of a nested aggregate. Handle
4132 // this specially. For example,
4133 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
4134 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
4135 // %C = extractvalue {i32, { i32, i32 } } %B, 1
4136 // This can be changed into
4137 // %A = insertvalue {i32, i32 } undef, i32 10, 0
4138 // %C = insertvalue {i32, i32 } %A, i32 11, 1
4139 // which allows the unused 0,0 element from the nested struct to be
4140 // removed.
4141 return BuildSubAggregate(V, makeArrayRef(idx_range.begin(), req_idx),
4142 InsertBefore);
4143 }
4144
4145 // This insert value inserts something else than what we are looking for.
4146 // See if the (aggregate) value inserted into has the value we are
4147 // looking for, then.
4148 if (*req_idx != *i)
4149 return FindInsertedValue(I->getAggregateOperand(), idx_range,
4150 InsertBefore);
4151 }
4152 // If we end up here, the indices of the insertvalue match with those
4153 // requested (though possibly only partially). Now we recursively look at
4154 // the inserted value, passing any remaining indices.
4155 return FindInsertedValue(I->getInsertedValueOperand(),
4156 makeArrayRef(req_idx, idx_range.end()),
4157 InsertBefore);
4158 }
4159
4160 if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
4161 // If we're extracting a value from an aggregate that was extracted from
4162 // something else, we can extract from that something else directly instead.
4163 // However, we will need to chain I's indices with the requested indices.
4164
4165 // Calculate the number of indices required
4166 unsigned size = I->getNumIndices() + idx_range.size();
4167 // Allocate some space to put the new indices in
4168 SmallVector<unsigned, 5> Idxs;
4169 Idxs.reserve(size);
4170 // Add indices from the extract value instruction
4171 Idxs.append(I->idx_begin(), I->idx_end());
4172
4173 // Add requested indices
4174 Idxs.append(idx_range.begin(), idx_range.end());
4175
4176 assert(Idxs.size() == size(static_cast <bool> (Idxs.size() == size && "Number of indices added not correct?"
) ? void (0) : __assert_fail ("Idxs.size() == size && \"Number of indices added not correct?\""
, "llvm/lib/Analysis/ValueTracking.cpp", 4177, __extension__ __PRETTY_FUNCTION__
))
4177 && "Number of indices added not correct?")(static_cast <bool> (Idxs.size() == size && "Number of indices added not correct?"
) ? void (0) : __assert_fail ("Idxs.size() == size && \"Number of indices added not correct?\""
, "llvm/lib/Analysis/ValueTracking.cpp", 4177, __extension__ __PRETTY_FUNCTION__
))
;
4178
4179 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
4180 }
4181 // Otherwise, we don't know (such as, extracting from a function return value
4182 // or load instruction)
4183 return nullptr;
4184}
4185
4186bool llvm::isGEPBasedOnPointerToString(const GEPOperator *GEP,
4187 unsigned CharSize) {
4188 // Make sure the GEP has exactly three arguments.
4189 if (GEP->getNumOperands() != 3)
4190 return false;
4191
4192 // Make sure the index-ee is a pointer to array of \p CharSize integers.
4193 // CharSize.
4194 ArrayType *AT = dyn_cast<ArrayType>(GEP->getSourceElementType());
4195 if (!AT || !AT->getElementType()->isIntegerTy(CharSize))
4196 return false;
4197
4198 // Check to make sure that the first operand of the GEP is an integer and
4199 // has value 0 so that we are sure we're indexing into the initializer.
4200 const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
4201 if (!FirstIdx || !FirstIdx->isZero())
4202 return false;
4203
4204 return true;
4205}
4206
4207// If V refers to an initialized global constant, set Slice either to
4208// its initializer if the size of its elements equals ElementSize, or,
4209// for ElementSize == 8, to its representation as an array of unsiged
4210// char. Return true on success.
4211// Offset is in the unit "nr of ElementSize sized elements".
4212bool llvm::getConstantDataArrayInfo(const Value *V,
4213 ConstantDataArraySlice &Slice,
4214 unsigned ElementSize, uint64_t Offset) {
4215 assert(V && "V should not be null.")(static_cast <bool> (V && "V should not be null."
) ? void (0) : __assert_fail ("V && \"V should not be null.\""
, "llvm/lib/Analysis/ValueTracking.cpp", 4215, __extension__ __PRETTY_FUNCTION__
))
;
4216 assert((ElementSize % 8) == 0 &&(static_cast <bool> ((ElementSize % 8) == 0 && "ElementSize expected to be a multiple of the size of a byte."
) ? void (0) : __assert_fail ("(ElementSize % 8) == 0 && \"ElementSize expected to be a multiple of the size of a byte.\""
, "llvm/lib/Analysis/ValueTracking.cpp", 4217, __extension__ __PRETTY_FUNCTION__
))
4217 "ElementSize expected to be a multiple of the size of a byte.")(static_cast <bool> ((ElementSize % 8) == 0 && "ElementSize expected to be a multiple of the size of a byte."
) ? void (0) : __assert_fail ("(ElementSize % 8) == 0 && \"ElementSize expected to be a multiple of the size of a byte.\""
, "llvm/lib/Analysis/ValueTracking.cpp", 4217, __extension__ __PRETTY_FUNCTION__
))
;
4218 unsigned ElementSizeInBytes = ElementSize / 8;
4219
4220 // Drill down into the pointer expression V, ignoring any intervening
4221 // casts, and determine the identity of the object it references along
4222 // with the cumulative byte offset into it.
4223 const GlobalVariable *GV =
4224 dyn_cast<GlobalVariable>(getUnderlyingObject(V));
4225 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
4226 // Fail if V is not based on constant global object.
4227 return false;
4228
4229 const DataLayout &DL = GV->getParent()->getDataLayout();
4230 APInt Off(DL.getIndexTypeSizeInBits(V->getType()), 0);
4231
4232 if (GV != V->stripAndAccumulateConstantOffsets(DL, Off,
4233 /*AllowNonInbounds*/ true))
4234 // Fail if a constant offset could not be determined.
4235 return false;
4236
4237 uint64_t StartIdx = Off.getLimitedValue();
4238 if (StartIdx == UINT64_MAX(18446744073709551615UL))
4239 // Fail if the constant offset is excessive.
4240 return false;
4241
4242 // Off/StartIdx is in the unit of bytes. So we need to convert to number of
4243 // elements. Simply bail out if that isn't possible.
4244 if ((StartIdx % ElementSizeInBytes) != 0)
4245 return false;
4246
4247 Offset += StartIdx / ElementSizeInBytes;
4248 ConstantDataArray *Array = nullptr;
4249 ArrayType *ArrayTy = nullptr;
4250
4251 if (GV->getInitializer()->isNullValue()) {
4252 Type *GVTy = GV->getValueType();
4253 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedSize();
4254 uint64_t Length = SizeInBytes / ElementSizeInBytes;
4255
4256 Slice.Array = nullptr;
4257 Slice.Offset = 0;
4258 // Return an empty Slice for undersized constants to let callers
4259 // transform even undefined library calls into simpler, well-defined
4260 // expressions. This is preferable to making the calls although it
4261 // prevents sanitizers from detecting such calls.
4262 Slice.Length = Length < Offset ? 0 : Length - Offset;
4263 return true;
4264 }
4265
4266 auto *Init = const_cast<Constant *>(GV->getInitializer());
4267 if (auto *ArrayInit = dyn_cast<ConstantDataArray>(Init)) {
4268 Type *InitElTy = ArrayInit->getElementType();
4269 if (InitElTy->isIntegerTy(ElementSize)) {
4270 // If Init is an initializer for an array of the expected type
4271 // and size, use it as is.
4272 Array = ArrayInit;
4273 ArrayTy = ArrayInit->getType();
4274 }
4275 }
4276
4277 if (!Array) {
4278 if (ElementSize != 8)
4279 // TODO: Handle conversions to larger integral types.
4280 return false;
4281
4282 // Otherwise extract the portion of the initializer starting
4283 // at Offset as an array of bytes, and reset Offset.
4284 Init = ReadByteArrayFromGlobal(GV, Offset);
4285 if (!Init)
4286 return false;
4287
4288 Offset = 0;
4289 Array = dyn_cast<ConstantDataArray>(Init);
4290 ArrayTy = dyn_cast<ArrayType>(Init->getType());
4291 }
4292
4293 uint64_t NumElts = ArrayTy->getArrayNumElements();
4294 if (Offset > NumElts)
4295 return false;
4296
4297 Slice.Array = Array;
4298 Slice.Offset = Offset;
4299 Slice.Length = NumElts - Offset;
4300 return true;
4301}
4302
4303/// Extract bytes from the initializer of the constant array V, which need
4304/// not be a nul-terminated string. On success, store the bytes in Str and
4305/// return true. When TrimAtNul is set, Str will contain only the bytes up
4306/// to but not including the first nul. Return false on failure.
4307bool llvm::getConstantStringInfo(const Value *V, StringRef &Str,
4308 bool TrimAtNul) {
4309 ConstantDataArraySlice Slice;
4310 if (!getConstantDataArrayInfo(V, Slice, 8))
4311 return false;
4312
4313 if (Slice.Array == nullptr) {
4314 if (TrimAtNul) {
4315 // Return a nul-terminated string even for an empty Slice. This is
4316 // safe because all existing SimplifyLibcalls callers require string
4317 // arguments and the behavior of the functions they fold is undefined
4318 // otherwise. Folding the calls this way is preferable to making
4319 // the undefined library calls, even though it prevents sanitizers
4320 // from reporting such calls.
4321 Str = StringRef();
4322 return true;
4323 }
4324 if (Slice.Length == 1) {
4325 Str = StringRef("", 1);
4326 return true;
4327 }
4328 // We cannot instantiate a StringRef as we do not have an appropriate string
4329 // of 0s at hand.
4330 return false;
4331 }
4332
4333 // Start out with the entire array in the StringRef.
4334 Str = Slice.Array->getAsString();
4335 // Skip over 'offset' bytes.
4336 Str = Str.substr(Slice.Offset);
4337
4338 if (TrimAtNul) {
4339 // Trim off the \0 and anything after it. If the array is not nul
4340 // terminated, we just return the whole end of string. The client may know
4341 // some other way that the string is length-bound.
4342 Str = Str.substr(0, Str.find('\0'));
4343 }
4344 return true;
4345}
4346
4347// These next two are very similar to the above, but also look through PHI
4348// nodes.
4349// TODO: See if we can integrate these two together.
4350
4351/// If we can compute the length of the string pointed to by
4352/// the specified pointer, return 'len+1'. If we can't, return 0.
4353static uint64_t GetStringLengthH(const Value *V,
4354 SmallPtrSetImpl<const PHINode*> &PHIs,
4355 unsigned CharSize) {
4356 // Look through noop bitcast instructions.
4357 V = V->stripPointerCasts();
4358
4359 // If this is a PHI node, there are two cases: either we have already seen it
4360 // or we haven't.
4361 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
4362 if (!PHIs.insert(PN).second)
4363 return ~0ULL; // already in the set.
4364
4365 // If it was new, see if all the input strings are the same length.
4366 uint64_t LenSoFar = ~0ULL;
4367 for (Value *IncValue : PN->incoming_values()) {
4368 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
4369 if (Len == 0) return 0; // Unknown length -> unknown.
4370
4371 if (Len == ~0ULL) continue;
4372
4373 if (Len != LenSoFar && LenSoFar != ~0ULL)
4374 return 0; // Disagree -> unknown.
4375 LenSoFar = Len;
4376 }
4377
4378 // Success, all agree.
4379 return LenSoFar;
4380 }
4381
4382 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
4383 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
4384 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
4385 if (Len1 == 0) return 0;
4386 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
4387 if (Len2 == 0) return 0;
4388 if (Len1 == ~0ULL) return Len2;
4389 if (Len2 == ~0ULL) return Len1;
4390 if (Len1 != Len2) return 0;
4391 return Len1;
4392 }
4393
4394 // Otherwise, see if we can read the string.
4395 ConstantDataArraySlice Slice;
4396 if (!getConstantDataArrayInfo(V, Slice, CharSize))
4397 return 0;
4398
4399 if (Slice.Array == nullptr)
4400 // Zeroinitializer (including an empty one).
4401 return 1;
4402
4403 // Search for the first nul character. Return a conservative result even
4404 // when there is no nul. This is safe since otherwise the string function
4405 // being folded such as strlen is undefined, and can be preferable to
4406 // making the undefined library call.
4407 unsigned NullIndex = 0;
4408 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
4409 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
4410 break;
4411 }
4412
4413 return NullIndex + 1;
4414}
4415
4416/// If we can compute the length of the string pointed to by
4417/// the specified pointer, return 'len+1'. If we can't, return 0.
4418uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
4419 if (!V->getType()->isPointerTy())
4420 return 0;
4421
4422 SmallPtrSet<const PHINode*, 32> PHIs;
4423 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
4424 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
4425 // an empty string as a length.
4426 return Len == ~0ULL ? 1 : Len;
4427}
4428
4429const Value *
4430llvm::getArgumentAliasingToReturnedPointer(const CallBase *Call,
4431 bool MustPreserveNullness) {
4432 assert(Call &&(static_cast <bool> (Call && "getArgumentAliasingToReturnedPointer only works on nonnull calls"
) ? void (0) : __assert_fail ("Call && \"getArgumentAliasingToReturnedPointer only works on nonnull calls\""
, "llvm/lib/Analysis/ValueTracking.cpp", 4433, __extension__ __PRETTY_FUNCTION__
))
4433 "getArgumentAliasingToReturnedPointer only works on nonnull calls")(static_cast <bool> (Call && "getArgumentAliasingToReturnedPointer only works on nonnull calls"
) ? void (0) : __assert_fail ("Call && \"getArgumentAliasingToReturnedPointer only works on nonnull calls\""
, "llvm/lib/Analysis/ValueTracking.cpp", 4433, __extension__ __PRETTY_FUNCTION__
))
;
4434 if (const Value *RV = Call->getReturnedArgOperand())
4435 return RV;
4436 // This can be used only as a aliasing property.
4437 if (isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(
4438 Call, MustPreserveNullness))
4439 return Call->getArgOperand(0);
4440 return nullptr;
4441}
4442
4443bool llvm::isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(
4444 const CallBase *Call, bool MustPreserveNullness) {
4445 switch (Call->getIntrinsicID()) {
4446 case Intrinsic::launder_invariant_group:
4447 case Intrinsic::strip_invariant_group:
4448 case Intrinsic::aarch64_irg:
4449 case Intrinsic::aarch64_tagp:
4450 return true;
4451 case Intrinsic::ptrmask:
4452 return !MustPreserveNullness;
4453 default:
4454 return false;
4455 }
4456}
4457
4458/// \p PN defines a loop-variant pointer to an object. Check if the
4459/// previous iteration of the loop was referring to the same object as \p PN.
4460static bool isSameUnderlyingObjectInLoop(const PHINode *PN,
4461 const LoopInfo *LI) {
4462 // Find the loop-defined value.
4463 Loop *L = LI->getLoopFor(PN->getParent());
4464 if (PN->getNumIncomingValues() != 2)
4465 return true;
4466
4467 // Find the value from previous iteration.
4468 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
4469 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
4470 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
4471 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
4472 return true;
4473
4474 // If a new pointer is loaded in the loop, the pointer references a different
4475 // object in every iteration. E.g.:
4476 // for (i)
4477 // int *p = a[i];
4478 // ...
4479 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
4480 if (!L->isLoopInvariant(Load->getPointerOperand()))
4481 return false;
4482 return true;
4483}
4484
4485const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup) {
4486 if (!V->getType()->isPointerTy())
4487 return V;
4488 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
4489 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
4490 V = GEP->getPointerOperand();
4491 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
4492 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
4493 V = cast<Operator>(V)->getOperand(0);
4494 if (!V->getType()->isPointerTy())
4495 return V;
4496 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
4497 if (GA->isInterposable())
4498 return V;
4499 V = GA->getAliasee();
4500 } else {
4501 if (auto *PHI = dyn_cast<PHINode>(V)) {
4502 // Look through single-arg phi nodes created by LCSSA.
4503 if (PHI->getNumIncomingValues() == 1) {
4504 V = PHI->getIncomingValue(0);
4505 continue;
4506 }
4507 } else if (auto *Call = dyn_cast<CallBase>(V)) {
4508 // CaptureTracking can know about special capturing properties of some
4509 // intrinsics like launder.invariant.group, that can't be expressed with
4510 // the attributes, but have properties like returning aliasing pointer.
4511 // Because some analysis may assume that nocaptured pointer is not
4512 // returned from some special intrinsic (because function would have to
4513 // be marked with returns attribute), it is crucial to use this function
4514 // because it should be in sync with CaptureTracking. Not using it may
4515 // cause weird miscompilations where 2 aliasing pointers are assumed to
4516 // noalias.
4517 if (auto *RP = getArgumentAliasingToReturnedPointer(Call, false)) {
4518 V = RP;
4519 continue;
4520 }
4521 }
4522
4523 return V;
4524 }
4525 assert(V->getType()->isPointerTy() && "Unexpected operand type!")(static_cast <bool> (V->getType()->isPointerTy() &&
"Unexpected operand type!") ? void (0) : __assert_fail ("V->getType()->isPointerTy() && \"Unexpected operand type!\""
, "llvm/lib/Analysis/ValueTracking.cpp", 4525, __extension__ __PRETTY_FUNCTION__
))
;
4526 }
4527 return V;
4528}
4529
4530void llvm::getUnderlyingObjects(const Value *V,
4531 SmallVectorImpl<const Value *> &Objects,
4532 LoopInfo *LI, unsigned MaxLookup) {
4533 SmallPtrSet<const Value *, 4> Visited;
4534 SmallVector<const Value *, 4> Worklist;
4535 Worklist.push_back(V);
4536 do {
4537 const Value *P = Worklist.pop_back_val();
4538 P = getUnderlyingObject(P, MaxLookup);
4539
4540 if (!Visited.insert(P).second)
4541 continue;
4542
4543 if (auto *SI = dyn_cast<SelectInst>(P)) {
4544 Worklist.push_back(SI->getTrueValue());
4545 Worklist.push_back(SI->getFalseValue());
4546 continue;
4547 }
4548
4549 if (auto *PN = dyn_cast<PHINode>(P)) {
4550 // If this PHI changes the underlying object in every iteration of the
4551 // loop, don't look through it. Consider:
4552 // int **A;
4553 // for (i) {
4554 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
4555 // Curr = A[i];
4556 // *Prev, *Curr;
4557 //
4558 // Prev is tracking Curr one iteration behind so they refer to different
4559 // underlying objects.
4560 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
4561 isSameUnderlyingObjectInLoop(PN, LI))
4562 append_range(Worklist, PN->incoming_values());
4563 continue;
4564 }
4565
4566 Objects.push_back(P);
4567 } while (!Worklist.empty());
4568}
4569
4570/// This is the function that does the work of looking through basic
4571/// ptrtoint+arithmetic+inttoptr sequences.
4572static const Value *getUnderlyingObjectFromInt(const Value *V) {
4573 do {
4574 if (const Operator *U = dyn_cast<Operator>(V)) {
4575 // If we find a ptrtoint, we can transfer control back to the
4576 // regular getUnderlyingObjectFromInt.
4577 if (U->getOpcode() == Instruction::PtrToInt)
4578 return U->getOperand(0);
4579 // If we find an add of a constant, a multiplied value, or a phi, it's
4580 // likely that the other operand will lead us to the base
4581 // object. We don't have to worry about the case where the
4582 // object address is somehow being computed by the multiply,
4583 // because our callers only care when the result is an
4584 // identifiable object.
4585 if (U->getOpcode() != Instruction::Add ||
4586 (!isa<ConstantInt>(U->getOperand(1)) &&
4587 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
4588 !isa<PHINode>(U->getOperand(1))))
4589 return V;
4590 V = U->getOperand(0);
4591 } else {
4592 return V;
4593 }
4594 assert(V->getType()->isIntegerTy() && "Unexpected operand type!")(static_cast <bool> (V->getType()->isIntegerTy() &&
"Unexpected operand type!") ? void (0) : __assert_fail ("V->getType()->isIntegerTy() && \"Unexpected operand type!\""
, "llvm/lib/Analysis/ValueTracking.cpp", 4594, __extension__ __PRETTY_FUNCTION__
))
;
4595 } while (true);
4596}
4597
4598/// This is a wrapper around getUnderlyingObjects and adds support for basic
4599/// ptrtoint+arithmetic+inttoptr sequences.
4600/// It returns false if unidentified object is found in getUnderlyingObjects.
4601bool llvm::getUnderlyingObjectsForCodeGen(const Value *V,
4602 SmallVectorImpl<Value *> &Objects) {
4603 SmallPtrSet<const Value *, 16> Visited;
4604 SmallVector<const Value *, 4> Working(1, V);
4605 do {
4606 V = Working.pop_back_val();
4607
4608 SmallVector<const Value *, 4> Objs;
4609 getUnderlyingObjects(V, Objs);
4610
4611 for (const Value *V : Objs) {
4612 if (!Visited.insert(V).second)
4613 continue;
4614 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
4615 const Value *O =
4616 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
4617 if (O->getType()->isPointerTy()) {
4618 Working.push_back(O);
4619 continue;
4620 }
4621 }
4622 // If getUnderlyingObjects fails to find an identifiable object,
4623 // getUnderlyingObjectsForCodeGen also fails for safety.
4624 if (!isIdentifiedObject(V)) {
4625 Objects.clear();
4626 return false;
4627 }
4628 Objects.push_back(const_cast<Value *>(V));
4629 }
4630 } while (!Working.empty());
4631 return true;
4632}
4633
4634AllocaInst *llvm::findAllocaForValue(Value *V, bool OffsetZero) {
4635 AllocaInst *Result = nullptr;
4636 SmallPtrSet<Value *, 4> Visited;
4637 SmallVector<Value *, 4> Worklist;
4638
4639 auto AddWork = [&](Value *V) {
4640 if (Visited.insert(V).second)
4641 Worklist.push_back(V);
4642 };
4643
4644 AddWork(V);
4645 do {
4646 V = Worklist.pop_back_val();
4647 assert(Visited.count(V))(static_cast <bool> (Visited.count(V)) ? void (0) : __assert_fail
("Visited.count(V)", "llvm/lib/Analysis/ValueTracking.cpp", 4647
, __extension__ __PRETTY_FUNCTION__))
;
4648
4649 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
4650 if (Result && Result != AI)
4651 return nullptr;
4652 Result = AI;
4653 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
4654 AddWork(CI->getOperand(0));
4655 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
4656 for (Value *IncValue : PN->incoming_values())
4657 AddWork(IncValue);
4658 } else if (auto *SI = dyn_cast<SelectInst>(V)) {
4659 AddWork(SI->getTrueValue());
4660 AddWork(SI->getFalseValue());
4661 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
4662 if (OffsetZero && !GEP->hasAllZeroIndices())
4663 return nullptr;
4664 AddWork(GEP->getPointerOperand());
4665 } else if (CallBase *CB = dyn_cast<CallBase>(V)) {
4666 Value *Returned = CB->getReturnedArgOperand();
4667 if (Returned)
4668 AddWork(Returned);
4669 else
4670 return nullptr;
4671 } else {
4672 return nullptr;
4673 }
4674 } while (!Worklist.empty());
4675
4676 return Result;
4677}
4678
4679static bool onlyUsedByLifetimeMarkersOrDroppableInstsHelper(
4680 const Value *V, bool AllowLifetime, bool AllowDroppable) {
4681 for (const User *U : V->users()) {
4682 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
4683 if (!II)
4684 return false;
4685
4686 if (AllowLifetime && II->isLifetimeStartOrEnd())
4687 continue;
4688
4689 if (AllowDroppable && II->isDroppable())
4690 continue;
4691
4692 return false;
4693 }
4694 return true;
4695}
4696
4697bool llvm::onlyUsedByLifetimeMarkers(const Value *V) {
4698 return onlyUsedByLifetimeMarkersOrDroppableInstsHelper(
4699 V, /* AllowLifetime */ true, /* AllowDroppable */ false);
4700}
4701bool llvm::onlyUsedByLifetimeMarkersOrDroppableInsts(const Value *V) {
4702 return onlyUsedByLifetimeMarkersOrDroppableInstsHelper(
4703 V, /* AllowLifetime */ true, /* AllowDroppable */ true);
4704}
4705
4706bool llvm::mustSuppressSpeculation(const LoadInst &LI) {
4707 if (!LI.isUnordered())
4708 return true;
4709 const Function &F = *LI.getFunction();
4710 // Speculative load may create a race that did not exist in the source.
4711 return F.hasFnAttribute(Attribute::SanitizeThread) ||
4712 // Speculative load may load data from dirty regions.
4713 F.hasFnAttribute(Attribute::SanitizeAddress) ||
4714 F.hasFnAttribute(Attribute::SanitizeHWAddress);
4715}
4716
4717bool llvm::isSafeToSpeculativelyExecute(const Instruction *Inst,
4718 const Instruction *CtxI,
4719 AssumptionCache *AC,
4720 const DominatorTree *DT,
4721 const TargetLibraryInfo *TLI) {
4722 return isSafeToSpeculativelyExecuteWithOpcode(Inst->getOpcode(), Inst, CtxI,
4723 AC, DT, TLI);
4724}
4725
4726bool llvm::isSafeToSpeculativelyExecuteWithOpcode(
4727 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI,
4728 AssumptionCache *AC, const DominatorTree *DT,
4729 const TargetLibraryInfo *TLI) {
4730#ifndef NDEBUG
4731 if (Inst->getOpcode() != Opcode) {
4732 // Check that the operands are actually compatible with the Opcode override.
4733 auto hasEqualReturnAndLeadingOperandTypes =
4734 [](const Instruction *Inst, unsigned NumLeadingOperands) {
4735 if (Inst->getNumOperands() < NumLeadingOperands)
4736 return false;
4737 const Type *ExpectedType = Inst->getType();
4738 for (unsigned ItOp = 0; ItOp < NumLeadingOperands; ++ItOp)
4739 if (Inst->getOperand(ItOp)->getType() != ExpectedType)
4740 return false;
4741 return true;
4742 };
4743 assert(!Instruction::isBinaryOp(Opcode) ||(static_cast <bool> (!Instruction::isBinaryOp(Opcode) ||
hasEqualReturnAndLeadingOperandTypes(Inst, 2)) ? void (0) : __assert_fail
("!Instruction::isBinaryOp(Opcode) || hasEqualReturnAndLeadingOperandTypes(Inst, 2)"
, "llvm/lib/Analysis/ValueTracking.cpp", 4744, __extension__ __PRETTY_FUNCTION__
))
4744 hasEqualReturnAndLeadingOperandTypes(Inst, 2))(static_cast <bool> (!Instruction::isBinaryOp(Opcode) ||
hasEqualReturnAndLeadingOperandTypes(Inst, 2)) ? void (0) : __assert_fail
("!Instruction::isBinaryOp(Opcode) || hasEqualReturnAndLeadingOperandTypes(Inst, 2)"
, "llvm/lib/Analysis/ValueTracking.cpp", 4744, __extension__ __PRETTY_FUNCTION__
))
;
4745 assert(!Instruction::isUnaryOp(Opcode) ||(static_cast <bool> (!Instruction::isUnaryOp(Opcode) ||
hasEqualReturnAndLeadingOperandTypes(Inst, 1)) ? void (0) : __assert_fail
("!Instruction::isUnaryOp(Opcode) || hasEqualReturnAndLeadingOperandTypes(Inst, 1)"
, "llvm/lib/Analysis/ValueTracking.cpp", 4746, __extension__ __PRETTY_FUNCTION__
))
4746 hasEqualReturnAndLeadingOperandTypes(Inst, 1))(static_cast <bool> (!Instruction::isUnaryOp(Opcode) ||
hasEqualReturnAndLeadingOperandTypes(Inst, 1)) ? void (0) : __assert_fail
("!Instruction::isUnaryOp(Opcode) || hasEqualReturnAndLeadingOperandTypes(Inst, 1)"
, "llvm/lib/Analysis/ValueTracking.cpp", 4746, __extension__ __PRETTY_FUNCTION__
))
;
4747 }
4748#endif
4749
4750 switch (Opcode) {
4751 default:
4752 return true;
4753 case Instruction::UDiv:
4754 case Instruction::URem: {
4755 // x / y is undefined if y == 0.
4756 const APInt *V;
4757 if (match(Inst->getOperand(1), m_APInt(V)))
4758 return *V != 0;
4759 return false;
4760 }
4761 case Instruction::SDiv:
4762 case Instruction::SRem: {
4763 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
4764 const APInt *Numerator, *Denominator;
4765 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
4766 return false;
4767 // We cannot hoist this division if the denominator is 0.
4768 if (*Denominator == 0)
4769 return false;
4770 // It's safe to hoist if the denominator is not 0 or -1.
4771 if (!Denominator->isAllOnes())
4772 return true;
4773 // At this point we know that the denominator is -1. It is safe to hoist as
4774 // long we know that the numerator is not INT_MIN.
4775 if (match(Inst->getOperand(0), m_APInt(Numerator)))
4776 return !Numerator->isMinSignedValue();
4777 // The numerator *might* be MinSignedValue.
4778 return false;
4779 }
4780 case Instruction::Load: {
4781 const LoadInst *LI = dyn_cast<LoadInst>(Inst);
4782 if (!LI)
4783 return false;
4784 if (mustSuppressSpeculation(*LI))
4785 return false;
4786 const DataLayout &DL = LI->getModule()->getDataLayout();
4787 return isDereferenceableAndAlignedPointer(LI->getPointerOperand(),
4788 LI->getType(), LI->getAlign(), DL,
4789 CtxI, AC, DT, TLI);
4790 }
4791 case Instruction::Call: {
4792 auto *CI = dyn_cast<const CallInst>(Inst);
4793 if (!CI)
4794 return false;
4795 const Function *Callee = CI->getCalledFunction();
4796
4797 // The called function could have undefined behavior or side-effects, even
4798 // if marked readnone nounwind.
4799 return Callee && Callee->isSpeculatable();
4800 }
4801 case Instruction::VAArg:
4802 case Instruction::Alloca:
4803 case Instruction::Invoke:
4804 case Instruction::CallBr:
4805 case Instruction::PHI:
4806 case Instruction::Store:
4807 case Instruction::Ret:
4808 case Instruction::Br:
4809 case Instruction::IndirectBr:
4810 case Instruction::Switch:
4811 case Instruction::Unreachable:
4812 case Instruction::Fence:
4813 case Instruction::AtomicRMW:
4814 case Instruction::AtomicCmpXchg:
4815 case Instruction::LandingPad:
4816 case Instruction::Resume:
4817 case Instruction::CatchSwitch:
4818 case Instruction::CatchPad:
4819 case Instruction::CatchRet:
4820 case Instruction::CleanupPad:
4821 case Instruction::CleanupRet:
4822 return false; // Misc instructions which have effects
4823 }
4824}
4825
4826bool llvm::mayHaveNonDefUseDependency(const Instruction &I) {
4827 if (I.mayReadOrWriteMemory())
4828 // Memory dependency possible
4829 return true;
4830 if (!isSafeToSpeculativelyExecute(&I))
4831 // Can't move above a maythrow call or infinite loop. Or if an
4832 // inalloca alloca, above a stacksave call.
4833 return true;
4834 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
4835 // 1) Can't reorder two inf-loop calls, even if readonly
4836 // 2) Also can't reorder an inf-loop call below a instruction which isn't
4837 // safe to speculative execute. (Inverse of above)
4838 return true;
4839 return false;
4840}
4841
4842/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
4843static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR) {
4844 switch (OR) {
4845 case ConstantRange::OverflowResult::MayOverflow:
4846 return OverflowResult::MayOverflow;
4847 case ConstantRange::OverflowResult::AlwaysOverflowsLow:
4848 return OverflowResult::AlwaysOverflowsLow;
4849 case ConstantRange::OverflowResult::AlwaysOverflowsHigh:
4850 return OverflowResult::AlwaysOverflowsHigh;
4851 case ConstantRange::OverflowResult::NeverOverflows:
4852 return OverflowResult::NeverOverflows;
4853 }
4854 llvm_unreachable("Unknown OverflowResult")::llvm::llvm_unreachable_internal("Unknown OverflowResult", "llvm/lib/Analysis/ValueTracking.cpp"
, 4854)
;
4855}
4856
4857/// Combine constant ranges from computeConstantRange() and computeKnownBits().
4858static ConstantRange computeConstantRangeIncludingKnownBits(
4859 const Value *V, bool ForSigned, const DataLayout &DL, unsigned Depth,
4860 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
4861 OptimizationRemarkEmitter *ORE = nullptr, bool UseInstrInfo = true) {
4862 KnownBits Known = computeKnownBits(
4863 V, DL, Depth, AC, CxtI, DT, ORE, UseInstrInfo);
4864 ConstantRange CR1 = ConstantRange::fromKnownBits(Known, ForSigned);
4865 ConstantRange CR2 = computeConstantRange(V, UseInstrInfo);
4866 ConstantRange::PreferredRangeType RangeType =
4867 ForSigned ? ConstantRange::Signed : ConstantRange::Unsigned;
4868 return CR1.intersectWith(CR2, RangeType);
4869}
4870
4871OverflowResult llvm::computeOverflowForUnsignedMul(
4872 const Value *LHS, const Value *RHS, const DataLayout &DL,
4873 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
4874 bool UseInstrInfo) {
4875 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT,
4876 nullptr, UseInstrInfo);
4877 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT,
4878 nullptr, UseInstrInfo);
4879 ConstantRange LHSRange = ConstantRange::fromKnownBits(LHSKnown, false);
4880 ConstantRange RHSRange = ConstantRange::fromKnownBits(RHSKnown, false);
4881 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
4882}
4883
4884OverflowResult
4885llvm::computeOverflowForSignedMul(const Value *LHS, const Value *RHS,
4886 const DataLayout &DL, AssumptionCache *AC,
4887 const Instruction *CxtI,
4888 const DominatorTree *DT, bool UseInstrInfo) {
4889 // Multiplying n * m significant bits yields a result of n + m significant
4890 // bits. If the total number of significant bits does not exceed the
4891 // result bit width (minus 1), there is no overflow.
4892 // This means if we have enough leading sign bits in the operands
4893 // we can guarantee that the result does not overflow.
4894 // Ref: "Hacker's Delight" by Henry Warren
4895 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
4896
4897 // Note that underestimating the number of sign bits gives a more
4898 // conservative answer.
4899 unsigned SignBits = ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) +
4900 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT);
4901
4902 // First handle the easy case: if we have enough sign bits there's
4903 // definitely no overflow.
4904 if (SignBits > BitWidth + 1)
4905 return OverflowResult::NeverOverflows;
4906
4907 // There are two ambiguous cases where there can be no overflow:
4908 // SignBits == BitWidth + 1 and
4909 // SignBits == BitWidth
4910 // The second case is difficult to check, therefore we only handle the
4911 // first case.
4912 if (SignBits == BitWidth + 1) {
4913 // It overflows only when both arguments are negative and the true
4914 // product is exactly the minimum negative number.
4915 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
4916 // For simplicity we just check if at least one side is not negative.
4917 KnownBits LHSKnown = computeKnownBits(LHS, DL, /*Depth=*/0, AC, CxtI, DT,
4918 nullptr, UseInstrInfo);
4919 KnownBits RHSKnown = computeKnownBits(RHS, DL, /*Depth=*/0, AC, CxtI, DT,
4920 nullptr, UseInstrInfo);
4921 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
4922 return OverflowResult::NeverOverflows;
4923 }
4924 return OverflowResult::MayOverflow;
4925}
4926
4927OverflowResult llvm::computeOverflowForUnsignedAdd(
4928 const Value *LHS, const Value *RHS, const DataLayout &DL,
4929 AssumptionCache *AC, const Instruction *CxtI, const DominatorTree *DT,
4930 bool UseInstrInfo) {
4931 ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4932 LHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT,
4933 nullptr, UseInstrInfo);
4934 ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4935 RHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT,
4936 nullptr, UseInstrInfo);
4937 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
4938}
4939
4940static OverflowResult computeOverflowForSignedAdd(const Value *LHS,
4941 const Value *RHS,
4942 const AddOperator *Add,
4943 const DataLayout &DL,
4944 AssumptionCache *AC,
4945 const Instruction *CxtI,
4946 const DominatorTree *DT) {
4947 if (Add && Add->hasNoSignedWrap()) {
4948 return OverflowResult::NeverOverflows;
4949 }
4950
4951 // If LHS and RHS each have at least two sign bits, the addition will look
4952 // like
4953 //
4954 // XX..... +
4955 // YY.....
4956 //
4957 // If the carry into the most significant position is 0, X and Y can't both
4958 // be 1 and therefore the carry out of the addition is also 0.
4959 //
4960 // If the carry into the most significant position is 1, X and Y can't both
4961 // be 0 and therefore the carry out of the addition is also 1.
4962 //
4963 // Since the carry into the most significant position is always equal to
4964 // the carry out of the addition, there is no signed overflow.
4965 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
4966 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
4967 return OverflowResult::NeverOverflows;
4968
4969 ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
4970 LHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4971 ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
4972 RHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
4973 OverflowResult OR =
4974 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
4975 if (OR != OverflowResult::MayOverflow)
4976 return OR;
4977
4978 // The remaining code needs Add to be available. Early returns if not so.
4979 if (!Add)
4980 return OverflowResult::MayOverflow;
4981
4982 // If the sign of Add is the same as at least one of the operands, this add
4983 // CANNOT overflow. If this can be determined from the known bits of the
4984 // operands the above signedAddMayOverflow() check will have already done so.
4985 // The only other way to improve on the known bits is from an assumption, so
4986 // call computeKnownBitsFromAssume() directly.
4987 bool LHSOrRHSKnownNonNegative =
4988 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
4989 bool LHSOrRHSKnownNegative =
4990 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
4991 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
4992 KnownBits AddKnown(LHSRange.getBitWidth());
4993 computeKnownBitsFromAssume(
4994 Add, AddKnown, /*Depth=*/0, Query(DL, AC, CxtI, DT, true));
4995 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
4996 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
4997 return OverflowResult::NeverOverflows;
4998 }
4999
5000 return OverflowResult::MayOverflow;
5001}
5002
5003OverflowResult llvm::computeOverflowForUnsignedSub(const Value *LHS,
5004 const Value *RHS,
5005 const DataLayout &DL,
5006 AssumptionCache *AC,
5007 const Instruction *CxtI,
5008 const DominatorTree *DT) {
5009 // X - (X % ?)
5010 // The remainder of a value can't have greater magnitude than itself,
5011 // so the subtraction can't overflow.
5012
5013 // X - (X -nuw ?)
5014 // In the minimal case, this would simplify to "?", so there's no subtract
5015 // at all. But if this analysis is used to peek through casts, for example,
5016 // then determining no-overflow may allow other transforms.
5017
5018 // TODO: There are other patterns like this.
5019 // See simplifyICmpWithBinOpOnLHS() for candidates.
5020 if (match(RHS, m_URem(m_Specific(LHS), m_Value())) ||
5021 match(RHS, m_NUWSub(m_Specific(LHS), m_Value())))
5022 if (isGuaranteedNotToBeUndefOrPoison(LHS, AC, CxtI, DT))
5023 return OverflowResult::NeverOverflows;
5024
5025 // Checking for conditions implied by dominating conditions may be expensive.
5026 // Limit it to usub_with_overflow calls for now.
5027 if (match(CxtI,
5028 m_Intrinsic<Intrinsic::usub_with_overflow>(m_Value(), m_Value())))
5029 if (auto C =
5030 isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, CxtI, DL)) {
5031 if (*C)
5032 return OverflowResult::NeverOverflows;
5033 return OverflowResult::AlwaysOverflowsLow;
5034 }
5035 ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
5036 LHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT);
5037 ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
5038 RHS, /*ForSigned=*/false, DL, /*Depth=*/0, AC, CxtI, DT);
5039 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
5040}
5041
5042OverflowResult llvm::computeOverflowForSignedSub(const Value *LHS,
5043 const Value *RHS,
5044 const DataLayout &DL,
5045 AssumptionCache *AC,
5046 const Instruction *CxtI,
5047 const DominatorTree *DT) {
5048 // X - (X % ?)
5049 // The remainder of a value can't have greater magnitude than itself,
5050 // so the subtraction can't overflow.
5051
5052 // X - (X -nsw ?)
5053 // In the minimal case, this would simplify to "?", so there's no subtract
5054 // at all. But if this analysis is used to peek through casts, for example,
5055 // then determining no-overflow may allow other transforms.
5056 if (match(RHS, m_SRem(m_Specific(LHS), m_Value())) ||
5057 match(RHS, m_NSWSub(m_Specific(LHS), m_Value())))
5058 if (isGuaranteedNotToBeUndefOrPoison(LHS, AC, CxtI, DT))
5059 return OverflowResult::NeverOverflows;
5060
5061 // If LHS and RHS each have at least two sign bits, the subtraction
5062 // cannot overflow.
5063 if (ComputeNumSignBits(LHS, DL, 0, AC, CxtI, DT) > 1 &&
5064 ComputeNumSignBits(RHS, DL, 0, AC, CxtI, DT) > 1)
5065 return OverflowResult::NeverOverflows;
5066
5067 ConstantRange LHSRange = computeConstantRangeIncludingKnownBits(
5068 LHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
5069 ConstantRange RHSRange = computeConstantRangeIncludingKnownBits(
5070 RHS, /*ForSigned=*/true, DL, /*Depth=*/0, AC, CxtI, DT);
5071 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
5072}
5073
5074bool llvm::isOverflowIntrinsicNoWrap(const WithOverflowInst *WO,
5075 const DominatorTree &DT) {
5076 SmallVector<const BranchInst *, 2> GuardingBranches;
5077 SmallVector<const ExtractValueInst *, 2> Results;
5078
5079 for (const User *U : WO->users()) {
5080 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
5081 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type")(static_cast <bool> (EVI->getNumIndices() == 1 &&
"Obvious from CI's type") ? void (0) : __assert_fail ("EVI->getNumIndices() == 1 && \"Obvious from CI's type\""
, "llvm/lib/Analysis/ValueTracking.cpp", 5081, __extension__ __PRETTY_FUNCTION__
))
;
5082
5083 if (EVI->getIndices()[0] == 0)
5084 Results.push_back(EVI);
5085 else {
5086 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type")(static_cast <bool> (EVI->getIndices()[0] == 1 &&
"Obvious from CI's type") ? void (0) : __assert_fail ("EVI->getIndices()[0] == 1 && \"Obvious from CI's type\""
, "llvm/lib/Analysis/ValueTracking.cpp", 5086, __extension__ __PRETTY_FUNCTION__
))
;
5087
5088 for (const auto *U : EVI->users())
5089 if (const auto *B = dyn_cast<BranchInst>(U)) {
5090 assert(B->isConditional() && "How else is it using an i1?")(static_cast <bool> (B->isConditional() && "How else is it using an i1?"
) ? void (0) : __assert_fail ("B->isConditional() && \"How else is it using an i1?\""
, "llvm/lib/Analysis/ValueTracking.cpp", 5090, __extension__ __PRETTY_FUNCTION__
))
;
5091 GuardingBranches.push_back(B);
5092 }
5093 }
5094 } else {
5095 // We are using the aggregate directly in a way we don't want to analyze
5096 // here (storing it to a global, say).
5097 return false;
5098 }
5099 }
5100
5101 auto AllUsesGuardedByBranch = [&](const BranchInst *BI) {
5102 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
5103 if (!NoWrapEdge.isSingleEdge())
5104 return false;
5105
5106 // Check if all users of the add are provably no-wrap.
5107 for (const auto *Result : Results) {
5108 // If the extractvalue itself is not executed on overflow, the we don't
5109 // need to check each use separately, since domination is transitive.
5110 if (DT.dominates(NoWrapEdge, Result->getParent()))
5111 continue;
5112
5113 for (const auto &RU : Result->uses())
5114 if (!DT.dominates(NoWrapEdge, RU))
5115 return false;
5116 }
5117
5118 return true;
5119 };
5120
5121 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
5122}
5123
5124static bool canCreateUndefOrPoison(const Operator *Op, bool PoisonOnly,
5125 bool ConsiderFlags) {
5126
5127 if (ConsiderFlags && Op->hasPoisonGeneratingFlags())
5128 return true;
5129
5130 unsigned Opcode = Op->getOpcode();
5131
5132 // Check whether opcode is a poison/undef-generating operation
5133 switch (Opcode) {
5134 case Instruction::Shl:
5135 case Instruction::AShr:
5136 case Instruction::LShr: {
5137 // Shifts return poison if shiftwidth is larger than the bitwidth.
5138 if (auto *C = dyn_cast<Constant>(Op->getOperand(1))) {
5139 SmallVector<Constant *, 4> ShiftAmounts;
5140 if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
5141 unsigned NumElts = FVTy->getNumElements();
5142 for (unsigned i = 0; i < NumElts; ++i)
5143 ShiftAmounts.push_back(C->getAggregateElement(i));
5144 } else if (isa<ScalableVectorType>(C->getType()))
5145 return true; // Can't tell, just return true to be safe
5146 else
5147 ShiftAmounts.push_back(C);
5148
5149 bool Safe = llvm::all_of(ShiftAmounts, [](Constant *C) {
5150 auto *CI = dyn_cast_or_null<ConstantInt>(C);
5151 return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
5152 });
5153 return !Safe;
5154 }
5155 return true;
5156 }
5157 case Instruction::FPToSI:
5158 case Instruction::FPToUI:
5159 // fptosi/ui yields poison if the resulting value does not fit in the
5160 // destination type.
5161 return true;
5162 case Instruction::Call:
5163 if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
5164 switch (II->getIntrinsicID()) {
5165 // TODO: Add more intrinsics.
5166 case Intrinsic::ctpop:
5167 case Intrinsic::sadd_with_overflow:
5168 case Intrinsic::ssub_with_overflow:
5169 case Intrinsic::smul_with_overflow:
5170 case Intrinsic::uadd_with_overflow:
5171 case Intrinsic::usub_with_overflow:
5172 case Intrinsic::umul_with_overflow:
5173 return false;
5174 }
5175 }
5176 [[fallthrough]];
5177 case Instruction::CallBr:
5178 case Instruction::Invoke: {
5179 const auto *CB = cast<CallBase>(Op);
5180 return !CB->hasRetAttr(Attribute::NoUndef);
5181 }
5182 case Instruction::InsertElement:
5183 case Instruction::ExtractElement: {
5184 // If index exceeds the length of the vector, it returns poison
5185 auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
5186 unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
5187 auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
5188 if (!Idx || Idx->getValue().uge(VTy->getElementCount().getKnownMinValue()))
5189 return true;
5190 return false;
5191 }
5192 case Instruction::ShuffleVector: {
5193 // shufflevector may return undef.
5194 if (PoisonOnly)
5195 return false;
5196 ArrayRef<int> Mask = isa<ConstantExpr>(Op)
5197 ? cast<ConstantExpr>(Op)->getShuffleMask()
5198 : cast<ShuffleVectorInst>(Op)->getShuffleMask();
5199 return is_contained(Mask, UndefMaskElem);
5200 }
5201 case Instruction::FNeg:
5202 case Instruction::PHI:
5203 case Instruction::Select:
5204 case Instruction::URem:
5205 case Instruction::SRem:
5206 case Instruction::ExtractValue:
5207 case Instruction::InsertValue:
5208 case Instruction::Freeze:
5209 case Instruction::ICmp:
5210 case Instruction::FCmp:
5211 return false;
5212 case Instruction::GetElementPtr:
5213 // inbounds is handled above
5214 // TODO: what about inrange on constexpr?
5215 return false;
5216 default: {
5217 const auto *CE = dyn_cast<ConstantExpr>(Op);
5218 if (isa<CastInst>(Op) || (CE && CE->isCast()))
5219 return false;
5220 else if (Instruction::isBinaryOp(Opcode))
5221 return false;
5222 // Be conservative and return true.
5223 return true;
5224 }
5225 }
5226}
5227
5228bool llvm::canCreateUndefOrPoison(const Operator *Op, bool ConsiderFlags) {
5229 return ::canCreateUndefOrPoison(Op, /*PoisonOnly=*/false, ConsiderFlags);
5230}
5231
5232bool llvm::canCreatePoison(const Operator *Op, bool ConsiderFlags) {
5233 return ::canCreateUndefOrPoison(Op, /*PoisonOnly=*/true, ConsiderFlags);
5234}
5235
5236static bool directlyImpliesPoison(const Value *ValAssumedPoison,
5237 const Value *V, unsigned Depth) {
5238 if (ValAssumedPoison == V)
5239 return true;
5240
5241 const unsigned MaxDepth = 2;
5242 if (Depth >= MaxDepth)
5243 return false;
5244
5245 if (const auto *I = dyn_cast<Instruction>(V)) {
5246 if (propagatesPoison(cast<Operator>(I)))
5247 return any_of(I->operands(), [=](const Value *Op) {
5248 return directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
5249 });
5250
5251 // 'select ValAssumedPoison, _, _' is poison.
5252 if (const auto *SI = dyn_cast<SelectInst>(I))
5253 return directlyImpliesPoison(ValAssumedPoison, SI->getCondition(),
5254 Depth + 1);
5255 // V = extractvalue V0, idx
5256 // V2 = extractvalue V0, idx2
5257 // V0's elements are all poison or not. (e.g., add_with_overflow)
5258 const WithOverflowInst *II;
5259 if (match(I, m_ExtractValue(m_WithOverflowInst(II))) &&
5260 (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
5261 llvm::is_contained(II->args(), ValAssumedPoison)))
5262 return true;
5263 }
5264 return false;
5265}
5266
5267static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
5268 unsigned Depth) {
5269 if (isGuaranteedNotToBeUndefOrPoison(ValAssumedPoison))
5270 return true;
5271
5272 if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
5273 return true;
5274
5275 const unsigned MaxDepth = 2;
5276 if (Depth >= MaxDepth)
5277 return false;
5278
5279 const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
5280 if (I && !canCreatePoison(cast<Operator>(I))) {
5281 return all_of(I->operands(), [=](const Value *Op) {
5282 return impliesPoison(Op, V, Depth + 1);
5283 });
5284 }
5285 return false;
5286}
5287
5288bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
5289 return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
5290}
5291
5292static bool programUndefinedIfUndefOrPoison(const Value *V,
5293 bool PoisonOnly);
5294
5295static bool isGuaranteedNotToBeUndefOrPoison(const Value *V,
5296 AssumptionCache *AC,
5297 const Instruction *CtxI,
5298 const DominatorTree *DT,
5299 unsigned Depth, bool PoisonOnly) {
5300 if (Depth >= MaxAnalysisRecursionDepth)
5301 return false;
5302
5303 if (isa<MetadataAsValue>(V))
5304 return false;
5305
5306 if (const auto *A = dyn_cast<Argument>(V)) {
5307 if (A->hasAttribute(Attribute::NoUndef))
5308 return true;
5309 }
5310
5311 if (auto *C = dyn_cast<Constant>(V)) {
5312 if (isa<UndefValue>(C))
5313 return PoisonOnly && !isa<PoisonValue>(C);
5314
5315 if (isa<ConstantInt>(C) || isa<GlobalVariable>(C) || isa<ConstantFP>(V) ||
5316 isa<ConstantPointerNull>(C) || isa<Function>(C))
5317 return true;
5318
5319 if (C->getType()->isVectorTy() && !isa<ConstantExpr>(C))
5320 return (PoisonOnly ? !C->containsPoisonElement()
5321 : !C->containsUndefOrPoisonElement()) &&
5322 !C->containsConstantExpression();
5323 }
5324
5325 // Strip cast operations from a pointer value.
5326 // Note that stripPointerCastsSameRepresentation can strip off getelementptr
5327 // inbounds with zero offset. To guarantee that the result isn't poison, the
5328 // stripped pointer is checked as it has to be pointing into an allocated
5329 // object or be null `null` to ensure `inbounds` getelement pointers with a
5330 // zero offset could not produce poison.
5331 // It can strip off addrspacecast that do not change bit representation as
5332 // well. We believe that such addrspacecast is equivalent to no-op.
5333 auto *StrippedV = V->stripPointerCastsSameRepresentation();
5334 if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
5335 isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
5336 return true;
5337
5338 auto OpCheck = [&](const Value *V) {
5339 return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1,
5340 PoisonOnly);
5341 };
5342
5343 if (auto *Opr = dyn_cast<Operator>(V)) {
5344 // If the value is a freeze instruction, then it can never
5345 // be undef or poison.
5346 if (isa<FreezeInst>(V))
5347 return true;
5348
5349 if (const auto *CB = dyn_cast<CallBase>(V)) {
5350 if (CB->hasRetAttr(Attribute::NoUndef))
5351 return true;
5352 }
5353
5354 if (const auto *PN = dyn_cast<PHINode>(V)) {
5355 unsigned Num = PN->getNumIncomingValues();
5356 bool IsWellDefined = true;
5357 for (unsigned i = 0; i < Num; ++i) {
5358 auto *TI = PN->getIncomingBlock(i)->getTerminator();
5359 if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
5360 DT, Depth + 1, PoisonOnly)) {
5361 IsWellDefined = false;
5362 break;
5363 }
5364 }
5365 if (IsWellDefined)
5366 return true;
5367 } else if (!canCreateUndefOrPoison(Opr) && all_of(Opr->operands(), OpCheck))
5368 return true;
5369 }
5370
5371 if (auto *I = dyn_cast<LoadInst>(V))
5372 if (I->hasMetadata(LLVMContext::MD_noundef) ||
5373 I->hasMetadata(LLVMContext::MD_dereferenceable) ||
5374 I->hasMetadata(LLVMContext::MD_dereferenceable_or_null))
5375 return true;
5376
5377 if (programUndefinedIfUndefOrPoison(V, PoisonOnly))
5378 return true;
5379
5380 // CxtI may be null or a cloned instruction.
5381 if (!CtxI || !CtxI->getParent() || !DT)
5382 return false;
5383
5384 auto *DNode = DT->getNode(CtxI->getParent());
5385 if (!DNode)
5386 // Unreachable block
5387 return false;
5388
5389 // If V is used as a branch condition before reaching CtxI, V cannot be
5390 // undef or poison.
5391 // br V, BB1, BB2
5392 // BB1:
5393 // CtxI ; V cannot be undef or poison here
5394 auto *Dominator = DNode->getIDom();
5395 while (Dominator) {
5396 auto *TI = Dominator->getBlock()->getTerminator();
5397
5398 Value *Cond = nullptr;
5399 if (auto BI = dyn_cast_or_null<BranchInst>(TI)) {
5400 if (BI->isConditional())
5401 Cond = BI->getCondition();
5402 } else if (auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
5403 Cond = SI->getCondition();
5404 }
5405
5406 if (Cond) {
5407 if (Cond == V)
5408 return true;
5409 else if (PoisonOnly && isa<Operator>(Cond)) {
5410 // For poison, we can analyze further
5411 auto *Opr = cast<Operator>(Cond);
5412 if (propagatesPoison(Opr) && is_contained(Opr->operand_values(), V))
5413 return true;
5414 }
5415 }
5416
5417 Dominator = Dominator->getIDom();
5418 }
5419
5420 if (getKnowledgeValidInContext(V, {Attribute::NoUndef}, CtxI, DT, AC))
5421 return true;
5422
5423 return false;
5424}
5425
5426bool llvm::isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC,
5427 const Instruction *CtxI,
5428 const DominatorTree *DT,
5429 unsigned Depth) {
5430 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth, false);
5431}
5432
5433bool llvm::isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC,
5434 const Instruction *CtxI,
5435 const DominatorTree *DT, unsigned Depth) {
5436 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth, true);
5437}
5438
5439OverflowResult llvm::computeOverflowForSignedAdd(const AddOperator *Add,
5440 const DataLayout &DL,
5441 AssumptionCache *AC,
5442 const Instruction *CxtI,
5443 const DominatorTree *DT) {
5444 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
5445 Add, DL, AC, CxtI, DT);
5446}
5447
5448OverflowResult llvm::computeOverflowForSignedAdd(const Value *LHS,
5449 const Value *RHS,
5450 const DataLayout &DL,
5451 AssumptionCache *AC,
5452 const Instruction *CxtI,
5453 const DominatorTree *DT) {
5454 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, DL, AC, CxtI, DT);
5455}
5456
5457bool llvm::isGuaranteedToTransferExecutionToSuccessor(const Instruction *I) {
5458 // Note: An atomic operation isn't guaranteed to return in a reasonable amount
5459 // of time because it's possible for another thread to interfere with it for an
5460 // arbitrary length of time, but programs aren't allowed to rely on that.
5461
5462 // If there is no successor, then execution can't transfer to it.
5463 if (isa<ReturnInst>(I))
5464 return false;
5465 if (isa<UnreachableInst>(I))
5466 return false;
5467
5468 // Note: Do not add new checks here; instead, change Instruction::mayThrow or
5469 // Instruction::willReturn.
5470 //
5471 // FIXME: Move this check into Instruction::willReturn.
5472 if (isa<CatchPadInst>(I)) {
5473 switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) {
5474 default:
5475 // A catchpad may invoke exception object constructors and such, which
5476 // in some languages can be arbitrary code, so be conservative by default.
5477 return false;
5478 case EHPersonality::CoreCLR:
5479 // For CoreCLR, it just involves a type test.
5480 return true;
5481 }
5482 }
5483
5484 // An instruction that returns without throwing must transfer control flow
5485 // to a successor.
5486 return !I->mayThrow() && I->willReturn();
5487}
5488
5489bool llvm::isGuaranteedToTransferExecutionToSuccessor(const BasicBlock *BB) {
5490 // TODO: This is slightly conservative for invoke instruction since exiting
5491 // via an exception *is* normal control for them.
5492 for (const Instruction &I : *BB)
5493 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5494 return false;
5495 return true;
5496}
5497
5498bool llvm::isGuaranteedToTransferExecutionToSuccessor(
5499 BasicBlock::const_iterator Begin, BasicBlock::const_iterator End,
5500 unsigned ScanLimit) {
5501 return isGuaranteedToTransferExecutionToSuccessor(make_range(Begin, End),
5502 ScanLimit);
5503}
5504
5505bool llvm::isGuaranteedToTransferExecutionToSuccessor(
5506 iterator_range<BasicBlock::const_iterator> Range, unsigned ScanLimit) {
5507 assert(ScanLimit && "scan limit must be non-zero")(static_cast <bool> (ScanLimit && "scan limit must be non-zero"
) ? void (0) : __assert_fail ("ScanLimit && \"scan limit must be non-zero\""
, "llvm/lib/Analysis/ValueTracking.cpp", 5507, __extension__ __PRETTY_FUNCTION__
))
;
5508 for (const Instruction &I : Range) {
5509 if (isa<DbgInfoIntrinsic>(I))
5510 continue;
5511 if (--ScanLimit == 0)
5512 return false;
5513 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5514 return false;
5515 }
5516 return true;
5517}
5518
5519bool llvm::isGuaranteedToExecuteForEveryIteration(const Instruction *I,
5520 const Loop *L) {
5521 // The loop header is guaranteed to be executed for every iteration.
5522 //
5523 // FIXME: Relax this constraint to cover all basic blocks that are
5524 // guaranteed to be executed at every iteration.
5525 if (I->getParent() != L->getHeader()) return false;
5526
5527 for (const Instruction &LI : *L->getHeader()) {
5528 if (&LI == I) return true;
5529 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
5530 }
5531 llvm_unreachable("Instruction not contained in its own parent basic block.")::llvm::llvm_unreachable_internal("Instruction not contained in its own parent basic block."
, "llvm/lib/Analysis/ValueTracking.cpp", 5531)
;
5532}
5533
5534bool llvm::propagatesPoison(const Operator *I) {
5535 switch (I->getOpcode()) {
5536 case Instruction::Freeze:
5537 case Instruction::Select:
5538 case Instruction::PHI:
5539 case Instruction::Invoke:
5540 return false;
5541 case Instruction::Call:
5542 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
5543 switch (II->getIntrinsicID()) {
5544 // TODO: Add more intrinsics.
5545 case Intrinsic::sadd_with_overflow:
5546 case Intrinsic::ssub_with_overflow:
5547 case Intrinsic::smul_with_overflow:
5548 case Intrinsic::uadd_with_overflow:
5549 case Intrinsic::usub_with_overflow:
5550 case Intrinsic::umul_with_overflow:
5551 // If an input is a vector containing a poison element, the
5552 // two output vectors (calculated results, overflow bits)'
5553 // corresponding lanes are poison.
5554 return true;
5555 case Intrinsic::ctpop:
5556 return true;
5557 }
5558 }
5559 return false;
5560 case Instruction::ICmp:
5561 case Instruction::FCmp:
5562 case Instruction::GetElementPtr:
5563 return true;
5564 default:
5565 if (isa<BinaryOperator>(I) || isa<UnaryOperator>(I) || isa<CastInst>(I))
5566 return true;
5567
5568 // Be conservative and return false.
5569 return false;
5570 }
5571}
5572
5573void llvm::getGuaranteedWellDefinedOps(
5574 const Instruction *I, SmallPtrSetImpl<const Value *> &Operands) {
5575 switch (I->getOpcode()) {
5576 case Instruction::Store:
5577 Operands.insert(cast<StoreInst>(I)->getPointerOperand());
5578 break;
5579
5580 case Instruction::Load:
5581 Operands.insert(cast<LoadInst>(I)->getPointerOperand());
5582 break;
5583
5584 // Since dereferenceable attribute imply noundef, atomic operations
5585 // also implicitly have noundef pointers too
5586 case Instruction::AtomicCmpXchg:
5587 Operands.insert(cast<AtomicCmpXchgInst>(I)->getPointerOperand());
5588 break;
5589
5590 case Instruction::AtomicRMW:
5591 Operands.insert(cast<AtomicRMWInst>(I)->getPointerOperand());
5592 break;
5593
5594 case Instruction::Call:
5595 case Instruction::Invoke: {
5596 const CallBase *CB = cast<CallBase>(I);
5597 if (CB->isIndirectCall())
5598 Operands.insert(CB->getCalledOperand());
5599 for (unsigned i = 0; i < CB->arg_size(); ++i) {
5600 if (CB->paramHasAttr(i, Attribute::NoUndef) ||
5601 CB->paramHasAttr(i, Attribute::Dereferenceable))
5602 Operands.insert(CB->getArgOperand(i));
5603 }
5604 break;
5605 }
5606 case Instruction::Ret:
5607 if (I->getFunction()->hasRetAttribute(Attribute::NoUndef))
5608 Operands.insert(I->getOperand(0));
5609 break;
5610 default:
5611 break;
5612 }
5613}
5614
5615void llvm::getGuaranteedNonPoisonOps(const Instruction *I,
5616 SmallPtrSetImpl<const Value *> &Operands) {
5617 getGuaranteedWellDefinedOps(I, Operands);
5618 switch (I->getOpcode()) {
5619 // Divisors of these operations are allowed to be partially undef.
5620 case Instruction::UDiv:
5621 case Instruction::SDiv:
5622 case Instruction::URem:
5623 case Instruction::SRem:
5624 Operands.insert(I->getOperand(1));
5625 break;
5626 case Instruction::Switch:
5627 if (BranchOnPoisonAsUB)
5628 Operands.insert(cast<SwitchInst>(I)->getCondition());
5629 break;
5630 case Instruction::Br: {
5631 auto *BR = cast<BranchInst>(I);
5632 if (BranchOnPoisonAsUB && BR->isConditional())
5633 Operands.insert(BR->getCondition());
5634 break;
5635 }
5636 default:
5637 break;
5638 }
5639}
5640
5641bool llvm::mustTriggerUB(const Instruction *I,
5642 const SmallSet<const Value *, 16>& KnownPoison) {
5643 SmallPtrSet<const Value *, 4> NonPoisonOps;
5644 getGuaranteedNonPoisonOps(I, NonPoisonOps);
5645
5646 for (const auto *V : NonPoisonOps)
5647 if (KnownPoison.count(V))
5648 return true;
5649
5650 return false;
5651}
5652
5653static bool programUndefinedIfUndefOrPoison(const Value *V,
5654 bool PoisonOnly) {
5655 // We currently only look for uses of values within the same basic
5656 // block, as that makes it easier to guarantee that the uses will be
5657 // executed given that Inst is executed.
5658 //
5659 // FIXME: Expand this to consider uses beyond the same basic block. To do
5660 // this, look out for the distinction between post-dominance and strong
5661 // post-dominance.
5662 const BasicBlock *BB = nullptr;
5663 BasicBlock::const_iterator Begin;
5664 if (const auto *Inst = dyn_cast<Instruction>(V)) {
5665 BB = Inst->getParent();
5666 Begin = Inst->getIterator();
5667 Begin++;
5668 } else if (const auto *Arg = dyn_cast<Argument>(V)) {
5669 BB = &Arg->getParent()->getEntryBlock();
5670 Begin = BB->begin();
5671 } else {
5672 return false;
5673 }
5674
5675 // Limit number of instructions we look at, to avoid scanning through large
5676 // blocks. The current limit is chosen arbitrarily.
5677 unsigned ScanLimit = 32;
5678 BasicBlock::const_iterator End = BB->end();
5679
5680 if (!PoisonOnly) {
5681 // Since undef does not propagate eagerly, be conservative & just check
5682 // whether a value is directly passed to an instruction that must take
5683 // well-defined operands.
5684
5685 for (const auto &I : make_range(Begin, End)) {
5686 if (isa<DbgInfoIntrinsic>(I))
5687 continue;
5688 if (--ScanLimit == 0)
5689 break;
5690
5691 SmallPtrSet<const Value *, 4> WellDefinedOps;
5692 getGuaranteedWellDefinedOps(&I, WellDefinedOps);
5693 if (WellDefinedOps.contains(V))
5694 return true;
5695
5696 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5697 break;
5698 }
5699 return false;
5700 }
5701
5702 // Set of instructions that we have proved will yield poison if Inst
5703 // does.
5704 SmallSet<const Value *, 16> YieldsPoison;
5705 SmallSet<const BasicBlock *, 4> Visited;
5706
5707 YieldsPoison.insert(V);
5708 Visited.insert(BB);
5709
5710 while (true) {
5711 for (const auto &I : make_range(Begin, End)) {
5712 if (isa<DbgInfoIntrinsic>(I))
5713 continue;
5714 if (--ScanLimit == 0)
5715 return false;
5716 if (mustTriggerUB(&I, YieldsPoison))
5717 return true;
5718 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
5719 return false;
5720
5721 // If this instruction propagates poison, mark it as poison if any of
5722 // its operands are poison
5723 if (propagatesPoison(cast<Operator>(&I))) {
5724 for (const Value *Op : I.operands()) {
5725 if (YieldsPoison.count(Op)) {
5726 YieldsPoison.insert(&I);
5727 break;
5728 }
5729 }
5730 }
5731 }
5732
5733