LLVM 24.0.0git
ValueTracking.cpp
Go to the documentation of this file.
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
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/ScopeExit.h"
22#include "llvm/ADT/StringRef.h"
32#include "llvm/Analysis/Loads.h"
37#include "llvm/IR/Argument.h"
38#include "llvm/IR/Attributes.h"
39#include "llvm/IR/BasicBlock.h"
41#include "llvm/IR/Constant.h"
44#include "llvm/IR/Constants.h"
47#include "llvm/IR/Dominators.h"
49#include "llvm/IR/Function.h"
51#include "llvm/IR/GlobalAlias.h"
52#include "llvm/IR/GlobalValue.h"
54#include "llvm/IR/InstrTypes.h"
55#include "llvm/IR/Instruction.h"
58#include "llvm/IR/Intrinsics.h"
59#include "llvm/IR/IntrinsicsAArch64.h"
60#include "llvm/IR/IntrinsicsAMDGPU.h"
61#include "llvm/IR/IntrinsicsRISCV.h"
62#include "llvm/IR/IntrinsicsX86.h"
63#include "llvm/IR/LLVMContext.h"
64#include "llvm/IR/Metadata.h"
65#include "llvm/IR/Module.h"
66#include "llvm/IR/Operator.h"
68#include "llvm/IR/Type.h"
69#include "llvm/IR/User.h"
70#include "llvm/IR/Value.h"
80#include <algorithm>
81#include <cassert>
82#include <cstdint>
83#include <optional>
84#include <utility>
85
86using namespace llvm;
87using namespace llvm::PatternMatch;
88
89// Controls the number of uses of the value searched for possible
90// dominating comparisons.
91static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
92 cl::Hidden, cl::init(20));
93
94/// Maximum number of instructions to check between assume and context
95/// instruction.
96static constexpr unsigned MaxInstrsToCheckForFree = 32;
97
98/// Returns the bitwidth of the given scalar or pointer type. For vector types,
99/// returns the element type's bitwidth.
100static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
101 if (unsigned BitWidth = Ty->getScalarSizeInBits())
102 return BitWidth;
103
104 return DL.getPointerTypeSizeInBits(Ty);
105}
106
107// Given the provided Value and, potentially, a context instruction, return
108// the preferred context instruction (if any).
109static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
110 // If we've been provided with a context instruction, then use that (provided
111 // it has been inserted).
112 if (CxtI && CxtI->getParent())
113 return CxtI;
114
115 // If the value is really an already-inserted instruction, then use that.
116 CxtI = dyn_cast<Instruction>(V);
117 if (CxtI && CxtI->getParent())
118 return CxtI;
119
120 return nullptr;
121}
122
124 const APInt &DemandedElts,
125 APInt &DemandedLHS, APInt &DemandedRHS) {
126 if (isa<ScalableVectorType>(Shuf->getType())) {
127 assert(DemandedElts == APInt(1,1));
128 DemandedLHS = DemandedRHS = DemandedElts;
129 return true;
130 }
131
132 int NumElts =
133 cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
134 return llvm::getShuffleDemandedElts(NumElts, Shuf->getShuffleMask(),
135 DemandedElts, DemandedLHS, DemandedRHS);
136}
137
138static void computeKnownBits(const Value *V, const APInt &DemandedElts,
139 KnownBits &Known, const SimplifyQuery &Q,
140 unsigned Depth);
141
143 const SimplifyQuery &Q, unsigned Depth) {
144 // Since the number of lanes in a scalable vector is unknown at compile time,
145 // we track one bit which is implicitly broadcast to all lanes. This means
146 // that all lanes in a scalable vector are considered demanded.
147 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
148 APInt DemandedElts =
149 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
150 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
151}
152
154 const DataLayout &DL, AssumptionCache *AC,
155 const Instruction *CxtI, const DominatorTree *DT,
156 bool UseInstrInfo, unsigned Depth) {
158 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo),
159 Depth);
160}
161
163 AssumptionCache *AC, const Instruction *CxtI,
164 const DominatorTree *DT, bool UseInstrInfo,
165 unsigned Depth) {
166 return computeKnownBits(
167 V, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
168}
169
170KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
171 const DataLayout &DL, AssumptionCache *AC,
172 const Instruction *CxtI,
173 const DominatorTree *DT, bool UseInstrInfo,
174 unsigned Depth) {
175 return computeKnownBits(
176 V, DemandedElts,
177 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
178}
179
182 const SimplifyQuery &SQ) {
183 // Look for an inverted mask: (X & ~M) op (Y & M).
184 {
185 Value *M;
186 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
188 return isGuaranteedNotToBeUndef(M, SQ.AC, SQ.CxtI, SQ.DT)
191 }
192
193 // X op (Y & ~X)
195 return isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT)
198
199 // X op ((X & Y) ^ Y) -- this is the canonical form of the previous pattern
200 // for constant Y.
201 Value *Y;
202 if (match(RHS,
204 bool IsNoUndef = isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT) &&
205 isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CxtI, SQ.DT);
206 return IsNoUndef ? NoCommonBitsSetResult::Known
208 }
209
210 // Peek through extends to find a 'not' of the other side:
211 // (ext Y) op ext(~Y)
212 if (match(LHS, m_ZExtOrSExt(m_Value(Y))) &&
214 return isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CxtI, SQ.DT)
217
218 // Look for: (A & B) op ~(A | B)
219 {
220 Value *A, *B;
221 if (match(LHS, m_And(m_Value(A), m_Value(B))) &&
223 bool IsNoUndef = isGuaranteedNotToBeUndef(A, SQ.AC, SQ.CxtI, SQ.DT) &&
224 isGuaranteedNotToBeUndef(B, SQ.AC, SQ.CxtI, SQ.DT);
225 return IsNoUndef ? NoCommonBitsSetResult::Known
227 }
228 }
229
230 // Look for: (X << V) op (Y >> (BitWidth - V))
231 // or (X >> V) op (Y << (BitWidth - V))
232 {
233 const Value *V;
234 const APInt *R;
235 if (((match(RHS, m_Shl(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
236 match(LHS, m_LShr(m_Value(), m_Specific(V)))) ||
237 (match(RHS, m_LShr(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
238 match(LHS, m_Shl(m_Value(), m_Specific(V))))) &&
239 R->uge(LHS->getType()->getScalarSizeInBits()))
241 }
242
244}
245
248 const WithCache<const Value *> &RHSCache,
249 const SimplifyQuery &SQ) {
250 const Value *LHS = LHSCache.getValue();
251 const Value *RHS = RHSCache.getValue();
252
253 assert(LHS->getType() == RHS->getType() &&
254 "LHS and RHS should have the same type");
255 assert(LHS->getType()->isIntOrIntVectorTy() &&
256 "LHS and RHS should be integers");
257
259 if (Result == NoCommonBitsSetResult::Known)
261
262 NoCommonBitsSetResult CommuteResult =
264 if (CommuteResult == NoCommonBitsSetResult::Known)
266
268 RHSCache.getKnownBits(SQ)))
270
274
276}
277
279 const WithCache<const Value *> &RHSCache,
280 const SimplifyQuery &SQ) {
281 NoCommonBitsSetResult Result =
282 getNoCommonBitsSetResult(LHSCache, RHSCache, SQ);
283 return Result == NoCommonBitsSetResult::Known;
284}
285
287 return !I->user_empty() &&
288 all_of(I->users(), match_fn(m_ICmp(m_Value(), m_Zero())));
289}
290
292 return !I->user_empty() && all_of(I->users(), [](const User *U) {
293 CmpPredicate P;
294 return match(U, m_ICmp(P, m_Value(), m_Zero())) && ICmpInst::isEquality(P);
295 });
296}
297
299 bool OrZero, AssumptionCache *AC,
300 const Instruction *CxtI,
301 const DominatorTree *DT, bool UseInstrInfo,
302 unsigned Depth) {
303 return ::isKnownToBeAPowerOfTwo(
304 V, OrZero, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo),
305 Depth);
306}
307
308static bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
309 const SimplifyQuery &Q, unsigned Depth);
310
312 unsigned Depth) {
313 return computeKnownBits(V, SQ, Depth).isNonNegative();
314}
315
317 unsigned Depth) {
318 if (auto *CI = dyn_cast<ConstantInt>(V))
319 return CI->getValue().isStrictlyPositive();
320
321 // If `isKnownNonNegative` ever becomes more sophisticated, make sure to keep
322 // this updated.
324 return Known.isNonNegative() &&
325 (Known.isNonZero() || isKnownNonZero(V, SQ, Depth));
326}
327
329 unsigned Depth) {
330 return computeKnownBits(V, SQ, Depth).isNegative();
331}
332
333static bool isKnownNonEqual(const Value *V1, const Value *V2,
334 const APInt &DemandedElts, const SimplifyQuery &Q,
335 unsigned Depth);
336
337static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
338 const Value *RHS);
339
340bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
341 const SimplifyQuery &Q, unsigned Depth) {
342 // We don't support looking through casts.
343 if (V1 == V2 || V1->getType() != V2->getType())
344 return false;
345 auto *FVTy = dyn_cast<FixedVectorType>(V1->getType());
346 APInt DemandedElts =
347 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
348 return ::isKnownNonEqual(V1, V2, DemandedElts, Q, Depth);
349}
350
351bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
352 const SimplifyQuery &SQ, unsigned Depth) {
353 KnownBits Known(Mask.getBitWidth());
355 return Mask.isSubsetOf(Known.Zero);
356}
357
358static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
359 const SimplifyQuery &Q, unsigned Depth);
360
361static unsigned ComputeNumSignBits(const Value *V, const SimplifyQuery &Q,
362 unsigned Depth = 0) {
363 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
364 APInt DemandedElts =
365 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
366 return ComputeNumSignBits(V, DemandedElts, Q, Depth);
367}
368
369unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
370 AssumptionCache *AC, const Instruction *CxtI,
371 const DominatorTree *DT, bool UseInstrInfo,
372 unsigned Depth) {
373 return ::ComputeNumSignBits(
374 V, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
375}
376
378 AssumptionCache *AC,
379 const Instruction *CxtI,
380 const DominatorTree *DT,
381 unsigned Depth) {
382 unsigned SignBits = ComputeNumSignBits(V, DL, AC, CxtI, DT, Depth);
383 return V->getType()->getScalarSizeInBits() - SignBits + 1;
384}
385
386/// Try to detect the lerp pattern: a * (b - c) + c * d
387/// where a >= 0, b >= 0, c >= 0, d >= 0, and b >= c.
388///
389/// In that particular case, we can use the following chain of reasoning:
390///
391/// a * (b - c) + c * d <= a' * (b - c) + a' * c = a' * b where a' = max(a, d)
392///
393/// Since that is true for arbitrary a, b, c and d within our constraints, we
394/// can conclude that:
395///
396/// max(a * (b - c) + c * d) <= max(max(a), max(d)) * max(b) = U
397///
398/// Considering that any result of the lerp would be less or equal to U, it
399/// would have at least the number of leading 0s as in U.
400///
401/// While being quite a specific situation, it is fairly common in computer
402/// graphics in the shape of alpha blending.
403///
404/// Modifies given KnownOut in-place with the inferred information.
405static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1,
406 const APInt &DemandedElts,
407 KnownBits &KnownOut,
408 const SimplifyQuery &Q,
409 unsigned Depth) {
410
411 Type *Ty = Op0->getType();
412 const unsigned BitWidth = Ty->getScalarSizeInBits();
413
414 // Only handle scalar types for now
415 if (Ty->isVectorTy())
416 return;
417
418 // Try to match: a * (b - c) + c * d.
419 // When a == 1 => A == nullptr, the same applies to d/D as well.
420 const Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
421 const Instruction *SubBC = nullptr;
422
423 const auto MatchSubBC = [&]() {
424 // (b - c) can have two forms that interest us:
425 //
426 // 1. sub nuw %b, %c
427 // 2. xor %c, %b
428 //
429 // For the first case, nuw flag guarantees our requirement b >= c.
430 //
431 // The second case might happen when the analysis can infer that b is a mask
432 // for c and we can transform sub operation into xor (that is usually true
433 // for constant b's). Even though xor is symmetrical, canonicalization
434 // ensures that the constant will be the RHS. We have additional checks
435 // later on to ensure that this xor operation is equivalent to subtraction.
437 m_Xor(m_Value(C), m_Value(B))));
438 };
439
440 const auto MatchASubBC = [&]() {
441 // Cases:
442 // - a * (b - c)
443 // - (b - c) * a
444 // - (b - c) <- a implicitly equals 1
445 return m_CombineOr(m_c_Mul(m_Value(A), MatchSubBC()), MatchSubBC());
446 };
447
448 const auto MatchCD = [&]() {
449 // Cases:
450 // - d * c
451 // - c * d
452 // - c <- d implicitly equals 1
454 };
455
456 const auto Match = [&](const Value *LHS, const Value *RHS) {
457 // We do use m_Specific(C) in MatchCD, so we have to make sure that
458 // it's bound to anything and match(LHS, MatchASubBC()) absolutely
459 // has to evaluate first and return true.
460 //
461 // If Match returns true, it is guaranteed that B != nullptr, C != nullptr.
462 return match(LHS, MatchASubBC()) && match(RHS, MatchCD());
463 };
464
465 if (!Match(Op0, Op1) && !Match(Op1, Op0))
466 return;
467
468 const auto ComputeKnownBitsOrOne = [&](const Value *V) {
469 // For some of the values we use the convention of leaving
470 // it nullptr to signify an implicit constant 1.
471 return V ? computeKnownBits(V, DemandedElts, Q, Depth + 1)
473 };
474
475 // Check that all operands are non-negative
476 const KnownBits KnownA = ComputeKnownBitsOrOne(A);
477 if (!KnownA.isNonNegative())
478 return;
479
480 const KnownBits KnownD = ComputeKnownBitsOrOne(D);
481 if (!KnownD.isNonNegative())
482 return;
483
484 const KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
485 if (!KnownB.isNonNegative())
486 return;
487
488 const KnownBits KnownC = computeKnownBits(C, DemandedElts, Q, Depth + 1);
489 if (!KnownC.isNonNegative())
490 return;
491
492 // If we matched subtraction as xor, we need to actually check that xor
493 // is semantically equivalent to subtraction.
494 //
495 // For that to be true, b has to be a mask for c or that b's known
496 // ones cover all known and possible ones of c.
497 if (SubBC->getOpcode() == Instruction::Xor &&
498 !KnownC.getMaxValue().isSubsetOf(KnownB.getMinValue()))
499 return;
500
501 const APInt MaxA = KnownA.getMaxValue();
502 const APInt MaxD = KnownD.getMaxValue();
503 const APInt MaxAD = APIntOps::umax(MaxA, MaxD);
504 const APInt MaxB = KnownB.getMaxValue();
505
506 // We can't infer leading zeros info if the upper-bound estimate wraps.
507 bool Overflow;
508 const APInt UpperBound = MaxAD.umul_ov(MaxB, Overflow);
509
510 if (Overflow)
511 return;
512
513 // If we know that x <= y and both are positive than x has at least the same
514 // number of leading zeros as y.
515 const unsigned MinimumNumberOfLeadingZeros = UpperBound.countl_zero();
516 KnownOut.Zero.setHighBits(MinimumNumberOfLeadingZeros);
517}
518
519static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
520 bool NSW, bool NUW,
521 const APInt &DemandedElts,
522 KnownBits &KnownOut, KnownBits &Known2,
523 const SimplifyQuery &Q, unsigned Depth) {
524 computeKnownBits(Op1, DemandedElts, KnownOut, Q, Depth + 1);
525
526 // If one operand is unknown and we have no nowrap information,
527 // the result will be unknown independently of the second operand.
528 if (KnownOut.isUnknown() && !NSW && !NUW)
529 return;
530
531 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
532 KnownOut = KnownBits::computeForAddSub(Add, NSW, NUW, Known2, KnownOut);
533
534 if (!Add && NSW && !KnownOut.isNonNegative() &&
536 .value_or(false) ||
537 match(Op1, m_c_SMin(m_Specific(Op0), m_Value()))))
538 KnownOut.makeNonNegative();
539
540 if (Add)
541 // Try to match lerp pattern and combine results
542 computeKnownBitsFromLerpPattern(Op0, Op1, DemandedElts, KnownOut, Q, Depth);
543}
544
545static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
546 bool NUW, const APInt &DemandedElts,
547 KnownBits &Known, KnownBits &Known2,
548 const SimplifyQuery &Q, unsigned Depth) {
549 computeKnownBits(Op1, DemandedElts, Known, Q, Depth + 1);
550 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
551
552 bool isKnownNegative = false;
553 bool isKnownNonNegative = false;
554 // If the multiplication is known not to overflow, compute the sign bit.
555 if (NSW) {
556 if (Op0 == Op1) {
557 // The product of a number with itself is non-negative.
558 isKnownNonNegative = true;
559 } else {
560 bool isKnownNonNegativeOp1 = Known.isNonNegative();
561 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
562 bool isKnownNegativeOp1 = Known.isNegative();
563 bool isKnownNegativeOp0 = Known2.isNegative();
564 // The product of two numbers with the same sign is non-negative.
565 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
566 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
567 if (!isKnownNonNegative && NUW) {
568 // mul nuw nsw with a factor > 1 is non-negative.
569 KnownBits One = KnownBits::makeConstant(APInt(Known.getBitWidth(), 1));
570 isKnownNonNegative = KnownBits::sgt(Known, One).value_or(false) ||
571 KnownBits::sgt(Known2, One).value_or(false);
572 }
573
574 // The product of a negative number and a non-negative number is either
575 // negative or zero.
578 (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
579 Known2.isNonZero()) ||
580 (isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.isNonZero());
581 }
582 }
583
584 bool SelfMultiply = Op0 == Op1;
585 if (SelfMultiply)
586 SelfMultiply &=
587 isGuaranteedNotToBeUndef(Op0, Q.AC, Q.CxtI, Q.DT, Depth + 1);
588 Known = KnownBits::mul(Known, Known2, SelfMultiply);
589
590 if (SelfMultiply) {
591 unsigned SignBits = ComputeNumSignBits(Op0, DemandedElts, Q, Depth + 1);
592 unsigned TyBits = Op0->getType()->getScalarSizeInBits();
593 unsigned OutValidBits = 2 * (TyBits - SignBits + 1);
594
595 if (OutValidBits < TyBits) {
596 APInt KnownZeroMask =
597 APInt::getHighBitsSet(TyBits, TyBits - OutValidBits + 1);
598 Known.Zero |= KnownZeroMask;
599 }
600 }
601
602 // Only make use of no-wrap flags if we failed to compute the sign bit
603 // directly. This matters if the multiplication always overflows, in
604 // which case we prefer to follow the result of the direct computation,
605 // though as the program is invoking undefined behaviour we can choose
606 // whatever we like here.
607 if (isKnownNonNegative && !Known.isNegative())
608 Known.makeNonNegative();
609 else if (isKnownNegative && !Known.isNonNegative())
610 Known.makeNegative();
611}
612
614 KnownBits &Known) {
615 unsigned BitWidth = Known.getBitWidth();
616 unsigned NumRanges = Ranges.getNumOperands() / 2;
617 assert(NumRanges >= 1);
618
619 Known.setAllConflict();
620
621 for (unsigned i = 0; i < NumRanges; ++i) {
623 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
625 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
626 ConstantRange Range(Lower->getValue(), Upper->getValue());
627 // BitWidth must equal the Ranges BitWidth for the correct number of high
628 // bits to be set.
629 assert(BitWidth == Range.getBitWidth() &&
630 "Known bit width must match range bit width!");
631
632 // The first CommonPrefixBits of all values in Range are equal.
633 unsigned CommonPrefixBits =
634 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countl_zero();
635 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
636 APInt UnsignedMax = Range.getUnsignedMax().zextOrTrunc(BitWidth);
637 Known.One &= UnsignedMax & Mask;
638 Known.Zero &= ~UnsignedMax & Mask;
639 }
640}
641
642static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
643 // The instruction defining an assumption's condition itself is always
644 // considered ephemeral to that assumption (even if it has other
645 // non-ephemeral users). See r246696's test case for an example.
646 if (is_contained(I->operands(), E))
647 return true;
648
649 const auto *EI = dyn_cast<Instruction>(E);
650 if (!EI)
651 return false;
652
653 if (EI == I)
654 return true;
655
658 Visited.insert(EI);
659 WorkList.push_back(EI);
660 bool ReachesI = false;
661 while (!WorkList.empty()) {
662 const Instruction *V = WorkList.pop_back_val();
663 for (const User *U : V->users()) {
664 const auto *UI = cast<Instruction>(U);
665 if (UI == I) {
666 ReachesI = true;
667 continue;
668 }
669 if (UI->mayHaveSideEffects() || UI->isTerminator())
670 return false;
671 if (Visited.insert(UI).second)
672 WorkList.push_back(UI);
673 }
674 }
675 return ReachesI;
676}
677
678// Is this an intrinsic that cannot be speculated but also cannot trap?
680 if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(I))
681 return CI->isAssumeLikeIntrinsic();
682
683 return false;
684}
685
687 const Instruction *CxtI,
688 const DominatorTree *DT,
689 bool AllowEphemerals) {
690 // There are two restrictions on the use of an assume:
691 // 1. The assume must dominate the context (or the control flow must
692 // reach the assume whenever it reaches the context).
693 // 2. The context must not be in the assume's set of ephemeral values
694 // (otherwise we will use the assume to prove that the condition
695 // feeding the assume is trivially true, thus causing the removal of
696 // the assume).
697
698 if (Inv->getParent() == CxtI->getParent()) {
699 // If Inv and CtxI are in the same block, check if the assume (Inv) is first
700 // in the BB.
701 if (Inv->comesBefore(CxtI))
702 return true;
703
704 // Don't let an assume affect itself - this would cause the problems
705 // `isEphemeralValueOf` is trying to prevent, and it would also make
706 // the loop below go out of bounds.
707 if (!AllowEphemerals && Inv == CxtI)
708 return false;
709
710 // The context comes first, but they're both in the same block.
711 // Make sure there is nothing in between that might interrupt
712 // the control flow, not even CxtI itself.
713 // We limit the scan distance between the assume and its context instruction
714 // to avoid a compile-time explosion. This limit is chosen arbitrarily, so
715 // it can be adjusted if needed (could be turned into a cl::opt).
716 auto Range = make_range(CxtI->getIterator(), Inv->getIterator());
718 return false;
719
720 return AllowEphemerals || !isEphemeralValueOf(Inv, CxtI);
721 }
722
723 // Inv and CxtI are in different blocks.
724 if (DT) {
725 if (DT->dominates(Inv, CxtI))
726 return true;
727 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor() ||
728 Inv->getParent()->isEntryBlock()) {
729 // We don't have a DT, but this trivially dominates.
730 return true;
731 }
732
733 return false;
734}
735
737 const Instruction *CtxI) {
738 // Helper to check if there are any calls in the range that may free memory.
739 unsigned NumChecked = 0;
740 auto hasNoFreeInRange = [&NumChecked](auto Range) {
741 for (const Instruction &I : Range) {
742 if (NumChecked++ > MaxInstrsToCheckForFree)
743 return false;
744
745 if (auto *CB = dyn_cast<CallBase>(&I)) {
746 if (!CB->hasFnAttr(Attribute::NoFree))
747 return false;
748 } else if (I.maySynchronize())
749 return false;
750 }
751 return true;
752 };
753
754 const BasicBlock *CtxBB = CtxI->getParent();
755 const BasicBlock *AssumeBB = Assume->getParent();
756 BasicBlock::const_iterator CtxIter = CtxI->getIterator();
757 if (CtxBB == AssumeBB) {
758 // Same block case: check that Assume comes before CtxI.
759 if (Assume != CtxI && !Assume->comesBefore(CtxI))
760 return false;
761 return hasNoFreeInRange(make_range(Assume->getIterator(), CtxIter));
762 }
763
764 // Handle chain of single-predecessor blocks.
765 const BasicBlock *CurBB = CtxBB;
766 while (true) {
767 if (CurBB == AssumeBB)
768 return hasNoFreeInRange(
769 make_range(Assume->getIterator(), AssumeBB->end()));
770
771 const BasicBlock *PredBB = CurBB->getSinglePredecessor();
772 if (!PredBB)
773 return false;
774
775 if (!hasNoFreeInRange(make_range(CurBB->begin(),
776 CurBB == CtxBB ? CtxIter : CurBB->end())))
777 return false;
778 CurBB = PredBB;
779 }
780}
781
782// TODO: cmpExcludesZero misses many cases where `RHS` is non-constant but
783// we still have enough information about `RHS` to conclude non-zero. For
784// example Pred=EQ, RHS=isKnownNonZero. cmpExcludesZero is called in loops
785// so the extra compile time may not be worth it, but possibly a second API
786// should be created for use outside of loops.
787static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS) {
788 // v u> y implies v != 0.
789 if (Pred == ICmpInst::ICMP_UGT)
790 return true;
791
792 // Special-case v != 0 to also handle v != null.
793 if (Pred == ICmpInst::ICMP_NE)
794 return match(RHS, m_Zero());
795
796 // All other predicates - rely on generic ConstantRange handling.
797 const APInt *C;
798 auto Zero = APInt::getZero(RHS->getType()->getScalarSizeInBits());
799 if (match(RHS, m_APInt(C))) {
801 return !TrueValues.contains(Zero);
802 }
803
805 if (VC == nullptr)
806 return false;
807
808 for (unsigned ElemIdx = 0, NElem = VC->getNumElements(); ElemIdx < NElem;
809 ++ElemIdx) {
811 Pred, VC->getElementAsAPInt(ElemIdx));
812 if (TrueValues.contains(Zero))
813 return false;
814 }
815 return true;
816}
817
818static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI,
819 Value *&ValOut, Instruction *&CtxIOut,
820 const PHINode **PhiOut = nullptr) {
821 ValOut = U->get();
822 if (ValOut == PHI)
823 return;
824 CtxIOut = PHI->getIncomingBlock(*U)->getTerminator();
825 if (PhiOut)
826 *PhiOut = PHI;
827 Value *V;
828 // If the Use is a select of this phi, compute analysis on other arm to break
829 // recursion.
830 // TODO: Min/Max
831 if (match(ValOut, m_Select(m_Value(), m_Specific(PHI), m_Value(V))) ||
832 match(ValOut, m_Select(m_Value(), m_Value(V), m_Specific(PHI))))
833 ValOut = V;
834
835 // Same for select, if this phi is 2-operand phi, compute analysis on other
836 // incoming value to break recursion.
837 // TODO: We could handle any number of incoming edges as long as we only have
838 // two unique values.
839 if (auto *IncPhi = dyn_cast<PHINode>(ValOut);
840 IncPhi && IncPhi->getNumIncomingValues() == 2) {
841 for (int Idx = 0; Idx < 2; ++Idx) {
842 if (IncPhi->getIncomingValue(Idx) == PHI) {
843 ValOut = IncPhi->getIncomingValue(1 - Idx);
844 if (PhiOut)
845 *PhiOut = IncPhi;
846 CtxIOut = IncPhi->getIncomingBlock(1 - Idx)->getTerminator();
847 break;
848 }
849 }
850 }
851}
852
853static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q) {
854 // Use of assumptions is context-sensitive. If we don't have a context, we
855 // cannot use them!
856 if (!Q.AC || !Q.CxtI)
857 return false;
858
859 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
860 if (!Elem.Assume)
861 continue;
862
863 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
864 assert(I->getFunction() == Q.CxtI->getFunction() &&
865 "Got assumption for the wrong function!");
866
867 if (Elem.Index != AssumptionCache::ExprResultIdx) {
869 I->getOperandBundleAt(Elem.Index)) &&
871 return true;
872 continue;
873 }
874
875 // Warning: This loop can end up being somewhat performance sensitive.
876 // We're running this loop for once for each value queried resulting in a
877 // runtime of ~O(#assumes * #values).
878
879 Value *RHS;
880 CmpPredicate Pred;
881 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
882 if (!match(I->getArgOperand(0), m_c_ICmp(Pred, m_V, m_Value(RHS))))
883 continue;
884
886 return true;
887 }
888
889 return false;
890}
891
894 const SimplifyQuery &Q) {
895 if (RHS->getType()->isPointerTy()) {
896 // Handle comparison of pointer to null explicitly, as it will not be
897 // covered by the m_APInt() logic below.
898 if (LHS == V && match(RHS, m_Zero())) {
899 switch (Pred) {
901 Known.setAllZero();
902 break;
905 Known.makeNonNegative();
906 break;
908 Known.makeNegative();
909 break;
910 default:
911 break;
912 }
913 }
914 return;
915 }
916
917 unsigned BitWidth = Known.getBitWidth();
918 auto m_V =
920
921 Value *Y;
922 const APInt *Mask, *C;
923 if (!match(RHS, m_APInt(C)))
924 return;
925
926 uint64_t ShAmt;
927 switch (Pred) {
929 // assume(V = C)
930 if (match(LHS, m_V)) {
931 Known = Known.unionWith(KnownBits::makeConstant(*C));
932 // assume(V & Mask = C)
933 } else if (match(LHS, m_c_And(m_V, m_Value(Y)))) {
934 // For one bits in Mask, we can propagate bits from C to V.
935 Known.One |= *C;
936 if (match(Y, m_APInt(Mask)))
937 Known.Zero |= ~*C & *Mask;
938 // assume(V | Mask = C)
939 } else if (match(LHS, m_c_Or(m_V, m_Value(Y)))) {
940 // For zero bits in Mask, we can propagate bits from C to V.
941 Known.Zero |= ~*C;
942 if (match(Y, m_APInt(Mask)))
943 Known.One |= *C & ~*Mask;
944 // assume(V << ShAmt = C)
945 } else if (match(LHS, m_Shl(m_V, m_ConstantInt(ShAmt))) &&
946 ShAmt < BitWidth) {
947 // For those bits in C that are known, we can propagate them to known
948 // bits in V shifted to the right by ShAmt.
950 RHSKnown >>= ShAmt;
951 Known = Known.unionWith(RHSKnown);
952 // assume(V >> ShAmt = C)
953 } else if (match(LHS, m_Shr(m_V, m_ConstantInt(ShAmt))) &&
954 ShAmt < BitWidth) {
955 // For those bits in RHS that are known, we can propagate them to known
956 // bits in V shifted to the right by C.
958 RHSKnown <<= ShAmt;
959 Known = Known.unionWith(RHSKnown);
960 }
961 break;
962 case ICmpInst::ICMP_NE: {
963 // assume (V & B != 0) where B is a power of 2
964 const APInt *BPow2;
965 if (C->isZero() && match(LHS, m_And(m_V, m_Power2(BPow2))))
966 Known.One |= *BPow2;
967 break;
968 }
969 default: {
970 const APInt *Offset = nullptr;
971 if (match(LHS, m_CombineOr(m_V, m_AddLike(m_V, m_APInt(Offset))))) {
973 if (Offset)
974 LHSRange = LHSRange.sub(*Offset);
975 Known = Known.unionWith(LHSRange.toKnownBits());
976 }
977 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
978 // X & Y u> C -> X u> C && Y u> C
979 // X nuw- Y u> C -> X u> C
980 if (match(LHS, m_c_And(m_V, m_Value())) ||
981 match(LHS, m_NUWSub(m_V, m_Value())))
982 Known.One.setHighBits(
983 (*C + (Pred == ICmpInst::ICMP_UGT)).countLeadingOnes());
984 }
985 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
986 // X | Y u< C -> X u< C && Y u< C
987 // X nuw+ Y u< C -> X u< C && Y u< C
988 if (match(LHS, m_c_Or(m_V, m_Value())) ||
989 match(LHS, m_c_NUWAdd(m_V, m_Value()))) {
990 Known.Zero.setHighBits(
991 (*C - (Pred == ICmpInst::ICMP_ULT)).countLeadingZeros());
992 }
993 }
994 } break;
995 }
996}
997
998static void computeKnownBitsFromICmpCond(const Value *V, ICmpInst *Cmp,
1000 const SimplifyQuery &SQ, bool Invert) {
1001 ICmpInst::Predicate Pred =
1002 Invert ? Cmp->getInversePredicate() : Cmp->getPredicate();
1003 Value *LHS = Cmp->getOperand(0);
1004 Value *RHS = Cmp->getOperand(1);
1005
1006 // Handle icmp pred (trunc V), C
1007 if (match(LHS, m_Trunc(m_Specific(V)))) {
1008 KnownBits DstKnown(LHS->getType()->getScalarSizeInBits());
1009 computeKnownBitsFromCmp(LHS, Pred, LHS, RHS, DstKnown, SQ);
1011 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1012 else
1013 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1014 return;
1015 }
1016
1017 computeKnownBitsFromCmp(V, Pred, LHS, RHS, Known, SQ);
1018}
1019
1021 KnownBits &Known, const SimplifyQuery &SQ,
1022 bool Invert, unsigned Depth) {
1023 Value *A, *B;
1026 KnownBits Known2(Known.getBitWidth());
1027 KnownBits Known3(Known.getBitWidth());
1028 computeKnownBitsFromCond(V, A, Known2, SQ, Invert, Depth + 1);
1029 computeKnownBitsFromCond(V, B, Known3, SQ, Invert, Depth + 1);
1030 if (Invert ? match(Cond, m_LogicalOr(m_Value(), m_Value()))
1032 Known2 = Known2.unionWith(Known3);
1033 else
1034 Known2 = Known2.intersectWith(Known3);
1035 Known = Known.unionWith(Known2);
1036 return;
1037 }
1038
1039 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
1040 computeKnownBitsFromICmpCond(V, Cmp, Known, SQ, Invert);
1041 return;
1042 }
1043
1044 if (match(Cond, m_Trunc(m_Specific(V)))) {
1045 KnownBits DstKnown(1);
1046 if (Invert) {
1047 DstKnown.setAllZero();
1048 } else {
1049 DstKnown.setAllOnes();
1050 }
1052 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1053 return;
1054 }
1055 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1056 return;
1057 }
1058
1060 computeKnownBitsFromCond(V, A, Known, SQ, !Invert, Depth + 1);
1061}
1062
1064 const SimplifyQuery &Q, unsigned Depth) {
1065 // Handle injected condition.
1066 if (Q.CC && Q.CC->AffectedValues.contains(V))
1068
1069 if (!Q.CxtI)
1070 return;
1071
1072 if (Q.DC && Q.DT) {
1073 // Handle dominating conditions.
1074 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
1075 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1076 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()))
1077 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1078 /*Invert*/ false, Depth);
1079
1080 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1081 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()))
1082 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1083 /*Invert*/ true, Depth);
1084 }
1085
1086 if (Known.hasConflict())
1087 Known.resetAll();
1088 }
1089
1090 if (!Q.AC)
1091 return;
1092
1093 unsigned BitWidth = Known.getBitWidth();
1094
1095 // Note that the patterns below need to be kept in sync with the code
1096 // in AssumptionCache::updateAffectedValues.
1097
1098 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
1099 if (!Elem.Assume)
1100 continue;
1101
1102 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
1103 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
1104 "Got assumption for the wrong function!");
1105
1106 if (Elem.Index != AssumptionCache::ExprResultIdx) {
1107 if (auto OBU = I->getOperandBundleAt(Elem.Index);
1108 getBundleAttrFromOBU(OBU) == BundleAttr::Align) {
1109 auto [Ptr, _, _2, Alignment, Offset] = getAssumeAlignInfo(OBU);
1110 if (Ptr == V && Alignment && Offset && isPowerOf2_64(*Alignment) &&
1112 Known.Zero |= (*Alignment - 1) & ~*Offset;
1113 Known.One |= (*Alignment - 1) & *Offset;
1114 }
1115 }
1116 continue;
1117 }
1118
1119 // Warning: This loop can end up being somewhat performance sensitive.
1120 // We're running this loop for once for each value queried resulting in a
1121 // runtime of ~O(#assumes * #values).
1122
1123 Value *Arg = I->getArgOperand(0);
1124
1125 if (Arg == V && isValidAssumeForContext(I, Q)) {
1126 assert(BitWidth == 1 && "assume operand is not i1?");
1127 (void)BitWidth;
1128 Known.setAllOnes();
1129 return;
1130 }
1131 if (match(Arg, m_Not(m_Specific(V))) &&
1133 assert(BitWidth == 1 && "assume operand is not i1?");
1134 (void)BitWidth;
1135 Known.setAllZero();
1136 return;
1137 }
1138 auto *Trunc = dyn_cast<TruncInst>(Arg);
1139 if (Trunc && Trunc->getOperand(0) == V &&
1141 if (Trunc->hasNoUnsignedWrap()) {
1143 return;
1144 }
1145 Known.One.setBit(0);
1146 return;
1147 }
1148
1149 // The remaining tests are all recursive, so bail out if we hit the limit.
1151 continue;
1152
1153 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
1154 if (!Cmp)
1155 continue;
1156
1157 if (!isValidAssumeForContext(I, Q))
1158 continue;
1159
1160 computeKnownBitsFromICmpCond(V, Cmp, Known, Q, /*Invert=*/false);
1161 }
1162
1163 // Conflicting assumption: Undefined behavior will occur on this execution
1164 // path.
1165 if (Known.hasConflict())
1166 Known.resetAll();
1167}
1168
1169/// Compute known bits from a shift operator, including those with a
1170/// non-constant shift amount. Known is the output of this function. Known2 is a
1171/// pre-allocated temporary with the same bit width as Known and on return
1172/// contains the known bit of the shift value source. KF is an
1173/// operator-specific function that, given the known-bits and a shift amount,
1174/// compute the implied known-bits of the shift operator's result respectively
1175/// for that shift amount. The results from calling KF are conservatively
1176/// combined for all permitted shift amounts.
1178 const Operator *I, const APInt &DemandedElts, KnownBits &Known,
1179 KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth,
1180 function_ref<KnownBits(const KnownBits &, const KnownBits &, bool)> KF) {
1181 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1182 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1183 // To limit compile-time impact, only query isKnownNonZero() if we know at
1184 // least something about the shift amount.
1185 bool ShAmtNonZero =
1186 Known.isNonZero() ||
1187 (Known.getMaxValue().ult(Known.getBitWidth()) &&
1188 isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth + 1));
1189 Known = KF(Known2, Known, ShAmtNonZero);
1190}
1191
1192static KnownBits
1193getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts,
1194 const KnownBits &KnownLHS, const KnownBits &KnownRHS,
1195 const SimplifyQuery &Q, unsigned Depth) {
1196 unsigned BitWidth = KnownLHS.getBitWidth();
1197 KnownBits KnownOut(BitWidth);
1198 bool IsAnd = false;
1199 bool HasKnownOne = !KnownLHS.One.isZero() || !KnownRHS.One.isZero();
1200 Value *X = nullptr, *Y = nullptr;
1201
1202 switch (I->getOpcode()) {
1203 case Instruction::And:
1204 KnownOut = KnownLHS & KnownRHS;
1205 IsAnd = true;
1206 // and(x, -x) is common idioms that will clear all but lowest set
1207 // bit. If we have a single known bit in x, we can clear all bits
1208 // above it.
1209 // TODO: instcombine often reassociates independent `and` which can hide
1210 // this pattern. Try to match and(x, and(-x, y)) / and(and(x, y), -x).
1211 if (HasKnownOne && match(I, m_c_And(m_Value(X), m_Neg(m_Deferred(X))))) {
1212 // -(-x) == x so using whichever (LHS/RHS) gets us a better result.
1213 if (KnownLHS.countMaxTrailingZeros() <= KnownRHS.countMaxTrailingZeros())
1214 KnownOut = KnownLHS.blsi();
1215 else
1216 KnownOut = KnownRHS.blsi();
1217 }
1218 break;
1219 case Instruction::Or:
1220 KnownOut = KnownLHS | KnownRHS;
1221 break;
1222 case Instruction::Xor:
1223 KnownOut = KnownLHS ^ KnownRHS;
1224 // xor(x, x-1) is common idioms that will clear all but lowest set
1225 // bit. If we have a single known bit in x, we can clear all bits
1226 // above it.
1227 // TODO: xor(x, x-1) is often rewritting as xor(x, x-C) where C !=
1228 // -1 but for the purpose of demanded bits (xor(x, x-C) &
1229 // Demanded) == (xor(x, x-1) & Demanded). Extend the xor pattern
1230 // to use arbitrary C if xor(x, x-C) as the same as xor(x, x-1).
1231 if (HasKnownOne &&
1233 const KnownBits &XBits = I->getOperand(0) == X ? KnownLHS : KnownRHS;
1234 KnownOut = XBits.blsmsk();
1235 }
1236 break;
1237 default:
1238 llvm_unreachable("Invalid Op used in 'analyzeKnownBitsFromAndXorOr'");
1239 }
1240
1241 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
1242 // xor/or(x, add (x, -1)) is an idiom that will always set the low bit.
1243 // here we handle the more general case of adding any odd number by
1244 // matching the form and/xor/or(x, add(x, y)) where y is odd.
1245 // TODO: This could be generalized to clearing any bit set in y where the
1246 // following bit is known to be unset in y.
1247 if (!KnownOut.Zero[0] && !KnownOut.One[0] &&
1251 KnownBits KnownY(BitWidth);
1252 computeKnownBits(Y, DemandedElts, KnownY, Q, Depth + 1);
1253 if (KnownY.countMinTrailingOnes() > 0) {
1254 if (IsAnd)
1255 KnownOut.Zero.setBit(0);
1256 else
1257 KnownOut.One.setBit(0);
1258 }
1259 }
1260 return KnownOut;
1261}
1262
1264 const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q,
1265 unsigned Depth,
1266 const function_ref<KnownBits(const KnownBits &, const KnownBits &)>
1267 KnownBitsFunc) {
1268 APInt DemandedEltsLHS, DemandedEltsRHS;
1270 DemandedElts, DemandedEltsLHS,
1271 DemandedEltsRHS);
1272
1273 const auto ComputeForSingleOpFunc =
1274 [Depth, &Q, KnownBitsFunc](const Value *Op, APInt &DemandedEltsOp) {
1275 return KnownBitsFunc(
1276 computeKnownBits(Op, DemandedEltsOp, Q, Depth + 1),
1277 computeKnownBits(Op, DemandedEltsOp << 1, Q, Depth + 1));
1278 };
1279
1280 if (DemandedEltsRHS.isZero())
1281 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS);
1282 if (DemandedEltsLHS.isZero())
1283 return ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS);
1284
1285 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS)
1286 .intersectWith(ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS));
1287}
1288
1289// Public so this can be used in `SimplifyDemandedUseBits`.
1291 const KnownBits &KnownLHS,
1292 const KnownBits &KnownRHS,
1293 const SimplifyQuery &SQ,
1294 unsigned Depth) {
1295 auto *FVTy = dyn_cast<FixedVectorType>(I->getType());
1296 APInt DemandedElts =
1297 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
1298
1299 return getKnownBitsFromAndXorOr(I, DemandedElts, KnownLHS, KnownRHS, SQ,
1300 Depth);
1301}
1302
1304 Attribute Attr = F->getFnAttribute(Attribute::VScaleRange);
1305 // Without vscale_range, we only know that vscale is non-zero.
1306 if (!Attr.isValid())
1308
1309 unsigned AttrMin = Attr.getVScaleRangeMin();
1310 // Minimum is larger than vscale width, result is always poison.
1311 if ((unsigned)llvm::bit_width(AttrMin) > BitWidth)
1312 return ConstantRange::getEmpty(BitWidth);
1313
1314 APInt Min(BitWidth, AttrMin);
1315 std::optional<unsigned> AttrMax = Attr.getVScaleRangeMax();
1316 if (!AttrMax || (unsigned)llvm::bit_width(*AttrMax) > BitWidth)
1318
1319 return ConstantRange(Min, APInt(BitWidth, *AttrMax) + 1);
1320}
1321
1322/// Return true if \p II reads a register named "vlenb". On RISC-V this is the
1323/// VLENB CSR, which holds VLEN/8: a non-zero power of two bounded by the
1324/// target's VLEN range. Callers must ensure the target is RISC-V.
1325static bool isReadVLENB(const IntrinsicInst &II) {
1326 auto *MAV = dyn_cast<MetadataAsValue>(II.getArgOperand(0));
1327 if (!MAV)
1328 return false;
1329 auto *MD = dyn_cast<MDNode>(MAV->getMetadata());
1330 if (!MD || MD->getNumOperands() != 1)
1331 return false;
1332 auto *RegName = dyn_cast<MDString>(MD->getOperand(0));
1333 return RegName && RegName->getString() == "vlenb";
1334}
1335
1336/// Return the value range of a RISC-V vlenb CSR read. RVV requires VLEN to be a
1337/// power of two in [32, 65536] (Zvl32b is the smallest vector extension), so
1338/// VLENB = VLEN/8 is in [4, 8192]. This architectural bound is independent of
1339/// any function attribute and stays sound for Zvl32b, whose VLEN (32) is not
1340/// representable as an integer vscale (VLEN / RVVBitsPerBlock). A vscale_range
1341/// attribute, when present, pins the subtarget's VLEN in units of
1342/// RVVBitsPerBlock (64 bits) and so gives a tighter VLENB = vscale *
1343/// RVVBytesPerBlock.
1345 unsigned Width) {
1346 // Architectural bounds: VLEN in [32, 65536] => VLENB in [4, 8192].
1347 ConstantRange Range(APInt(Width, 32 / 8), APInt(Width, 65536 / 8) + 1);
1348
1349 const Function *F = II.getFunction();
1350 if (F->getFnAttribute(Attribute::VScaleRange).isValid()) {
1351 ConstantRange VScale = getVScaleRange(F, Width);
1352 Range = Range.intersectWith(
1354 }
1355 return Range;
1356}
1357
1359 Value *Arm, bool Invert,
1360 const SimplifyQuery &Q, unsigned Depth) {
1361 // If we have a constant arm, we are done.
1362 if (Known.isConstant())
1363 return;
1364
1365 // See what condition implies about the bits of the select arm.
1366 KnownBits CondRes(Known.getBitWidth());
1367 computeKnownBitsFromCond(Arm, Cond, CondRes, Q, Invert, Depth + 1);
1368 // If we don't get any information from the condition, no reason to
1369 // proceed.
1370 if (CondRes.isUnknown())
1371 return;
1372
1373 // We can have conflict if the condition is dead. I.e if we have
1374 // (x | 64) < 32 ? (x | 64) : y
1375 // we will have conflict at bit 6 from the condition/the `or`.
1376 // In that case just return. Its not particularly important
1377 // what we do, as this select is going to be simplified soon.
1378 CondRes = CondRes.unionWith(Known);
1379 if (CondRes.hasConflict())
1380 return;
1381
1382 // Finally make sure the information we found is valid. This is relatively
1383 // expensive so it's left for the very end.
1384 if (!isGuaranteedNotToBeUndef(Arm, Q.AC, Q.CxtI, Q.DT, Depth + 1))
1385 return;
1386
1387 // Finally, we know we get information from the condition and its valid,
1388 // so return it.
1389 Known = std::move(CondRes);
1390}
1391
1392// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
1393// Returns the input and lower/upper bounds.
1394static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
1395 const APInt *&CLow, const APInt *&CHigh) {
1397 cast<Operator>(Select)->getOpcode() == Instruction::Select &&
1398 "Input should be a Select!");
1399
1400 const Value *LHS = nullptr, *RHS = nullptr;
1402 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
1403 return false;
1404
1405 if (!match(RHS, m_APInt(CLow)))
1406 return false;
1407
1408 const Value *LHS2 = nullptr, *RHS2 = nullptr;
1410 if (getInverseMinMaxFlavor(SPF) != SPF2)
1411 return false;
1412
1413 if (!match(RHS2, m_APInt(CHigh)))
1414 return false;
1415
1416 if (SPF == SPF_SMIN)
1417 std::swap(CLow, CHigh);
1418
1419 In = LHS2;
1420 return CLow->sle(*CHigh);
1421}
1422
1424 const APInt *&CLow,
1425 const APInt *&CHigh) {
1426 assert((II->getIntrinsicID() == Intrinsic::smin ||
1427 II->getIntrinsicID() == Intrinsic::smax) &&
1428 "Must be smin/smax");
1429
1430 Intrinsic::ID InverseID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
1431 auto *InnerII = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
1432 if (!InnerII || InnerII->getIntrinsicID() != InverseID ||
1433 !match(II->getArgOperand(1), m_APInt(CLow)) ||
1434 !match(InnerII->getArgOperand(1), m_APInt(CHigh)))
1435 return false;
1436
1437 if (II->getIntrinsicID() == Intrinsic::smin)
1438 std::swap(CLow, CHigh);
1439 return CLow->sle(*CHigh);
1440}
1441
1443 KnownBits &Known) {
1444 const APInt *CLow, *CHigh;
1445 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
1446 Known = Known.unionWith(
1447 ConstantRange::getNonEmpty(*CLow, *CHigh + 1).toKnownBits());
1448}
1449
1451 const APInt &DemandedElts,
1453 const SimplifyQuery &Q,
1454 unsigned Depth) {
1455 unsigned BitWidth = Known.getBitWidth();
1456
1457 KnownBits Known2(BitWidth);
1458 switch (I->getOpcode()) {
1459 default: break;
1460 case Instruction::Load:
1461 if (MDNode *MD =
1462 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
1464 break;
1465 case Instruction::And:
1466 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1467 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1468
1469 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1470 break;
1471 case Instruction::Or:
1472 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1473 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1474
1475 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1476 break;
1477 case Instruction::Xor:
1478 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1479 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1480
1481 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1482 break;
1483 case Instruction::Mul: {
1486 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, NUW,
1487 DemandedElts, Known, Known2, Q, Depth);
1488 break;
1489 }
1490 case Instruction::UDiv: {
1491 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1492 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1493 Known =
1495 break;
1496 }
1497 case Instruction::SDiv: {
1498 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1499 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1500 Known =
1502 break;
1503 }
1504 case Instruction::Select: {
1505 auto ComputeForArm = [&](Value *Arm, bool Invert) {
1506 KnownBits Res(Known.getBitWidth());
1507 computeKnownBits(Arm, DemandedElts, Res, Q, Depth + 1);
1508 adjustKnownBitsForSelectArm(Res, I->getOperand(0), Arm, Invert, Q, Depth);
1509 return Res;
1510 };
1511 // Only known if known in both the LHS and RHS.
1512 Known =
1513 ComputeForArm(I->getOperand(1), /*Invert=*/false)
1514 .intersectWith(ComputeForArm(I->getOperand(2), /*Invert=*/true));
1515 break;
1516 }
1517 case Instruction::FPToSI: {
1518 // fptosi is poison if the rounded value doesn't fit in the result type,
1519 // so we can assume the conversion is well-defined and rounds towards
1520 // zero. +-Inf can never fit in an integer type, so it is always poison,
1521 // like NaN. Negative subnormals and negative zero round to 0. That
1522 // leaves negative normals as the only class that can produce a defined
1523 // negative result.
1524 KnownFPClass SrcFPClass = computeKnownFPClass(
1525 I->getOperand(0), DemandedElts, fcNegNormal, Q, Depth + 1);
1526 if (SrcFPClass.isKnownNever(fcNegNormal))
1527 Known.makeNonNegative();
1528 break;
1529 }
1530 case Instruction::FPTrunc:
1531 case Instruction::FPExt:
1532 case Instruction::FPToUI:
1533 case Instruction::SIToFP:
1534 case Instruction::UIToFP:
1535 break; // Can't work with floating point.
1536 case Instruction::PtrToInt:
1537 case Instruction::PtrToAddr:
1538 case Instruction::IntToPtr:
1539 // Fall through and handle them the same as zext/trunc.
1540 [[fallthrough]];
1541 case Instruction::ZExt:
1542 case Instruction::Trunc: {
1543 Type *SrcTy = I->getOperand(0)->getType();
1544
1545 unsigned SrcBitWidth;
1546 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1547 // which fall through here.
1548 Type *ScalarTy = SrcTy->getScalarType();
1549 SrcBitWidth = ScalarTy->isPointerTy() ?
1550 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
1551 Q.DL.getTypeSizeInBits(ScalarTy);
1552
1553 assert(SrcBitWidth && "SrcBitWidth can't be zero");
1554 Known = Known.anyextOrTrunc(SrcBitWidth);
1555 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1556 if (auto *Inst = dyn_cast<PossiblyNonNegInst>(I);
1557 Inst && Inst->hasNonNeg() && !Known.isNegative())
1558 Known.makeNonNegative();
1559 Known = Known.zextOrTrunc(BitWidth);
1560 break;
1561 }
1562 case Instruction::BitCast: {
1563 Type *SrcTy = I->getOperand(0)->getType();
1564 if (SrcTy->isIntOrPtrTy() &&
1565 // TODO: For now, not handling conversions like:
1566 // (bitcast i64 %x to <2 x i32>)
1567 !I->getType()->isVectorTy()) {
1568 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1569 break;
1570 }
1571
1572 const Value *V;
1573 // Handle bitcast from floating point to integer.
1574 if (match(I, m_ElementWiseBitCast(m_Value(V))) &&
1575 V->getType()->isFPOrFPVectorTy()) {
1576 Type *FPType = V->getType()->getScalarType();
1577 KnownFPClass Result =
1578 computeKnownFPClass(V, DemandedElts, fcAllFlags, Q, Depth + 1);
1579
1580 Known = Result.toKnownBits(FPType->getFltSemantics());
1581
1582 break;
1583 }
1584
1585 // Handle cast from vector integer type to scalar or vector integer.
1586 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcTy);
1587 if (!SrcVecTy || !SrcVecTy->getElementType()->isIntegerTy() ||
1588 !I->getType()->isIntOrIntVectorTy() ||
1589 isa<ScalableVectorType>(I->getType()))
1590 break;
1591
1592 unsigned NumElts = DemandedElts.getBitWidth();
1593 bool IsLE = Q.DL.isLittleEndian();
1594 // Look through a cast from narrow vector elements to wider type.
1595 // Examples: v4i32 -> v2i64, v3i8 -> v24
1596 unsigned SubBitWidth = SrcVecTy->getScalarSizeInBits();
1597 if (BitWidth % SubBitWidth == 0) {
1598 // Known bits are automatically intersected across demanded elements of a
1599 // vector. So for example, if a bit is computed as known zero, it must be
1600 // zero across all demanded elements of the vector.
1601 //
1602 // For this bitcast, each demanded element of the output is sub-divided
1603 // across a set of smaller vector elements in the source vector. To get
1604 // the known bits for an entire element of the output, compute the known
1605 // bits for each sub-element sequentially. This is done by shifting the
1606 // one-set-bit demanded elements parameter across the sub-elements for
1607 // consecutive calls to computeKnownBits. We are using the demanded
1608 // elements parameter as a mask operator.
1609 //
1610 // The known bits of each sub-element are then inserted into place
1611 // (dependent on endian) to form the full result of known bits.
1612 unsigned SubScale = BitWidth / SubBitWidth;
1613 APInt SubDemandedElts = APInt::getZero(NumElts * SubScale);
1614 for (unsigned i = 0; i != NumElts; ++i) {
1615 if (DemandedElts[i])
1616 SubDemandedElts.setBit(i * SubScale);
1617 }
1618
1619 KnownBits KnownSrc(SubBitWidth);
1620 for (unsigned i = 0; i != SubScale; ++i) {
1621 computeKnownBits(I->getOperand(0), SubDemandedElts.shl(i), KnownSrc, Q,
1622 Depth + 1);
1623 unsigned ShiftElt = IsLE ? i : SubScale - 1 - i;
1624 Known.insertBits(KnownSrc, ShiftElt * SubBitWidth);
1625 }
1626 }
1627 // Look through a cast from wider vector elements to narrow type.
1628 // Examples: v2i64 -> v4i32
1629 if (SubBitWidth % BitWidth == 0) {
1630 unsigned SubScale = SubBitWidth / BitWidth;
1631 KnownBits KnownSrc(SubBitWidth);
1632 APInt SubDemandedElts =
1633 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
1634 computeKnownBits(I->getOperand(0), SubDemandedElts, KnownSrc, Q,
1635 Depth + 1);
1636
1637 Known.setAllConflict();
1638 for (unsigned i = 0; i != NumElts; ++i) {
1639 if (DemandedElts[i]) {
1640 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
1641 unsigned Offset = (Shifts % SubScale) * BitWidth;
1642 Known = Known.intersectWith(KnownSrc.extractBits(BitWidth, Offset));
1643 if (Known.isUnknown())
1644 break;
1645 }
1646 }
1647 }
1648 break;
1649 }
1650 case Instruction::SExt: {
1651 // Compute the bits in the result that are not present in the input.
1652 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1653
1654 Known = Known.trunc(SrcBitWidth);
1655 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1656 // If the sign bit of the input is known set or clear, then we know the
1657 // top bits of the result.
1658 Known = Known.sext(BitWidth);
1659 break;
1660 }
1661 case Instruction::Shl: {
1664 auto KF = [NUW, NSW](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1665 bool ShAmtNonZero) {
1666 return KnownBits::shl(KnownVal, KnownAmt, NUW, NSW, ShAmtNonZero);
1667 };
1668 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1669 KF);
1670 // Trailing zeros of a right-shifted constant never decrease.
1671 const APInt *C;
1672 if (match(I->getOperand(0), m_APInt(C)))
1673 Known.Zero.setLowBits(C->countr_zero());
1674
1675 // shl X, sub(Y, xor(ctlz(X, true), BitWidth-1)) shifts X so that its MSB
1676 // lands at bit Y, when BitWidth is a power of 2.
1677 const APInt *YC;
1678 Value *X = I->getOperand(0);
1679 if (isPowerOf2_32(BitWidth) &&
1680 match(I->getOperand(1),
1682 m_SpecificInt(BitWidth - 1)))) &&
1683 YC->ult(BitWidth - 1)) {
1684 unsigned Y = YC->getZExtValue();
1685 Known.One.setBit(Y);
1686 Known.Zero.setBitsFrom(Y + 1);
1687 }
1688 break;
1689 }
1690 case Instruction::LShr: {
1691 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1692 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1693 bool ShAmtNonZero) {
1694 return KnownBits::lshr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1695 };
1696 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1697 KF);
1698 // Leading zeros of a left-shifted constant never decrease.
1699 const APInt *C;
1700 if (match(I->getOperand(0), m_APInt(C)))
1701 Known.Zero.setHighBits(C->countl_zero());
1702 break;
1703 }
1704 case Instruction::AShr: {
1705 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1706 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1707 bool ShAmtNonZero) {
1708 return KnownBits::ashr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1709 };
1710 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1711 KF);
1712 break;
1713 }
1714 case Instruction::Sub: {
1717 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW, NUW,
1718 DemandedElts, Known, Known2, Q, Depth);
1719 break;
1720 }
1721 case Instruction::Add: {
1724 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW, NUW,
1725 DemandedElts, Known, Known2, Q, Depth);
1726 break;
1727 }
1728 case Instruction::SRem:
1729 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1730 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1731 Known = KnownBits::srem(Known, Known2);
1732 break;
1733
1734 case Instruction::URem:
1735 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1736 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1737 Known = KnownBits::urem(Known, Known2);
1738 break;
1739 case Instruction::Alloca:
1740 Known.Zero.setLowBits(Log2(cast<AllocaInst>(I)->getAlign()));
1741 break;
1742 case Instruction::GetElementPtr: {
1743 // Analyze all of the subscripts of this getelementptr instruction
1744 // to determine if we can prove known low zero bits.
1745 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1746 // Accumulate the constant indices in a separate variable
1747 // to minimize the number of calls to computeForAddSub.
1748 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(I->getType());
1749 APInt AccConstIndices(IndexWidth, 0);
1750
1751 auto AddIndexToKnown = [&](KnownBits IndexBits) {
1752 if (IndexWidth == BitWidth) {
1753 // Note that inbounds does *not* guarantee nsw for the addition, as only
1754 // the offset is signed, while the base address is unsigned.
1755 Known = KnownBits::add(Known, IndexBits);
1756 } else {
1757 // If the index width is smaller than the pointer width, only add the
1758 // value to the low bits.
1759 assert(IndexWidth < BitWidth &&
1760 "Index width can't be larger than pointer width");
1761 Known.insertBits(KnownBits::add(Known.trunc(IndexWidth), IndexBits), 0);
1762 }
1763 };
1764
1766 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1767 // TrailZ can only become smaller, short-circuit if we hit zero.
1768 if (Known.isUnknown())
1769 break;
1770
1771 Value *Index = I->getOperand(i);
1772
1773 // Handle case when index is zero.
1774 Constant *CIndex = dyn_cast<Constant>(Index);
1775 if (CIndex && CIndex->isNullValue())
1776 continue;
1777
1778 if (StructType *STy = GTI.getStructTypeOrNull()) {
1779 // Handle struct member offset arithmetic.
1780
1781 assert(CIndex &&
1782 "Access to structure field must be known at compile time");
1783
1784 if (CIndex->getType()->isVectorTy())
1785 Index = CIndex->getSplatValue();
1786
1787 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1788 const StructLayout *SL = Q.DL.getStructLayout(STy);
1789 uint64_t Offset = SL->getElementOffset(Idx);
1790 AccConstIndices += Offset;
1791 continue;
1792 }
1793
1794 // Handle array index arithmetic.
1795 Type *IndexedTy = GTI.getIndexedType();
1796 if (!IndexedTy->isSized()) {
1797 Known.resetAll();
1798 break;
1799 }
1800
1801 TypeSize Stride = GTI.getSequentialElementStride(Q.DL);
1802 uint64_t StrideInBytes = Stride.getKnownMinValue();
1803 if (!Stride.isScalable()) {
1804 // Fast path for constant offset.
1805 if (auto *CI = dyn_cast<ConstantInt>(Index)) {
1806 AccConstIndices +=
1807 CI->getValue().sextOrTrunc(IndexWidth) * StrideInBytes;
1808 continue;
1809 }
1810 }
1811
1812 KnownBits IndexBits =
1813 computeKnownBits(Index, Q, Depth + 1).sextOrTrunc(IndexWidth);
1814 KnownBits ScalingFactor(IndexWidth);
1815 // Multiply by current sizeof type.
1816 // &A[i] == A + i * sizeof(*A[i]).
1817 if (Stride.isScalable()) {
1818 // For scalable types the only thing we know about sizeof is
1819 // that this is a multiple of the minimum size.
1820 ScalingFactor.Zero.setLowBits(llvm::countr_zero(StrideInBytes));
1821 } else {
1822 ScalingFactor =
1823 KnownBits::makeConstant(APInt(IndexWidth, StrideInBytes));
1824 }
1825 AddIndexToKnown(KnownBits::mul(IndexBits, ScalingFactor));
1826 }
1827 if (!Known.isUnknown() && !AccConstIndices.isZero())
1828 AddIndexToKnown(KnownBits::makeConstant(AccConstIndices));
1829 break;
1830 }
1831 case Instruction::PHI: {
1832 const PHINode *P = cast<PHINode>(I);
1833 BinaryOperator *BO = nullptr;
1834 Value *Start = nullptr, *Step = nullptr;
1835 KnownBits &KnownStart = Known2;
1836 if (matchSimpleRecurrence(P, BO, Start, Step)) {
1837 // Handle the case of a simple two-predecessor recurrence PHI.
1838 // There's a lot more that could theoretically be done here, but
1839 // this is sufficient to catch some interesting cases.
1840 unsigned Opcode = BO->getOpcode();
1841
1842 switch (Opcode) {
1843 // If this is a shift recurrence, we know the bits being shifted in. We
1844 // can combine that with information about the start value of the
1845 // recurrence to conclude facts about the result. If this is a udiv
1846 // recurrence, we know that the result can never exceed either the
1847 // numerator or the start value, whichever is greater.
1848 case Instruction::LShr:
1849 case Instruction::AShr:
1850 case Instruction::Shl:
1851 case Instruction::UDiv:
1852 if (BO->getOperand(0) != I)
1853 break;
1854 [[fallthrough]];
1855
1856 // For a urem recurrence, the result can never exceed the start value. The
1857 // phi could either be the numerator or the denominator.
1858 case Instruction::URem: {
1859 // We have matched a recurrence of the form:
1860 // %iv = [R, %entry], [%iv.next, %backedge]
1861 // %iv.next = shift_op %iv, L
1862
1863 // Recurse with the phi context to avoid concern about whether facts
1864 // inferred hold at original context instruction. TODO: It may be
1865 // correct to use the original context. IF warranted, explore and
1866 // add sufficient tests to cover.
1868 RecQ.CxtI = P;
1869 computeKnownBits(Start, DemandedElts, KnownStart, RecQ, Depth + 1);
1870 switch (Opcode) {
1871 case Instruction::Shl:
1872 // A shl recurrence will only increase the tailing zeros
1873 Known.Zero.setLowBits(KnownStart.countMinTrailingZeros());
1874 break;
1875 case Instruction::LShr:
1876 case Instruction::UDiv:
1877 case Instruction::URem:
1878 // lshr, udiv, and urem recurrences will preserve the leading zeros of
1879 // the start value.
1880 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
1881 break;
1882 case Instruction::AShr:
1883 // An ashr recurrence will extend the initial sign bit
1884 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
1885 Known.One.setHighBits(KnownStart.countMinLeadingOnes());
1886 break;
1887 }
1888 break;
1889 }
1890
1891 // Check for operations that have the property that if
1892 // both their operands have low zero bits, the result
1893 // will have low zero bits.
1894 case Instruction::Add:
1895 case Instruction::Sub:
1896 case Instruction::And:
1897 case Instruction::Or:
1898 case Instruction::Mul: {
1899 // Change the context instruction to the "edge" that flows into the
1900 // phi. This is important because that is where the value is actually
1901 // "evaluated" even though it is used later somewhere else. (see also
1902 // D69571).
1904
1905 unsigned OpNum = P->getOperand(0) == Start ? 0 : 1;
1906 Instruction *StartTerm = P->getIncomingBlock(OpNum)->getTerminator();
1907 Instruction *LatchTerm =
1908 P->getIncomingBlock(1 - OpNum)->getTerminator();
1909
1910 // Ok, we have a recurrence of the form {Start,op,Step}. Check for low
1911 // zero bits.
1912 RecQ.CxtI = StartTerm;
1913 computeKnownBits(Start, DemandedElts, KnownStart, RecQ, Depth + 1);
1914
1915 // We need to take the minimum number of known bits.
1916 // The step may be loop-variant, so make sure we don't make use of
1917 // any conditions that only hold on the last iteration.
1918 KnownBits KnownStep(BitWidth);
1919 RecQ.CxtI = LatchTerm;
1920 computeKnownBits(Step, DemandedElts, KnownStep, RecQ, Depth + 1);
1921
1922 Known.Zero.setLowBits(std::min(KnownStart.countMinTrailingZeros(),
1923 KnownStep.countMinTrailingZeros()));
1924
1925 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO);
1926 if (!OverflowOp || !Q.IIQ.hasNoSignedWrap(OverflowOp))
1927 break;
1928
1929 switch (Opcode) {
1930 // If initial value of recurrence is nonnegative, and we are adding
1931 // a nonnegative number with nsw, the result can only be nonnegative
1932 // or poison value regardless of the number of times we execute the
1933 // add in phi recurrence. If initial value is negative and we are
1934 // adding a negative number with nsw, the result can only be
1935 // negative or poison value. Similar arguments apply to sub and mul.
1936 //
1937 // (add non-negative, non-negative) --> non-negative
1938 // (add negative, negative) --> negative
1939 case Instruction::Add: {
1940 if (KnownStart.isNonNegative() && KnownStep.isNonNegative())
1941 Known.makeNonNegative();
1942 else if (KnownStart.isNegative() && KnownStep.isNegative())
1943 Known.makeNegative();
1944 break;
1945 }
1946
1947 // (sub nsw non-negative, negative) --> non-negative
1948 // (sub nsw negative, non-negative) --> negative
1949 case Instruction::Sub: {
1950 if (BO->getOperand(0) != I)
1951 break;
1952 if (KnownStart.isNonNegative() && KnownStep.isNegative())
1953 Known.makeNonNegative();
1954 else if (KnownStart.isNegative() && KnownStep.isNonNegative())
1955 Known.makeNegative();
1956 break;
1957 }
1958
1959 // (mul nsw non-negative, non-negative) --> non-negative
1960 case Instruction::Mul:
1961 if (KnownStart.isNonNegative() && KnownStep.isNonNegative())
1962 Known.makeNonNegative();
1963 break;
1964
1965 default:
1966 break;
1967 }
1968 break;
1969 }
1970
1971 default:
1972 break;
1973 }
1974 }
1975
1976 // Unreachable blocks may have zero-operand PHI nodes.
1977 if (P->getNumIncomingValues() == 0)
1978 break;
1979
1980 // Otherwise take the unions of the known bit sets of the operands,
1981 // taking conservative care to avoid excessive recursion.
1982 if (Depth < MaxAnalysisRecursionDepth - 1 && Known.isUnknown()) {
1983 // Skip if every incoming value references to ourself.
1984 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
1985 break;
1986
1987 Known.setAllConflict();
1988 for (const Use &U : P->operands()) {
1989 Value *IncValue;
1990 const PHINode *CxtPhi;
1991 Instruction *CxtI;
1992 breakSelfRecursivePHI(&U, P, IncValue, CxtI, &CxtPhi);
1993 // Skip direct self references.
1994 if (IncValue == P)
1995 continue;
1996
1997 // Change the context instruction to the "edge" that flows into the
1998 // phi. This is important because that is where the value is actually
1999 // "evaluated" even though it is used later somewhere else. (see also
2000 // D69571).
2002
2003 Known2 = KnownBits(BitWidth);
2004
2005 // Recurse, but cap the recursion to one level, because we don't
2006 // want to waste time spinning around in loops.
2007 // TODO: See if we can base recursion limiter on number of incoming phi
2008 // edges so we don't overly clamp analysis.
2009 computeKnownBits(IncValue, DemandedElts, Known2, RecQ,
2011
2012 // See if we can further use a conditional branch into the phi
2013 // to help us determine the range of the value.
2014 if (!Known2.isConstant()) {
2015 CmpPredicate Pred;
2016 const APInt *RHSC;
2017 BasicBlock *TrueSucc, *FalseSucc;
2018 // TODO: Use RHS Value and compute range from its known bits.
2019 if (match(RecQ.CxtI,
2020 m_Br(m_c_ICmp(Pred, m_Specific(IncValue), m_APInt(RHSC)),
2021 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
2022 // Check for cases of duplicate successors.
2023 if ((TrueSucc == CxtPhi->getParent()) !=
2024 (FalseSucc == CxtPhi->getParent())) {
2025 // If we're using the false successor, invert the predicate.
2026 if (FalseSucc == CxtPhi->getParent())
2027 Pred = CmpInst::getInversePredicate(Pred);
2028 // Get the knownbits implied by the incoming phi condition.
2029 auto CR = ConstantRange::makeExactICmpRegion(Pred, *RHSC);
2030 KnownBits KnownUnion = Known2.unionWith(CR.toKnownBits());
2031 // We can have conflicts here if we are analyzing deadcode (its
2032 // impossible for us reach this BB based the icmp).
2033 if (KnownUnion.hasConflict()) {
2034 // No reason to continue analyzing in a known dead region, so
2035 // just resetAll and break. This will cause us to also exit the
2036 // outer loop.
2037 Known.resetAll();
2038 break;
2039 }
2040 Known2 = KnownUnion;
2041 }
2042 }
2043 }
2044
2045 Known = Known.intersectWith(Known2);
2046 // If all bits have been ruled out, there's no need to check
2047 // more operands.
2048 if (Known.isUnknown())
2049 break;
2050 }
2051 }
2052 break;
2053 }
2054 case Instruction::Call:
2055 case Instruction::Invoke: {
2056 // If range metadata is attached to this call, set known bits from that,
2057 // and then intersect with known bits based on other properties of the
2058 // function.
2059 if (MDNode *MD =
2060 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
2062
2063 const auto *CB = cast<CallBase>(I);
2064
2065 if (std::optional<ConstantRange> Range = CB->getRange())
2066 Known = Known.unionWith(Range->toKnownBits());
2067
2068 if (const Value *RV = CB->getReturnedArgOperand()) {
2069 if (RV->getType() == I->getType()) {
2070 computeKnownBits(RV, Known2, Q, Depth + 1);
2071 Known = Known.unionWith(Known2);
2072 // If the function doesn't return properly for all input values
2073 // (e.g. unreachable exits) then there might be conflicts between the
2074 // argument value and the range metadata. Simply discard the known bits
2075 // in case of conflicts.
2076 if (Known.hasConflict())
2077 Known.resetAll();
2078 }
2079 }
2080 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2081 switch (II->getIntrinsicID()) {
2082 default:
2083 break;
2084 case Intrinsic::abs: {
2085 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2086 bool IntMinIsPoison = match(II->getArgOperand(1), m_One());
2087 Known = Known.unionWith(Known2.abs(IntMinIsPoison));
2088 break;
2089 }
2090 case Intrinsic::bitreverse:
2091 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2092 Known = Known.unionWith(Known2.reverseBits());
2093 break;
2094 case Intrinsic::bswap:
2095 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2096 Known = Known.unionWith(Known2.byteSwap());
2097 break;
2098 case Intrinsic::ctlz: {
2099 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2100 // If we have a known 1, its position is our upper bound.
2101 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2102 // If this call is poison for 0 input, the result will be less than 2^n.
2103 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2104 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
2105 unsigned LowBits = llvm::bit_width(PossibleLZ);
2106 Known.Zero.setBitsFrom(LowBits);
2107 break;
2108 }
2109 case Intrinsic::cttz: {
2110 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2111 // If we have a known 1, its position is our upper bound.
2112 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2113 // If this call is poison for 0 input, the result will be less than 2^n.
2114 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2115 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
2116 unsigned LowBits = llvm::bit_width(PossibleTZ);
2117 Known.Zero.setBitsFrom(LowBits);
2118 break;
2119 }
2120 case Intrinsic::ctpop: {
2121 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2122 // We can bound the space the count needs. Also, bits known to be zero
2123 // can't contribute to the population.
2124 unsigned BitsPossiblySet = Known2.countMaxPopulation();
2125 unsigned LowBits = llvm::bit_width(BitsPossiblySet);
2126 Known.Zero.setBitsFrom(LowBits);
2127 // TODO: we could bound KnownOne using the lower bound on the number
2128 // of bits which might be set provided by popcnt KnownOne2.
2129 break;
2130 }
2131 case Intrinsic::fshr:
2132 case Intrinsic::fshl: {
2133 const APInt *SA;
2134 if (!match(I->getOperand(2), m_APInt(SA)))
2135 break;
2136
2137 KnownBits Known3(BitWidth);
2138 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2139 computeKnownBits(I->getOperand(1), DemandedElts, Known3, Q, Depth + 1);
2140 Known = II->getIntrinsicID() == Intrinsic::fshl
2141 ? KnownBits::fshl(Known2, Known3, *SA)
2142 : KnownBits::fshr(Known2, Known3, *SA);
2143 break;
2144 }
2145 case Intrinsic::clmul:
2146 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2147 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2148 Known = KnownBits::clmul(Known, Known2);
2149 break;
2150 case Intrinsic::pext:
2151 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2152 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2153 Known = KnownBits::pext(Known, Known2);
2154 break;
2155 case Intrinsic::pdep:
2156 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2157 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2158 Known = KnownBits::pdep(Known, Known2);
2159 break;
2160 case Intrinsic::uadd_sat:
2161 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2162 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2163 Known = KnownBits::uadd_sat(Known, Known2);
2164 break;
2165 case Intrinsic::usub_sat:
2166 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2167 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2168 Known = KnownBits::usub_sat(Known, Known2);
2169 break;
2170 case Intrinsic::sadd_sat:
2171 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2172 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2173 Known = KnownBits::sadd_sat(Known, Known2);
2174 break;
2175 case Intrinsic::ssub_sat:
2176 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2177 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2178 Known = KnownBits::ssub_sat(Known, Known2);
2179 break;
2180 // Vec reverse preserves bits from input vec.
2181 case Intrinsic::vector_reverse:
2182 computeKnownBits(I->getOperand(0), DemandedElts.reverseBits(), Known, Q,
2183 Depth + 1);
2184 break;
2185 // for min/max/and/or reduce, any bit common to each element in the
2186 // input vec is set in the output.
2187 case Intrinsic::vector_reduce_and:
2188 case Intrinsic::vector_reduce_or:
2189 case Intrinsic::vector_reduce_umax:
2190 case Intrinsic::vector_reduce_umin:
2191 case Intrinsic::vector_reduce_smax:
2192 case Intrinsic::vector_reduce_smin:
2193 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2194 break;
2195 case Intrinsic::vector_reduce_xor: {
2196 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2197 // The zeros common to all vecs are zero in the output.
2198 // If the number of elements is odd, then the common ones remain. If the
2199 // number of elements is even, then the common ones becomes zeros.
2200 auto *VecTy = cast<VectorType>(I->getOperand(0)->getType());
2201 // Even, so the ones become zeros.
2202 bool EvenCnt = VecTy->getElementCount().isKnownEven();
2203 if (EvenCnt)
2204 Known.Zero |= Known.One;
2205 // Maybe even element count so need to clear ones.
2206 if (VecTy->isScalableTy() || EvenCnt)
2207 Known.One.clearAllBits();
2208 break;
2209 }
2210 case Intrinsic::vector_reduce_add: {
2211 auto *VecTy = dyn_cast<FixedVectorType>(I->getOperand(0)->getType());
2212 if (!VecTy)
2213 break;
2214 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2215 Known = Known.reduceAdd(VecTy->getNumElements());
2216 break;
2217 }
2218 case Intrinsic::umin:
2219 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2220 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2221 Known = KnownBits::umin(Known, Known2);
2222 break;
2223 case Intrinsic::umax:
2224 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2225 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2226 Known = KnownBits::umax(Known, Known2);
2227 break;
2228 case Intrinsic::smin:
2229 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2230 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2231 Known = KnownBits::smin(Known, Known2);
2233 break;
2234 case Intrinsic::smax:
2235 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2236 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2237 Known = KnownBits::smax(Known, Known2);
2239 break;
2240 case Intrinsic::ptrmask: {
2241 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2242
2243 const Value *Mask = I->getOperand(1);
2244 Known2 = KnownBits(Mask->getType()->getScalarSizeInBits());
2245 computeKnownBits(Mask, DemandedElts, Known2, Q, Depth + 1);
2246 // TODO: 1-extend would be more precise.
2247 Known &= Known2.anyextOrTrunc(BitWidth);
2248 break;
2249 }
2250 case Intrinsic::x86_sse2_pmulh_w:
2251 case Intrinsic::x86_avx2_pmulh_w:
2252 case Intrinsic::x86_avx512_pmulh_w_512:
2253 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2254 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2255 Known = KnownBits::mulhs(Known, Known2);
2256 break;
2257 case Intrinsic::x86_sse2_pmulhu_w:
2258 case Intrinsic::x86_avx2_pmulhu_w:
2259 case Intrinsic::x86_avx512_pmulhu_w_512:
2260 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2261 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2262 Known = KnownBits::mulhu(Known, Known2);
2263 break;
2264 case Intrinsic::x86_sse42_crc32_64_64:
2265 Known.Zero.setBitsFrom(32);
2266 break;
2267 case Intrinsic::x86_ssse3_phadd_d_128:
2268 case Intrinsic::x86_ssse3_phadd_w_128:
2269 case Intrinsic::x86_avx2_phadd_d:
2270 case Intrinsic::x86_avx2_phadd_w: {
2272 I, DemandedElts, Q, Depth,
2273 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2274 return KnownBits::add(KnownLHS, KnownRHS);
2275 });
2276 break;
2277 }
2278 case Intrinsic::x86_ssse3_phadd_sw_128:
2279 case Intrinsic::x86_avx2_phadd_sw: {
2281 I, DemandedElts, Q, Depth, KnownBits::sadd_sat);
2282 break;
2283 }
2284 case Intrinsic::x86_ssse3_phsub_d_128:
2285 case Intrinsic::x86_ssse3_phsub_w_128:
2286 case Intrinsic::x86_avx2_phsub_d:
2287 case Intrinsic::x86_avx2_phsub_w: {
2289 I, DemandedElts, Q, Depth,
2290 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2291 return KnownBits::sub(KnownLHS, KnownRHS);
2292 });
2293 break;
2294 }
2295 case Intrinsic::x86_ssse3_phsub_sw_128:
2296 case Intrinsic::x86_avx2_phsub_sw: {
2298 I, DemandedElts, Q, Depth, KnownBits::ssub_sat);
2299 break;
2300 }
2301 case Intrinsic::riscv_vsetvli:
2302 case Intrinsic::riscv_vsetvlimax: {
2303 bool HasAVL = II->getIntrinsicID() == Intrinsic::riscv_vsetvli;
2304 const ConstantRange Range = getVScaleRange(II->getFunction(), BitWidth);
2306 cast<ConstantInt>(II->getArgOperand(HasAVL))->getZExtValue());
2307 RISCVVType::VLMUL VLMUL = static_cast<RISCVVType::VLMUL>(
2308 cast<ConstantInt>(II->getArgOperand(1 + HasAVL))->getZExtValue());
2309 uint64_t MaxVLEN =
2310 Range.getUnsignedMax().getZExtValue() * RISCV::RVVBitsPerBlock;
2311 uint64_t MaxVL = MaxVLEN / RISCVVType::getSEWLMULRatio(SEW, VLMUL);
2312
2313 // Result of vsetvli must be not larger than AVL.
2314 if (HasAVL)
2315 if (auto *CI = dyn_cast<ConstantInt>(II->getArgOperand(0)))
2316 MaxVL = std::min(MaxVL, CI->getZExtValue());
2317
2318 unsigned KnownZeroFirstBit = Log2_32(MaxVL) + 1;
2319 if (BitWidth > KnownZeroFirstBit)
2320 Known.Zero.setBitsFrom(KnownZeroFirstBit);
2321 break;
2322 }
2323 case Intrinsic::amdgcn_mbcnt_hi:
2324 case Intrinsic::amdgcn_mbcnt_lo: {
2325 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
2326 // most 31 + src1.
2327 Known.Zero.setBitsFrom(
2328 II->getIntrinsicID() == Intrinsic::amdgcn_mbcnt_lo ? 6 : 5);
2329 computeKnownBits(I->getOperand(1), Known2, Q, Depth + 1);
2330 Known = KnownBits::add(Known, Known2);
2331 break;
2332 }
2333 case Intrinsic::vscale: {
2334 if (!II->getParent() || !II->getFunction())
2335 break;
2336
2337 Known = getVScaleRange(II->getFunction(), BitWidth).toKnownBits();
2338 break;
2339 }
2340 case Intrinsic::stepvector: {
2341 auto *VecTy = cast<VectorType>(II->getType());
2342 unsigned MinNumElts = VecTy->getElementCount().getKnownMinValue();
2343 if (!isUIntN(BitWidth, MinNumElts))
2344 break;
2345
2346 bool Overflow = false;
2347 APInt MaxNumElts(BitWidth, MinNumElts);
2348 if (VecTy->isScalableTy()) {
2349 if (!II->getParent() || !II->getFunction())
2350 break;
2351 MaxNumElts = getVScaleRange(II->getFunction(), BitWidth)
2353 .umul_ov(MaxNumElts, Overflow);
2354 }
2355
2356 // Give up if the lane count could wrap. Stepvector truncates lane
2357 // indices that do not fit in the element type.
2358 if (Overflow)
2359 break;
2360
2361 Known.Zero.setHighBits((MaxNumElts - 1).countl_zero());
2362 break;
2363 }
2364 }
2365 }
2366 break;
2367 }
2368 case Instruction::ShuffleVector: {
2369 if (auto *Splat = getSplatValue(I)) {
2371 break;
2372 }
2373
2374 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
2375 // FIXME: Do we need to handle ConstantExpr involving shufflevectors?
2376 if (!Shuf) {
2377 Known.resetAll();
2378 return;
2379 }
2380 // For undef elements, we don't know anything about the common state of
2381 // the shuffle result.
2382 APInt DemandedLHS, DemandedRHS;
2383 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) {
2384 Known.resetAll();
2385 return;
2386 }
2387 Known.setAllConflict();
2388 if (!!DemandedLHS) {
2389 const Value *LHS = Shuf->getOperand(0);
2390 computeKnownBits(LHS, DemandedLHS, Known, Q, Depth + 1);
2391 // If we don't know any bits, early out.
2392 if (Known.isUnknown())
2393 break;
2394 }
2395 if (!!DemandedRHS) {
2396 const Value *RHS = Shuf->getOperand(1);
2397 computeKnownBits(RHS, DemandedRHS, Known2, Q, Depth + 1);
2398 Known = Known.intersectWith(Known2);
2399 }
2400 break;
2401 }
2402 case Instruction::InsertElement: {
2403 if (isa<ScalableVectorType>(I->getType())) {
2404 Known.resetAll();
2405 return;
2406 }
2407 const Value *Vec = I->getOperand(0);
2408 const Value *Elt = I->getOperand(1);
2409 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
2410 unsigned NumElts = DemandedElts.getBitWidth();
2411 APInt DemandedVecElts = DemandedElts;
2412 bool NeedsElt = true;
2413 // If we know the index we are inserting too, clear it from Vec check.
2414 if (CIdx && CIdx->getValue().ult(NumElts)) {
2415 DemandedVecElts.clearBit(CIdx->getZExtValue());
2416 NeedsElt = DemandedElts[CIdx->getZExtValue()];
2417 }
2418
2419 Known.setAllConflict();
2420 if (NeedsElt) {
2421 computeKnownBits(Elt, Known, Q, Depth + 1);
2422 // If we don't know any bits, early out.
2423 if (Known.isUnknown())
2424 break;
2425 }
2426
2427 if (!DemandedVecElts.isZero()) {
2428 computeKnownBits(Vec, DemandedVecElts, Known2, Q, Depth + 1);
2429 Known = Known.intersectWith(Known2);
2430 }
2431 break;
2432 }
2433 case Instruction::ExtractElement: {
2434 // Look through extract element. If the index is non-constant or
2435 // out-of-range demand all elements, otherwise just the extracted element.
2436 const Value *Vec = I->getOperand(0);
2437 const Value *Idx = I->getOperand(1);
2438 auto *CIdx = dyn_cast<ConstantInt>(Idx);
2439 if (isa<ScalableVectorType>(Vec->getType())) {
2440 // FIXME: there's probably *something* we can do with scalable vectors
2441 Known.resetAll();
2442 break;
2443 }
2444 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
2445 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
2446 if (CIdx && CIdx->getValue().ult(NumElts))
2447 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2448 computeKnownBits(Vec, DemandedVecElts, Known, Q, Depth + 1);
2449 break;
2450 }
2451 case Instruction::ExtractValue:
2452 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
2454 if (EVI->getNumIndices() != 1) break;
2455 if (EVI->getIndices()[0] == 0) {
2456 switch (II->getIntrinsicID()) {
2457 default: break;
2458 case Intrinsic::uadd_with_overflow:
2459 case Intrinsic::sadd_with_overflow:
2461 true, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2462 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2463 break;
2464 case Intrinsic::usub_with_overflow:
2465 case Intrinsic::ssub_with_overflow:
2467 false, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2468 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2469 break;
2470 case Intrinsic::umul_with_overflow:
2471 case Intrinsic::smul_with_overflow:
2472 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
2473 false, DemandedElts, Known, Known2, Q, Depth);
2474 break;
2475 }
2476 }
2477 }
2478 break;
2479 case Instruction::Freeze:
2480 if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
2481 Depth + 1))
2482 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2483 break;
2484 }
2485}
2486
2487/// Determine which bits of V are known to be either zero or one and return
2488/// them.
2489KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
2490 const SimplifyQuery &Q, unsigned Depth) {
2491 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2492 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
2493 return Known;
2494}
2495
2496/// Determine which bits of V are known to be either zero or one and return
2497/// them.
2499 unsigned Depth) {
2500 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2502 return Known;
2503}
2504
2505/// Determine which bits of V are known to be either zero or one and return
2506/// them in the Known bit set.
2507///
2508/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
2509/// we cannot optimize based on the assumption that it is zero without changing
2510/// it to be an explicit zero. If we don't change it to zero, other code could
2511/// optimized based on the contradictory assumption that it is non-zero.
2512/// Because instcombine aggressively folds operations with undef args anyway,
2513/// this won't lose us code quality.
2514///
2515/// This function is defined on values with integer type, values with pointer
2516/// type, and vectors of integers. In the case
2517/// where V is a vector, known zero, and known one values are the
2518/// same width as the vector element, and the bit is set only if it is true
2519/// for all of the demanded elements in the vector specified by DemandedElts.
2520void computeKnownBits(const Value *V, const APInt &DemandedElts,
2521 KnownBits &Known, const SimplifyQuery &Q,
2522 unsigned Depth) {
2523 if (!DemandedElts) {
2524 // No demanded elts, better to assume we don't know anything.
2525 Known.resetAll();
2526 return;
2527 }
2528
2529 assert(V && "No Value?");
2530 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2531
2532#ifndef NDEBUG
2533 Type *Ty = V->getType();
2534 unsigned BitWidth = Known.getBitWidth();
2535
2536 assert((Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) &&
2537 "Not integer or pointer type!");
2538
2539 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2540 assert(
2541 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
2542 "DemandedElt width should equal the fixed vector number of elements");
2543 } else {
2544 assert(DemandedElts == APInt(1, 1) &&
2545 "DemandedElt width should be 1 for scalars or scalable vectors");
2546 }
2547
2548 Type *ScalarTy = Ty->getScalarType();
2549 if (ScalarTy->isPointerTy()) {
2550 assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) &&
2551 "V and Known should have same BitWidth");
2552 } else {
2553 assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) &&
2554 "V and Known should have same BitWidth");
2555 }
2556#endif
2557
2558 const APInt *C;
2559 if (match(V, m_APInt(C))) {
2560 // We know all of the bits for a scalar constant or a splat vector constant!
2562 return;
2563 }
2564 // Null and aggregate-zero are all-zeros.
2566 Known.setAllZero();
2567 return;
2568 }
2569 // Handle a constant vector by taking the intersection of the known bits of
2570 // each element.
2572 assert(!isa<ScalableVectorType>(V->getType()));
2573 // We know that CDV must be a vector of integers. Take the intersection of
2574 // each element.
2575 Known.setAllConflict();
2576 for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
2577 if (!DemandedElts[i])
2578 continue;
2579 APInt Elt = CDV->getElementAsAPInt(i);
2580 Known.Zero &= ~Elt;
2581 Known.One &= Elt;
2582 }
2583 if (Known.hasConflict())
2584 Known.resetAll();
2585 return;
2586 }
2587
2588 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
2589 assert(!isa<ScalableVectorType>(V->getType()));
2590 // We know that CV must be a vector of integers. Take the intersection of
2591 // each element.
2592 Known.setAllConflict();
2593 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
2594 if (!DemandedElts[i])
2595 continue;
2596 Constant *Element = CV->getAggregateElement(i);
2597 if (isa<PoisonValue>(Element))
2598 continue;
2599 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
2600 if (!ElementCI) {
2601 Known.resetAll();
2602 return;
2603 }
2604 const APInt &Elt = ElementCI->getValue();
2605 Known.Zero &= ~Elt;
2606 Known.One &= Elt;
2607 }
2608 if (Known.hasConflict())
2609 Known.resetAll();
2610 return;
2611 }
2612
2613 // Start out not knowing anything.
2614 Known.resetAll();
2615
2616 // We can't imply anything about undefs.
2617 if (isa<UndefValue>(V))
2618 return;
2619
2620 // There's no point in looking through other users of ConstantData for
2621 // assumptions. Confirm that we've handled them all.
2622 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
2623
2624 if (const auto *A = dyn_cast<Argument>(V))
2625 if (std::optional<ConstantRange> Range = A->getRange())
2626 Known = Range->toKnownBits();
2627
2628 // All recursive calls that increase depth must come after this.
2630 return;
2631
2632 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
2633 // the bits of its aliasee.
2634 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2635 if (!GA->isInterposable())
2636 computeKnownBits(GA->getAliasee(), Known, Q, Depth + 1);
2637 return;
2638 }
2639
2640 if (const Operator *I = dyn_cast<Operator>(V))
2641 computeKnownBitsFromOperator(I, DemandedElts, Known, Q, Depth);
2642 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2643 if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange())
2644 Known = CR->toKnownBits();
2645 }
2646
2647 // Aligned pointers have trailing zeros - refine Known.Zero set
2648 if (isa<PointerType>(V->getType())) {
2649 Align Alignment = V->getPointerAlignment(Q.DL);
2650 Known.Zero.setLowBits(Log2(Alignment));
2651 }
2652
2653 // computeKnownBitsFromContext strictly refines Known.
2654 // Therefore, we run them after computeKnownBitsFromOperator.
2655
2656 // Check whether we can determine known bits from context such as assumes.
2658}
2659
2660/// Try to detect a recurrence that the value of the induction variable is
2661/// always a power of two (or zero).
2662static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero,
2663 SimplifyQuery &Q, unsigned Depth) {
2664 BinaryOperator *BO = nullptr;
2665 Value *Start = nullptr, *Step = nullptr;
2666 if (!matchSimpleRecurrence(PN, BO, Start, Step))
2667 return false;
2668
2669 // Initial value must be a power of two.
2670 for (const Use &U : PN->operands()) {
2671 if (U.get() == Start) {
2672 // Initial value comes from a different BB, need to adjust context
2673 // instruction for analysis.
2674 Q.CxtI = PN->getIncomingBlock(U)->getTerminator();
2675 if (!isKnownToBeAPowerOfTwo(Start, OrZero, Q, Depth))
2676 return false;
2677 }
2678 }
2679
2680 // Except for Mul, the induction variable must be on the left side of the
2681 // increment expression, otherwise its value can be arbitrary.
2682 if (BO->getOpcode() != Instruction::Mul && BO->getOperand(1) != Step)
2683 return false;
2684
2685 Q.CxtI = BO->getParent()->getTerminator();
2686 switch (BO->getOpcode()) {
2687 case Instruction::Mul:
2688 // Power of two is closed under multiplication.
2689 return (OrZero || Q.IIQ.hasNoUnsignedWrap(BO) ||
2690 Q.IIQ.hasNoSignedWrap(BO)) &&
2691 isKnownToBeAPowerOfTwo(Step, OrZero, Q, Depth);
2692 case Instruction::SDiv:
2693 // Start value must not be signmask for signed division, so simply being a
2694 // power of two is not sufficient, and it has to be a constant.
2695 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2696 return false;
2697 [[fallthrough]];
2698 case Instruction::UDiv:
2699 // Divisor must be a power of two.
2700 // If OrZero is false, cannot guarantee induction variable is non-zero after
2701 // division, same for Shr, unless it is exact division.
2702 return (OrZero || Q.IIQ.isExact(BO)) &&
2703 isKnownToBeAPowerOfTwo(Step, false, Q, Depth);
2704 case Instruction::Shl:
2705 return OrZero || Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO);
2706 case Instruction::AShr:
2707 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2708 return false;
2709 [[fallthrough]];
2710 case Instruction::LShr:
2711 return OrZero || Q.IIQ.isExact(BO);
2712 default:
2713 return false;
2714 }
2715}
2716
2717/// Return true if we can infer that \p V is known to be a power of 2 from
2718/// dominating condition \p Cond (e.g., ctpop(V) == 1).
2719static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero,
2720 const Value *Cond,
2721 bool CondIsTrue) {
2722 CmpPredicate Pred;
2723 const APInt *RHSC;
2724 if (!match(Cond, m_ICmp(Pred, m_Ctpop(m_Specific(V)), m_APInt(RHSC))))
2725 return false;
2726 if (!CondIsTrue)
2727 Pred = ICmpInst::getInversePredicate(Pred);
2728 // ctpop(V) u< 2
2729 if (OrZero && Pred == ICmpInst::ICMP_ULT && *RHSC == 2)
2730 return true;
2731 // ctpop(V) == 1
2732 return Pred == ICmpInst::ICMP_EQ && *RHSC == 1;
2733}
2734
2735/// Return true if the given value is known to have exactly one
2736/// bit set when defined. For vectors return true if every element is known to
2737/// be a power of two when defined. Supports values with integer or pointer
2738/// types and vectors of integers.
2739bool llvm::isKnownToBeAPowerOfTwo(const Value *V, bool OrZero,
2740 const SimplifyQuery &Q, unsigned Depth) {
2741 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2742
2743 if (isa<Constant>(V))
2744 return OrZero ? match(V, m_Power2OrZero()) : match(V, m_Power2());
2745
2746 // i1 is by definition a power of 2 or zero.
2747 if (OrZero && V->getType()->getScalarSizeInBits() == 1)
2748 return true;
2749
2750 // Try to infer from assumptions.
2751 if (Q.AC && Q.CxtI) {
2752 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
2753 if (!AssumeVH)
2754 continue;
2755 CallInst *I = cast<CallInst>(AssumeVH);
2756 if (isImpliedToBeAPowerOfTwoFromCond(V, OrZero, I->getArgOperand(0),
2757 /*CondIsTrue=*/true) &&
2759 return true;
2760 }
2761 }
2762
2763 // Handle dominating conditions.
2764 if (Q.DC && Q.CxtI && Q.DT) {
2765 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
2766 Value *Cond = BI->getCondition();
2767
2768 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
2770 /*CondIsTrue=*/true) &&
2771 Q.DT->dominates(Edge0, Q.CxtI->getParent()))
2772 return true;
2773
2774 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
2776 /*CondIsTrue=*/false) &&
2777 Q.DT->dominates(Edge1, Q.CxtI->getParent()))
2778 return true;
2779 }
2780 }
2781
2782 auto *I = dyn_cast<Instruction>(V);
2783 if (!I)
2784 return false;
2785
2786 if (Q.CxtI && match(V, m_VScale())) {
2787 const Function *F = Q.CxtI->getFunction();
2788 // The vscale_range indicates vscale is a power-of-two.
2789 return F->hasFnAttribute(Attribute::VScaleRange);
2790 }
2791
2792 // 1 << X is clearly a power of two if the one is not shifted off the end. If
2793 // it is shifted off the end then the result is undefined.
2794 if (match(I, m_Shl(m_One(), m_Value())))
2795 return true;
2796
2797 // (signmask) >>l X is clearly a power of two if the one is not shifted off
2798 // the bottom. If it is shifted off the bottom then the result is undefined.
2799 if (match(I, m_LShr(m_SignMask(), m_Value())))
2800 return true;
2801
2802 // The remaining tests are all recursive, so bail out if we hit the limit.
2804 return false;
2805
2806 switch (I->getOpcode()) {
2807 case Instruction::ZExt:
2808 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2809 case Instruction::Trunc:
2810 return OrZero && isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2811 case Instruction::Shl:
2812 if (OrZero || Q.IIQ.hasNoUnsignedWrap(I) || Q.IIQ.hasNoSignedWrap(I))
2813 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2814 return false;
2815 case Instruction::LShr:
2816 if (OrZero || Q.IIQ.isExact(cast<BinaryOperator>(I)))
2817 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2818 return false;
2819 case Instruction::UDiv:
2821 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2822 return false;
2823 case Instruction::Mul:
2824 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2825 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth) &&
2826 (OrZero || isKnownNonZero(I, Q, Depth));
2827 case Instruction::And:
2828 // A power of two and'd with anything is a power of two or zero.
2829 if (OrZero &&
2830 (isKnownToBeAPowerOfTwo(I->getOperand(1), /*OrZero*/ true, Q, Depth) ||
2831 isKnownToBeAPowerOfTwo(I->getOperand(0), /*OrZero*/ true, Q, Depth)))
2832 return true;
2833 // X & (-X) is always a power of two or zero.
2834 if (match(I->getOperand(0), m_Neg(m_Specific(I->getOperand(1)))) ||
2835 match(I->getOperand(1), m_Neg(m_Specific(I->getOperand(0)))))
2836 return OrZero || isKnownNonZero(I->getOperand(0), Q, Depth);
2837 return false;
2838 case Instruction::Add: {
2839 // Adding a power-of-two or zero to the same power-of-two or zero yields
2840 // either the original power-of-two, a larger power-of-two or zero.
2842 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
2843 Q.IIQ.hasNoSignedWrap(VOBO)) {
2844 if (match(I->getOperand(0),
2845 m_c_And(m_Specific(I->getOperand(1)), m_Value())) &&
2846 isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth))
2847 return true;
2848 if (match(I->getOperand(1),
2849 m_c_And(m_Specific(I->getOperand(0)), m_Value())) &&
2850 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth))
2851 return true;
2852
2853 unsigned BitWidth = V->getType()->getScalarSizeInBits();
2854 KnownBits LHSBits(BitWidth);
2855 computeKnownBits(I->getOperand(0), LHSBits, Q, Depth);
2856
2857 KnownBits RHSBits(BitWidth);
2858 computeKnownBits(I->getOperand(1), RHSBits, Q, Depth);
2859 // If i8 V is a power of two or zero:
2860 // ZeroBits: 1 1 1 0 1 1 1 1
2861 // ~ZeroBits: 0 0 0 1 0 0 0 0
2862 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
2863 // If OrZero isn't set, we cannot give back a zero result.
2864 // Make sure either the LHS or RHS has a bit set.
2865 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
2866 return true;
2867 }
2868
2869 // LShr(UINT_MAX, Y) + 1 is a power of two (if add is nuw) or zero.
2870 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO))
2871 if (match(I, m_Add(m_LShr(m_AllOnes(), m_Value()), m_One())))
2872 return true;
2873 return false;
2874 }
2875 case Instruction::Select:
2876 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2877 isKnownToBeAPowerOfTwo(I->getOperand(2), OrZero, Q, Depth);
2878 case Instruction::PHI: {
2879 // A PHI node is power of two if all incoming values are power of two, or if
2880 // it is an induction variable where in each step its value is a power of
2881 // two.
2882 auto *PN = cast<PHINode>(I);
2884
2885 // Check if it is an induction variable and always power of two.
2886 if (isPowerOfTwoRecurrence(PN, OrZero, RecQ, Depth))
2887 return true;
2888
2889 // Recursively check all incoming values. Limit recursion to 2 levels, so
2890 // that search complexity is limited to number of operands^2.
2891 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
2892 return llvm::all_of(PN->operands(), [&](const Use &U) {
2893 // Value is power of 2 if it is coming from PHI node itself by induction.
2894 if (U.get() == PN)
2895 return true;
2896
2897 // Change the context instruction to the incoming block where it is
2898 // evaluated.
2899 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
2900 return isKnownToBeAPowerOfTwo(U.get(), OrZero, RecQ, NewDepth);
2901 });
2902 }
2903 case Instruction::Invoke:
2904 case Instruction::Call: {
2905 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2906 switch (II->getIntrinsicID()) {
2907 case Intrinsic::umax:
2908 case Intrinsic::smax:
2909 case Intrinsic::umin:
2910 case Intrinsic::smin:
2911 return isKnownToBeAPowerOfTwo(II->getArgOperand(1), OrZero, Q, Depth) &&
2912 isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2913 // bswap/bitreverse just move around bits, but don't change any 1s/0s
2914 // thus dont change pow2/non-pow2 status.
2915 case Intrinsic::bitreverse:
2916 case Intrinsic::bswap:
2917 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2918 case Intrinsic::fshr:
2919 case Intrinsic::fshl:
2920 // If Op0 == Op1, this is a rotate. is_pow2(rotate(x, y)) == is_pow2(x)
2921 if (II->getArgOperand(0) == II->getArgOperand(1))
2922 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2923 break;
2924 case Intrinsic::riscv_vsetvlimax:
2925 // VLMAX is VLEN * LMUL / SEW, which is always a non-zero power of two
2926 // for any valid vtype, so it is a power of two regardless of OrZero.
2927 return true;
2928 case Intrinsic::read_register:
2929 case Intrinsic::read_volatile_register: {
2930 // The RISC-V vlenb CSR holds VLEN/8, which is always a non-zero power
2931 // of two, so it is a power of two regardless of OrZero.
2932 const Module *M = II->getModule();
2933 if (!M || !M->getTargetTriple().isRISCV())
2934 break;
2935 return isReadVLENB(*II);
2936 }
2937 default:
2938 break;
2939 }
2940 }
2941 return false;
2942 }
2943 default:
2944 return false;
2945 }
2946}
2947
2948/// Test whether a GEP's result is known to be non-null.
2949///
2950/// Uses properties inherent in a GEP to try to determine whether it is known
2951/// to be non-null.
2952///
2953/// Currently this routine does not support vector GEPs.
2954static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q,
2955 unsigned Depth) {
2956 const Function *F = nullptr;
2957 if (const Instruction *I = dyn_cast<Instruction>(GEP))
2958 F = I->getFunction();
2959
2960 // If the gep is nuw or inbounds with invalid null pointer, then the GEP
2961 // may be null iff the base pointer is null and the offset is zero.
2962 if (!GEP->hasNoUnsignedWrap() &&
2963 !(GEP->isInBounds() &&
2964 !NullPointerIsDefined(F, GEP->getPointerAddressSpace())))
2965 return false;
2966
2967 // FIXME: Support vector-GEPs.
2968 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
2969
2970 // If the base pointer is non-null, we cannot walk to a null address with an
2971 // inbounds GEP in address space zero.
2972 if (isKnownNonZero(GEP->getPointerOperand(), Q, Depth))
2973 return true;
2974
2975 // Walk the GEP operands and see if any operand introduces a non-zero offset.
2976 // If so, then the GEP cannot produce a null pointer, as doing so would
2977 // inherently violate the inbounds contract within address space zero.
2979 GTI != GTE; ++GTI) {
2980 // Struct types are easy -- they must always be indexed by a constant.
2981 if (StructType *STy = GTI.getStructTypeOrNull()) {
2982 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
2983 unsigned ElementIdx = OpC->getZExtValue();
2984 const StructLayout *SL = Q.DL.getStructLayout(STy);
2985 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
2986 if (ElementOffset > 0)
2987 return true;
2988 continue;
2989 }
2990
2991 // If we have a zero-sized type, the index doesn't matter. Keep looping.
2992 if (GTI.getSequentialElementStride(Q.DL).isZero())
2993 continue;
2994
2995 // Fast path the constant operand case both for efficiency and so we don't
2996 // increment Depth when just zipping down an all-constant GEP.
2997 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
2998 if (!OpC->isZero())
2999 return true;
3000 continue;
3001 }
3002
3003 // We post-increment Depth here because while isKnownNonZero increments it
3004 // as well, when we pop back up that increment won't persist. We don't want
3005 // to recurse 10k times just because we have 10k GEP operands. We don't
3006 // bail completely out because we want to handle constant GEPs regardless
3007 // of depth.
3009 continue;
3010
3011 if (isKnownNonZero(GTI.getOperand(), Q, Depth))
3012 return true;
3013 }
3014
3015 return false;
3016}
3017
3019 const Instruction *CtxI,
3020 const DominatorTree *DT) {
3021 assert(!isa<Constant>(V) && "Called for constant?");
3022
3023 if (!CtxI || !DT)
3024 return false;
3025
3026 unsigned NumUsesExplored = 0;
3027 for (auto &U : V->uses()) {
3028 // Avoid massive lists
3029 if (NumUsesExplored >= DomConditionsMaxUses)
3030 break;
3031 NumUsesExplored++;
3032
3033 const Instruction *UI = cast<Instruction>(U.getUser());
3034 // If the value is used as an argument to a call or invoke, then argument
3035 // attributes may provide an answer about null-ness.
3036 if (V->getType()->isPointerTy()) {
3037 if (const auto *CB = dyn_cast<CallBase>(UI)) {
3038 if (CB->isArgOperand(&U) &&
3039 CB->paramHasNonNullAttr(CB->getArgOperandNo(&U),
3040 /*AllowUndefOrPoison=*/false) &&
3041 DT->dominates(CB, CtxI))
3042 return true;
3043 }
3044 }
3045
3046 // If the value is used as a load/store, then the pointer must be non null.
3047 if (V == getLoadStorePointerOperand(UI)) {
3050 DT->dominates(UI, CtxI))
3051 return true;
3052 }
3053
3054 if ((match(UI, m_IDiv(m_Value(), m_Specific(V))) ||
3055 match(UI, m_IRem(m_Value(), m_Specific(V)))) &&
3056 isValidAssumeForContext(UI, CtxI, DT))
3057 return true;
3058
3059 // Consider only compare instructions uniquely controlling a branch
3060 Value *RHS;
3061 CmpPredicate Pred;
3062 if (!match(UI, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS))))
3063 continue;
3064
3065 bool NonNullIfTrue;
3066 if (cmpExcludesZero(Pred, RHS))
3067 NonNullIfTrue = true;
3069 NonNullIfTrue = false;
3070 else
3071 continue;
3072
3075 for (const auto *CmpU : UI->users()) {
3076 assert(WorkList.empty() && "Should be!");
3077 if (Visited.insert(CmpU).second)
3078 WorkList.push_back(CmpU);
3079
3080 while (!WorkList.empty()) {
3081 auto *Curr = WorkList.pop_back_val();
3082
3083 // If a user is an AND, add all its users to the work list. We only
3084 // propagate "pred != null" condition through AND because it is only
3085 // correct to assume that all conditions of AND are met in true branch.
3086 // TODO: Support similar logic of OR and EQ predicate?
3087 if (NonNullIfTrue)
3088 if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) {
3089 for (const auto *CurrU : Curr->users())
3090 if (Visited.insert(CurrU).second)
3091 WorkList.push_back(CurrU);
3092 continue;
3093 }
3094
3095 if (const CondBrInst *BI = dyn_cast<CondBrInst>(Curr)) {
3096 BasicBlock *NonNullSuccessor =
3097 BI->getSuccessor(NonNullIfTrue ? 0 : 1);
3098 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3099 if (DT->dominates(Edge, CtxI->getParent()))
3100 return true;
3101 } else if (NonNullIfTrue && isGuard(Curr) &&
3102 DT->dominates(cast<Instruction>(Curr), CtxI)) {
3103 return true;
3104 }
3105 }
3106 }
3107 }
3108
3109 return false;
3110}
3111
3112/// Does the 'Range' metadata (which must be a valid MD_range operand list)
3113/// ensure that the value it's attached to is never Value? 'RangeType' is
3114/// is the type of the value described by the range.
3115static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
3116 const unsigned NumRanges = Ranges->getNumOperands() / 2;
3117 assert(NumRanges >= 1);
3118 for (unsigned i = 0; i < NumRanges; ++i) {
3120 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
3122 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
3123 ConstantRange Range(Lower->getValue(), Upper->getValue());
3124 if (Range.contains(Value))
3125 return false;
3126 }
3127 return true;
3128}
3129
3130/// Try to detect a recurrence that monotonically increases/decreases from a
3131/// non-zero starting value. These are common as induction variables.
3132static bool isNonZeroRecurrence(const PHINode *PN) {
3133 BinaryOperator *BO = nullptr;
3134 Value *Start = nullptr, *Step = nullptr;
3135 const APInt *StartC, *StepC;
3136 if (!matchSimpleRecurrence(PN, BO, Start, Step) ||
3137 !match(Start, m_APInt(StartC)) || StartC->isZero())
3138 return false;
3139
3140 switch (BO->getOpcode()) {
3141 case Instruction::Add:
3142 // Starting from non-zero and stepping away from zero can never wrap back
3143 // to zero.
3144 return BO->hasNoUnsignedWrap() ||
3145 (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) &&
3146 StartC->isNegative() == StepC->isNegative());
3147 case Instruction::Mul:
3148 return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) &&
3149 match(Step, m_APInt(StepC)) && !StepC->isZero();
3150 case Instruction::Shl:
3151 return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap();
3152 case Instruction::AShr:
3153 case Instruction::LShr:
3154 return BO->isExact();
3155 default:
3156 return false;
3157 }
3158}
3159
3160static bool matchOpWithOpEqZero(Value *Op0, Value *Op1) {
3162 m_Specific(Op1), m_Zero()))) ||
3164 m_Specific(Op0), m_Zero())));
3165}
3166
3167static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q,
3168 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3169 bool NUW, unsigned Depth) {
3170 // (X + (X != 0)) is non zero
3171 if (matchOpWithOpEqZero(X, Y))
3172 return true;
3173
3174 if (NUW)
3175 return isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3176 isKnownNonZero(X, DemandedElts, Q, Depth);
3177
3178 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3179 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3180
3181 // If X and Y are both non-negative (as signed values) then their sum is not
3182 // zero unless both X and Y are zero.
3183 if (XKnown.isNonNegative() && YKnown.isNonNegative())
3184 if (isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3185 isKnownNonZero(X, DemandedElts, Q, Depth))
3186 return true;
3187
3188 // If X and Y are both negative (as signed values) then their sum is not
3189 // zero unless both X and Y equal INT_MIN.
3190 if (XKnown.isNegative() && YKnown.isNegative()) {
3192 // The sign bit of X is set. If some other bit is set then X is not equal
3193 // to INT_MIN.
3194 if (XKnown.One.intersects(Mask))
3195 return true;
3196 // The sign bit of Y is set. If some other bit is set then Y is not equal
3197 // to INT_MIN.
3198 if (YKnown.One.intersects(Mask))
3199 return true;
3200 }
3201
3202 // The sum of a non-negative number and a power of two is not zero.
3203 if (XKnown.isNonNegative() &&
3204 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Q, Depth))
3205 return true;
3206 if (YKnown.isNonNegative() &&
3207 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Q, Depth))
3208 return true;
3209
3210 return KnownBits::add(XKnown, YKnown, NSW, NUW).isNonZero();
3211}
3212
3213static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q,
3214 unsigned BitWidth, Value *X, Value *Y,
3215 unsigned Depth) {
3216 // (X - (X != 0)) is non zero
3217 // ((X != 0) - X) is non zero
3218 if (matchOpWithOpEqZero(X, Y))
3219 return true;
3220
3221 // TODO: Move this case into isKnownNonEqual().
3222 if (auto *C = dyn_cast<Constant>(X))
3223 if (C->isNullValue() && isKnownNonZero(Y, DemandedElts, Q, Depth))
3224 return true;
3225
3226 return ::isKnownNonEqual(X, Y, DemandedElts, Q, Depth);
3227}
3228
3229static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q,
3230 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3231 bool NUW, unsigned Depth) {
3232 // If X and Y are non-zero then so is X * Y as long as the multiplication
3233 // does not overflow.
3234 if (NSW || NUW)
3235 return isKnownNonZero(X, DemandedElts, Q, Depth) &&
3236 isKnownNonZero(Y, DemandedElts, Q, Depth);
3237
3238 // If either X or Y is odd, then if the other is non-zero the result can't
3239 // be zero.
3240 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3241 if (XKnown.One[0])
3242 return isKnownNonZero(Y, DemandedElts, Q, Depth);
3243
3244 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3245 if (YKnown.One[0])
3246 return XKnown.isNonZero() || isKnownNonZero(X, DemandedElts, Q, Depth);
3247
3248 // If there exists any subset of X (sX) and subset of Y (sY) s.t sX * sY is
3249 // non-zero, then X * Y is non-zero. We can find sX and sY by just taking
3250 // the lowest known One of X and Y. If they are non-zero, the result
3251 // must be non-zero. We can check if LSB(X) * LSB(Y) != 0 by doing
3252 // X.CountLeadingZeros + Y.CountLeadingZeros < BitWidth.
3253 return (XKnown.countMaxTrailingZeros() + YKnown.countMaxTrailingZeros()) <
3254 BitWidth;
3255}
3256
3257static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts,
3258 const SimplifyQuery &Q, const KnownBits &KnownVal,
3259 unsigned Depth) {
3260 auto ShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3261 switch (I->getOpcode()) {
3262 case Instruction::Shl:
3263 return Lhs.shl(Rhs);
3264 case Instruction::LShr:
3265 return Lhs.lshr(Rhs);
3266 case Instruction::AShr:
3267 return Lhs.ashr(Rhs);
3268 default:
3269 llvm_unreachable("Unknown Shift Opcode");
3270 }
3271 };
3272
3273 auto InvShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3274 switch (I->getOpcode()) {
3275 case Instruction::Shl:
3276 return Lhs.lshr(Rhs);
3277 case Instruction::LShr:
3278 case Instruction::AShr:
3279 return Lhs.shl(Rhs);
3280 default:
3281 llvm_unreachable("Unknown Shift Opcode");
3282 }
3283 };
3284
3285 if (KnownVal.isUnknown())
3286 return false;
3287
3288 KnownBits KnownCnt =
3289 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3290 APInt MaxShift = KnownCnt.getMaxValue();
3291 unsigned NumBits = KnownVal.getBitWidth();
3292 if (MaxShift.uge(NumBits))
3293 return false;
3294
3295 if (!ShiftOp(KnownVal.One, MaxShift).isZero())
3296 return true;
3297
3298 // If all of the bits shifted out are known to be zero, and Val is known
3299 // non-zero then at least one non-zero bit must remain.
3300 if (InvShiftOp(KnownVal.Zero, NumBits - MaxShift)
3301 .eq(InvShiftOp(APInt::getAllOnes(NumBits), NumBits - MaxShift)) &&
3302 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth))
3303 return true;
3304
3305 return false;
3306}
3307
3309 const APInt &DemandedElts,
3310 const SimplifyQuery &Q, unsigned Depth) {
3311 unsigned BitWidth = getBitWidth(I->getType()->getScalarType(), Q.DL);
3312 switch (I->getOpcode()) {
3313 case Instruction::Alloca:
3314 // Alloca never returns null, malloc might.
3315 return I->getType()->getPointerAddressSpace() == 0;
3316 case Instruction::GetElementPtr:
3317 if (I->getType()->isPointerTy())
3319 break;
3320 case Instruction::BitCast: {
3321 // We need to be a bit careful here. We can only peek through the bitcast
3322 // if the scalar size of elements in the operand are smaller than and a
3323 // multiple of the size they are casting too. Take three cases:
3324 //
3325 // 1) Unsafe:
3326 // bitcast <2 x i16> %NonZero to <4 x i8>
3327 //
3328 // %NonZero can have 2 non-zero i16 elements, but isKnownNonZero on a
3329 // <4 x i8> requires that all 4 i8 elements be non-zero which isn't
3330 // guranteed (imagine just sign bit set in the 2 i16 elements).
3331 //
3332 // 2) Unsafe:
3333 // bitcast <4 x i3> %NonZero to <3 x i4>
3334 //
3335 // Even though the scalar size of the src (`i3`) is smaller than the
3336 // scalar size of the dst `i4`, because `i3` is not a multiple of `i4`
3337 // its possible for the `3 x i4` elements to be zero because there are
3338 // some elements in the destination that don't contain any full src
3339 // element.
3340 //
3341 // 3) Safe:
3342 // bitcast <4 x i8> %NonZero to <2 x i16>
3343 //
3344 // This is always safe as non-zero in the 4 i8 elements implies
3345 // non-zero in the combination of any two adjacent ones. Since i8 is a
3346 // multiple of i16, each i16 is guranteed to have 2 full i8 elements.
3347 // This all implies the 2 i16 elements are non-zero.
3348 Type *FromTy = I->getOperand(0)->getType();
3349 if ((FromTy->isIntOrIntVectorTy() || FromTy->isPtrOrPtrVectorTy()) &&
3350 (BitWidth % getBitWidth(FromTy->getScalarType(), Q.DL)) == 0)
3351 return isKnownNonZero(I->getOperand(0), Q, Depth);
3352 } break;
3353 case Instruction::IntToPtr:
3354 // Note that we have to take special care to avoid looking through
3355 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
3356 // as casts that can alter the value, e.g., AddrSpaceCasts.
3357 if (!isa<ScalableVectorType>(I->getType()) &&
3358 Q.DL.getTypeSizeInBits(I->getOperand(0)->getType()).getFixedValue() <=
3359 Q.DL.getTypeSizeInBits(I->getType()).getFixedValue())
3360 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3361 break;
3362 case Instruction::PtrToAddr:
3363 // isKnownNonZero() for pointers refers to the address bits being non-zero,
3364 // so we can directly forward.
3365 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3366 case Instruction::PtrToInt:
3367 // For inttoptr, make sure the result size is >= the address size. If the
3368 // address is non-zero, any larger value is also non-zero.
3369 if (Q.DL.getAddressSizeInBits(I->getOperand(0)->getType()) <=
3370 I->getType()->getScalarSizeInBits())
3371 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3372 break;
3373 case Instruction::Trunc:
3374 // nuw/nsw trunc preserves zero/non-zero status of input.
3375 if (auto *TI = dyn_cast<TruncInst>(I))
3376 if (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap())
3377 return isKnownNonZero(TI->getOperand(0), DemandedElts, Q, Depth);
3378 break;
3379
3380 // Iff x - y != 0, then x ^ y != 0
3381 // Therefore we can do the same exact checks
3382 case Instruction::Xor:
3383 case Instruction::Sub:
3384 return isNonZeroSub(DemandedElts, Q, BitWidth, I->getOperand(0),
3385 I->getOperand(1), Depth);
3386 case Instruction::Or:
3387 // (X | (X != 0)) is non zero
3388 if (matchOpWithOpEqZero(I->getOperand(0), I->getOperand(1)))
3389 return true;
3390 // X | Y != 0 if X != Y.
3391 if (isKnownNonEqual(I->getOperand(0), I->getOperand(1), DemandedElts, Q,
3392 Depth))
3393 return true;
3394 // X | Y != 0 if X != 0 or Y != 0.
3395 return isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth) ||
3396 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3397 case Instruction::SExt:
3398 case Instruction::ZExt:
3399 // ext X != 0 if X != 0.
3400 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3401
3402 case Instruction::Shl: {
3403 // shl nsw/nuw can't remove any non-zero bits.
3405 if (Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO))
3406 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3407
3408 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
3409 // if the lowest bit is shifted off the end.
3411 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth);
3412 if (Known.One[0])
3413 return true;
3414
3415 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3416 }
3417 case Instruction::LShr:
3418 case Instruction::AShr: {
3419 // shr exact can only shift out zero bits.
3421 if (BO->isExact())
3422 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3423
3424 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
3425 // defined if the sign bit is shifted off the end.
3427 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3428 if (Known.isNegative())
3429 return true;
3430
3431 // shr (add nuw A, B), C is non-zero if A or B has a known-one bit at
3432 // position >= C, because the sum >= max(A, B).
3433 Value *A, *B;
3434 const APInt *C;
3435 if (Depth + 1 < MaxAnalysisRecursionDepth &&
3436 match(I->getOperand(0), m_NUWAdd(m_Value(A), m_Value(B))) &&
3437 match(I->getOperand(1), m_APInt(C)) && C->ult(BitWidth)) {
3438 KnownBits KnownA = computeKnownBits(A, DemandedElts, Q, Depth + 1);
3439 if (!KnownA.One.lshr(*C).isZero())
3440 return true;
3441 KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
3442 if (!KnownB.One.lshr(*C).isZero())
3443 return true;
3444 }
3445
3446 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3447 }
3448 case Instruction::UDiv:
3449 case Instruction::SDiv: {
3450 // X / Y
3451 // div exact can only produce a zero if the dividend is zero.
3452 if (cast<PossiblyExactOperator>(I)->isExact())
3453 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3454
3455 KnownBits XKnown =
3456 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3457 // If X is fully unknown we won't be able to figure anything out so don't
3458 // both computing knownbits for Y.
3459 if (XKnown.isUnknown())
3460 return false;
3461
3462 KnownBits YKnown =
3463 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3464 if (I->getOpcode() == Instruction::SDiv) {
3465 // For signed division need to compare abs value of the operands.
3466 XKnown = XKnown.abs(/*IntMinIsPoison*/ false);
3467 YKnown = YKnown.abs(/*IntMinIsPoison*/ false);
3468 }
3469 // If X u>= Y then div is non zero (0/0 is UB).
3470 std::optional<bool> XUgeY = KnownBits::uge(XKnown, YKnown);
3471 // If X is total unknown or X u< Y we won't be able to prove non-zero
3472 // with compute known bits so just return early.
3473 return XUgeY && *XUgeY;
3474 }
3475 case Instruction::Add: {
3476 // X + Y.
3477
3478 // If Add has nuw wrap flag, then if either X or Y is non-zero the result is
3479 // non-zero.
3481 return isNonZeroAdd(DemandedElts, Q, BitWidth, I->getOperand(0),
3482 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3483 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3484 }
3485 case Instruction::Mul: {
3487 return isNonZeroMul(DemandedElts, Q, BitWidth, I->getOperand(0),
3488 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3489 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3490 }
3491 case Instruction::Select: {
3492 // (C ? X : Y) != 0 if X != 0 and Y != 0.
3493
3494 // First check if the arm is non-zero using `isKnownNonZero`. If that fails,
3495 // then see if the select condition implies the arm is non-zero. For example
3496 // (X != 0 ? X : Y), we know the true arm is non-zero as the `X` "return" is
3497 // dominated by `X != 0`.
3498 auto SelectArmIsNonZero = [&](bool IsTrueArm) {
3499 Value *Op;
3500 Op = IsTrueArm ? I->getOperand(1) : I->getOperand(2);
3501 // Op is trivially non-zero.
3502 if (isKnownNonZero(Op, DemandedElts, Q, Depth))
3503 return true;
3504
3505 // The condition of the select dominates the true/false arm. Check if the
3506 // condition implies that a given arm is non-zero.
3507 Value *X;
3508 CmpPredicate Pred;
3509 if (!match(I->getOperand(0), m_c_ICmp(Pred, m_Specific(Op), m_Value(X))))
3510 return false;
3511
3512 if (!IsTrueArm)
3513 Pred = ICmpInst::getInversePredicate(Pred);
3514
3515 return cmpExcludesZero(Pred, X);
3516 };
3517
3518 if (SelectArmIsNonZero(/* IsTrueArm */ true) &&
3519 SelectArmIsNonZero(/* IsTrueArm */ false))
3520 return true;
3521 break;
3522 }
3523 case Instruction::PHI: {
3524 auto *PN = cast<PHINode>(I);
3526 return true;
3527
3528 // Check if all incoming values are non-zero using recursion.
3530 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
3531 return llvm::all_of(PN->operands(), [&](const Use &U) {
3532 if (U.get() == PN)
3533 return true;
3534 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
3535 // Check if the branch on the phi excludes zero.
3536 CmpPredicate Pred;
3537 Value *X;
3538 BasicBlock *TrueSucc, *FalseSucc;
3539 if (match(RecQ.CxtI,
3540 m_Br(m_c_ICmp(Pred, m_Specific(U.get()), m_Value(X)),
3541 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
3542 // Check for cases of duplicate successors.
3543 if ((TrueSucc == PN->getParent()) != (FalseSucc == PN->getParent())) {
3544 // If we're using the false successor, invert the predicate.
3545 if (FalseSucc == PN->getParent())
3546 Pred = CmpInst::getInversePredicate(Pred);
3547 if (cmpExcludesZero(Pred, X))
3548 return true;
3549 }
3550 }
3551 // Finally recurse on the edge and check it directly.
3552 return isKnownNonZero(U.get(), DemandedElts, RecQ, NewDepth);
3553 });
3554 }
3555 case Instruction::InsertElement: {
3556 if (isa<ScalableVectorType>(I->getType()))
3557 break;
3558
3559 const Value *Vec = I->getOperand(0);
3560 const Value *Elt = I->getOperand(1);
3561 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
3562
3563 unsigned NumElts = DemandedElts.getBitWidth();
3564 APInt DemandedVecElts = DemandedElts;
3565 bool SkipElt = false;
3566 // If we know the index we are inserting too, clear it from Vec check.
3567 if (CIdx && CIdx->getValue().ult(NumElts)) {
3568 DemandedVecElts.clearBit(CIdx->getZExtValue());
3569 SkipElt = !DemandedElts[CIdx->getZExtValue()];
3570 }
3571
3572 // Result is zero if Elt is non-zero and rest of the demanded elts in Vec
3573 // are non-zero.
3574 return (SkipElt || isKnownNonZero(Elt, Q, Depth)) &&
3575 (DemandedVecElts.isZero() ||
3576 isKnownNonZero(Vec, DemandedVecElts, Q, Depth));
3577 }
3578 case Instruction::ExtractElement:
3579 if (const auto *EEI = dyn_cast<ExtractElementInst>(I)) {
3580 const Value *Vec = EEI->getVectorOperand();
3581 const Value *Idx = EEI->getIndexOperand();
3582 auto *CIdx = dyn_cast<ConstantInt>(Idx);
3583 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
3584 unsigned NumElts = VecTy->getNumElements();
3585 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
3586 if (CIdx && CIdx->getValue().ult(NumElts))
3587 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
3588 return isKnownNonZero(Vec, DemandedVecElts, Q, Depth);
3589 }
3590 }
3591 break;
3592 case Instruction::ShuffleVector: {
3593 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
3594 if (!Shuf)
3595 break;
3596 APInt DemandedLHS, DemandedRHS;
3597 // For undef elements, we don't know anything about the common state of
3598 // the shuffle result.
3599 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
3600 break;
3601 // If demanded elements for both vecs are non-zero, the shuffle is non-zero.
3602 return (DemandedRHS.isZero() ||
3603 isKnownNonZero(Shuf->getOperand(1), DemandedRHS, Q, Depth)) &&
3604 (DemandedLHS.isZero() ||
3605 isKnownNonZero(Shuf->getOperand(0), DemandedLHS, Q, Depth));
3606 }
3607 case Instruction::Freeze:
3608 return isKnownNonZero(I->getOperand(0), Q, Depth) &&
3609 isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
3610 Depth);
3611 case Instruction::Load: {
3612 auto *LI = cast<LoadInst>(I);
3613 // A Load tagged with nonnull or dereferenceable with null pointer undefined
3614 // is never null.
3615 if (auto *PtrT = dyn_cast<PointerType>(I->getType())) {
3616 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull) ||
3617 (Q.IIQ.getMetadata(LI, LLVMContext::MD_dereferenceable) &&
3618 !NullPointerIsDefined(LI->getFunction(), PtrT->getAddressSpace())))
3619 return true;
3620 } else if (MDNode *Ranges = Q.IIQ.getMetadata(LI, LLVMContext::MD_range)) {
3622 }
3623
3624 // No need to fall through to computeKnownBits as range metadata is already
3625 // handled in isKnownNonZero.
3626 return false;
3627 }
3628 case Instruction::ExtractValue: {
3629 const WithOverflowInst *WO;
3631 switch (WO->getBinaryOp()) {
3632 default:
3633 break;
3634 case Instruction::Add:
3635 return isNonZeroAdd(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3636 WO->getArgOperand(1),
3637 /*NSW=*/false,
3638 /*NUW=*/false, Depth);
3639 case Instruction::Sub:
3640 return isNonZeroSub(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3641 WO->getArgOperand(1), Depth);
3642 case Instruction::Mul:
3643 return isNonZeroMul(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3644 WO->getArgOperand(1),
3645 /*NSW=*/false, /*NUW=*/false, Depth);
3646 break;
3647 }
3648 }
3649 break;
3650 }
3651 case Instruction::Call:
3652 case Instruction::Invoke: {
3653 const auto *Call = cast<CallBase>(I);
3654 if (I->getType()->isPointerTy()) {
3655 if (Call->isReturnNonNull())
3656 return true;
3657 if (const auto *RP = getArgumentAliasingToReturnedPointer(
3658 Call, /*MustPreserveOffset=*/true))
3659 return isKnownNonZero(RP, Q, Depth);
3660 } else {
3661 if (MDNode *Ranges = Q.IIQ.getMetadata(Call, LLVMContext::MD_range))
3663 if (std::optional<ConstantRange> Range = Call->getRange()) {
3664 const APInt ZeroValue(Range->getBitWidth(), 0);
3665 if (!Range->contains(ZeroValue))
3666 return true;
3667 }
3668 if (const Value *RV = Call->getReturnedArgOperand())
3669 if (RV->getType() == I->getType() && isKnownNonZero(RV, Q, Depth))
3670 return true;
3671 }
3672
3673 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
3674 switch (II->getIntrinsicID()) {
3675 case Intrinsic::sshl_sat:
3676 case Intrinsic::ushl_sat:
3677 case Intrinsic::abs:
3678 case Intrinsic::bitreverse:
3679 case Intrinsic::bswap:
3680 case Intrinsic::ctpop:
3681 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3682 // NB: We don't do usub_sat here as in any case we can prove its
3683 // non-zero, we will fold it to `sub nuw` in InstCombine.
3684 case Intrinsic::ssub_sat:
3685 // For most types, if x != y then ssub.sat x, y != 0. But
3686 // ssub.sat.i1 0, -1 = 0, because 1 saturates to 0. This means
3687 // isNonZeroSub will do the wrong thing for ssub.sat.i1.
3688 if (BitWidth == 1)
3689 return false;
3690 return isNonZeroSub(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3691 II->getArgOperand(1), Depth);
3692 case Intrinsic::sadd_sat:
3693 return isNonZeroAdd(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3694 II->getArgOperand(1),
3695 /*NSW=*/true, /* NUW=*/false, Depth);
3696 // Vec reverse preserves zero/non-zero status from input vec.
3697 case Intrinsic::vector_reverse:
3698 return isKnownNonZero(II->getArgOperand(0), DemandedElts.reverseBits(),
3699 Q, Depth);
3700 // umin/smin/smax/smin/or of all non-zero elements is always non-zero.
3701 case Intrinsic::vector_reduce_or:
3702 case Intrinsic::vector_reduce_umax:
3703 case Intrinsic::vector_reduce_umin:
3704 case Intrinsic::vector_reduce_smax:
3705 case Intrinsic::vector_reduce_smin:
3706 return isKnownNonZero(II->getArgOperand(0), Q, Depth);
3707 case Intrinsic::umax:
3708 case Intrinsic::uadd_sat:
3709 // umax(X, (X != 0)) is non zero
3710 // X +usat (X != 0) is non zero
3711 if (matchOpWithOpEqZero(II->getArgOperand(0), II->getArgOperand(1)))
3712 return true;
3713
3714 return isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth) ||
3715 isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3716 case Intrinsic::smax: {
3717 // If either arg is strictly positive the result is non-zero. Otherwise
3718 // the result is non-zero if both ops are non-zero.
3719 auto IsNonZero = [&](Value *Op, std::optional<bool> &OpNonZero,
3720 const KnownBits &OpKnown) {
3721 if (!OpNonZero.has_value())
3722 OpNonZero = OpKnown.isNonZero() ||
3723 isKnownNonZero(Op, DemandedElts, Q, Depth);
3724 return *OpNonZero;
3725 };
3726 // Avoid re-computing isKnownNonZero.
3727 std::optional<bool> Op0NonZero, Op1NonZero;
3728 KnownBits Op1Known =
3729 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3730 if (Op1Known.isNonNegative() &&
3731 IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known))
3732 return true;
3733 KnownBits Op0Known =
3734 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3735 if (Op0Known.isNonNegative() &&
3736 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known))
3737 return true;
3738 return IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known) &&
3739 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known);
3740 }
3741 case Intrinsic::smin: {
3742 // If either arg is negative the result is non-zero. Otherwise
3743 // the result is non-zero if both ops are non-zero.
3744 KnownBits Op1Known =
3745 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3746 if (Op1Known.isNegative())
3747 return true;
3748 KnownBits Op0Known =
3749 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3750 if (Op0Known.isNegative())
3751 return true;
3752
3753 if (Op1Known.isNonZero() && Op0Known.isNonZero())
3754 return true;
3755 }
3756 [[fallthrough]];
3757 case Intrinsic::umin:
3758 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth) &&
3759 isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth);
3760 case Intrinsic::cttz:
3761 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3762 .Zero[0];
3763 case Intrinsic::ctlz:
3764 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3765 .isNonNegative();
3766 case Intrinsic::fshr:
3767 case Intrinsic::fshl:
3768 // If Op0 == Op1, this is a rotate. rotate(x, y) != 0 iff x != 0.
3769 if (II->getArgOperand(0) == II->getArgOperand(1))
3770 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3771 break;
3772 case Intrinsic::vscale:
3773 return true;
3774 case Intrinsic::experimental_get_vector_length:
3775 return isKnownNonZero(I->getOperand(0), Q, Depth);
3776 default:
3777 break;
3778 }
3779 break;
3780 }
3781
3782 return false;
3783 }
3784 }
3785
3787 computeKnownBits(I, DemandedElts, Known, Q, Depth);
3788 return Known.One != 0;
3789}
3790
3791/// Return true if the given value is known to be non-zero when defined. For
3792/// vectors, return true if every demanded element is known to be non-zero when
3793/// defined. For pointers, if the context instruction and dominator tree are
3794/// specified, perform context-sensitive analysis and return true if the
3795/// pointer couldn't possibly be null at the specified instruction.
3796/// Supports values with integer or pointer type and vectors of integers.
3797bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
3798 const SimplifyQuery &Q, unsigned Depth) {
3799 Type *Ty = V->getType();
3800
3801#ifndef NDEBUG
3802 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
3803
3804 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
3805 assert(
3806 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
3807 "DemandedElt width should equal the fixed vector number of elements");
3808 } else {
3809 assert(DemandedElts == APInt(1, 1) &&
3810 "DemandedElt width should be 1 for scalars");
3811 }
3812#endif
3813
3814 if (auto *C = dyn_cast<Constant>(V)) {
3815 if (C->isNullValue())
3816 return false;
3817 if (isa<ConstantInt>(C))
3818 // Must be non-zero due to null test above.
3819 return true;
3820
3821 // For constant vectors, check that all elements are poison or known
3822 // non-zero to determine that the whole vector is known non-zero.
3823 if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
3824 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
3825 if (!DemandedElts[i])
3826 continue;
3827 Constant *Elt = C->getAggregateElement(i);
3828 if (!Elt || Elt->isNullValue())
3829 return false;
3830 if (!isa<PoisonValue>(Elt) && !isa<ConstantInt>(Elt))
3831 return false;
3832 }
3833 return true;
3834 }
3835
3836 // Constant ptrauth can be null, iff the base pointer can be.
3837 if (auto *CPA = dyn_cast<ConstantPtrAuth>(V))
3838 return isKnownNonZero(CPA->getPointer(), DemandedElts, Q, Depth);
3839
3840 // A global variable in address space 0 is non null unless extern weak
3841 // or an absolute symbol reference. Other address spaces may have null as a
3842 // valid address for a global, so we can't assume anything.
3843 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3844 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
3845 GV->getType()->getAddressSpace() == 0)
3846 return true;
3847 }
3848
3849 // For constant expressions, fall through to the Operator code below.
3850 if (!isa<ConstantExpr>(V))
3851 return false;
3852 }
3853
3854 if (const auto *A = dyn_cast<Argument>(V))
3855 if (std::optional<ConstantRange> Range = A->getRange()) {
3856 const APInt ZeroValue(Range->getBitWidth(), 0);
3857 if (!Range->contains(ZeroValue))
3858 return true;
3859 }
3860
3861 if (!isa<Constant>(V) && isKnownNonZeroFromAssume(V, Q))
3862 return true;
3863
3864 // Some of the tests below are recursive, so bail out if we hit the limit.
3866 return false;
3867
3868 // Check for pointer simplifications.
3869
3870 if (PointerType *PtrTy = dyn_cast<PointerType>(Ty)) {
3871 // A byval, inalloca may not be null in a non-default addres space. A
3872 // nonnull argument is assumed never 0.
3873 if (const Argument *A = dyn_cast<Argument>(V)) {
3874 if (((A->hasPassPointeeByValueCopyAttr() &&
3875 !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
3876 A->hasNonNullAttr()))
3877 return true;
3878 }
3879 }
3880
3881 if (const auto *I = dyn_cast<Operator>(V))
3882 if (isKnownNonZeroFromOperator(I, DemandedElts, Q, Depth))
3883 return true;
3884
3885 if (!isa<Constant>(V) &&
3887 return true;
3888
3889 if (const Value *Stripped = stripNullTest(V))
3890 return isKnownNonZero(Stripped, DemandedElts, Q, Depth);
3891
3892 return false;
3893}
3894
3896 unsigned Depth) {
3897 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
3898 APInt DemandedElts =
3899 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
3900 return ::isKnownNonZero(V, DemandedElts, Q, Depth);
3901}
3902
3903/// If the pair of operators are the same invertible function, return the
3904/// the operands of the function corresponding to each input. Otherwise,
3905/// return std::nullopt. An invertible function is one that is 1-to-1 and maps
3906/// every input value to exactly one output value. This is equivalent to
3907/// saying that Op1 and Op2 are equal exactly when the specified pair of
3908/// operands are equal, (except that Op1 and Op2 may be poison more often.)
3909static std::optional<std::pair<Value*, Value*>>
3911 const Operator *Op2) {
3912 if (Op1->getOpcode() != Op2->getOpcode())
3913 return std::nullopt;
3914
3915 auto getOperands = [&](unsigned OpNum) -> auto {
3916 return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
3917 };
3918
3919 switch (Op1->getOpcode()) {
3920 default:
3921 break;
3922 case Instruction::Or:
3923 if (!cast<PossiblyDisjointInst>(Op1)->isDisjoint() ||
3924 !cast<PossiblyDisjointInst>(Op2)->isDisjoint())
3925 break;
3926 [[fallthrough]];
3927 case Instruction::Xor:
3928 case Instruction::Add: {
3929 Value *Other;
3930 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(0)), m_Value(Other))))
3931 return std::make_pair(Op1->getOperand(1), Other);
3932 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(1)), m_Value(Other))))
3933 return std::make_pair(Op1->getOperand(0), Other);
3934 break;
3935 }
3936 case Instruction::Sub:
3937 if (Op1->getOperand(0) == Op2->getOperand(0))
3938 return getOperands(1);
3939 if (Op1->getOperand(1) == Op2->getOperand(1))
3940 return getOperands(0);
3941 break;
3942 case Instruction::Mul: {
3943 // invertible if A * B == (A * B) mod 2^N where A, and B are integers
3944 // and N is the bitwdith. The nsw case is non-obvious, but proven by
3945 // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
3946 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3947 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3948 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3949 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3950 break;
3951
3952 // Assume operand order has been canonicalized
3953 if (Op1->getOperand(1) == Op2->getOperand(1) &&
3954 isa<ConstantInt>(Op1->getOperand(1)) &&
3955 !cast<ConstantInt>(Op1->getOperand(1))->isZero())
3956 return getOperands(0);
3957 break;
3958 }
3959 case Instruction::Shl: {
3960 // Same as multiplies, with the difference that we don't need to check
3961 // for a non-zero multiply. Shifts always multiply by non-zero.
3962 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3963 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3964 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3965 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3966 break;
3967
3968 if (Op1->getOperand(1) == Op2->getOperand(1))
3969 return getOperands(0);
3970 break;
3971 }
3972 case Instruction::AShr:
3973 case Instruction::LShr: {
3974 auto *PEO1 = cast<PossiblyExactOperator>(Op1);
3975 auto *PEO2 = cast<PossiblyExactOperator>(Op2);
3976 if (!PEO1->isExact() || !PEO2->isExact())
3977 break;
3978
3979 if (Op1->getOperand(1) == Op2->getOperand(1))
3980 return getOperands(0);
3981 break;
3982 }
3983 case Instruction::SExt:
3984 case Instruction::ZExt:
3985 if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
3986 return getOperands(0);
3987 break;
3988 case Instruction::PHI: {
3989 const PHINode *PN1 = cast<PHINode>(Op1);
3990 const PHINode *PN2 = cast<PHINode>(Op2);
3991
3992 // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
3993 // are a single invertible function of the start values? Note that repeated
3994 // application of an invertible function is also invertible
3995 BinaryOperator *BO1 = nullptr;
3996 Value *Start1 = nullptr, *Step1 = nullptr;
3997 BinaryOperator *BO2 = nullptr;
3998 Value *Start2 = nullptr, *Step2 = nullptr;
3999 if (PN1->getParent() != PN2->getParent() ||
4000 !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
4001 !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
4002 break;
4003
4005 cast<Operator>(BO2));
4006 if (!Values)
4007 break;
4008
4009 // We have to be careful of mutually defined recurrences here. Ex:
4010 // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
4011 // * X_i = Y_i = X_(i-1) OP Y_(i-1)
4012 // The invertibility of these is complicated, and not worth reasoning
4013 // about (yet?).
4014 if (Values->first != PN1 || Values->second != PN2)
4015 break;
4016
4017 return std::make_pair(Start1, Start2);
4018 }
4019 }
4020 return std::nullopt;
4021}
4022
4023/// Return true if V1 == (binop V2, X), where X is known non-zero.
4024/// Only handle a small subset of binops where (binop V2, X) with non-zero X
4025/// implies V2 != V1.
4026static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2,
4027 const APInt &DemandedElts,
4028 const SimplifyQuery &Q, unsigned Depth) {
4030 if (!BO)
4031 return false;
4032 switch (BO->getOpcode()) {
4033 default:
4034 break;
4035 case Instruction::Or:
4036 if (!cast<PossiblyDisjointInst>(V1)->isDisjoint())
4037 break;
4038 [[fallthrough]];
4039 case Instruction::Xor:
4040 case Instruction::Add:
4041 Value *Op = nullptr;
4042 if (V2 == BO->getOperand(0))
4043 Op = BO->getOperand(1);
4044 else if (V2 == BO->getOperand(1))
4045 Op = BO->getOperand(0);
4046 else
4047 return false;
4048 return isKnownNonZero(Op, DemandedElts, Q, Depth + 1);
4049 }
4050 return false;
4051}
4052
4053/// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
4054/// the multiplication is nuw or nsw.
4055static bool isNonEqualMul(const Value *V1, const Value *V2,
4056 const APInt &DemandedElts, const SimplifyQuery &Q,
4057 unsigned Depth) {
4058 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4059 const APInt *C;
4060 return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
4061 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4062 !C->isZero() && !C->isOne() &&
4063 isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4064 }
4065 return false;
4066}
4067
4068/// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
4069/// the shift is nuw or nsw.
4070static bool isNonEqualShl(const Value *V1, const Value *V2,
4071 const APInt &DemandedElts, const SimplifyQuery &Q,
4072 unsigned Depth) {
4073 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4074 const APInt *C;
4075 return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
4076 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4077 !C->isZero() && isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4078 }
4079 return false;
4080}
4081
4082static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
4083 const APInt &DemandedElts, const SimplifyQuery &Q,
4084 unsigned Depth) {
4085 // Check two PHIs are in same block.
4086 if (PN1->getParent() != PN2->getParent())
4087 return false;
4088
4090 bool UsedFullRecursion = false;
4091 for (const BasicBlock *IncomBB : PN1->blocks()) {
4092 if (!VisitedBBs.insert(IncomBB).second)
4093 continue; // Don't reprocess blocks that we have dealt with already.
4094 const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
4095 const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
4096 const APInt *C1, *C2;
4097 if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
4098 continue;
4099
4100 // Only one pair of phi operands is allowed for full recursion.
4101 if (UsedFullRecursion)
4102 return false;
4103
4105 RecQ.CxtI = IncomBB->getTerminator();
4106 if (!isKnownNonEqual(IV1, IV2, DemandedElts, RecQ, Depth + 1))
4107 return false;
4108 UsedFullRecursion = true;
4109 }
4110 return true;
4111}
4112
4113static bool isNonEqualSelect(const Value *V1, const Value *V2,
4114 const APInt &DemandedElts, const SimplifyQuery &Q,
4115 unsigned Depth) {
4116 const SelectInst *SI1 = dyn_cast<SelectInst>(V1);
4117 if (!SI1)
4118 return false;
4119
4120 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) {
4121 const Value *Cond1 = SI1->getCondition();
4122 const Value *Cond2 = SI2->getCondition();
4123 if (Cond1 == Cond2)
4124 return isKnownNonEqual(SI1->getTrueValue(), SI2->getTrueValue(),
4125 DemandedElts, Q, Depth + 1) &&
4126 isKnownNonEqual(SI1->getFalseValue(), SI2->getFalseValue(),
4127 DemandedElts, Q, Depth + 1);
4128 }
4129 return isKnownNonEqual(SI1->getTrueValue(), V2, DemandedElts, Q, Depth + 1) &&
4130 isKnownNonEqual(SI1->getFalseValue(), V2, DemandedElts, Q, Depth + 1);
4131}
4132
4133// Check to see if A is both a GEP and is the incoming value for a PHI in the
4134// loop, and B is either a ptr or another GEP. If the PHI has 2 incoming values,
4135// one of them being the recursive GEP A and the other a ptr at same base and at
4136// the same/higher offset than B we are only incrementing the pointer further in
4137// loop if offset of recursive GEP is greater than 0.
4139 const SimplifyQuery &Q) {
4140 if (!A->getType()->isPointerTy() || !B->getType()->isPointerTy())
4141 return false;
4142
4143 auto *GEPA = dyn_cast<GEPOperator>(A);
4144 if (!GEPA || GEPA->getNumIndices() != 1 || !isa<Constant>(GEPA->idx_begin()))
4145 return false;
4146
4147 // Handle 2 incoming PHI values with one being a recursive GEP.
4148 auto *PN = dyn_cast<PHINode>(GEPA->getPointerOperand());
4149 if (!PN || PN->getNumIncomingValues() != 2)
4150 return false;
4151
4152 // Search for the recursive GEP as an incoming operand, and record that as
4153 // Step.
4154 Value *Start = nullptr;
4155 Value *Step = const_cast<Value *>(A);
4156 if (PN->getIncomingValue(0) == Step)
4157 Start = PN->getIncomingValue(1);
4158 else if (PN->getIncomingValue(1) == Step)
4159 Start = PN->getIncomingValue(0);
4160 else
4161 return false;
4162
4163 // Other incoming node base should match the B base.
4164 // StartOffset >= OffsetB && StepOffset > 0?
4165 // StartOffset <= OffsetB && StepOffset < 0?
4166 // Is non-equal if above are true.
4167 // We use stripAndAccumulateInBoundsConstantOffsets to restrict the
4168 // optimisation to inbounds GEPs only.
4169 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(Start->getType());
4170 APInt StartOffset(IndexWidth, 0);
4171 Start = Start->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StartOffset);
4172 APInt StepOffset(IndexWidth, 0);
4173 Step = Step->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StepOffset);
4174
4175 // Check if Base Pointer of Step matches the PHI.
4176 if (Step != PN)
4177 return false;
4178 APInt OffsetB(IndexWidth, 0);
4179 B = B->stripAndAccumulateInBoundsConstantOffsets(Q.DL, OffsetB);
4180 return Start == B &&
4181 ((StartOffset.sge(OffsetB) && StepOffset.isStrictlyPositive()) ||
4182 (StartOffset.sle(OffsetB) && StepOffset.isNegative()));
4183}
4184
4185static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2,
4186 const SimplifyQuery &Q, unsigned Depth) {
4187 if (!Q.CxtI)
4188 return false;
4189
4190 // Try to infer NonEqual based on information from dominating conditions.
4191 if (Q.DC && Q.DT) {
4192 auto IsKnownNonEqualFromDominatingCondition = [&](const Value *V) {
4193 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4194 Value *Cond = BI->getCondition();
4195 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
4196 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()) &&
4198 /*LHSIsTrue=*/true, Depth)
4199 .value_or(false))
4200 return true;
4201
4202 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
4203 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()) &&
4205 /*LHSIsTrue=*/false, Depth)
4206 .value_or(false))
4207 return true;
4208 }
4209
4210 return false;
4211 };
4212
4213 if (IsKnownNonEqualFromDominatingCondition(V1) ||
4214 IsKnownNonEqualFromDominatingCondition(V2))
4215 return true;
4216 }
4217
4218 if (!Q.AC)
4219 return false;
4220
4221 // Try to infer NonEqual based on information from assumptions.
4222 for (auto &AssumeVH : Q.AC->assumptionsFor(V1)) {
4223 if (!AssumeVH)
4224 continue;
4225 CallInst *I = cast<CallInst>(AssumeVH);
4226
4227 assert(I->getFunction() == Q.CxtI->getFunction() &&
4228 "Got assumption for the wrong function!");
4229 assert(I->getIntrinsicID() == Intrinsic::assume &&
4230 "must be an assume intrinsic");
4231
4232 if (isImpliedCondition(I->getArgOperand(0), ICmpInst::ICMP_NE, V1, V2, Q.DL,
4233 /*LHSIsTrue=*/true, Depth)
4234 .value_or(false) &&
4236 return true;
4237 }
4238
4239 return false;
4240}
4241
4242static bool isNonEqualURem(const Value *X, const Value *Rem,
4243 const SimplifyQuery &Q) {
4244 const Value *Y;
4245 if (!match(Rem, m_URem(m_Specific(X), m_Value(Y))))
4246 return false;
4247
4248 // For a defined urem, X != X urem Y exactly when X u>= Y.
4249 // isTruePredicate does not handle UGE, so use the equivalent Y u<= X.
4251 return true;
4252
4253 std::optional<bool> Implied =
4255 return Implied && *Implied;
4256}
4257
4258/// Return true if it is known that V1 != V2.
4259static bool isKnownNonEqual(const Value *V1, const Value *V2,
4260 const APInt &DemandedElts, const SimplifyQuery &Q,
4261 unsigned Depth) {
4262 if (V1 == V2)
4263 return false;
4264 if (V1->getType() != V2->getType())
4265 // We can't look through casts yet.
4266 return false;
4267
4269 return false;
4270
4271 // See if we can recurse through (exactly one of) our operands. This
4272 // requires our operation be 1-to-1 and map every input value to exactly
4273 // one output value. Such an operation is invertible.
4274 auto *O1 = dyn_cast<Operator>(V1);
4275 auto *O2 = dyn_cast<Operator>(V2);
4276 if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
4277 if (auto Values = getInvertibleOperands(O1, O2))
4278 return isKnownNonEqual(Values->first, Values->second, DemandedElts, Q,
4279 Depth + 1);
4280
4281 if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
4282 const PHINode *PN2 = cast<PHINode>(V2);
4283 // FIXME: This is missing a generalization to handle the case where one is
4284 // a PHI and another one isn't.
4285 if (isNonEqualPHIs(PN1, PN2, DemandedElts, Q, Depth))
4286 return true;
4287 };
4288 }
4289
4290 if (isModifyingBinopOfNonZero(V1, V2, DemandedElts, Q, Depth) ||
4291 isModifyingBinopOfNonZero(V2, V1, DemandedElts, Q, Depth))
4292 return true;
4293
4294 if (isNonEqualMul(V1, V2, DemandedElts, Q, Depth) ||
4295 isNonEqualMul(V2, V1, DemandedElts, Q, Depth))
4296 return true;
4297
4298 if (isNonEqualShl(V1, V2, DemandedElts, Q, Depth) ||
4299 isNonEqualShl(V2, V1, DemandedElts, Q, Depth))
4300 return true;
4301
4302 if (V1->getType()->isIntOrIntVectorTy()) {
4303 // Are any known bits in V1 contradictory to known bits in V2? If V1
4304 // has a known zero where V2 has a known one, they must not be equal.
4305 KnownBits Known1 = computeKnownBits(V1, DemandedElts, Q, Depth);
4306 if (!Known1.isUnknown()) {
4307 KnownBits Known2 = computeKnownBits(V2, DemandedElts, Q, Depth);
4308 if (Known1.Zero.intersects(Known2.One) ||
4309 Known2.Zero.intersects(Known1.One))
4310 return true;
4311 }
4312 }
4313
4314 if (isNonEqualSelect(V1, V2, DemandedElts, Q, Depth) ||
4315 isNonEqualSelect(V2, V1, DemandedElts, Q, Depth))
4316 return true;
4317
4320 return true;
4321
4322 Value *A, *B;
4323 // PtrToInts are NonEqual if their Ptrs are NonEqual.
4324 // Check PtrToInt type matches the pointer size.
4325 if (match(V1, m_PtrToIntSameSize(Q.DL, m_Value(A))) &&
4327 return isKnownNonEqual(A, B, DemandedElts, Q, Depth + 1);
4328
4329 if (isNonEqualURem(V1, V2, Q) || isNonEqualURem(V2, V1, Q))
4330 return true;
4331
4332 if (isKnownNonEqualFromContext(V1, V2, Q, Depth))
4333 return true;
4334
4335 return false;
4336}
4337
4338/// For vector constants, loop over the elements and find the constant with the
4339/// minimum number of sign bits. Return 0 if the value is not a vector constant
4340/// or if any element was not analyzed; otherwise, return the count for the
4341/// element with the minimum number of sign bits.
4343 const APInt &DemandedElts,
4344 unsigned TyBits) {
4345 const auto *CV = dyn_cast<Constant>(V);
4346 if (!CV || !isa<FixedVectorType>(CV->getType()))
4347 return 0;
4348
4349 unsigned MinSignBits = TyBits;
4350 unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
4351 for (unsigned i = 0; i != NumElts; ++i) {
4352 if (!DemandedElts[i])
4353 continue;
4354 // If we find a non-ConstantInt, bail out.
4355 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
4356 if (!Elt)
4357 return 0;
4358
4359 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
4360 }
4361
4362 return MinSignBits;
4363}
4364
4365static unsigned ComputeNumSignBitsImpl(const Value *V,
4366 const APInt &DemandedElts,
4367 const SimplifyQuery &Q, unsigned Depth);
4368
4369static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
4370 const SimplifyQuery &Q, unsigned Depth) {
4371 unsigned Result = ComputeNumSignBitsImpl(V, DemandedElts, Q, Depth);
4372 assert(Result > 0 && "At least one sign bit needs to be present!");
4373 return Result;
4374}
4375
4376/// Return the number of times the sign bit of the register is replicated into
4377/// the other bits. We know that at least 1 bit is always equal to the sign bit
4378/// (itself), but other cases can give us information. For example, immediately
4379/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
4380/// other, so we return 3. For vectors, return the number of sign bits for the
4381/// vector element with the minimum number of known sign bits of the demanded
4382/// elements in the vector specified by DemandedElts.
4383static unsigned ComputeNumSignBitsImpl(const Value *V,
4384 const APInt &DemandedElts,
4385 const SimplifyQuery &Q, unsigned Depth) {
4386 Type *Ty = V->getType();
4387#ifndef NDEBUG
4388 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
4389
4390 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
4391 assert(
4392 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
4393 "DemandedElt width should equal the fixed vector number of elements");
4394 } else {
4395 assert(DemandedElts == APInt(1, 1) &&
4396 "DemandedElt width should be 1 for scalars");
4397 }
4398#endif
4399
4400 // We return the minimum number of sign bits that are guaranteed to be present
4401 // in V, so for undef we have to conservatively return 1. We don't have the
4402 // same behavior for poison though -- that's a FIXME today.
4403
4404 Type *ScalarTy = Ty->getScalarType();
4405 unsigned TyBits = ScalarTy->isPointerTy() ?
4406 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
4407 Q.DL.getTypeSizeInBits(ScalarTy);
4408
4409 unsigned Tmp, Tmp2;
4410 unsigned FirstAnswer = 1;
4411
4412 // Note that ConstantInt is handled by the general computeKnownBits case
4413 // below.
4414
4416 return 1;
4417
4418 if (auto *U = dyn_cast<Operator>(V)) {
4419 switch (Operator::getOpcode(V)) {
4420 default: break;
4421 case Instruction::BitCast: {
4422 Value *Src = U->getOperand(0);
4423 Type *SrcTy = Src->getType();
4424
4425 // Skip if the source type is not an integer or integer vector type
4426 // This ensures we only process integer-like types
4427 if (!SrcTy->isIntOrIntVectorTy())
4428 break;
4429
4430 unsigned SrcBits = SrcTy->getScalarSizeInBits();
4431
4432 // Bitcast 'large element' scalar/vector to 'small element' vector.
4433 if ((SrcBits % TyBits) != 0)
4434 break;
4435
4436 // Only proceed if the destination type is a fixed-size vector
4437 if (isa<FixedVectorType>(Ty)) {
4438 // Fast case - sign splat can be simply split across the small elements.
4439 // This works for both vector and scalar sources
4440 Tmp = ComputeNumSignBits(Src, Q, Depth + 1);
4441 if (Tmp == SrcBits)
4442 return TyBits;
4443 }
4444 break;
4445 }
4446 case Instruction::SExt:
4447 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
4448 return ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1) +
4449 Tmp;
4450
4451 case Instruction::SDiv: {
4452 const APInt *Denominator;
4453 // sdiv X, C -> adds log(C) sign bits.
4454 if (match(U->getOperand(1), m_APInt(Denominator))) {
4455
4456 // Ignore non-positive denominator.
4457 if (!Denominator->isStrictlyPositive())
4458 break;
4459
4460 // Calculate the incoming numerator bits.
4461 unsigned NumBits =
4462 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4463
4464 // Add floor(log(C)) bits to the numerator bits.
4465 return std::min(TyBits, NumBits + Denominator->logBase2());
4466 }
4467 break;
4468 }
4469
4470 case Instruction::SRem: {
4471 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4472
4473 const APInt *Denominator;
4474 // srem X, C -> we know that the result is within [-C+1,C) when C is a
4475 // positive constant. This let us put a lower bound on the number of sign
4476 // bits.
4477 if (match(U->getOperand(1), m_APInt(Denominator))) {
4478
4479 // Ignore non-positive denominator.
4480 if (Denominator->isStrictlyPositive()) {
4481 // Calculate the leading sign bit constraints by examining the
4482 // denominator. Given that the denominator is positive, there are two
4483 // cases:
4484 //
4485 // 1. The numerator is positive. The result range is [0,C) and
4486 // [0,C) u< (1 << ceilLogBase2(C)).
4487 //
4488 // 2. The numerator is negative. Then the result range is (-C,0] and
4489 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
4490 //
4491 // Thus a lower bound on the number of sign bits is `TyBits -
4492 // ceilLogBase2(C)`.
4493
4494 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
4495 Tmp = std::max(Tmp, ResBits);
4496 }
4497 }
4498 return Tmp;
4499 }
4500
4501 case Instruction::AShr: {
4502 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4503 // ashr X, C -> adds C sign bits. Vectors too.
4504 const APInt *ShAmt;
4505 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4506 if (ShAmt->uge(TyBits))
4507 break; // Bad shift.
4508 unsigned ShAmtLimited = ShAmt->getZExtValue();
4509 Tmp += ShAmtLimited;
4510 if (Tmp > TyBits) Tmp = TyBits;
4511 }
4512 return Tmp;
4513 }
4514 case Instruction::Shl: {
4515 const APInt *ShAmt;
4516 Value *X = nullptr;
4517 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4518 // shl destroys sign bits.
4519 if (ShAmt->uge(TyBits))
4520 break; // Bad shift.
4521 // We can look through a zext (more or less treating it as a sext) if
4522 // all extended bits are shifted out.
4523 if (match(U->getOperand(0), m_ZExt(m_Value(X))) &&
4524 ShAmt->uge(TyBits - X->getType()->getScalarSizeInBits())) {
4525 Tmp = ComputeNumSignBits(X, DemandedElts, Q, Depth + 1);
4526 Tmp += TyBits - X->getType()->getScalarSizeInBits();
4527 } else
4528 Tmp =
4529 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4530 if (ShAmt->uge(Tmp))
4531 break; // Shifted all sign bits out.
4532 Tmp2 = ShAmt->getZExtValue();
4533 return Tmp - Tmp2;
4534 }
4535 break;
4536 }
4537 case Instruction::And:
4538 case Instruction::Or:
4539 case Instruction::Xor: // NOT is handled here.
4540 // Logical binary ops preserve the number of sign bits at the worst.
4541 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4542 if (Tmp != 1) {
4543 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4544 FirstAnswer = std::min(Tmp, Tmp2);
4545 // We computed what we know about the sign bits as our first
4546 // answer. Now proceed to the generic code that uses
4547 // computeKnownBits, and pick whichever answer is better.
4548 }
4549 break;
4550
4551 case Instruction::Select: {
4552 // If we have a clamp pattern, we know that the number of sign bits will
4553 // be the minimum of the clamp min/max range.
4554 const Value *X;
4555 const APInt *CLow, *CHigh;
4556 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
4557 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4558
4559 Tmp = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4560 if (Tmp == 1)
4561 break;
4562 Tmp2 = ComputeNumSignBits(U->getOperand(2), DemandedElts, Q, Depth + 1);
4563 return std::min(Tmp, Tmp2);
4564 }
4565
4566 case Instruction::Add:
4567 // Add can have at most one carry bit. Thus we know that the output
4568 // is, at worst, one more bit than the inputs.
4569 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4570 if (Tmp == 1) break;
4571
4572 // Special case decrementing a value (ADD X, -1):
4573 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
4574 if (CRHS->isAllOnesValue()) {
4575 KnownBits Known(TyBits);
4576 computeKnownBits(U->getOperand(0), DemandedElts, Known, Q, Depth + 1);
4577
4578 // If the input is known to be 0 or 1, the output is 0/-1, which is
4579 // all sign bits set.
4580 if ((Known.Zero | 1).isAllOnes())
4581 return TyBits;
4582
4583 // If we are subtracting one from a positive number, there is no carry
4584 // out of the result.
4585 if (Known.isNonNegative())
4586 return Tmp;
4587 }
4588
4589 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4590 if (Tmp2 == 1)
4591 break;
4592 return std::min(Tmp, Tmp2) - 1;
4593
4594 case Instruction::Sub:
4595 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4596 if (Tmp2 == 1)
4597 break;
4598
4599 // Handle NEG.
4600 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
4601 if (CLHS->isNullValue()) {
4602 KnownBits Known(TyBits);
4603 computeKnownBits(U->getOperand(1), DemandedElts, Known, Q, Depth + 1);
4604 // If the input is known to be 0 or 1, the output is 0/-1, which is
4605 // all sign bits set.
4606 if ((Known.Zero | 1).isAllOnes())
4607 return TyBits;
4608
4609 // If the input is known to be positive (the sign bit is known clear),
4610 // the output of the NEG has the same number of sign bits as the
4611 // input.
4612 if (Known.isNonNegative())
4613 return Tmp2;
4614
4615 // Otherwise, we treat this like a SUB.
4616 }
4617
4618 // Sub can have at most one carry bit. Thus we know that the output
4619 // is, at worst, one more bit than the inputs.
4620 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4621 if (Tmp == 1)
4622 break;
4623 return std::min(Tmp, Tmp2) - 1;
4624
4625 case Instruction::Mul: {
4626 // The output of the Mul can be at most twice the valid bits in the
4627 // inputs.
4628 unsigned SignBitsOp0 =
4629 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4630 if (SignBitsOp0 == 1)
4631 break;
4632 unsigned SignBitsOp1 =
4633 ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4634 if (SignBitsOp1 == 1)
4635 break;
4636 unsigned OutValidBits =
4637 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
4638 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
4639 }
4640
4641 case Instruction::PHI: {
4642 const PHINode *PN = cast<PHINode>(U);
4643 unsigned NumIncomingValues = PN->getNumIncomingValues();
4644 // Don't analyze large in-degree PHIs.
4645 if (NumIncomingValues > 4) break;
4646 // Unreachable blocks may have zero-operand PHI nodes.
4647 if (NumIncomingValues == 0) break;
4648
4649 // Take the minimum of all incoming values. This can't infinitely loop
4650 // because of our depth threshold.
4652 Tmp = TyBits;
4653 for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
4654 if (Tmp == 1) return Tmp;
4655 RecQ.CxtI = PN->getIncomingBlock(i)->getTerminator();
4656 Tmp = std::min(Tmp, ComputeNumSignBits(PN->getIncomingValue(i),
4657 DemandedElts, RecQ, Depth + 1));
4658 }
4659 return Tmp;
4660 }
4661
4662 case Instruction::Trunc: {
4663 // If the input contained enough sign bits that some remain after the
4664 // truncation, then we can make use of that. Otherwise we don't know
4665 // anything.
4666 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4667 unsigned OperandTyBits = U->getOperand(0)->getType()->getScalarSizeInBits();
4668 if (Tmp > (OperandTyBits - TyBits))
4669 return Tmp - (OperandTyBits - TyBits);
4670
4671 return 1;
4672 }
4673
4674 case Instruction::ExtractElement:
4675 // Look through extract element. At the moment we keep this simple and
4676 // skip tracking the specific element. But at least we might find
4677 // information valid for all elements of the vector (for example if vector
4678 // is sign extended, shifted, etc).
4679 return ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4680
4681 case Instruction::ShuffleVector: {
4682 // Collect the minimum number of sign bits that are shared by every vector
4683 // element referenced by the shuffle.
4684 auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
4685 if (!Shuf) {
4686 // FIXME: Add support for shufflevector constant expressions.
4687 return 1;
4688 }
4689 APInt DemandedLHS, DemandedRHS;
4690 // For undef elements, we don't know anything about the common state of
4691 // the shuffle result.
4692 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
4693 return 1;
4694 Tmp = std::numeric_limits<unsigned>::max();
4695 if (!!DemandedLHS) {
4696 const Value *LHS = Shuf->getOperand(0);
4697 Tmp = ComputeNumSignBits(LHS, DemandedLHS, Q, Depth + 1);
4698 }
4699 // If we don't know anything, early out and try computeKnownBits
4700 // fall-back.
4701 if (Tmp == 1)
4702 break;
4703 if (!!DemandedRHS) {
4704 const Value *RHS = Shuf->getOperand(1);
4705 Tmp2 = ComputeNumSignBits(RHS, DemandedRHS, Q, Depth + 1);
4706 Tmp = std::min(Tmp, Tmp2);
4707 }
4708 // If we don't know anything, early out and try computeKnownBits
4709 // fall-back.
4710 if (Tmp == 1)
4711 break;
4712 assert(Tmp <= TyBits && "Failed to determine minimum sign bits");
4713 return Tmp;
4714 }
4715 case Instruction::Call: {
4716 if (const auto *II = dyn_cast<IntrinsicInst>(U)) {
4717 switch (II->getIntrinsicID()) {
4718 default:
4719 break;
4720 case Intrinsic::abs:
4721 Tmp =
4722 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4723 if (Tmp == 1)
4724 break;
4725
4726 // Absolute value reduces number of sign bits by at most 1.
4727 return Tmp - 1;
4728 case Intrinsic::smin:
4729 case Intrinsic::smax: {
4730 const APInt *CLow, *CHigh;
4731 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
4732 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4733 }
4734 }
4735 }
4736 }
4737 }
4738 }
4739
4740 // Finally, if we can prove that the top bits of the result are 0's or 1's,
4741 // use this information.
4742
4743 // If we can examine all elements of a vector constant successfully, we're
4744 // done (we can't do any better than that). If not, keep trying.
4745 if (unsigned VecSignBits =
4746 computeNumSignBitsVectorConstant(V, DemandedElts, TyBits))
4747 return VecSignBits;
4748
4749 KnownBits Known(TyBits);
4750 computeKnownBits(V, DemandedElts, Known, Q, Depth);
4751
4752 // If we know that the sign bit is either zero or one, determine the number of
4753 // identical bits in the top of the input value.
4754 return std::max(FirstAnswer, Known.countMinSignBits());
4755}
4756
4758 const TargetLibraryInfo *TLI) {
4759 const Function *F = CB.getCalledFunction();
4760 if (!F)
4762
4763 if (F->isIntrinsic())
4764 return F->getIntrinsicID();
4765
4766 // We are going to infer semantics of a library function based on mapping it
4767 // to an LLVM intrinsic. Check that the library function is available from
4768 // this callbase and in this environment.
4769 if (F->hasLocalLinkage() || !TLI || !CB.onlyReadsMemory())
4771
4772 LibFunc Func = TLI->getLibFunc(CB);
4773 if (Func == NotLibFunc)
4775
4776 switch (Func) {
4777 default:
4778 break;
4779 case LibFunc_sin:
4780 case LibFunc_sinf:
4781 case LibFunc_sinl:
4782 return Intrinsic::sin;
4783 case LibFunc_cos:
4784 case LibFunc_cosf:
4785 case LibFunc_cosl:
4786 return Intrinsic::cos;
4787 case LibFunc_tan:
4788 case LibFunc_tanf:
4789 case LibFunc_tanl:
4790 return Intrinsic::tan;
4791 case LibFunc_asin:
4792 case LibFunc_asinf:
4793 case LibFunc_asinl:
4794 return Intrinsic::asin;
4795 case LibFunc_acos:
4796 case LibFunc_acosf:
4797 case LibFunc_acosl:
4798 return Intrinsic::acos;
4799 case LibFunc_atan:
4800 case LibFunc_atanf:
4801 case LibFunc_atanl:
4802 return Intrinsic::atan;
4803 case LibFunc_atan2:
4804 case LibFunc_atan2f:
4805 case LibFunc_atan2l:
4806 return Intrinsic::atan2;
4807 case LibFunc_sinh:
4808 case LibFunc_sinhf:
4809 case LibFunc_sinhl:
4810 return Intrinsic::sinh;
4811 case LibFunc_cosh:
4812 case LibFunc_coshf:
4813 case LibFunc_coshl:
4814 return Intrinsic::cosh;
4815 case LibFunc_tanh:
4816 case LibFunc_tanhf:
4817 case LibFunc_tanhl:
4818 return Intrinsic::tanh;
4819 case LibFunc_exp:
4820 case LibFunc_expf:
4821 case LibFunc_expl:
4822 return Intrinsic::exp;
4823 case LibFunc_exp2:
4824 case LibFunc_exp2f:
4825 case LibFunc_exp2l:
4826 return Intrinsic::exp2;
4827 case LibFunc_exp10:
4828 case LibFunc_exp10f:
4829 case LibFunc_exp10l:
4830 return Intrinsic::exp10;
4831 case LibFunc_log:
4832 case LibFunc_logf:
4833 case LibFunc_logl:
4834 return Intrinsic::log;
4835 case LibFunc_log10:
4836 case LibFunc_log10f:
4837 case LibFunc_log10l:
4838 return Intrinsic::log10;
4839 case LibFunc_log2:
4840 case LibFunc_log2f:
4841 case LibFunc_log2l:
4842 return Intrinsic::log2;
4843 case LibFunc_fabs:
4844 case LibFunc_fabsf:
4845 case LibFunc_fabsl:
4846 return Intrinsic::fabs;
4847 case LibFunc_fmin:
4848 case LibFunc_fminf:
4849 case LibFunc_fminl:
4850 return Intrinsic::minnum;
4851 case LibFunc_fmax:
4852 case LibFunc_fmaxf:
4853 case LibFunc_fmaxl:
4854 return Intrinsic::maxnum;
4855 case LibFunc_copysign:
4856 case LibFunc_copysignf:
4857 case LibFunc_copysignl:
4858 return Intrinsic::copysign;
4859 case LibFunc_floor:
4860 case LibFunc_floorf:
4861 case LibFunc_floorl:
4862 return Intrinsic::floor;
4863 case LibFunc_ceil:
4864 case LibFunc_ceilf:
4865 case LibFunc_ceill:
4866 return Intrinsic::ceil;
4867 case LibFunc_trunc:
4868 case LibFunc_truncf:
4869 case LibFunc_truncl:
4870 return Intrinsic::trunc;
4871 case LibFunc_rint:
4872 case LibFunc_rintf:
4873 case LibFunc_rintl:
4874 return Intrinsic::rint;
4875 case LibFunc_nearbyint:
4876 case LibFunc_nearbyintf:
4877 case LibFunc_nearbyintl:
4878 return Intrinsic::nearbyint;
4879 case LibFunc_round:
4880 case LibFunc_roundf:
4881 case LibFunc_roundl:
4882 return Intrinsic::round;
4883 case LibFunc_roundeven:
4884 case LibFunc_roundevenf:
4885 case LibFunc_roundevenl:
4886 return Intrinsic::roundeven;
4887 case LibFunc_pow:
4888 case LibFunc_powf:
4889 case LibFunc_powl:
4890 return Intrinsic::pow;
4891 case LibFunc_sqrt:
4892 case LibFunc_sqrtf:
4893 case LibFunc_sqrtl:
4894 return Intrinsic::sqrt;
4895 }
4896
4898}
4899
4900/// Given an exploded icmp instruction, return true if the comparison only
4901/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if
4902/// the result of the comparison is true when the input value is signed.
4904 bool &TrueIfSigned) {
4905 switch (Pred) {
4906 case ICmpInst::ICMP_SLT: // True if LHS s< 0
4907 TrueIfSigned = true;
4908 return RHS.isZero();
4909 case ICmpInst::ICMP_SLE: // True if LHS s<= -1
4910 TrueIfSigned = true;
4911 return RHS.isAllOnes();
4912 case ICmpInst::ICMP_SGT: // True if LHS s> -1
4913 TrueIfSigned = false;
4914 return RHS.isAllOnes();
4915 case ICmpInst::ICMP_SGE: // True if LHS s>= 0
4916 TrueIfSigned = false;
4917 return RHS.isZero();
4918 case ICmpInst::ICMP_UGT:
4919 // True if LHS u> RHS and RHS == sign-bit-mask - 1
4920 TrueIfSigned = true;
4921 return RHS.isMaxSignedValue();
4922 case ICmpInst::ICMP_UGE:
4923 // True if LHS u>= RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4924 TrueIfSigned = true;
4925 return RHS.isMinSignedValue();
4926 case ICmpInst::ICMP_ULT:
4927 // True if LHS u< RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4928 TrueIfSigned = false;
4929 return RHS.isMinSignedValue();
4930 case ICmpInst::ICMP_ULE:
4931 // True if LHS u<= RHS and RHS == sign-bit-mask - 1
4932 TrueIfSigned = false;
4933 return RHS.isMaxSignedValue();
4934 default:
4935 return false;
4936 }
4937}
4938
4940 bool CondIsTrue,
4941 const Instruction *CxtI,
4942 KnownFPClass &KnownFromContext,
4943 unsigned Depth = 0) {
4944 Value *A, *B;
4946 (CondIsTrue ? match(Cond, m_LogicalAnd(m_Value(A), m_Value(B)))
4947 : match(Cond, m_LogicalOr(m_Value(A), m_Value(B))))) {
4948 computeKnownFPClassFromCond(V, A, CondIsTrue, CxtI, KnownFromContext,
4949 Depth + 1);
4950 computeKnownFPClassFromCond(V, B, CondIsTrue, CxtI, KnownFromContext,
4951 Depth + 1);
4952 return;
4953 }
4955 computeKnownFPClassFromCond(V, A, !CondIsTrue, CxtI, KnownFromContext,
4956 Depth + 1);
4957 return;
4958 }
4959 CmpPredicate Pred;
4960 Value *LHS;
4961 uint64_t ClassVal = 0;
4962 const APFloat *CRHS;
4963 const APInt *RHS;
4964 if (match(Cond, m_FCmp(Pred, m_Value(LHS), m_APFloat(CRHS)))) {
4965 auto [CmpVal, MaskIfTrue, MaskIfFalse] = fcmpImpliesClass(
4966 Pred, *cast<Instruction>(Cond)->getParent()->getParent(), LHS, *CRHS,
4967 LHS != V);
4968 if (CmpVal == V)
4969 KnownFromContext.knownNot(~(CondIsTrue ? MaskIfTrue : MaskIfFalse));
4971 m_Specific(V), m_ConstantInt(ClassVal)))) {
4972 FPClassTest Mask = static_cast<FPClassTest>(ClassVal);
4973 KnownFromContext.knownNot(CondIsTrue ? ~Mask : Mask);
4974 } else if (match(Cond, m_ICmp(Pred, m_ElementWiseBitCast(m_Specific(V)),
4975 m_APInt(RHS)))) {
4976 bool TrueIfSigned;
4977 if (!isSignBitCheck(Pred, *RHS, TrueIfSigned))
4978 return;
4979 if (TrueIfSigned == CondIsTrue)
4980 KnownFromContext.signBitMustBeOne();
4981 else
4982 KnownFromContext.signBitMustBeZero();
4983 }
4984}
4985
4986/// Compute the minimum and maximum values (inclusive) for the exponent of \p V,
4987/// assuming it is not nan. Returns {min, max, max-assuming-nonzero}. A value
4988/// frexp(0) = 0, so the tighter max-assuming-nonzero bound is only usable when
4989/// \p V is known not to be a logical zero (e.g., for fabs(x) < 0.25, the non-0
4990/// exponent range is [-149, -2], but the 0 edge case is above this range).
4991static std::tuple<int, int, int>
4993 if (!Q.CxtI || !Q.DC || !Q.DT)
4995
4996 // Intersect the bounds implied by every dominating condition, keeping the
4997 // tightest maximum. A value may participate in multiple compares
4998 // (e.g. fabs(x) < 2.0 and fabs(x) < 1.0), and the tighter one wins.
4999 int MaxExp = APFloat::IEK_Inf;
5000 int MaxExpNonZero = APFloat::IEK_Inf;
5001
5002 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5003 CmpPredicate Pred;
5004 const APFloat *LimitC;
5005 if (!match(BI->getCondition(),
5006 m_FCmp(Pred, m_FAbs(m_Specific(V)), m_Finite(LimitC))))
5007 continue;
5008
5009 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO ||
5010 Pred == FCmpInst::FCMP_TRUE || Pred == FCmpInst::FCMP_FALSE)
5011 continue;
5012
5013 // If fabs(x) <= K, implies the exponent min exp range.
5014 // if fabs(x) >= K, swap the successor
5015 bool IsLessEqual =
5016 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
5017 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE ||
5018 Pred == FCmpInst::FCMP_OEQ || Pred == FCmpInst::FCMP_UEQ;
5019
5020 bool KnownStrictlyLess =
5021 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT ||
5022 Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
5023
5024 BasicBlockEdge Edge1(BI->getParent(),
5025 BI->getSuccessor(IsLessEqual ? 0 : 1));
5026 if (Q.DT->dominates(Edge1, Q.CxtI->getParent())) {
5027 // frexp returns an exponent one greater than ilogb.
5028 int Exp = ilogb(*LimitC) + 1;
5029
5030 // A strict bound fabs(V) < 2^n forces ilogb(V) <= n - 1, so the max frexp
5031 // exponent drops by one when K is exact power of two.
5032 if (KnownStrictlyLess && LimitC->getExactLog2Abs() != INT_MIN)
5033 --Exp;
5034
5035 // frexp(0) = 0, which the bound above (assuming a normal nonzero value)
5036 // may exclude.
5037
5038 // TODO: Figure out lower bound to detect no-underflow.
5039 MaxExpNonZero = std::min(MaxExpNonZero, Exp);
5040 MaxExp = std::min(MaxExp, std::max(Exp, 0));
5041 }
5042 }
5043
5044 return {APFloat::IEK_NaN, MaxExp, MaxExpNonZero};
5045}
5046
5048 const SimplifyQuery &Q) {
5049 KnownFPClass KnownFromContext;
5050
5051 if (Q.CC && Q.CC->AffectedValues.contains(V))
5053 KnownFromContext);
5054
5055 if (!Q.CxtI)
5056 return KnownFromContext;
5057
5058 if (Q.DC && Q.DT) {
5059 // Handle dominating conditions.
5060 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5061 Value *Cond = BI->getCondition();
5062
5063 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
5064 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()))
5065 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/true, Q.CxtI,
5066 KnownFromContext);
5067
5068 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
5069 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()))
5070 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/false, Q.CxtI,
5071 KnownFromContext);
5072 }
5073 }
5074
5075 if (!Q.AC)
5076 return KnownFromContext;
5077
5078 // Try to restrict the floating-point classes based on information from
5079 // assumptions.
5080 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
5081 if (!AssumeVH)
5082 continue;
5083 CallInst *I = cast<CallInst>(AssumeVH);
5084
5085 assert(I->getFunction() == Q.CxtI->getParent()->getParent() &&
5086 "Got assumption for the wrong function!");
5087 assert(I->getIntrinsicID() == Intrinsic::assume &&
5088 "must be an assume intrinsic");
5089
5090 if (!isValidAssumeForContext(I, Q))
5091 continue;
5092
5093 computeKnownFPClassFromCond(V, I->getArgOperand(0),
5094 /*CondIsTrue=*/true, Q.CxtI, KnownFromContext);
5095 }
5096
5097 return KnownFromContext;
5098}
5099
5101 Value *Arm, bool Invert,
5102 const SimplifyQuery &SQ,
5103 unsigned Depth) {
5104
5105 KnownFPClass KnownSrc;
5107 /*CondIsTrue=*/!Invert, SQ.CxtI, KnownSrc,
5108 Depth + 1);
5109 KnownSrc = KnownSrc.unionWith(Known);
5110 if (KnownSrc.isUnknown())
5111 return;
5112
5113 if (isGuaranteedNotToBeUndef(Arm, SQ.AC, SQ.CxtI, SQ.DT, Depth + 1))
5114 Known = KnownSrc;
5115}
5116
5117void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5118 FPClassTest InterestedClasses, KnownFPClass &Known,
5119 const SimplifyQuery &Q, unsigned Depth);
5120
5122 FPClassTest InterestedClasses,
5123 const SimplifyQuery &Q, unsigned Depth) {
5124 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
5125 APInt DemandedElts =
5126 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
5127 computeKnownFPClass(V, DemandedElts, InterestedClasses, Known, Q, Depth);
5128}
5129
5131 const APInt &DemandedElts,
5132 FPClassTest InterestedClasses,
5134 const SimplifyQuery &Q,
5135 unsigned Depth) {
5136 if ((InterestedClasses &
5138 return;
5139
5140 KnownFPClass KnownSrc;
5141 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5142 KnownSrc, Q, Depth + 1);
5143 Known = KnownFPClass::fptrunc(KnownSrc);
5144}
5145
5147 switch (IID) {
5148 case Intrinsic::minimum:
5150 case Intrinsic::maximum:
5152 case Intrinsic::minimumnum:
5154 case Intrinsic::maximumnum:
5156 case Intrinsic::minnum:
5158 case Intrinsic::maxnum:
5160 default:
5161 llvm_unreachable("not a floating-point min-max intrinsic");
5162 }
5163}
5164
5165/// \return true if this is a floating point value that is known to have a
5166/// magnitude smaller than 1. i.e., fabs(X) <= 1.0 or is nan.
5167static bool isAbsoluteValueULEOne(const Value *V) {
5168 // TODO: Handle frexp
5169 // TODO: Other rounding intrinsics?
5170 // TODO: Try computeKnownExponentRangeFromContext
5171
5172 // fabs(x - floor(x)) <= 1
5173 const Value *SubFloorX;
5174 if (match(V, m_FSub(m_Value(SubFloorX),
5176 return true;
5177
5180}
5181
5182void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5183 FPClassTest InterestedClasses, KnownFPClass &Known,
5184 const SimplifyQuery &Q, unsigned Depth) {
5185 assert(Known.isUnknown() && "should not be called with known information");
5186
5187 if (!DemandedElts) {
5188 // No demanded elts, better to assume we don't know anything.
5189 Known.resetAll();
5190 return;
5191 }
5192
5193 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
5194
5195 if (auto *CFP = dyn_cast<ConstantFP>(V)) {
5196 Known = KnownFPClass(CFP->getValueAPF());
5197 return;
5198 }
5199
5201 Known.setKnownFPClasses(fcPosZero);
5202 Known.setSignBit(false);
5203 return;
5204 }
5205
5206 if (isa<PoisonValue>(V)) {
5207 Known.setKnownFPClasses(fcNone);
5208 Known.setSignBit(false);
5209 return;
5210 }
5211
5212 // Try to handle fixed width vector constants
5213 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
5214 const Constant *CV = dyn_cast<Constant>(V);
5215 if (VFVTy && CV) {
5216 Known.setKnownFPClasses(fcNone);
5217 bool SignBitAllZero = true;
5218 bool SignBitAllOne = true;
5219
5220 // For vectors, verify that each element is not NaN.
5221 unsigned NumElts = VFVTy->getNumElements();
5222 for (unsigned i = 0; i != NumElts; ++i) {
5223 if (!DemandedElts[i])
5224 continue;
5225
5226 Constant *Elt = CV->getAggregateElement(i);
5227 if (!Elt) {
5228 Known = KnownFPClass();
5229 return;
5230 }
5231 if (isa<PoisonValue>(Elt))
5232 continue;
5233 auto *CElt = dyn_cast<ConstantFP>(Elt);
5234 if (!CElt) {
5235 Known = KnownFPClass();
5236 return;
5237 }
5238
5239 const APFloat &C = CElt->getValueAPF();
5240 Known.setKnownFPClasses(Known.getKnownFPClasses() | C.classify());
5241 if (C.isNegative())
5242 SignBitAllZero = false;
5243 else
5244 SignBitAllOne = false;
5245 }
5246 if (SignBitAllOne != SignBitAllZero)
5247 Known.setSignBit(SignBitAllOne);
5248 return;
5249 }
5250
5251 if (const auto *CDS = dyn_cast<ConstantDataSequential>(V)) {
5252 Known.setKnownFPClasses(fcNone);
5253 for (size_t I = 0, E = CDS->getNumElements(); I != E; ++I)
5254 Known |= CDS->getElementAsAPFloat(I).classify();
5255 return;
5256 }
5257
5258 if (const auto *CA = dyn_cast<ConstantAggregate>(V)) {
5259 // TODO: Handle complex aggregates
5260 Known.setKnownFPClasses(fcNone);
5261 for (const Use &Op : CA->operands()) {
5262 auto *CFP = dyn_cast<ConstantFP>(Op.get());
5263 if (!CFP) {
5264 Known = KnownFPClass();
5265 return;
5266 }
5267
5268 Known |= CFP->getValueAPF().classify();
5269 }
5270
5271 return;
5272 }
5273
5274 FPClassTest KnownNotFromFlags = fcNone;
5275 if (const auto *CB = dyn_cast<CallBase>(V))
5276 KnownNotFromFlags |= CB->getRetNoFPClass();
5277 else if (const auto *Arg = dyn_cast<Argument>(V))
5278 KnownNotFromFlags |= Arg->getNoFPClass();
5279
5280 const Operator *Op = dyn_cast<Operator>(V);
5282 if (FPOp->hasNoNaNs())
5283 KnownNotFromFlags |= fcNan;
5284 if (FPOp->hasNoInfs())
5285 KnownNotFromFlags |= fcInf;
5286 }
5287
5288 KnownFPClass AssumedClasses = computeKnownFPClassFromContext(V, Q);
5289 KnownNotFromFlags |= ~AssumedClasses.getKnownFPClasses();
5290
5291 // We no longer need to find out about these bits from inputs if we can
5292 // assume this from flags/attributes.
5293 InterestedClasses &= ~KnownNotFromFlags;
5294
5295 llvm::scope_exit ClearClassesFromFlags([=, &Known] {
5296 Known.knownNot(KnownNotFromFlags);
5297 if (!Known.getSignBit() && AssumedClasses.getSignBit()) {
5298 if (*AssumedClasses.getSignBit())
5299 Known.signBitMustBeOne();
5300 else
5301 Known.signBitMustBeZero();
5302 }
5303 });
5304
5305 if (!Op)
5306 return;
5307
5308 // All recursive calls that increase depth must come after this.
5310 return;
5311
5312 const unsigned Opc = Op->getOpcode();
5313 switch (Opc) {
5314 case Instruction::FNeg: {
5315 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5316 Known, Q, Depth + 1);
5317 Known.fneg();
5318 break;
5319 }
5320 case Instruction::Select: {
5321 auto ComputeForArm = [&](Value *Arm, bool Invert) {
5322 KnownFPClass Res;
5323 computeKnownFPClass(Arm, DemandedElts, InterestedClasses, Res, Q,
5324 Depth + 1);
5325 adjustKnownFPClassForSelectArm(Res, Op->getOperand(0), Arm, Invert, Q,
5326 Depth);
5327 return Res;
5328 };
5329 // Only known if known in both the LHS and RHS.
5330 Known =
5331 ComputeForArm(Op->getOperand(1), /*Invert=*/false)
5332 .intersectWith(ComputeForArm(Op->getOperand(2), /*Invert=*/true));
5333 break;
5334 }
5335 case Instruction::Load: {
5336 const MDNode *NoFPClass =
5337 cast<LoadInst>(Op)->getMetadata(LLVMContext::MD_nofpclass);
5338 if (!NoFPClass)
5339 break;
5340
5341 ConstantInt *MaskVal =
5343 Known.knownNot(static_cast<FPClassTest>(MaskVal->getZExtValue()));
5344 break;
5345 }
5346 case Instruction::Call: {
5347 const CallInst *II = cast<CallInst>(Op);
5348 const Intrinsic::ID IID = II->getIntrinsicID();
5349 switch (IID) {
5350 case Intrinsic::fabs: {
5351 if ((InterestedClasses & (fcNan | fcPositive)) != fcNone) {
5352 // If we only care about the sign bit we don't need to inspect the
5353 // operand.
5354 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5355 InterestedClasses, Known, Q, Depth + 1);
5356 }
5357
5358 Known.fabs();
5359 break;
5360 }
5361 case Intrinsic::copysign: {
5362 KnownFPClass KnownSign;
5363
5364 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5365 Known, Q, Depth + 1);
5366 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5367 KnownSign, Q, Depth + 1);
5368 Known.copysign(KnownSign);
5369 break;
5370 }
5371 case Intrinsic::fma:
5372 case Intrinsic::fmuladd: {
5373 if ((InterestedClasses & fcNegative) == fcNone)
5374 break;
5375
5376 // FIXME: This should check isGuaranteedNotToBeUndef
5377 if (II->getArgOperand(0) == II->getArgOperand(1)) {
5378 KnownFPClass KnownSrc, KnownAddend;
5379 computeKnownFPClass(II->getArgOperand(2), DemandedElts,
5380 InterestedClasses, KnownAddend, Q, Depth + 1);
5381 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5382 InterestedClasses, KnownSrc, Q, Depth + 1);
5383
5384 const Function *F = II->getFunction();
5385 const fltSemantics &FltSem =
5386 II->getType()->getScalarType()->getFltSemantics();
5388 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5389
5390 if (KnownNotFromFlags & fcNan) {
5391 KnownSrc.knownNot(fcNan);
5392 KnownAddend.knownNot(fcNan);
5393 }
5394
5395 if (KnownNotFromFlags & fcInf) {
5396 KnownSrc.knownNot(fcInf);
5397 KnownAddend.knownNot(fcInf);
5398 }
5399
5400 Known = KnownFPClass::fma_square(KnownSrc, KnownAddend, Mode);
5401 break;
5402 }
5403
5404 KnownFPClass KnownSrc[3];
5405 for (int I = 0; I != 3; ++I) {
5406 computeKnownFPClass(II->getArgOperand(I), DemandedElts,
5407 InterestedClasses, KnownSrc[I], Q, Depth + 1);
5408 if (KnownSrc[I].isUnknown())
5409 return;
5410
5411 if (KnownNotFromFlags & fcNan)
5412 KnownSrc[I].knownNot(fcNan);
5413 if (KnownNotFromFlags & fcInf)
5414 KnownSrc[I].knownNot(fcInf);
5415 }
5416
5417 const Function *F = II->getFunction();
5418 const fltSemantics &FltSem =
5419 II->getType()->getScalarType()->getFltSemantics();
5421 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5422 Known = KnownFPClass::fma(KnownSrc[0], KnownSrc[1], KnownSrc[2], Mode);
5423 break;
5424 }
5425 case Intrinsic::sqrt:
5426 case Intrinsic::experimental_constrained_sqrt: {
5427 KnownFPClass KnownSrc;
5428 FPClassTest InterestedSrcs = InterestedClasses;
5429 if (InterestedClasses & fcNan)
5430 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5431
5432 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5433 KnownSrc, Q, Depth + 1);
5434
5436
5437 bool HasNSZ = Q.IIQ.hasNoSignedZeros(II);
5438 if (!HasNSZ) {
5439 const Function *F = II->getFunction();
5440 const fltSemantics &FltSem =
5441 II->getType()->getScalarType()->getFltSemantics();
5442 Mode = F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5443 }
5444
5445 Known = KnownFPClass::sqrt(KnownSrc, Mode);
5446 if (HasNSZ)
5447 Known.knownNot(fcNegZero);
5448
5449 break;
5450 }
5451 case Intrinsic::sin: {
5452 KnownFPClass KnownSrc;
5453 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5454 KnownSrc, Q, Depth + 1);
5455 Known = KnownFPClass::sin(KnownSrc);
5456 break;
5457 }
5458 case Intrinsic::cos: {
5459 KnownFPClass KnownSrc;
5460 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5461 KnownSrc, Q, Depth + 1);
5462 Known = KnownFPClass::cos(KnownSrc);
5463 break;
5464 }
5465 case Intrinsic::tan: {
5466 KnownFPClass KnownSrc;
5467 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5468 KnownSrc, Q, Depth + 1);
5469 Known = KnownFPClass::tan(KnownSrc);
5470 break;
5471 }
5472 case Intrinsic::sinh: {
5473 KnownFPClass KnownSrc;
5474 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5475 KnownSrc, Q, Depth + 1);
5476 Known = KnownFPClass::sinh(KnownSrc);
5477 break;
5478 }
5479 case Intrinsic::cosh: {
5480 KnownFPClass KnownSrc;
5481 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5482 KnownSrc, Q, Depth + 1);
5483 Known = KnownFPClass::cosh(KnownSrc);
5484 break;
5485 }
5486 case Intrinsic::tanh: {
5487 KnownFPClass KnownSrc;
5488 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5489 KnownSrc, Q, Depth + 1);
5490 Known = KnownFPClass::tanh(KnownSrc);
5491 break;
5492 }
5493 case Intrinsic::asin: {
5494 KnownFPClass KnownSrc;
5495 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5496 KnownSrc, Q, Depth + 1);
5497 Known = KnownFPClass::asin(KnownSrc);
5498 break;
5499 }
5500 case Intrinsic::acos: {
5501 KnownFPClass KnownSrc;
5502 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5503 KnownSrc, Q, Depth + 1);
5504 Known = KnownFPClass::acos(KnownSrc);
5505 break;
5506 }
5507 case Intrinsic::atan: {
5508 KnownFPClass KnownSrc;
5509 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5510 KnownSrc, Q, Depth + 1);
5511 Known = KnownFPClass::atan(KnownSrc);
5512 break;
5513 }
5514 case Intrinsic::atan2: {
5515 FPClassTest InterestedY = InterestedClasses;
5516 FPClassTest InterestedX = InterestedClasses;
5517
5518 // We can rule out zero and subnormal if x cannot have a positive value.
5519 if ((InterestedClasses & (fcZero | fcSubnormal)) != fcNone)
5520 InterestedX |= fcPositive | fcNegSubnormal;
5521
5522 KnownFPClass KnownY, KnownX;
5523 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedY,
5524 KnownY, Q, Depth + 1);
5525 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedX,
5526 KnownX, Q, Depth + 1);
5527
5528 const Function *F = II->getFunction();
5530 F ? F->getDenormalMode(
5531 II->getType()->getScalarType()->getFltSemantics())
5533 Known = KnownFPClass::atan2(KnownY, KnownX, Mode);
5534 break;
5535 }
5536 case Intrinsic::maxnum:
5537 case Intrinsic::minnum:
5538 case Intrinsic::minimum:
5539 case Intrinsic::maximum:
5540 case Intrinsic::minimumnum:
5541 case Intrinsic::maximumnum: {
5542 KnownFPClass KnownLHS, KnownRHS;
5543 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5544 KnownLHS, Q, Depth + 1);
5545 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5546 KnownRHS, Q, Depth + 1);
5547
5548 const Function *F = II->getFunction();
5549
5551 F ? F->getDenormalMode(
5552 II->getType()->getScalarType()->getFltSemantics())
5554
5555 Known = KnownFPClass::minMaxLike(KnownLHS, KnownRHS, getMinMaxKind(IID),
5556 Mode);
5557 break;
5558 }
5559 case Intrinsic::canonicalize: {
5560 KnownFPClass KnownSrc;
5561 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5562 KnownSrc, Q, Depth + 1);
5563
5564 const Function *F = II->getFunction();
5565 DenormalMode DenormMode =
5566 F ? F->getDenormalMode(
5567 II->getType()->getScalarType()->getFltSemantics())
5569 Known = KnownFPClass::canonicalize(KnownSrc, DenormMode);
5570 break;
5571 }
5572 case Intrinsic::vector_reduce_fmax:
5573 case Intrinsic::vector_reduce_fmin:
5574 case Intrinsic::vector_reduce_fmaximum:
5575 case Intrinsic::vector_reduce_fminimum:
5576 case Intrinsic::vector_reduce_fmaximumnum:
5577 case Intrinsic::vector_reduce_fminimumnum: {
5578 // reduce min/max will choose an element from one of the vector elements,
5579 // so we can infer and class information that is common to all elements.
5580 Known = computeKnownFPClass(II->getArgOperand(0), II->getFastMathFlags(),
5581 InterestedClasses, Q, Depth + 1);
5582 // Can only propagate sign if output is never NaN.
5583 if (!Known.isKnownNeverNaN())
5584 Known.setSignBit(std::nullopt);
5585 break;
5586 }
5587 // reverse preserves all characteristics of the input vec's element.
5588 case Intrinsic::vector_reverse:
5590 II->getArgOperand(0), DemandedElts.reverseBits(),
5591 II->getFastMathFlags(), InterestedClasses, Q, Depth + 1);
5592 break;
5593 case Intrinsic::trunc:
5594 case Intrinsic::floor:
5595 case Intrinsic::ceil:
5596 case Intrinsic::rint:
5597 case Intrinsic::nearbyint:
5598 case Intrinsic::round:
5599 case Intrinsic::roundeven: {
5600 KnownFPClass KnownSrc;
5601 FPClassTest InterestedSrcs = InterestedClasses;
5602 if (InterestedSrcs & fcPosFinite)
5603 InterestedSrcs |= fcPosFinite;
5604 if (InterestedSrcs & fcNegFinite)
5605 InterestedSrcs |= fcNegFinite;
5606 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5607 KnownSrc, Q, Depth + 1);
5608
5610 KnownSrc, IID == Intrinsic::trunc,
5611 V->getType()->getScalarType()->isMultiUnitFPType());
5612 break;
5613 }
5614 case Intrinsic::exp:
5615 case Intrinsic::exp2:
5616 case Intrinsic::exp10:
5617 case Intrinsic::amdgcn_exp2: {
5618 KnownFPClass KnownSrc;
5619 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5620 KnownSrc, Q, Depth + 1);
5621
5622 Known = KnownFPClass::exp(KnownSrc);
5623
5624 Type *EltTy = II->getType()->getScalarType();
5625 if (IID == Intrinsic::amdgcn_exp2 && EltTy->isFloatTy())
5626 Known.knownNot(fcSubnormal);
5627
5628 break;
5629 }
5630 case Intrinsic::fptrunc_round: {
5631 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known,
5632 Q, Depth);
5633 break;
5634 }
5635 case Intrinsic::log:
5636 case Intrinsic::log10:
5637 case Intrinsic::log2:
5638 case Intrinsic::experimental_constrained_log:
5639 case Intrinsic::experimental_constrained_log10:
5640 case Intrinsic::experimental_constrained_log2:
5641 case Intrinsic::amdgcn_log: {
5642 FPClassTest InterestedSrcs = fcNone;
5643
5644 // log(negative) produces NaN.
5645 if ((InterestedClasses & fcNan) != fcNone)
5646 InterestedSrcs |= fcNan | fcNegative;
5647
5648 // log(logical-zero) produces negative infinity.
5649 if ((InterestedClasses & fcNegInf) != fcNone)
5650 InterestedSrcs |= fcZero | fcSubnormal;
5651
5652 // log(x) < -0.0 if x < +1.0
5653 if ((InterestedClasses & fcNegNormal) != fcNone)
5654 InterestedSrcs |= fcPosSubnormal | fcPosNormal;
5655
5656 // log(x) >= +0.0 if x >= +1.0
5657 if ((InterestedClasses & (fcPosZero | fcPosNormal)) != fcNone)
5658 InterestedSrcs |= fcPosNormal;
5659
5660 // log(x) is positive infinity iff x is positive infinity.
5661 if ((InterestedClasses & fcPosInf) != fcNone)
5662 InterestedSrcs |= fcPosInf;
5663
5664 KnownFPClass KnownSrc;
5665 if (InterestedSrcs != fcNone)
5666 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5667 KnownSrc, Q, Depth + 1);
5668 const Function *F = II->getFunction();
5670 F ? F->getDenormalMode(
5671 II->getType()->getScalarType()->getFltSemantics())
5673 Known = KnownFPClass::log(KnownSrc, Mode);
5674 break;
5675 }
5676 case Intrinsic::pow: {
5677 const bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5678 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
5679 if (!WantNaN && !WantNegative)
5680 break;
5681
5682 FPClassTest InterestedLHS = fcNone;
5683 FPClassTest InterestedRHS = fcNone;
5684 if (WantNaN) {
5685 // pow may return NaN if one of the arguments is NaN. NaN may also be
5686 // produced from a negative, non-zero finite base and a non-integer
5687 // exponent.
5688 InterestedLHS |= fcNan | fcNegNormal | fcNegSubnormal;
5689 InterestedRHS |= fcNan;
5690 }
5691 if (WantNegative) {
5692 // A negative value is returned when a negative base is raised to an odd
5693 // integer power. Only normal values can be odd integers.
5694 InterestedLHS |= fcNegative;
5695 InterestedRHS |= fcNormal;
5696 }
5697
5698 KnownFPClass KnownLHS;
5699 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedLHS,
5700 KnownLHS, Q, Depth + 1);
5701
5702 // If the LHS is unknown, then querying the RHS is only useful for rare
5703 // edge cases.
5704 if (KnownLHS.isUnknown())
5705 break;
5706
5707 KnownFPClass KnownRHS;
5708 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedRHS,
5709 KnownRHS, Q, Depth + 1);
5710 Known = KnownFPClass::pow(KnownLHS, KnownRHS);
5711 break;
5712 }
5713 case Intrinsic::powi: {
5714 if ((InterestedClasses & (fcNan | fcInf | fcNegative)) == fcNone)
5715 break;
5716
5717 // The exponent is always a scalar, even when raising a vector to a power.
5718 const Value *Exp = II->getArgOperand(1);
5719 unsigned BitWidth = Exp->getType()->getIntegerBitWidth();
5720 KnownBits ExponentKnownBits(BitWidth);
5721 computeKnownBits(Exp, APInt(1, 1), ExponentKnownBits, Q, Depth + 1);
5722
5723 FPClassTest InterestedSrcs = fcNone;
5724 if (InterestedClasses & fcNan)
5725 InterestedSrcs |= fcNan;
5726 if (!ExponentKnownBits.isZero()) {
5727 if (InterestedClasses & fcInf)
5728 InterestedSrcs |= fcFinite | fcInf;
5729 if ((InterestedClasses & fcNegative) && !ExponentKnownBits.isEven())
5730 InterestedSrcs |= fcNegative;
5731 }
5732
5733 KnownFPClass KnownSrc;
5734 if (InterestedSrcs != fcNone)
5735 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5736 KnownSrc, Q, Depth + 1);
5737
5738 Known = KnownFPClass::powi(KnownSrc, ExponentKnownBits);
5739 break;
5740 }
5741 case Intrinsic::ldexp: {
5742 KnownFPClass KnownSrc;
5743 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5744 KnownSrc, Q, Depth + 1);
5745 // Can refine inf/zero handling based on the exponent operand.
5746 const FPClassTest ExpInfoMask = fcZero | fcSubnormal | fcInf;
5747
5748 const Value *ExpArg = II->getArgOperand(1);
5749 ConstantRange ExpKnownRange =
5750 ((KnownSrc.getKnownFPClasses() & ExpInfoMask) != fcNone)
5751 ? computeConstantRange(ExpArg, /*ForSigned=*/true, Q, Depth + 1)
5752 : ConstantRange::getFull(
5753 ExpArg->getType()->getScalarSizeInBits());
5754
5755 const fltSemantics &Flt =
5756 II->getType()->getScalarType()->getFltSemantics();
5757
5758 const Function *F = II->getFunction();
5760 F ? F->getDenormalMode(Flt) : DenormalMode::getDynamic();
5761
5762 Known = KnownFPClass::ldexp(KnownSrc, ExpKnownRange.getSignedMin(),
5763 ExpKnownRange.getSignedMax(), Flt, Mode);
5764 break;
5765 }
5766 case Intrinsic::arithmetic_fence: {
5767 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5768 Known, Q, Depth + 1);
5769 break;
5770 }
5771 case Intrinsic::experimental_constrained_sitofp:
5772 case Intrinsic::experimental_constrained_uitofp:
5773 // Cannot produce nan
5774 Known.knownNot(fcNan);
5775
5776 // sitofp and uitofp turn into +0.0 for zero.
5777 Known.knownNot(fcNegZero);
5778
5779 // Integers cannot be subnormal
5780 Known.knownNot(fcSubnormal);
5781
5782 if (IID == Intrinsic::experimental_constrained_uitofp)
5783 Known.signBitMustBeZero();
5784
5785 // TODO: Copy inf handling from instructions
5786 break;
5787
5788 case Intrinsic::amdgcn_fract: {
5789 Known.knownNot(fcInf);
5790
5791 if (InterestedClasses & fcNan) {
5792 KnownFPClass KnownSrc;
5793 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5794 InterestedClasses, KnownSrc, Q, Depth + 1);
5795
5796 if (KnownSrc.isKnownNeverInfOrNaN())
5797 Known.knownNot(fcNan);
5798 else if (KnownSrc.isKnownNever(fcSNan))
5799 Known.knownNot(fcSNan);
5800 }
5801
5802 break;
5803 }
5804 case Intrinsic::amdgcn_rcp: {
5805 KnownFPClass KnownSrc;
5806 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5807 KnownSrc, Q, Depth + 1);
5808
5809 Known.propagateNonNaN(KnownSrc);
5810
5811 Type *EltTy = II->getType()->getScalarType();
5812
5813 // f32 denormal always flushed.
5814 if (EltTy->isFloatTy()) {
5815 Known.knownNot(fcSubnormal);
5816 KnownSrc.knownNot(fcSubnormal);
5817 }
5818
5819 if (KnownSrc.isKnownNever(fcNegative))
5820 Known.knownNot(fcNegative);
5821 if (KnownSrc.isKnownNever(fcPositive))
5822 Known.knownNot(fcPositive);
5823
5824 if (const Function *F = II->getFunction()) {
5825 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5826 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5827 Known.knownNot(fcPosInf);
5828 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5829 Known.knownNot(fcNegInf);
5830 }
5831
5832 break;
5833 }
5834 case Intrinsic::amdgcn_rsq: {
5835 KnownFPClass KnownSrc;
5836 // The only negative value that can be returned is -inf for -0 inputs.
5838
5839 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5840 KnownSrc, Q, Depth + 1);
5841
5842 // Negative -> nan
5843 if (KnownSrc.isKnownNeverNaN() && KnownSrc.cannotBeOrderedLessThanZero())
5844 Known.knownNot(fcNan);
5845 else if (KnownSrc.isKnownNever(fcSNan))
5846 Known.knownNot(fcSNan);
5847
5848 // +inf -> +0
5849 if (KnownSrc.isKnownNeverPosInfinity())
5850 Known.knownNot(fcPosZero);
5851
5852 Type *EltTy = II->getType()->getScalarType();
5853
5854 // f32 denormal always flushed.
5855 if (EltTy->isFloatTy())
5856 Known.knownNot(fcPosSubnormal);
5857
5858 if (const Function *F = II->getFunction()) {
5859 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5860
5861 // -0 -> -inf
5862 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5863 Known.knownNot(fcNegInf);
5864
5865 // +0 -> +inf
5866 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5867 Known.knownNot(fcPosInf);
5868 }
5869
5870 break;
5871 }
5872 case Intrinsic::amdgcn_trig_preop: {
5873 // Always returns a value [0, 1)
5874 Known.knownNot(fcNan | fcInf | fcNegative);
5875 break;
5876 }
5877 case Intrinsic::convert_from_arbitrary_fp: {
5878 auto *MD = cast<MetadataAsValue>(II->getArgOperand(1))->getMetadata();
5879 StringRef FormatStr = cast<MDString>(MD)->getString();
5880
5881 const fltSemantics *SrcSemantics =
5883 if (!SrcSemantics)
5884 break;
5885
5886 const fltSemantics DstSemantics =
5887 II->getType()->getScalarType()->getFltSemantics();
5888
5889 if (!APFloat::semanticsHasNaN(*SrcSemantics))
5890 Known.knownNot(fcNan);
5891
5892 // fcInf can only be cleared if the source format has no Inf encoding
5893 // and the dst max exp can accommodate src max exp.
5894 if (!APFloat::semanticsHasInf(*SrcSemantics) &&
5895 APFloat::semanticsMaxExponent(*SrcSemantics) <=
5896 APFloat::semanticsMaxExponent(DstSemantics))
5897 Known.knownNot(fcInf);
5898
5899 // Check and clear all neg flags for formats that do not have signed
5900 // representation.
5901 if (!APFloat::semanticsHasSignedRepr(*SrcSemantics))
5902 Known.knownNot(fcNegative);
5903
5904 // Check if format has no zero at all (Float8E8M0FNU), or no negative
5905 // zero.
5906 if (!APFloat::semanticsHasZero(*SrcSemantics))
5907 Known.knownNot(fcZero);
5908 else if (SrcSemantics->nanEncoding == fltNanEncoding::NegativeZero)
5909 Known.knownNot(fcNegZero);
5910
5911 // If src lands normally in dest, the result can never be subnormal.
5912 if (APFloat::isRepresentableAsNormalIn(*SrcSemantics, DstSemantics))
5913 Known.knownNot(fcSubnormal);
5914 break;
5915 }
5916 default:
5917 break;
5918 }
5919
5920 break;
5921 }
5922 case Instruction::FAdd:
5923 case Instruction::FSub: {
5924 KnownFPClass KnownLHS, KnownRHS;
5925 bool WantNegative =
5926 Op->getOpcode() == Instruction::FAdd &&
5927 (InterestedClasses & KnownFPClass::OrderedLessThanZeroMask) != fcNone;
5928 bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5929 bool WantNegZero = (InterestedClasses & fcNegZero) != fcNone;
5930
5931 if (!WantNaN && !WantNegative && !WantNegZero)
5932 break;
5933
5934 FPClassTest InterestedSrcs = InterestedClasses;
5935 if (WantNegative)
5936 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5937 if (InterestedClasses & fcNan)
5938 InterestedSrcs |= fcInf;
5939 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedSrcs,
5940 KnownRHS, Q, Depth + 1);
5941
5942 // Special case fadd x, x, which is the canonical form of fmul x, 2.
5943 bool Self = Op->getOperand(0) == Op->getOperand(1) &&
5944 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT,
5945 Depth + 1);
5946 if (Self)
5947 KnownLHS = KnownRHS;
5948
5949 if ((WantNaN && KnownRHS.isKnownNeverNaN()) ||
5950 (WantNegative && KnownRHS.cannotBeOrderedLessThanZero()) ||
5951 WantNegZero || Opc == Instruction::FSub) {
5952
5953 // FIXME: Context function should always be passed in separately
5954 const Function *F = cast<Instruction>(Op)->getFunction();
5955 const fltSemantics &FltSem =
5956 Op->getType()->getScalarType()->getFltSemantics();
5958 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5959
5960 if (Self && Opc == Instruction::FAdd) {
5961 Known = KnownFPClass::fadd_self(KnownLHS, Mode);
5962 } else {
5963 // RHS is canonically cheaper to compute. Skip inspecting the LHS if
5964 // there's no point.
5965
5966 if (!Self) {
5967 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
5968 KnownLHS, Q, Depth + 1);
5969 }
5970
5971 Known = Opc == Instruction::FAdd
5972 ? KnownFPClass::fadd(KnownLHS, KnownRHS, Mode)
5973 : KnownFPClass::fsub(KnownLHS, KnownRHS, Mode);
5974 }
5975 }
5976
5977 break;
5978 }
5979 case Instruction::FMul: {
5980 const Function *F = cast<Instruction>(Op)->getFunction();
5982 F ? F->getDenormalMode(
5983 Op->getType()->getScalarType()->getFltSemantics())
5985
5986 Value *LHS = Op->getOperand(0);
5987 Value *RHS = Op->getOperand(1);
5988 // X * X is always non-negative or a NaN.
5989 // FIXME: Should check isGuaranteedNotToBeUndef
5990 if (LHS == RHS) {
5991 KnownFPClass KnownSrc;
5992 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownSrc, Q,
5993 Depth + 1);
5994 Known = KnownFPClass::square(KnownSrc, Mode);
5995 break;
5996 }
5997
5998 KnownFPClass KnownLHS, KnownRHS;
5999
6000 const APFloat *CRHS;
6001 if (match(RHS, m_APFloat(CRHS))) {
6002 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
6003 Depth + 1);
6004 Known = KnownFPClass::fmul(KnownLHS, *CRHS, Mode);
6005 } else {
6006 computeKnownFPClass(RHS, DemandedElts, fcAllFlags, KnownRHS, Q,
6007 Depth + 1);
6008 // TODO: Improve accuracy in unfused FMA pattern. We can prove an
6009 // additional not-nan if the addend is known-not negative infinity if the
6010 // multiply is known-not infinity.
6011
6012 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
6013 Depth + 1);
6014 Known = KnownFPClass::fmul(KnownLHS, KnownRHS, Mode);
6015 }
6016
6017 /// Propgate no-infs if the other source is known smaller than one, such
6018 /// that this cannot introduce overflow.
6019 if (KnownLHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(RHS))
6020 Known.knownNot(fcInf);
6021 else if (KnownRHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(LHS))
6022 Known.knownNot(fcInf);
6023
6024 break;
6025 }
6026 case Instruction::FDiv: {
6027 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
6028
6029 const Function *F = cast<Instruction>(Op)->getFunction();
6030 const fltSemantics &FltSem =
6031 Op->getType()->getScalarType()->getFltSemantics();
6033 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6034
6035 if (Op->getOperand(0) == Op->getOperand(1) &&
6036 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT)) {
6037 // X / X is always exactly 1.0 or a NaN.
6038 Known.setKnownFPClasses(fcNan | fcPosNormal);
6039
6040 if (!WantNan)
6041 break;
6042
6043 KnownFPClass KnownSrc;
6044 computeKnownFPClass(Op->getOperand(0), DemandedElts,
6045 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
6046 Depth + 1);
6047
6048 Known = KnownFPClass::fdiv_self(KnownSrc, Mode);
6049 break;
6050 }
6051
6052 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
6053 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
6054 if (!WantNan && !WantNegative && !WantPositive)
6055 break;
6056
6057 KnownFPClass KnownLHS, KnownRHS;
6058 computeKnownFPClass(Op->getOperand(1), DemandedElts, fcAllFlags, KnownRHS,
6059 Q, Depth + 1);
6060
6061 bool KnowSomethingUseful =
6062 KnownRHS.isKnownNeverNaN() ||
6065
6066 if (KnowSomethingUseful)
6067 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
6068 Q, Depth + 1);
6069
6070 Known = KnownFPClass::fdiv(KnownLHS, KnownRHS, Mode);
6071 break;
6072 }
6073 case Instruction::FRem: {
6074 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
6075
6076 Known.knownNot(fcInf);
6077
6078 const Function *F = cast<Instruction>(Op)->getFunction();
6080 F ? F->getDenormalMode(
6081 Op->getType()->getScalarType()->getFltSemantics())
6083
6084 if (Op->getOperand(0) == Op->getOperand(1) &&
6085 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT)) {
6086 // X % X is always exactly [+-]0.0 or a NaN.
6087 Known.setKnownFPClasses(fcNan | fcZero);
6088
6089 if (!WantNan)
6090 break;
6091
6092 KnownFPClass KnownSrc;
6093 computeKnownFPClass(Op->getOperand(0), DemandedElts,
6094 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
6095 Depth + 1);
6096
6097 Known = KnownFPClass::frem_self(KnownSrc, Mode);
6098 break;
6099 }
6100
6101 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
6102 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
6103 if (!WantNan && !WantNegative && !WantPositive)
6104 break;
6105
6106 KnownFPClass KnownLHS, KnownRHS;
6107 computeKnownFPClass(Op->getOperand(1), DemandedElts,
6108 fcNan | fcInf | fcZero | fcNegative, KnownRHS, Q,
6109 Depth + 1);
6110
6111 bool KnowSomethingUseful = KnownRHS.isKnownNeverNaN() ||
6112 KnownRHS.isKnownNever(fcNegative) ||
6113 KnownRHS.isKnownNever(fcPositive);
6114
6115 if (KnowSomethingUseful || WantPositive)
6116 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
6117 Q, Depth + 1);
6118
6119 Known = KnownFPClass::frem(KnownLHS, KnownRHS, Mode);
6120
6121 break;
6122 }
6123 case Instruction::FPExt: {
6124 KnownFPClass KnownSrc;
6125 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
6126 KnownSrc, Q, Depth + 1);
6127
6128 const fltSemantics &DstTy =
6129 Op->getType()->getScalarType()->getFltSemantics();
6130 const fltSemantics &SrcTy =
6131 Op->getOperand(0)->getType()->getScalarType()->getFltSemantics();
6132
6133 Known = KnownFPClass::fpext(KnownSrc, DstTy, SrcTy);
6134 break;
6135 }
6136 case Instruction::FPTrunc: {
6137 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known, Q,
6138 Depth);
6139 break;
6140 }
6141 case Instruction::SIToFP:
6142 case Instruction::UIToFP: {
6143 // Cannot produce nan
6144 Known.knownNot(fcNan);
6145
6146 // Integers cannot be subnormal
6147 Known.knownNot(fcSubnormal);
6148
6149 // sitofp and uitofp turn into +0.0 for zero.
6150 Known.knownNot(fcNegZero);
6151
6152 // UIToFP is always non-negative regardless of known bits.
6153 if (Op->getOpcode() == Instruction::UIToFP)
6154 Known.signBitMustBeZero();
6155
6156 // Only compute known bits if we can learn something useful from them.
6157 if (!(InterestedClasses & (fcPosZero | fcNormal | fcInf)))
6158 break;
6159
6160 KnownBits IntKnown =
6161 computeKnownBits(Op->getOperand(0), DemandedElts, Q, Depth + 1);
6162
6163 // If the integer is non-zero, the result cannot be +0.0
6164 if (IntKnown.isNonZero())
6165 Known.knownNot(fcPosZero);
6166
6167 if (Op->getOpcode() == Instruction::SIToFP) {
6168 // If the signed integer is known non-negative, the result is
6169 // non-negative. If the signed integer is known negative, the result is
6170 // negative.
6171 if (IntKnown.isNonNegative()) {
6172 Known.signBitMustBeZero();
6173 } else if (IntKnown.isNegative()) {
6174 Known.signBitMustBeOne();
6175 }
6176 }
6177
6178 // Guard kept for ilogb()
6179 if (InterestedClasses & fcInf) {
6180 // Get width of largest magnitude integer known.
6181 // This still works for a signed minimum value because the largest FP
6182 // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx).
6183 int IntSize = IntKnown.getBitWidth();
6184 if (Op->getOpcode() == Instruction::UIToFP)
6185 IntSize -= IntKnown.countMinLeadingZeros();
6186 else if (Op->getOpcode() == Instruction::SIToFP)
6187 IntSize -= IntKnown.countMinSignBits();
6188
6189 // If the exponent of the largest finite FP value can hold the largest
6190 // integer, the result of the cast must be finite.
6191 Type *FPTy = Op->getType()->getScalarType();
6192 if (ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize)
6193 Known.knownNot(fcInf);
6194 }
6195
6196 break;
6197 }
6198 case Instruction::ExtractElement: {
6199 // Look through extract element. If the index is non-constant or
6200 // out-of-range demand all elements, otherwise just the extracted element.
6201 const Value *Vec = Op->getOperand(0);
6202
6203 APInt DemandedVecElts;
6204 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
6205 unsigned NumElts = VecTy->getNumElements();
6206 DemandedVecElts = APInt::getAllOnes(NumElts);
6207 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(1));
6208 if (CIdx && CIdx->getValue().ult(NumElts))
6209 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
6210 } else {
6211 DemandedVecElts = APInt(1, 1);
6212 }
6213
6214 return computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known,
6215 Q, Depth + 1);
6216 }
6217 case Instruction::InsertElement: {
6218 if (isa<ScalableVectorType>(Op->getType()))
6219 return;
6220
6221 const Value *Vec = Op->getOperand(0);
6222 const Value *Elt = Op->getOperand(1);
6223 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(2));
6224 unsigned NumElts = DemandedElts.getBitWidth();
6225 APInt DemandedVecElts = DemandedElts;
6226 bool NeedsElt = true;
6227 // If we know the index we are inserting to, clear it from Vec check.
6228 if (CIdx && CIdx->getValue().ult(NumElts)) {
6229 DemandedVecElts.clearBit(CIdx->getZExtValue());
6230 NeedsElt = DemandedElts[CIdx->getZExtValue()];
6231 }
6232
6233 // Do we demand the inserted element?
6234 if (NeedsElt) {
6235 computeKnownFPClass(Elt, Known, InterestedClasses, Q, Depth + 1);
6236 // If we don't know any bits, early out.
6237 if (Known.isUnknown())
6238 break;
6239 } else {
6240 Known.setKnownFPClasses(fcNone);
6241 }
6242
6243 // Do we need anymore elements from Vec?
6244 if (!DemandedVecElts.isZero()) {
6245 KnownFPClass Known2;
6246 computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known2, Q,
6247 Depth + 1);
6248 Known |= Known2;
6249 }
6250
6251 break;
6252 }
6253 case Instruction::ShuffleVector: {
6254 // Handle vector splat idiom
6255 if (Value *Splat = getSplatValue(V)) {
6256 computeKnownFPClass(Splat, Known, InterestedClasses, Q, Depth + 1);
6257 break;
6258 }
6259
6260 // For undef elements, we don't know anything about the common state of
6261 // the shuffle result.
6262 APInt DemandedLHS, DemandedRHS;
6263 auto *Shuf = dyn_cast<ShuffleVectorInst>(Op);
6264 if (!Shuf || !getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
6265 return;
6266
6267 if (!!DemandedLHS) {
6268 const Value *LHS = Shuf->getOperand(0);
6269 computeKnownFPClass(LHS, DemandedLHS, InterestedClasses, Known, Q,
6270 Depth + 1);
6271
6272 // If we don't know any bits, early out.
6273 if (Known.isUnknown())
6274 break;
6275 } else {
6276 Known.setKnownFPClasses(fcNone);
6277 }
6278
6279 if (!!DemandedRHS) {
6280 KnownFPClass Known2;
6281 const Value *RHS = Shuf->getOperand(1);
6282 computeKnownFPClass(RHS, DemandedRHS, InterestedClasses, Known2, Q,
6283 Depth + 1);
6284 Known |= Known2;
6285 }
6286
6287 break;
6288 }
6289 case Instruction::ExtractValue: {
6290 const ExtractValueInst *Extract = cast<ExtractValueInst>(Op);
6291 ArrayRef<unsigned> Indices = Extract->getIndices();
6292 const Value *Src = Extract->getAggregateOperand();
6293 if (isa<StructType>(Src->getType()) && Indices.size() == 1 &&
6294 Indices[0] == 0) {
6295 if (const auto *II = dyn_cast<IntrinsicInst>(Src)) {
6296 switch (II->getIntrinsicID()) {
6297 case Intrinsic::frexp: {
6298 Known.knownNot(fcSubnormal);
6299
6300 KnownFPClass KnownSrc;
6301 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
6302 InterestedClasses, KnownSrc, Q, Depth + 1);
6303
6304 const Function *F = cast<Instruction>(Op)->getFunction();
6305 const fltSemantics &FltSem =
6306 Op->getType()->getScalarType()->getFltSemantics();
6307
6309 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6310 Known = KnownFPClass::frexp_mant(KnownSrc, Mode);
6311 return;
6312 }
6313 default:
6314 break;
6315 }
6316 }
6317 }
6318
6319 computeKnownFPClass(Src, DemandedElts, InterestedClasses, Known, Q,
6320 Depth + 1);
6321 break;
6322 }
6323 case Instruction::PHI: {
6324 const PHINode *P = cast<PHINode>(Op);
6325 // Unreachable blocks may have zero-operand PHI nodes.
6326 if (P->getNumIncomingValues() == 0)
6327 break;
6328
6329 // Otherwise take the unions of the known bit sets of the operands,
6330 // taking conservative care to avoid excessive recursion.
6331 const unsigned PhiRecursionLimit = MaxAnalysisRecursionDepth - 2;
6332
6333 if (Depth < PhiRecursionLimit) {
6334 // Skip if every incoming value references to ourself.
6335 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
6336 break;
6337
6338 bool First = true;
6339
6340 for (const Use &U : P->operands()) {
6341 Value *IncValue;
6342 Instruction *CxtI;
6343 breakSelfRecursivePHI(&U, P, IncValue, CxtI);
6344 // Skip direct self references.
6345 if (IncValue == P)
6346 continue;
6347
6348 KnownFPClass KnownSrc;
6349 // Recurse, but cap the recursion to two levels, because we don't want
6350 // to waste time spinning around in loops. We need at least depth 2 to
6351 // detect known sign bits.
6352 computeKnownFPClass(IncValue, DemandedElts, InterestedClasses, KnownSrc,
6354 PhiRecursionLimit);
6355
6356 if (First) {
6357 Known = KnownSrc;
6358 First = false;
6359 } else {
6360 Known |= KnownSrc;
6361 }
6362
6363 if (Known.getKnownFPClasses() == fcAllFlags)
6364 break;
6365 }
6366 }
6367
6368 // Look for the case of a for loop which has a positive
6369 // initial value and is incremented by a squared value.
6370 // This will propagate sign information out of such loops.
6371 if (P->getNumIncomingValues() != 2 || Known.cannotBeOrderedLessThanZero())
6372 break;
6373 for (unsigned I = 0; I < 2; I++) {
6374 Value *RecurValue = P->getIncomingValue(1 - I);
6376 if (!II)
6377 continue;
6378 Value *R, *L, *Init;
6379 PHINode *PN;
6381 PN == P) {
6382 switch (II->getIntrinsicID()) {
6383 case Intrinsic::fma:
6384 case Intrinsic::fmuladd: {
6385 KnownFPClass KnownStart;
6386 computeKnownFPClass(Init, DemandedElts, InterestedClasses, KnownStart,
6387 Q, Depth + 1);
6388 if (KnownStart.cannotBeOrderedLessThanZero() && L == R &&
6389 isGuaranteedNotToBeUndef(L, Q.AC, Q.CxtI, Q.DT, Depth + 1))
6391 break;
6392 }
6393 }
6394 }
6395 }
6396 break;
6397 }
6398 case Instruction::BitCast: {
6399 const Value *Src;
6400 if (!match(Op, m_ElementWiseBitCast(m_Value(Src))) ||
6401 !Src->getType()->isIntOrIntVectorTy())
6402 break;
6403
6404 const Type *Ty = Op->getType();
6405
6406 Value *CastLHS, *CastRHS;
6407
6408 // Match bitcast(umax(bitcast(a), bitcast(b)))
6409 if (match(Src, m_c_MaxOrMin(m_BitCast(m_Value(CastLHS)),
6410 m_BitCast(m_Value(CastRHS)))) &&
6411 CastLHS->getType() == Ty && CastRHS->getType() == Ty) {
6412 KnownFPClass KnownLHS, KnownRHS;
6413 computeKnownFPClass(CastRHS, DemandedElts, InterestedClasses, KnownRHS, Q,
6414 Depth + 1);
6415 if (!KnownRHS.isUnknown()) {
6416 computeKnownFPClass(CastLHS, DemandedElts, InterestedClasses, KnownLHS,
6417 Q, Depth + 1);
6418 Known = KnownLHS | KnownRHS;
6419 }
6420
6421 return;
6422 }
6423
6424 const Type *EltTy = Ty->getScalarType();
6425 KnownBits Bits(EltTy->getPrimitiveSizeInBits());
6426 computeKnownBits(Src, DemandedElts, Bits, Q, Depth + 1);
6427
6429 break;
6430 }
6431 default:
6432 break;
6433 }
6434}
6435
6437 const APInt &DemandedElts,
6438 FPClassTest InterestedClasses,
6439 const SimplifyQuery &SQ,
6440 unsigned Depth) {
6441 KnownFPClass KnownClasses;
6442 ::computeKnownFPClass(V, DemandedElts, InterestedClasses, KnownClasses, SQ,
6443 Depth);
6444 return KnownClasses;
6445}
6446
6448 FPClassTest InterestedClasses,
6449 const SimplifyQuery &SQ,
6450 unsigned Depth) {
6452 ::computeKnownFPClass(V, Known, InterestedClasses, SQ, Depth);
6453 return Known;
6454}
6455
6457 const Value *V, const DataLayout &DL, FPClassTest InterestedClasses,
6458 const TargetLibraryInfo *TLI, AssumptionCache *AC, const Instruction *CxtI,
6459 const DominatorTree *DT, bool UseInstrInfo, unsigned Depth) {
6460 return computeKnownFPClass(V, InterestedClasses,
6461 SimplifyQuery(DL, TLI, DT, AC, CxtI, UseInstrInfo),
6462 Depth);
6463}
6464
6466llvm::computeKnownFPClass(const Value *V, const APInt &DemandedElts,
6467 FastMathFlags FMF, FPClassTest InterestedClasses,
6468 const SimplifyQuery &SQ, unsigned Depth) {
6469 if (FMF.noNaNs())
6470 InterestedClasses &= ~fcNan;
6471 if (FMF.noInfs())
6472 InterestedClasses &= ~fcInf;
6473
6474 KnownFPClass Result =
6475 computeKnownFPClass(V, DemandedElts, InterestedClasses, SQ, Depth);
6476
6477 if (FMF.noNaNs())
6478 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcNan);
6479 if (FMF.noInfs())
6480 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcInf);
6481 return Result;
6482}
6483
6485 FPClassTest InterestedClasses,
6486 const SimplifyQuery &SQ,
6487 unsigned Depth) {
6488 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
6489 APInt DemandedElts =
6490 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
6491 return computeKnownFPClass(V, DemandedElts, FMF, InterestedClasses, SQ,
6492 Depth);
6493}
6494
6496 unsigned Depth) {
6498 return Known.isKnownNeverNegZero();
6499}
6500
6502 unsigned Depth) {
6505 return Known.cannotBeOrderedLessThanZero();
6506}
6507
6509 unsigned Depth) {
6511 return Known.isKnownNeverInfinity();
6512}
6513
6514/// Return true if the floating-point value can never contain a NaN or infinity.
6516 unsigned Depth) {
6518 return Known.isKnownNeverNaN() && Known.isKnownNeverInfinity();
6519}
6520
6521/// Return true if the floating-point scalar value is not a NaN or if the
6522/// floating-point vector value has no NaN elements. Return false if a value
6523/// could ever be NaN.
6525 unsigned Depth) {
6527 return Known.isKnownNeverNaN();
6528}
6529
6530/// Return false if we can prove that the specified FP value's sign bit is 0.
6531/// Return true if we can prove that the specified FP value's sign bit is 1.
6532/// Otherwise return std::nullopt.
6533std::optional<bool> llvm::computeKnownFPSignBit(const Value *V,
6534 const SimplifyQuery &SQ,
6535 unsigned Depth) {
6537 return Known.getSignBit();
6538}
6539
6541 auto *User = cast<Instruction>(U.getUser());
6542 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6543 if (FPOp->hasNoSignedZeros())
6544 return true;
6545 }
6546
6547 switch (User->getOpcode()) {
6548 case Instruction::FPToSI:
6549 case Instruction::FPToUI:
6550 return true;
6551 case Instruction::FCmp:
6552 // fcmp treats both positive and negative zero as equal.
6553 return true;
6554 case Instruction::Call:
6555 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6556 switch (II->getIntrinsicID()) {
6557 case Intrinsic::fabs:
6558 return true;
6559 case Intrinsic::copysign:
6560 return U.getOperandNo() == 0;
6561 case Intrinsic::is_fpclass: {
6562 auto Test =
6563 static_cast<FPClassTest>(
6564 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue()) &
6567 }
6568 default:
6569 return false;
6570 }
6571 }
6572 return false;
6573 default:
6574 return false;
6575 }
6576}
6577
6579 auto *User = cast<Instruction>(U.getUser());
6580 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6581 if (FPOp->hasNoNaNs())
6582 return true;
6583 }
6584
6585 switch (User->getOpcode()) {
6586 case Instruction::FPToSI:
6587 case Instruction::FPToUI:
6588 return true;
6589 // Proper FP math operations ignore the sign bit of NaN.
6590 case Instruction::FAdd:
6591 case Instruction::FSub:
6592 case Instruction::FMul:
6593 case Instruction::FDiv:
6594 case Instruction::FRem:
6595 case Instruction::FPTrunc:
6596 case Instruction::FPExt:
6597 case Instruction::FCmp:
6598 return true;
6599 // Bitwise FP operations should preserve the sign bit of NaN.
6600 case Instruction::FNeg:
6601 case Instruction::Select:
6602 case Instruction::PHI:
6603 return false;
6604 case Instruction::Ret:
6605 return User->getFunction()->getAttributes().getRetNoFPClass() &
6607 case Instruction::Call:
6608 case Instruction::Invoke: {
6609 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6610 switch (II->getIntrinsicID()) {
6611 case Intrinsic::fabs:
6612 return true;
6613 case Intrinsic::copysign:
6614 return U.getOperandNo() == 0;
6615 // Other proper FP math intrinsics ignore the sign bit of NaN.
6616 case Intrinsic::maxnum:
6617 case Intrinsic::minnum:
6618 case Intrinsic::maximum:
6619 case Intrinsic::minimum:
6620 case Intrinsic::maximumnum:
6621 case Intrinsic::minimumnum:
6622 case Intrinsic::canonicalize:
6623 case Intrinsic::fma:
6624 case Intrinsic::fmuladd:
6625 case Intrinsic::sqrt:
6626 case Intrinsic::pow:
6627 case Intrinsic::powi:
6628 case Intrinsic::fptoui_sat:
6629 case Intrinsic::fptosi_sat:
6630 case Intrinsic::is_fpclass:
6631 return true;
6632 default:
6633 return false;
6634 }
6635 }
6636
6637 FPClassTest NoFPClass =
6638 cast<CallBase>(User)->getParamNoFPClass(U.getOperandNo());
6639 return NoFPClass & FPClassTest::fcNan;
6640 }
6641 default:
6642 return false;
6643 }
6644}
6645
6647 FastMathFlags FMF) {
6648 if (isa<PoisonValue>(V))
6649 return true;
6650 if (isa<UndefValue>(V))
6651 return false;
6652
6653 if (match(V, m_CheckedFp([](const APFloat &Val) { return Val.isInteger(); })))
6654 return true;
6655
6657 if (!I)
6658 return false;
6659
6660 switch (I->getOpcode()) {
6661 case Instruction::SIToFP:
6662 case Instruction::UIToFP:
6663 // TODO: Could check nofpclass(inf) on incoming argument
6664 if (FMF.noInfs())
6665 return true;
6666
6667 // Need to check int size cannot produce infinity, which computeKnownFPClass
6668 // knows how to do already.
6669 return isKnownNeverInfinity(I, SQ);
6670 case Instruction::Call: {
6671 const CallInst *CI = cast<CallInst>(I);
6672 switch (CI->getIntrinsicID()) {
6673 case Intrinsic::trunc:
6674 case Intrinsic::floor:
6675 case Intrinsic::ceil:
6676 case Intrinsic::rint:
6677 case Intrinsic::nearbyint:
6678 case Intrinsic::round:
6679 case Intrinsic::roundeven:
6680 return (FMF.noInfs() && FMF.noNaNs()) || isKnownNeverInfOrNaN(I, SQ);
6681 default:
6682 break;
6683 }
6684
6685 break;
6686 }
6687 default:
6688 break;
6689 }
6690
6691 return false;
6692}
6693
6695
6696 // All byte-wide stores are splatable, even of arbitrary variables.
6697 if (V->getType()->isIntegerTy(8))
6698 return V;
6699
6700 LLVMContext &Ctx = V->getContext();
6701
6702 // Undef don't care.
6703 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
6704 if (isa<UndefValue>(V))
6705 return UndefInt8;
6706
6707 // Return poison for zero-sized type.
6708 if (DL.getTypeStoreSize(V->getType()).isZero())
6709 return PoisonValue::get(Type::getInt8Ty(Ctx));
6710
6712 if (!C) {
6713 // Conceptually, we could handle things like:
6714 // %a = zext i8 %X to i16
6715 // %b = shl i16 %a, 8
6716 // %c = or i16 %a, %b
6717 // but until there is an example that actually needs this, it doesn't seem
6718 // worth worrying about.
6719 return nullptr;
6720 }
6721
6722 // Handle 'null' ConstantArrayZero etc.
6723 if (C->isNullValue())
6725
6726 // Constant floating-point values can be handled as integer values if the
6727 // corresponding integer value is "byteable". An important case is 0.0.
6728 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
6729 Type *ScalarTy = CFP->getType()->getScalarType();
6730 if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
6731 return isBytewiseValue(
6732 ConstantInt::get(Ctx, CFP->getValue().bitcastToAPInt()), DL);
6733
6734 // Don't handle long double formats, which have strange constraints.
6735 return nullptr;
6736 }
6737
6738 // We can handle constant integers that are multiple of 8 bits.
6739 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
6740 if (CI->getBitWidth() % 8 == 0) {
6741 if (!CI->getValue().isSplat(8))
6742 return nullptr;
6743 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
6744 }
6745 }
6746
6747 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
6748 if (CE->getOpcode() == Instruction::IntToPtr) {
6749 if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
6750 unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
6752 CE->getOperand(0), Type::getIntNTy(Ctx, BitWidth), false, DL))
6753 return isBytewiseValue(Op, DL);
6754 }
6755 }
6756 }
6757
6758 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
6759 if (LHS == RHS)
6760 return LHS;
6761 if (!LHS || !RHS)
6762 return nullptr;
6763 if (LHS == UndefInt8)
6764 return RHS;
6765 if (RHS == UndefInt8)
6766 return LHS;
6767 return nullptr;
6768 };
6769
6771 Value *Val = UndefInt8;
6772 for (uint64_t I = 0, E = CA->getNumElements(); I != E; ++I)
6773 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
6774 return nullptr;
6775 return Val;
6776 }
6777
6779 Value *Val = UndefInt8;
6780 for (Value *Op : C->operands())
6781 if (!(Val = Merge(Val, isBytewiseValue(Op, DL))))
6782 return nullptr;
6783 return Val;
6784 }
6785
6786 // Don't try to handle the handful of other constants.
6787 return nullptr;
6788}
6789
6790// This is the recursive version of BuildSubAggregate. It takes a few different
6791// arguments. Idxs is the index within the nested struct From that we are
6792// looking at now (which is of type IndexedType). IdxSkip is the number of
6793// indices from Idxs that should be left out when inserting into the resulting
6794// struct. To is the result struct built so far, new insertvalue instructions
6795// build on that.
6796static Value *BuildSubAggregate(Value *From, Value *To, Type *IndexedType,
6798 unsigned IdxSkip,
6799 BasicBlock::iterator InsertBefore) {
6800 StructType *STy = dyn_cast<StructType>(IndexedType);
6801 if (STy) {
6802 // Save the original To argument so we can modify it
6803 Value *OrigTo = To;
6804 // General case, the type indexed by Idxs is a struct
6805 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
6806 // Process each struct element recursively
6807 Idxs.push_back(i);
6808 Value *PrevTo = To;
6809 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
6810 InsertBefore);
6811 Idxs.pop_back();
6812 if (!To) {
6813 // Couldn't find any inserted value for this index? Cleanup
6814 while (PrevTo != OrigTo) {
6816 PrevTo = Del->getAggregateOperand();
6817 Del->eraseFromParent();
6818 }
6819 // Stop processing elements
6820 break;
6821 }
6822 }
6823 // If we successfully found a value for each of our subaggregates
6824 if (To)
6825 return To;
6826 }
6827 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
6828 // the struct's elements had a value that was inserted directly. In the latter
6829 // case, perhaps we can't determine each of the subelements individually, but
6830 // we might be able to find the complete struct somewhere.
6831
6832 // Find the value that is at that particular spot
6833 Value *V = FindInsertedValue(From, Idxs);
6834
6835 if (!V)
6836 return nullptr;
6837
6838 // Insert the value in the new (sub) aggregate
6839 return InsertValueInst::Create(To, V, ArrayRef(Idxs).slice(IdxSkip), "tmp",
6840 InsertBefore);
6841}
6842
6843// This helper takes a nested struct and extracts a part of it (which is again a
6844// struct) into a new value. For example, given the struct:
6845// { a, { b, { c, d }, e } }
6846// and the indices "1, 1" this returns
6847// { c, d }.
6848//
6849// It does this by inserting an insertvalue for each element in the resulting
6850// struct, as opposed to just inserting a single struct. This will only work if
6851// each of the elements of the substruct are known (ie, inserted into From by an
6852// insertvalue instruction somewhere).
6853//
6854// All inserted insertvalue instructions are inserted before InsertBefore
6856 BasicBlock::iterator InsertBefore) {
6857 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
6858 idx_range);
6859 Value *To = PoisonValue::get(IndexedType);
6860 SmallVector<unsigned, 10> Idxs(idx_range);
6861 unsigned IdxSkip = Idxs.size();
6862
6863 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
6864}
6865
6866/// Given an aggregate and a sequence of indices, see if the scalar value
6867/// indexed is already around as a register, for example if it was inserted
6868/// directly into the aggregate.
6869///
6870/// If InsertBefore is not null, this function will duplicate (modified)
6871/// insertvalues when a part of a nested struct is extracted.
6872Value *
6874 std::optional<BasicBlock::iterator> InsertBefore) {
6875 // Nothing to index? Just return V then (this is useful at the end of our
6876 // recursion).
6877 if (idx_range.empty())
6878 return V;
6879 // We have indices, so V should have an indexable type.
6880 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
6881 "Not looking at a struct or array?");
6882 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
6883 "Invalid indices for type?");
6884
6885 if (Constant *C = dyn_cast<Constant>(V)) {
6886 C = C->getAggregateElement(idx_range[0]);
6887 if (!C) return nullptr;
6888 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
6889 }
6890
6892 // Loop the indices for the insertvalue instruction in parallel with the
6893 // requested indices
6894 const unsigned *req_idx = idx_range.begin();
6895 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
6896 i != e; ++i, ++req_idx) {
6897 if (req_idx == idx_range.end()) {
6898 // We can't handle this without inserting insertvalues
6899 if (!InsertBefore)
6900 return nullptr;
6901
6902 // The requested index identifies a part of a nested aggregate. Handle
6903 // this specially. For example,
6904 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
6905 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
6906 // %C = extractvalue {i32, { i32, i32 } } %B, 1
6907 // This can be changed into
6908 // %A = insertvalue {i32, i32 } undef, i32 10, 0
6909 // %C = insertvalue {i32, i32 } %A, i32 11, 1
6910 // which allows the unused 0,0 element from the nested struct to be
6911 // removed.
6912 return BuildSubAggregate(V, ArrayRef(idx_range.begin(), req_idx),
6913 *InsertBefore);
6914 }
6915
6916 // This insert value inserts something else than what we are looking for.
6917 // See if the (aggregate) value inserted into has the value we are
6918 // looking for, then.
6919 if (*req_idx != *i)
6920 return FindInsertedValue(I->getAggregateOperand(), idx_range,
6921 InsertBefore);
6922 }
6923 // If we end up here, the indices of the insertvalue match with those
6924 // requested (though possibly only partially). Now we recursively look at
6925 // the inserted value, passing any remaining indices.
6926 return FindInsertedValue(I->getInsertedValueOperand(),
6927 ArrayRef(req_idx, idx_range.end()), InsertBefore);
6928 }
6929
6931 // If we're extracting a value from an aggregate that was extracted from
6932 // something else, we can extract from that something else directly instead.
6933 // However, we will need to chain I's indices with the requested indices.
6934
6935 // Calculate the number of indices required
6936 unsigned size = I->getNumIndices() + idx_range.size();
6937 // Allocate some space to put the new indices in
6939 Idxs.reserve(size);
6940 // Add indices from the extract value instruction
6941 Idxs.append(I->idx_begin(), I->idx_end());
6942
6943 // Add requested indices
6944 Idxs.append(idx_range.begin(), idx_range.end());
6945
6946 assert(Idxs.size() == size
6947 && "Number of indices added not correct?");
6948
6949 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
6950 }
6951 // Otherwise, we don't know (such as, extracting from a function return value
6952 // or load instruction)
6953 return nullptr;
6954}
6955
6956// If V refers to an initialized global constant, set Slice either to
6957// its initializer if the size of its elements equals ElementSize, or,
6958// for ElementSize == 8, to its representation as an array of unsiged
6959// char. Return true on success.
6960// Offset is in the unit "nr of ElementSize sized elements".
6963 unsigned ElementSize, uint64_t Offset) {
6964 assert(V && "V should not be null.");
6965 assert((ElementSize % 8) == 0 &&
6966 "ElementSize expected to be a multiple of the size of a byte.");
6967 unsigned ElementSizeInBytes = ElementSize / 8;
6968
6969 // Drill down into the pointer expression V, ignoring any intervening
6970 // casts, and determine the identity of the object it references along
6971 // with the cumulative byte offset into it.
6972 const GlobalVariable *GV =
6974 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
6975 // Fail if V is not based on constant global object.
6976 return false;
6977
6978 const DataLayout &DL = GV->getDataLayout();
6979 APInt Off(DL.getIndexTypeSizeInBits(V->getType()), 0);
6980
6981 if (GV != V->stripAndAccumulateConstantOffsets(DL, Off,
6982 /*AllowNonInbounds*/ true))
6983 // Fail if a constant offset could not be determined.
6984 return false;
6985
6986 uint64_t StartIdx = Off.getLimitedValue();
6987 if (StartIdx == UINT64_MAX)
6988 // Fail if the constant offset is excessive.
6989 return false;
6990
6991 // Off/StartIdx is in the unit of bytes. So we need to convert to number of
6992 // elements. Simply bail out if that isn't possible.
6993 if ((StartIdx % ElementSizeInBytes) != 0)
6994 return false;
6995
6996 Offset += StartIdx / ElementSizeInBytes;
6997 ConstantDataArray *Array = nullptr;
6998 ArrayType *ArrayTy = nullptr;
6999
7000 if (GV->getInitializer()->isNullValue()) {
7001 Type *GVTy = GV->getValueType();
7002 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedValue();
7003 uint64_t Length = SizeInBytes / ElementSizeInBytes;
7004
7005 Slice.Array = nullptr;
7006 Slice.Offset = 0;
7007 // Return an empty Slice for undersized constants to let callers
7008 // transform even undefined library calls into simpler, well-defined
7009 // expressions. This is preferable to making the calls although it
7010 // prevents sanitizers from detecting such calls.
7011 Slice.Length = Length < Offset ? 0 : Length - Offset;
7012 return true;
7013 }
7014
7015 auto *Init = const_cast<Constant *>(GV->getInitializer());
7016 if (auto *ArrayInit = dyn_cast<ConstantDataArray>(Init)) {
7017 Type *InitElTy = ArrayInit->getElementType();
7018 if (InitElTy->isIntegerTy(ElementSize)) {
7019 // If Init is an initializer for an array of the expected type
7020 // and size, use it as is.
7021 Array = ArrayInit;
7022 ArrayTy = ArrayInit->getType();
7023 }
7024 }
7025
7026 if (!Array) {
7027 if (ElementSize != 8)
7028 // TODO: Handle conversions to larger integral types.
7029 return false;
7030
7031 // Otherwise extract the portion of the initializer starting
7032 // at Offset as an array of bytes, and reset Offset.
7034 if (!Init)
7035 return false;
7036
7037 Offset = 0;
7039 ArrayTy = dyn_cast<ArrayType>(Init->getType());
7040 }
7041
7042 uint64_t NumElts = ArrayTy->getArrayNumElements();
7043 if (Offset > NumElts)
7044 return false;
7045
7046 Slice.Array = Array;
7047 Slice.Offset = Offset;
7048 Slice.Length = NumElts - Offset;
7049 return true;
7050}
7051
7052/// Extract bytes from the initializer of the constant array V, which need
7053/// not be a nul-terminated string. On success, store the bytes in Str and
7054/// return true. When TrimAtNul is set, Str will contain only the bytes up
7055/// to but not including the first nul. Return false on failure.
7057 bool TrimAtNul) {
7059 if (!getConstantDataArrayInfo(V, Slice, 8))
7060 return false;
7061
7062 if (Slice.Array == nullptr) {
7063 if (TrimAtNul) {
7064 // Return a nul-terminated string even for an empty Slice. This is
7065 // safe because all existing SimplifyLibcalls callers require string
7066 // arguments and the behavior of the functions they fold is undefined
7067 // otherwise. Folding the calls this way is preferable to making
7068 // the undefined library calls, even though it prevents sanitizers
7069 // from reporting such calls.
7070 Str = StringRef();
7071 return true;
7072 }
7073 if (Slice.Length == 1) {
7074 Str = StringRef("", 1);
7075 return true;
7076 }
7077 // We cannot instantiate a StringRef as we do not have an appropriate string
7078 // of 0s at hand.
7079 return false;
7080 }
7081
7082 // Start out with the entire array in the StringRef.
7083 Str = Slice.Array->getAsString();
7084 // Skip over 'offset' bytes.
7085 Str = Str.substr(Slice.Offset);
7086
7087 if (TrimAtNul) {
7088 // Trim off the \0 and anything after it. If the array is not nul
7089 // terminated, we just return the whole end of string. The client may know
7090 // some other way that the string is length-bound.
7091 Str = Str.substr(0, Str.find('\0'));
7092 }
7093 return true;
7094}
7095
7096// These next two are very similar to the above, but also look through PHI
7097// nodes.
7098// TODO: See if we can integrate these two together.
7099
7100/// If we can compute the length of the string pointed to by
7101/// the specified pointer, return 'len+1'. If we can't, return 0.
7104 unsigned CharSize) {
7105 // Look through noop bitcast instructions.
7106 V = V->stripPointerCasts();
7107
7108 // If this is a PHI node, there are two cases: either we have already seen it
7109 // or we haven't.
7110 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
7111 if (!PHIs.insert(PN).second)
7112 return ~0ULL; // already in the set.
7113
7114 // If it was new, see if all the input strings are the same length.
7115 uint64_t LenSoFar = ~0ULL;
7116 for (Value *IncValue : PN->incoming_values()) {
7117 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
7118 if (Len == 0) return 0; // Unknown length -> unknown.
7119
7120 if (Len == ~0ULL) continue;
7121
7122 if (Len != LenSoFar && LenSoFar != ~0ULL)
7123 return 0; // Disagree -> unknown.
7124 LenSoFar = Len;
7125 }
7126
7127 // Success, all agree.
7128 return LenSoFar;
7129 }
7130
7131 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
7132 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
7133 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
7134 if (Len1 == 0) return 0;
7135 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
7136 if (Len2 == 0) return 0;
7137 if (Len1 == ~0ULL) return Len2;
7138 if (Len2 == ~0ULL) return Len1;
7139 if (Len1 != Len2) return 0;
7140 return Len1;
7141 }
7142
7143 // Otherwise, see if we can read the string.
7145 if (!getConstantDataArrayInfo(V, Slice, CharSize))
7146 return 0;
7147
7148 if (Slice.Array == nullptr)
7149 // Zeroinitializer (including an empty one).
7150 return 1;
7151
7152 // Search for the first nul character. Return a conservative result even
7153 // when there is no nul. This is safe since otherwise the string function
7154 // being folded such as strlen is undefined, and can be preferable to
7155 // making the undefined library call.
7156 unsigned NullIndex = 0;
7157 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
7158 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
7159 break;
7160 }
7161
7162 return NullIndex + 1;
7163}
7164
7165/// If we can compute the length of the string pointed to by
7166/// the specified pointer, return 'len+1'. If we can't, return 0.
7167uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
7168 if (!V->getType()->isPointerTy())
7169 return 0;
7170
7172 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
7173 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
7174 // an empty string as a length.
7175 return Len == ~0ULL ? 1 : Len;
7176}
7177
7178const Value *
7180 bool MustPreserveOffset) {
7181 assert(Call &&
7182 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
7183 if (const Value *RV = Call->getReturnedArgOperand())
7184 return RV;
7185 // This can be used only as a aliasing property.
7187 Call, MustPreserveOffset))
7188 return Call->getArgOperand(0);
7189 return nullptr;
7190}
7191
7193 const CallBase *Call, bool MustPreserveOffset) {
7194 switch (Call->getIntrinsicID()) {
7195 case Intrinsic::launder_invariant_group:
7196 case Intrinsic::strip_invariant_group:
7197 case Intrinsic::aarch64_irg:
7198 case Intrinsic::aarch64_tagp:
7199 // The amdgcn_make_buffer_rsrc function does not alter the address of the
7200 // input pointer (and thus preserves the byte offset, which is the property
7201 // the MustPreserveOffset flag selects). However, it will not necessarily
7202 // map ptr addrspace(N) null to ptr addrspace(8) null, aka the "null
7203 // descriptor", which has "all loads return 0, all stores are dropped"
7204 // semantics. Given the context of this intrinsic list, no one should be
7205 // relying on such a strict bit-exact null mapping (and, at time of
7206 // writing, they are not), but we document this fact out of an abundance
7207 // of caution.
7208 case Intrinsic::amdgcn_make_buffer_rsrc:
7209 return true;
7210 case Intrinsic::ptrmask:
7211 return !MustPreserveOffset;
7212 case Intrinsic::threadlocal_address:
7213 // The underlying variable changes with thread ID. The Thread ID may change
7214 // at coroutine suspend points.
7215 return !Call->getParent()->getParent()->isPresplitCoroutine();
7216 default:
7217 return false;
7218 }
7219}
7220
7221/// \p PN defines a loop-variant pointer to an object. Check if the
7222/// previous iteration of the loop was referring to the same object as \p PN.
7224 const LoopInfo *LI) {
7225 // Find the loop-defined value.
7226 Loop *L = LI->getLoopFor(PN->getParent());
7227 if (PN->getNumIncomingValues() != 2)
7228 return true;
7229
7230 // Find the value from previous iteration.
7231 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
7232 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7233 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
7234 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7235 return true;
7236
7237 // If a new pointer is loaded in the loop, the pointer references a different
7238 // object in every iteration. E.g.:
7239 // for (i)
7240 // int *p = a[i];
7241 // ...
7242 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
7243 if (!L->isLoopInvariant(Load->getPointerOperand()))
7244 return false;
7245 return true;
7246}
7247
7248const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup) {
7249 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
7250 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
7251 const Value *PtrOp = GEP->getPointerOperand();
7252 if (!PtrOp->getType()->isPointerTy()) // Only handle scalar pointer base.
7253 return V;
7254 V = PtrOp;
7255 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
7256 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
7257 Value *NewV = cast<Operator>(V)->getOperand(0);
7258 if (!NewV->getType()->isPointerTy())
7259 return V;
7260 V = NewV;
7261 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
7262 if (GA->isInterposable())
7263 return V;
7264 V = GA->getAliasee();
7265 } else {
7266 if (auto *PHI = dyn_cast<PHINode>(V)) {
7267 // Look through single-arg phi nodes created by LCSSA.
7268 if (PHI->getNumIncomingValues() == 1) {
7269 V = PHI->getIncomingValue(0);
7270 continue;
7271 }
7272 } else if (auto *Call = dyn_cast<CallBase>(V)) {
7273 // CaptureTracking can know about special capturing properties of some
7274 // intrinsics like launder.invariant.group, that can't be expressed with
7275 // the attributes, but have properties like returning aliasing pointer.
7276 // Because some analysis may assume that nocaptured pointer is not
7277 // returned from some special intrinsic (because function would have to
7278 // be marked with returns attribute), it is crucial to use this function
7279 // because it should be in sync with CaptureTracking. Not using it may
7280 // cause weird miscompilations where 2 aliasing pointers are assumed to
7281 // noalias.
7283 Call, /*MustPreserveOffset=*/false)) {
7284 V = RP;
7285 continue;
7286 }
7287 }
7288
7289 return V;
7290 }
7291 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
7292 }
7293 return V;
7294}
7295
7298 const LoopInfo *LI, unsigned MaxLookup) {
7301 Worklist.push_back(V);
7302 do {
7303 const Value *P = Worklist.pop_back_val();
7304 P = getUnderlyingObject(P, MaxLookup);
7305
7306 if (!Visited.insert(P).second)
7307 continue;
7308
7309 if (auto *SI = dyn_cast<SelectInst>(P)) {
7310 Worklist.push_back(SI->getTrueValue());
7311 Worklist.push_back(SI->getFalseValue());
7312 continue;
7313 }
7314
7315 if (auto *PN = dyn_cast<PHINode>(P)) {
7316 // If this PHI changes the underlying object in every iteration of the
7317 // loop, don't look through it. Consider:
7318 // int **A;
7319 // for (i) {
7320 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
7321 // Curr = A[i];
7322 // *Prev, *Curr;
7323 //
7324 // Prev is tracking Curr one iteration behind so they refer to different
7325 // underlying objects.
7326 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
7328 append_range(Worklist, PN->incoming_values());
7329 else
7330 Objects.push_back(P);
7331 continue;
7332 }
7333
7334 Objects.push_back(P);
7335 } while (!Worklist.empty());
7336}
7337
7339 const unsigned MaxVisited = 8;
7340
7343 Worklist.push_back(V);
7344 const Value *Object = nullptr;
7345 // Used as fallback if we can't find a common underlying object through
7346 // recursion.
7347 bool First = true;
7348 const Value *FirstObject = getUnderlyingObject(V);
7349 do {
7350 const Value *P = Worklist.pop_back_val();
7351 P = First ? FirstObject : getUnderlyingObject(P);
7352 First = false;
7353
7354 if (!Visited.insert(P).second)
7355 continue;
7356
7357 if (Visited.size() == MaxVisited)
7358 return FirstObject;
7359
7360 if (auto *SI = dyn_cast<SelectInst>(P)) {
7361 Worklist.push_back(SI->getTrueValue());
7362 Worklist.push_back(SI->getFalseValue());
7363 continue;
7364 }
7365
7366 if (auto *PN = dyn_cast<PHINode>(P)) {
7367 append_range(Worklist, PN->incoming_values());
7368 continue;
7369 }
7370
7371 if (!Object)
7372 Object = P;
7373 else if (Object != P)
7374 return FirstObject;
7375 } while (!Worklist.empty());
7376
7377 return Object ? Object : FirstObject;
7378}
7379
7380/// This is the function that does the work of looking through basic
7381/// ptrtoint+arithmetic+inttoptr sequences.
7382static const Value *getUnderlyingObjectFromInt(const Value *V) {
7383 do {
7384 if (const Operator *U = dyn_cast<Operator>(V)) {
7385 // If we find a ptrtoint, we can transfer control back to the
7386 // regular getUnderlyingObjectFromInt.
7387 if (U->getOpcode() == Instruction::PtrToInt)
7388 return U->getOperand(0);
7389 // If we find an add of a constant, a multiplied value, or a phi, it's
7390 // likely that the other operand will lead us to the base
7391 // object. We don't have to worry about the case where the
7392 // object address is somehow being computed by the multiply,
7393 // because our callers only care when the result is an
7394 // identifiable object.
7395 if (U->getOpcode() != Instruction::Add ||
7396 (!isa<ConstantInt>(U->getOperand(1)) &&
7397 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
7398 !isa<PHINode>(U->getOperand(1))))
7399 return V;
7400 V = U->getOperand(0);
7401 } else {
7402 return V;
7403 }
7404 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
7405 } while (true);
7406}
7407
7408/// This is a wrapper around getUnderlyingObjects and adds support for basic
7409/// ptrtoint+arithmetic+inttoptr sequences.
7410/// It returns false if unidentified object is found in getUnderlyingObjects.
7412 SmallVectorImpl<Value *> &Objects) {
7414 SmallVector<const Value *, 4> Working(1, V);
7415 do {
7416 V = Working.pop_back_val();
7417
7419 getUnderlyingObjects(V, Objs);
7420
7421 for (const Value *V : Objs) {
7422 if (!Visited.insert(V).second)
7423 continue;
7424 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
7425 const Value *O =
7426 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
7427 if (O->getType()->isPointerTy()) {
7428 Working.push_back(O);
7429 continue;
7430 }
7431 }
7432 // If getUnderlyingObjects fails to find an identifiable object,
7433 // getUnderlyingObjectsForCodeGen also fails for safety.
7434 if (!isIdentifiedObject(V)) {
7435 Objects.clear();
7436 return false;
7437 }
7438 Objects.push_back(const_cast<Value *>(V));
7439 }
7440 } while (!Working.empty());
7441 return true;
7442}
7443
7445 AllocaInst *Result = nullptr;
7447 SmallVector<Value *, 4> Worklist;
7448
7449 auto AddWork = [&](Value *V) {
7450 if (Visited.insert(V).second)
7451 Worklist.push_back(V);
7452 };
7453
7454 AddWork(V);
7455 do {
7456 V = Worklist.pop_back_val();
7457 assert(Visited.count(V));
7458
7459 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
7460 if (Result && Result != AI)
7461 return nullptr;
7462 Result = AI;
7463 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
7464 AddWork(CI->getOperand(0));
7465 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
7466 for (Value *IncValue : PN->incoming_values())
7467 AddWork(IncValue);
7468 } else if (auto *SI = dyn_cast<SelectInst>(V)) {
7469 AddWork(SI->getTrueValue());
7470 AddWork(SI->getFalseValue());
7472 if (OffsetZero && !GEP->hasAllZeroIndices())
7473 return nullptr;
7474 AddWork(GEP->getPointerOperand());
7475 } else if (CallBase *CB = dyn_cast<CallBase>(V)) {
7476 Value *Returned = CB->getReturnedArgOperand();
7477 if (Returned)
7478 AddWork(Returned);
7479 else
7480 return nullptr;
7481 } else {
7482 return nullptr;
7483 }
7484 } while (!Worklist.empty());
7485
7486 return Result;
7487}
7488
7490 const Value *V, bool AllowLifetime, bool AllowDroppable) {
7491 for (const User *U : V->users()) {
7493 if (!II)
7494 return false;
7495
7496 if (AllowLifetime && II->isLifetimeStartOrEnd())
7497 continue;
7498
7499 if (AllowDroppable && II->isDroppable())
7500 continue;
7501
7502 return false;
7503 }
7504 return true;
7505}
7506
7509 V, /* AllowLifetime */ true, /* AllowDroppable */ false);
7510}
7513 V, /* AllowLifetime */ true, /* AllowDroppable */ true);
7514}
7515
7517 if (auto *II = dyn_cast<IntrinsicInst>(I))
7518 return isTriviallyVectorizable(II->getIntrinsicID());
7519 auto *Shuffle = dyn_cast<ShuffleVectorInst>(I);
7520 return (!Shuffle || Shuffle->isSelect()) &&
7522}
7523
7525 const Instruction *Inst, const Instruction *CtxI, AssumptionCache *AC,
7526 const DominatorTree *DT, const TargetLibraryInfo *TLI, bool UseVariableInfo,
7527 bool IgnoreUBImplyingAttrs) {
7528 return isSafeToSpeculativelyExecuteWithOpcode(Inst->getOpcode(), Inst, CtxI,
7529 AC, DT, TLI, UseVariableInfo,
7530 IgnoreUBImplyingAttrs);
7531}
7532
7534 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI,
7535 AssumptionCache *AC, const DominatorTree *DT, const TargetLibraryInfo *TLI,
7536 bool UseVariableInfo, bool IgnoreUBImplyingAttrs) {
7537#ifndef NDEBUG
7538 if (Inst->getOpcode() != Opcode) {
7539 // Check that the operands are actually compatible with the Opcode override.
7540 auto hasEqualReturnAndLeadingOperandTypes =
7541 [](const Instruction *Inst, unsigned NumLeadingOperands) {
7542 if (Inst->getNumOperands() < NumLeadingOperands)
7543 return false;
7544 const Type *ExpectedType = Inst->getType();
7545 for (unsigned ItOp = 0; ItOp < NumLeadingOperands; ++ItOp)
7546 if (Inst->getOperand(ItOp)->getType() != ExpectedType)
7547 return false;
7548 return true;
7549 };
7551 hasEqualReturnAndLeadingOperandTypes(Inst, 2));
7552 assert(!Instruction::isUnaryOp(Opcode) ||
7553 hasEqualReturnAndLeadingOperandTypes(Inst, 1));
7554 }
7555#endif
7556
7557 switch (Opcode) {
7558 default:
7559 return true;
7560 case Instruction::UDiv:
7561 case Instruction::URem: {
7562 // x / y is undefined if y == 0.
7563 const APInt *V;
7564 if (match(Inst->getOperand(1), m_APInt(V)))
7565 return *V != 0;
7566 return false;
7567 }
7568 case Instruction::SDiv:
7569 case Instruction::SRem: {
7570 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
7571 const APInt *Numerator, *Denominator;
7572 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
7573 return false;
7574 // We cannot hoist this division if the denominator is 0.
7575 if (*Denominator == 0)
7576 return false;
7577 // It's safe to hoist if the denominator is not 0 or -1.
7578 if (!Denominator->isAllOnes())
7579 return true;
7580 // At this point we know that the denominator is -1. It is safe to hoist as
7581 // long we know that the numerator is not INT_MIN.
7582 if (match(Inst->getOperand(0), m_APInt(Numerator)))
7583 return !Numerator->isMinSignedValue();
7584 // The numerator *might* be MinSignedValue.
7585 return false;
7586 }
7587 case Instruction::Load: {
7588 if (!UseVariableInfo)
7589 return false;
7590
7591 const LoadInst *LI = dyn_cast<LoadInst>(Inst);
7592 if (!LI)
7593 return false;
7594 if (mustSuppressSpeculation(*LI))
7595 return false;
7596 const DataLayout &DL = LI->getDataLayout();
7598 LI->getPointerOperand(), LI->getType(), LI->getAlign(),
7599 SimplifyQuery(DL, TLI, DT, AC, CtxI));
7600 }
7601 case Instruction::Call: {
7602 auto *CI = dyn_cast<const CallInst>(Inst);
7603 if (!CI)
7604 return false;
7605 const Function *Callee = CI->getCalledFunction();
7606
7607 // The called function could have undefined behavior or side-effects, even
7608 // if marked readnone nounwind.
7609 if (!Callee || !Callee->isSpeculatable())
7610 return false;
7611 // Since the operands may be changed after hoisting, undefined behavior may
7612 // be triggered by some UB-implying attributes.
7613 return IgnoreUBImplyingAttrs || !CI->hasUBImplyingAttrs();
7614 }
7615 case Instruction::VAArg:
7616 case Instruction::Alloca:
7617 case Instruction::Invoke:
7618 case Instruction::CallBr:
7619 case Instruction::PHI:
7620 case Instruction::Store:
7621 case Instruction::Ret:
7622 case Instruction::UncondBr:
7623 case Instruction::CondBr:
7624 case Instruction::IndirectBr:
7625 case Instruction::Switch:
7626 case Instruction::Unreachable:
7627 case Instruction::Fence:
7628 case Instruction::AtomicRMW:
7629 case Instruction::AtomicCmpXchg:
7630 case Instruction::LandingPad:
7631 case Instruction::Resume:
7632 case Instruction::CatchSwitch:
7633 case Instruction::CatchPad:
7634 case Instruction::CatchRet:
7635 case Instruction::CleanupPad:
7636 case Instruction::CleanupRet:
7637 return false; // Misc instructions which have effects
7638 }
7639}
7640
7642 if (I.mayReadOrWriteMemory())
7643 // Memory dependency possible
7644 return true;
7646 // Can't move above a maythrow call or infinite loop. Or if an
7647 // inalloca alloca, above a stacksave call.
7648 return true;
7650 // 1) Can't reorder two inf-loop calls, even if readonly
7651 // 2) Also can't reorder an inf-loop call below a instruction which isn't
7652 // safe to speculative execute. (Inverse of above)
7653 return true;
7654 return false;
7655}
7656
7657/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
7671
7672/// Combine constant ranges from computeConstantRange() and computeKnownBits().
7675 bool ForSigned,
7676 const SimplifyQuery &SQ) {
7677 ConstantRange CR1 =
7678 ConstantRange::fromKnownBits(V.getKnownBits(SQ), ForSigned);
7679 ConstantRange CR2 = computeConstantRange(V, ForSigned, SQ);
7682 return CR1.intersectWith(CR2, RangeType);
7683}
7684
7686 const Value *RHS,
7687 const SimplifyQuery &SQ,
7688 bool IsNSW) {
7689 ConstantRange LHSRange =
7690 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7691 ConstantRange RHSRange =
7692 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7693
7694 // mul nsw of two non-negative numbers is also nuw.
7695 if (IsNSW && LHSRange.isAllNonNegative() && RHSRange.isAllNonNegative())
7697
7698 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
7699}
7700
7702 const Value *RHS,
7703 const SimplifyQuery &SQ) {
7704 // Multiplying n * m significant bits yields a result of n + m significant
7705 // bits. If the total number of significant bits does not exceed the
7706 // result bit width (minus 1), there is no overflow.
7707 // This means if we have enough leading sign bits in the operands
7708 // we can guarantee that the result does not overflow.
7709 // Ref: "Hacker's Delight" by Henry Warren
7710 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
7711
7712 // Note that underestimating the number of sign bits gives a more
7713 // conservative answer.
7714 unsigned SignBits =
7715 ::ComputeNumSignBits(LHS, SQ) + ::ComputeNumSignBits(RHS, SQ);
7716
7717 // First handle the easy case: if we have enough sign bits there's
7718 // definitely no overflow.
7719 if (SignBits > BitWidth + 1)
7721
7722 // There are two ambiguous cases where there can be no overflow:
7723 // SignBits == BitWidth + 1 and
7724 // SignBits == BitWidth
7725 // The second case is difficult to check, therefore we only handle the
7726 // first case.
7727 if (SignBits == BitWidth + 1) {
7728 // It overflows only when both arguments are negative and the true
7729 // product is exactly the minimum negative number.
7730 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
7731 // For simplicity we just check if at least one side is not negative.
7732 KnownBits LHSKnown = computeKnownBits(LHS, SQ);
7733 KnownBits RHSKnown = computeKnownBits(RHS, SQ);
7734 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
7736 }
7738}
7739
7742 const WithCache<const Value *> &RHS,
7743 const SimplifyQuery &SQ) {
7744 ConstantRange LHSRange =
7745 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7746 ConstantRange RHSRange =
7747 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7748 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
7749}
7750
7751static OverflowResult
7754 const AddOperator *Add, const SimplifyQuery &SQ) {
7755 if (Add && Add->hasNoSignedWrap()) {
7757 }
7758
7759 // If LHS and RHS each have at least two sign bits, the addition will look
7760 // like
7761 //
7762 // XX..... +
7763 // YY.....
7764 //
7765 // If the carry into the most significant position is 0, X and Y can't both
7766 // be 1 and therefore the carry out of the addition is also 0.
7767 //
7768 // If the carry into the most significant position is 1, X and Y can't both
7769 // be 0 and therefore the carry out of the addition is also 1.
7770 //
7771 // Since the carry into the most significant position is always equal to
7772 // the carry out of the addition, there is no signed overflow.
7773 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7775
7776 ConstantRange LHSRange =
7777 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7778 ConstantRange RHSRange =
7779 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7780 OverflowResult OR =
7781 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
7783 return OR;
7784
7785 // The remaining code needs Add to be available. Early returns if not so.
7786 if (!Add)
7788
7789 // If the sign of Add is the same as at least one of the operands, this add
7790 // CANNOT overflow. If this can be determined from the known bits of the
7791 // operands the above signedAddMayOverflow() check will have already done so.
7792 // The only other way to improve on the known bits is from an assumption, so
7793 // call computeKnownBitsFromContext() directly.
7794 bool LHSOrRHSKnownNonNegative =
7795 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
7796 bool LHSOrRHSKnownNegative =
7797 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
7798 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
7799 KnownBits AddKnown(LHSRange.getBitWidth());
7800 computeKnownBitsFromContext(Add, AddKnown, SQ);
7801 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
7802 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
7804 }
7805
7807}
7808
7810 const Value *RHS,
7811 const SimplifyQuery &SQ) {
7812 // X - (X % ?)
7813 // The remainder of a value can't have greater magnitude than itself,
7814 // so the subtraction can't overflow.
7815
7816 // X - (X -nuw ?)
7817 // In the minimal case, this would simplify to "?", so there's no subtract
7818 // at all. But if this analysis is used to peek through casts, for example,
7819 // then determining no-overflow may allow other transforms.
7820
7821 // TODO: There are other patterns like this.
7822 // See simplifyICmpWithBinOpOnLHS() for candidates.
7823 if (match(RHS, m_URem(m_Specific(LHS), m_Value())) ||
7824 match(RHS, m_NUWSub(m_Specific(LHS), m_Value())))
7825 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT))
7827
7828 if (auto C = isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, SQ.CxtI,
7829 SQ.DL)) {
7830 if (*C)
7833 }
7834
7835 ConstantRange LHSRange =
7836 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7837 ConstantRange RHSRange =
7838 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7839 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
7840}
7841
7843 const Value *RHS,
7844 const SimplifyQuery &SQ) {
7845 // X - (X % ?)
7846 // The remainder of a value can't have greater magnitude than itself,
7847 // so the subtraction can't overflow.
7848
7849 // X - (X -nsw ?)
7850 // In the minimal case, this would simplify to "?", so there's no subtract
7851 // at all. But if this analysis is used to peek through casts, for example,
7852 // then determining no-overflow may allow other transforms.
7853 if (match(RHS, m_SRem(m_Specific(LHS), m_Value())) ||
7854 match(RHS, m_NSWSub(m_Specific(LHS), m_Value())))
7855 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT))
7857
7858 // If LHS and RHS each have at least two sign bits, the subtraction
7859 // cannot overflow.
7860 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7862
7863 ConstantRange LHSRange =
7864 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7865 ConstantRange RHSRange =
7866 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7867 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
7868}
7869
7871 const DominatorTree &DT) {
7872 SmallVector<const CondBrInst *, 2> GuardingBranches;
7874
7875 for (const User *U : WO->users()) {
7876 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
7877 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
7878
7879 if (EVI->getIndices()[0] == 0)
7880 Results.push_back(EVI);
7881 else {
7882 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
7883
7884 for (const auto *U : EVI->users())
7885 if (const auto *B = dyn_cast<CondBrInst>(U))
7886 GuardingBranches.push_back(B);
7887 }
7888 } else {
7889 // We are using the aggregate directly in a way we don't want to analyze
7890 // here (storing it to a global, say).
7891 return false;
7892 }
7893 }
7894
7895 auto AllUsesGuardedByBranch = [&](const CondBrInst *BI) {
7896 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
7897
7898 // Check if all users of the add are provably no-wrap.
7899 for (const auto *Result : Results) {
7900 // If the extractvalue itself is not executed on overflow, the we don't
7901 // need to check each use separately, since domination is transitive.
7902 if (DT.dominates(NoWrapEdge, Result->getParent()))
7903 continue;
7904
7905 for (const auto &RU : Result->uses())
7906 if (!DT.dominates(NoWrapEdge, RU))
7907 return false;
7908 }
7909
7910 return true;
7911 };
7912
7913 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
7914}
7915
7916/// Shifts return poison if shiftwidth is larger than the bitwidth.
7917static bool shiftAmountKnownInRange(const Value *ShiftAmount) {
7918 auto *C = dyn_cast<Constant>(ShiftAmount);
7919 if (!C)
7920 return false;
7921
7922 // Shifts return poison if shiftwidth is larger than the bitwidth.
7924 if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
7925 unsigned NumElts = FVTy->getNumElements();
7926 for (unsigned i = 0; i < NumElts; ++i)
7927 ShiftAmounts.push_back(C->getAggregateElement(i));
7928 } else if (isa<ScalableVectorType>(C->getType()))
7929 return false; // Can't tell, just return false to be safe
7930 else
7931 ShiftAmounts.push_back(C);
7932
7933 bool Safe = llvm::all_of(ShiftAmounts, [](const Constant *C) {
7934 auto *CI = dyn_cast_or_null<ConstantInt>(C);
7935 return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
7936 });
7937
7938 return Safe;
7939}
7940
7942 bool ConsiderFlagsAndMetadata) {
7943
7944 if (ConsiderFlagsAndMetadata && includesPoison(Kind) &&
7945 Op->hasPoisonGeneratingAnnotations())
7946 return true;
7947
7948 unsigned Opcode = Op->getOpcode();
7949
7950 // Check whether opcode is a poison/undef-generating operation
7951 switch (Opcode) {
7952 case Instruction::Shl:
7953 case Instruction::AShr:
7954 case Instruction::LShr:
7955 return includesPoison(Kind) && !shiftAmountKnownInRange(Op->getOperand(1));
7956 case Instruction::FPToSI:
7957 case Instruction::FPToUI:
7958 // fptosi/ui yields poison if the resulting value does not fit in the
7959 // destination type.
7960 return true;
7961 case Instruction::Call:
7962 if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
7963 switch (II->getIntrinsicID()) {
7964 // NOTE: Use IntrNoCreateUndefOrPoison when possible.
7965 case Intrinsic::ctlz:
7966 case Intrinsic::cttz:
7967 case Intrinsic::abs:
7968 // We're not considering flags so it is safe to just return false.
7969 return false;
7970 case Intrinsic::sshl_sat:
7971 case Intrinsic::ushl_sat:
7972 if (!includesPoison(Kind) ||
7973 shiftAmountKnownInRange(II->getArgOperand(1)))
7974 return false;
7975 break;
7976 }
7977 }
7978 [[fallthrough]];
7979 case Instruction::CallBr:
7980 case Instruction::Invoke: {
7981 const auto *CB = cast<CallBase>(Op);
7982 return !CB->hasRetAttr(Attribute::NoUndef) &&
7983 !CB->hasFnAttr(Attribute::NoCreateUndefOrPoison);
7984 }
7985 case Instruction::InsertElement:
7986 case Instruction::ExtractElement: {
7987 // If index exceeds the length of the vector, it returns poison
7988 auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
7989 unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
7990 auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
7991 if (includesPoison(Kind))
7992 return !Idx ||
7993 Idx->getValue().uge(VTy->getElementCount().getKnownMinValue());
7994 return false;
7995 }
7996 case Instruction::ShuffleVector: {
7998 ? cast<ConstantExpr>(Op)->getShuffleMask()
7999 : cast<ShuffleVectorInst>(Op)->getShuffleMask();
8000 return includesPoison(Kind) && is_contained(Mask, PoisonMaskElem);
8001 }
8002 case Instruction::FNeg:
8003 case Instruction::PHI:
8004 case Instruction::Select:
8005 case Instruction::ExtractValue:
8006 case Instruction::InsertValue:
8007 case Instruction::Freeze:
8008 case Instruction::ICmp:
8009 case Instruction::FCmp:
8010 case Instruction::GetElementPtr:
8011 return false;
8012 case Instruction::AddrSpaceCast:
8013 return true;
8014 default: {
8015 const auto *CE = dyn_cast<ConstantExpr>(Op);
8016 if (isa<CastInst>(Op) || (CE && CE->isCast()))
8017 return false;
8018 else if (Instruction::isBinaryOp(Opcode))
8019 return false;
8020 // Be conservative and return true.
8021 return true;
8022 }
8023 }
8024}
8025
8027 bool ConsiderFlagsAndMetadata) {
8028 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::UndefOrPoison,
8029 ConsiderFlagsAndMetadata);
8030}
8031
8032bool llvm::canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata) {
8033 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::PoisonOnly,
8034 ConsiderFlagsAndMetadata);
8035}
8036
8037static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V,
8038 unsigned Depth) {
8039 if (ValAssumedPoison == V)
8040 return true;
8041
8042 const unsigned MaxDepth = 2;
8043 if (Depth >= MaxDepth)
8044 return false;
8045
8046 if (const auto *I = dyn_cast<Instruction>(V)) {
8047 if (any_of(I->operands(), [=](const Use &Op) {
8048 return propagatesPoison(Op) &&
8049 directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
8050 }))
8051 return true;
8052
8053 // V = extractvalue V0, idx
8054 // V2 = extractvalue V0, idx2
8055 // V0's elements are all poison or not. (e.g., add_with_overflow)
8056 const WithOverflowInst *II;
8058 (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
8059 llvm::is_contained(II->args(), ValAssumedPoison)))
8060 return true;
8061 }
8062 return false;
8063}
8064
8065static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
8066 unsigned Depth) {
8067 if (isGuaranteedNotToBePoison(ValAssumedPoison))
8068 return true;
8069
8070 if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
8071 return true;
8072
8073 const unsigned MaxDepth = 2;
8074 if (Depth >= MaxDepth)
8075 return false;
8076
8077 const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
8078 if (I && !canCreatePoison(cast<Operator>(I))) {
8079 return all_of(I->operands(), [=](const Value *Op) {
8080 return impliesPoison(Op, V, Depth + 1);
8081 });
8082 }
8083 return false;
8084}
8085
8086bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
8087 return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
8088}
8089
8090static bool programUndefinedIfUndefOrPoison(const Value *V, bool PoisonOnly);
8091
8093 const Value *V, AssumptionCache *AC, const Instruction *CtxI,
8094 const DominatorTree *DT, unsigned Depth, UndefPoisonKind Kind) {
8096 return false;
8097
8098 if (isa<MetadataAsValue>(V))
8099 return false;
8100
8101 if (const auto *A = dyn_cast<Argument>(V)) {
8102 if (A->hasAttribute(Attribute::NoUndef) ||
8103 A->hasAttribute(Attribute::Dereferenceable) ||
8104 A->hasAttribute(Attribute::DereferenceableOrNull))
8105 return true;
8106 }
8107
8108 if (auto *C = dyn_cast<Constant>(V)) {
8109 if (isa<PoisonValue>(C))
8110 return !includesPoison(Kind);
8111
8112 if (isa<UndefValue>(C))
8113 return !includesUndef(Kind);
8114
8117 return true;
8118
8119 if (C->getType()->isVectorTy()) {
8120 if (isa<ConstantExpr>(C)) {
8121 // Scalable vectors can use a ConstantExpr to build a splat.
8122 if (Constant *SplatC = C->getSplatValue())
8123 if (isa<ConstantInt>(SplatC) || isa<ConstantFP>(SplatC))
8124 return true;
8125 } else {
8126 if (includesUndef(Kind) && C->containsUndefElement())
8127 return false;
8128 if (includesPoison(Kind) && C->containsPoisonElement())
8129 return false;
8130 return !C->containsConstantExpression();
8131 }
8132 }
8133 }
8134
8135 // Strip cast operations from a pointer value.
8136 // Note that stripPointerCastsSameRepresentation can strip off getelementptr
8137 // inbounds with zero offset. To guarantee that the result isn't poison, the
8138 // stripped pointer is checked as it has to be pointing into an allocated
8139 // object or be null `null` to ensure `inbounds` getelement pointers with a
8140 // zero offset could not produce poison.
8141 // It can strip off addrspacecast that do not change bit representation as
8142 // well. We believe that such addrspacecast is equivalent to no-op.
8143 auto *StrippedV = V->stripPointerCastsSameRepresentation();
8144 if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
8145 isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
8146 return true;
8147
8148 auto OpCheck = [&](const Value *V) {
8149 return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1, Kind);
8150 };
8151
8152 if (auto *Opr = dyn_cast<Operator>(V)) {
8153 // If the value is a freeze instruction, then it can never
8154 // be undef or poison.
8155 if (isa<FreezeInst>(V))
8156 return true;
8157
8158 if (const auto *CB = dyn_cast<CallBase>(V)) {
8159 if (CB->hasRetAttr(Attribute::NoUndef) ||
8160 CB->hasRetAttr(Attribute::Dereferenceable) ||
8161 CB->hasRetAttr(Attribute::DereferenceableOrNull))
8162 return true;
8163 }
8164
8165 if (!::canCreateUndefOrPoison(Opr, Kind,
8166 /*ConsiderFlagsAndMetadata=*/true)) {
8167 if (const auto *PN = dyn_cast<PHINode>(V)) {
8168 unsigned Num = PN->getNumIncomingValues();
8169 bool IsWellDefined = true;
8170 for (unsigned i = 0; i < Num; ++i) {
8171 if (PN == PN->getIncomingValue(i))
8172 continue;
8173 auto *TI = PN->getIncomingBlock(i)->getTerminator();
8174 if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
8175 DT, Depth + 1, Kind)) {
8176 IsWellDefined = false;
8177 break;
8178 }
8179 }
8180 if (IsWellDefined)
8181 return true;
8182 } else if (auto *Splat = isa<ShuffleVectorInst>(Opr) ? getSplatValue(Opr)
8183 : nullptr) {
8184 // For splats we only need to check the value being splatted.
8185 if (OpCheck(Splat))
8186 return true;
8187 } else if (all_of(Opr->operands(), OpCheck))
8188 return true;
8189 }
8190 }
8191
8192 if (auto *I = dyn_cast<LoadInst>(V))
8193 if (I->hasMetadata(LLVMContext::MD_noundef) ||
8194 I->hasMetadata(LLVMContext::MD_dereferenceable) ||
8195 I->hasMetadata(LLVMContext::MD_dereferenceable_or_null))
8196 return true;
8197
8199 return true;
8200
8201 // CxtI may be null or a cloned instruction.
8202 if (!CtxI || !CtxI->getParent() || !DT)
8203 return false;
8204
8205 auto *DNode = DT->getNode(CtxI->getParent());
8206 if (!DNode)
8207 // Unreachable block
8208 return false;
8209
8210 // If V is used as a branch condition before reaching CtxI, V cannot be
8211 // undef or poison.
8212 // br V, BB1, BB2
8213 // BB1:
8214 // CtxI ; V cannot be undef or poison here
8215 auto *Dominator = DNode->getIDom();
8216 // This check is purely for compile time reasons: we can skip the IDom walk
8217 // if what we are checking for includes undef and the value is not an integer.
8218 if (!includesUndef(Kind) || V->getType()->isIntegerTy())
8219 while (Dominator) {
8220 auto *TI = Dominator->getBlock()->getTerminatorOrNull();
8221
8222 Value *Cond = nullptr;
8223 if (auto BI = dyn_cast_or_null<CondBrInst>(TI)) {
8224 Cond = BI->getCondition();
8225 } else if (auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
8226 Cond = SI->getCondition();
8227 }
8228
8229 if (Cond) {
8230 if (Cond == V)
8231 return true;
8232 else if (!includesUndef(Kind) && isa<Operator>(Cond)) {
8233 // For poison, we can analyze further
8234 auto *Opr = cast<Operator>(Cond);
8235 if (any_of(Opr->operands(), [V](const Use &U) {
8236 return V == U && propagatesPoison(U);
8237 }))
8238 return true;
8239 }
8240 }
8241
8242 Dominator = Dominator->getIDom();
8243 }
8244
8245 if (AC && getKnowledgeValidInContext(V, {Attribute::NoUndef}, *AC, CtxI, DT))
8246 return true;
8247
8248 return false;
8249}
8250
8252 const Instruction *CtxI,
8253 const DominatorTree *DT,
8254 unsigned Depth) {
8255 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8257}
8258
8260 const Instruction *CtxI,
8261 const DominatorTree *DT, unsigned Depth) {
8262 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8264}
8265
8267 const Instruction *CtxI,
8268 const DominatorTree *DT, unsigned Depth) {
8269 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8271}
8272
8273/// Return true if undefined behavior would provably be executed on the path to
8274/// OnPathTo if Root produced a posion result. Note that this doesn't say
8275/// anything about whether OnPathTo is actually executed or whether Root is
8276/// actually poison. This can be used to assess whether a new use of Root can
8277/// be added at a location which is control equivalent with OnPathTo (such as
8278/// immediately before it) without introducing UB which didn't previously
8279/// exist. Note that a false result conveys no information.
8281 Instruction *OnPathTo,
8282 DominatorTree *DT) {
8283 // Basic approach is to assume Root is poison, propagate poison forward
8284 // through all users we can easily track, and then check whether any of those
8285 // users are provable UB and must execute before out exiting block might
8286 // exit.
8287
8288 // The set of all recursive users we've visited (which are assumed to all be
8289 // poison because of said visit)
8292 Worklist.push_back(Root);
8293 while (!Worklist.empty()) {
8294 const Instruction *I = Worklist.pop_back_val();
8295
8296 // If we know this must trigger UB on a path leading our target.
8297 if (mustTriggerUB(I, KnownPoison) && DT->dominates(I, OnPathTo))
8298 return true;
8299
8300 // If we can't analyze propagation through this instruction, just skip it
8301 // and transitive users. Safe as false is a conservative result.
8302 if (I != Root && !any_of(I->operands(), [&KnownPoison](const Use &U) {
8303 return KnownPoison.contains(U) && propagatesPoison(U);
8304 }))
8305 continue;
8306
8307 if (KnownPoison.insert(I).second)
8308 for (const User *User : I->users())
8309 Worklist.push_back(cast<Instruction>(User));
8310 }
8311
8312 // Might be non-UB, or might have a path we couldn't prove must execute on
8313 // way to exiting bb.
8314 return false;
8315}
8316
8318 const SimplifyQuery &SQ) {
8319 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
8320 Add, SQ);
8321}
8322
8325 const WithCache<const Value *> &RHS,
8326 const SimplifyQuery &SQ) {
8327 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, SQ);
8328}
8329
8331 // Note: An atomic operation isn't guaranteed to return in a reasonable amount
8332 // of time because it's possible for another thread to interfere with it for an
8333 // arbitrary length of time, but programs aren't allowed to rely on that.
8334
8335 // If there is no successor, then execution can't transfer to it.
8336 if (isa<ReturnInst>(I))
8337 return false;
8339 return false;
8340
8341 // Note: Do not add new checks here; instead, change Instruction::mayThrow or
8342 // Instruction::willReturn.
8343 //
8344 // FIXME: Move this check into Instruction::willReturn.
8345 if (isa<CatchPadInst>(I)) {
8346 switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) {
8347 default:
8348 // A catchpad may invoke exception object constructors and such, which
8349 // in some languages can be arbitrary code, so be conservative by default.
8350 return false;
8352 // For CoreCLR, it just involves a type test.
8353 return true;
8354 }
8355 }
8356
8357 // An instruction that returns without throwing must transfer control flow
8358 // to a successor.
8359 return !I->mayThrow() && I->willReturn();
8360}
8361
8363 // TODO: This is slightly conservative for invoke instruction since exiting
8364 // via an exception *is* normal control for them.
8365 for (const Instruction &I : *BB)
8367 return false;
8368 return true;
8369}
8370
8377
8380 assert(ScanLimit && "scan limit must be non-zero");
8381 for (const Instruction &I : Range) {
8382 if (--ScanLimit == 0)
8383 return false;
8385 return false;
8386 }
8387 return true;
8388}
8389
8391 const Loop *L) {
8392 // The loop header is guaranteed to be executed for every iteration.
8393 //
8394 // FIXME: Relax this constraint to cover all basic blocks that are
8395 // guaranteed to be executed at every iteration.
8396 if (I->getParent() != L->getHeader()) return false;
8397
8398 for (const Instruction &LI : *L->getHeader()) {
8399 if (&LI == I) return true;
8400 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
8401 }
8402 llvm_unreachable("Instruction not contained in its own parent basic block.");
8403}
8404
8406 switch (IID) {
8407 // TODO: Add more intrinsics.
8408 case Intrinsic::sadd_with_overflow:
8409 case Intrinsic::ssub_with_overflow:
8410 case Intrinsic::smul_with_overflow:
8411 case Intrinsic::uadd_with_overflow:
8412 case Intrinsic::usub_with_overflow:
8413 case Intrinsic::umul_with_overflow:
8414 // If an input is a vector containing a poison element, the
8415 // two output vectors (calculated results, overflow bits)'
8416 // corresponding lanes are poison.
8417 return true;
8418 case Intrinsic::ctpop:
8419 case Intrinsic::ctlz:
8420 case Intrinsic::cttz:
8421 case Intrinsic::abs:
8422 case Intrinsic::smax:
8423 case Intrinsic::smin:
8424 case Intrinsic::umax:
8425 case Intrinsic::umin:
8426 case Intrinsic::scmp:
8427 case Intrinsic::is_fpclass:
8428 case Intrinsic::ptrmask:
8429 case Intrinsic::ucmp:
8430 case Intrinsic::bitreverse:
8431 case Intrinsic::bswap:
8432 case Intrinsic::sadd_sat:
8433 case Intrinsic::ssub_sat:
8434 case Intrinsic::sshl_sat:
8435 case Intrinsic::uadd_sat:
8436 case Intrinsic::usub_sat:
8437 case Intrinsic::ushl_sat:
8438 case Intrinsic::smul_fix:
8439 case Intrinsic::smul_fix_sat:
8440 case Intrinsic::umul_fix:
8441 case Intrinsic::umul_fix_sat:
8442 case Intrinsic::pow:
8443 case Intrinsic::powi:
8444 case Intrinsic::sin:
8445 case Intrinsic::sinh:
8446 case Intrinsic::cos:
8447 case Intrinsic::cosh:
8448 case Intrinsic::sincos:
8449 case Intrinsic::sincospi:
8450 case Intrinsic::tan:
8451 case Intrinsic::tanh:
8452 case Intrinsic::asin:
8453 case Intrinsic::acos:
8454 case Intrinsic::atan:
8455 case Intrinsic::atan2:
8456 case Intrinsic::canonicalize:
8457 case Intrinsic::sqrt:
8458 case Intrinsic::exp:
8459 case Intrinsic::exp2:
8460 case Intrinsic::exp10:
8461 case Intrinsic::log:
8462 case Intrinsic::log2:
8463 case Intrinsic::log10:
8464 case Intrinsic::modf:
8465 case Intrinsic::floor:
8466 case Intrinsic::ceil:
8467 case Intrinsic::trunc:
8468 case Intrinsic::rint:
8469 case Intrinsic::nearbyint:
8470 case Intrinsic::round:
8471 case Intrinsic::roundeven:
8472 case Intrinsic::lrint:
8473 case Intrinsic::llrint:
8474 case Intrinsic::fshl:
8475 case Intrinsic::fshr:
8476 case Intrinsic::frexp:
8477 case Intrinsic::get_active_lane_mask:
8478 return true;
8479 default:
8480 return false;
8481 }
8482}
8483
8484bool llvm::propagatesPoison(const Use &PoisonOp) {
8485 const Operator *I = cast<Operator>(PoisonOp.getUser());
8486 switch (I->getOpcode()) {
8487 case Instruction::Freeze:
8488 case Instruction::PHI:
8489 case Instruction::Invoke:
8490 return false;
8491 case Instruction::Select:
8492 return PoisonOp.getOperandNo() == 0;
8493 case Instruction::Call:
8494 if (auto *II = dyn_cast<IntrinsicInst>(I))
8495 return intrinsicPropagatesPoison(II->getIntrinsicID());
8496 return false;
8497 case Instruction::ICmp:
8498 case Instruction::FCmp:
8499 case Instruction::GetElementPtr:
8500 return true;
8501 default:
8503 return true;
8504
8505 // Be conservative and return false.
8506 return false;
8507 }
8508}
8509
8510/// Enumerates all operands of \p I that are guaranteed to not be undef or
8511/// poison. If the callback \p Handle returns true, stop processing and return
8512/// true. Otherwise, return false.
8513template <typename CallableT>
8515 const CallableT &Handle) {
8516 switch (I->getOpcode()) {
8517 case Instruction::Store:
8518 if (Handle(cast<StoreInst>(I)->getPointerOperand()))
8519 return true;
8520 break;
8521
8522 case Instruction::Load:
8523 if (Handle(cast<LoadInst>(I)->getPointerOperand()))
8524 return true;
8525 break;
8526
8527 // Since dereferenceable attribute imply noundef, atomic operations
8528 // also implicitly have noundef pointers too
8529 case Instruction::AtomicCmpXchg:
8531 return true;
8532 break;
8533
8534 case Instruction::AtomicRMW:
8535 if (Handle(cast<AtomicRMWInst>(I)->getPointerOperand()))
8536 return true;
8537 break;
8538
8539 case Instruction::Call:
8540 case Instruction::Invoke: {
8541 const CallBase *CB = cast<CallBase>(I);
8542 if (CB->isIndirectCall() && Handle(CB->getCalledOperand()))
8543 return true;
8544 for (unsigned i = 0; i < CB->arg_size(); ++i)
8545 if ((CB->paramHasAttr(i, Attribute::NoUndef) ||
8546 CB->paramHasAttr(i, Attribute::Dereferenceable) ||
8547 CB->paramHasAttr(i, Attribute::DereferenceableOrNull)) &&
8548 Handle(CB->getArgOperand(i)))
8549 return true;
8550 break;
8551 }
8552 case Instruction::Ret:
8553 if (I->getFunction()->hasRetAttribute(Attribute::NoUndef) &&
8554 Handle(I->getOperand(0)))
8555 return true;
8556 break;
8557 case Instruction::Switch:
8558 if (Handle(cast<SwitchInst>(I)->getCondition()))
8559 return true;
8560 break;
8561 case Instruction::CondBr:
8562 if (Handle(cast<CondBrInst>(I)->getCondition()))
8563 return true;
8564 break;
8565 default:
8566 break;
8567 }
8568
8569 return false;
8570}
8571
8572/// Enumerates all operands of \p I that are guaranteed to not be poison.
8573template <typename CallableT>
8575 const CallableT &Handle) {
8576 if (handleGuaranteedWellDefinedOps(I, Handle))
8577 return true;
8578 switch (I->getOpcode()) {
8579 // Divisors of these operations are allowed to be partially undef.
8580 case Instruction::UDiv:
8581 case Instruction::SDiv:
8582 case Instruction::URem:
8583 case Instruction::SRem:
8584 return Handle(I->getOperand(1));
8585 default:
8586 return false;
8587 }
8588}
8589
8591 const SmallPtrSetImpl<const Value *> &KnownPoison) {
8593 I, [&](const Value *V) { return KnownPoison.count(V); });
8594}
8595
8597 bool PoisonOnly) {
8598 // We currently only look for uses of values within the same basic
8599 // block, as that makes it easier to guarantee that the uses will be
8600 // executed given that Inst is executed.
8601 //
8602 // FIXME: Expand this to consider uses beyond the same basic block. To do
8603 // this, look out for the distinction between post-dominance and strong
8604 // post-dominance.
8605 const BasicBlock *BB = nullptr;
8607 if (const auto *Inst = dyn_cast<Instruction>(V)) {
8608 BB = Inst->getParent();
8609 Begin = Inst->getIterator();
8610 Begin++;
8611 } else if (const auto *Arg = dyn_cast<Argument>(V)) {
8612 if (Arg->getParent()->isDeclaration())
8613 return false;
8614 BB = &Arg->getParent()->getEntryBlock();
8615 Begin = BB->begin();
8616 } else {
8617 return false;
8618 }
8619
8620 // Limit number of instructions we look at, to avoid scanning through large
8621 // blocks. The current limit is chosen arbitrarily.
8622 unsigned ScanLimit = 32;
8623 BasicBlock::const_iterator End = BB->end();
8624
8625 if (!PoisonOnly) {
8626 // Since undef does not propagate eagerly, be conservative & just check
8627 // whether a value is directly passed to an instruction that must take
8628 // well-defined operands.
8629
8630 for (const auto &I : make_range(Begin, End)) {
8631 if (--ScanLimit == 0)
8632 break;
8633
8634 if (handleGuaranteedWellDefinedOps(&I, [V](const Value *WellDefinedOp) {
8635 return WellDefinedOp == V;
8636 }))
8637 return true;
8638
8640 break;
8641 }
8642 return false;
8643 }
8644
8645 // Set of instructions that we have proved will yield poison if Inst
8646 // does.
8647 SmallPtrSet<const Value *, 16> YieldsPoison;
8649
8650 YieldsPoison.insert(V);
8651 Visited.insert(BB);
8652
8653 while (true) {
8654 for (const auto &I : make_range(Begin, End)) {
8655 if (--ScanLimit == 0)
8656 return false;
8657 if (mustTriggerUB(&I, YieldsPoison))
8658 return true;
8660 return false;
8661
8662 // If an operand is poison and propagates it, mark I as yielding poison.
8663 for (const Use &Op : I.operands()) {
8664 if (YieldsPoison.count(Op) && propagatesPoison(Op)) {
8665 YieldsPoison.insert(&I);
8666 break;
8667 }
8668 }
8669
8670 // Special handling for select, which returns poison if its operand 0 is
8671 // poison (handled in the loop above) *or* if both its true/false operands
8672 // are poison (handled here).
8673 if (I.getOpcode() == Instruction::Select &&
8674 YieldsPoison.count(I.getOperand(1)) &&
8675 YieldsPoison.count(I.getOperand(2))) {
8676 YieldsPoison.insert(&I);
8677 }
8678 }
8679
8680 BB = BB->getSingleSuccessor();
8681 if (!BB || !Visited.insert(BB).second)
8682 break;
8683
8684 Begin = BB->getFirstNonPHIIt();
8685 End = BB->end();
8686 }
8687 return false;
8688}
8689
8691 return ::programUndefinedIfUndefOrPoison(Inst, false);
8692}
8693
8695 return ::programUndefinedIfUndefOrPoison(Inst, true);
8696}
8697
8698static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
8699 if (FMF.noNaNs())
8700 return true;
8701
8702 if (auto *C = dyn_cast<ConstantFP>(V))
8703 return !C->isNaN();
8704
8705 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8706 if (!C->getElementType()->isFloatingPointTy())
8707 return false;
8708 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8709 if (C->getElementAsAPFloat(I).isNaN())
8710 return false;
8711 }
8712 return true;
8713 }
8714
8716 return true;
8717
8718 return false;
8719}
8720
8721static bool isKnownNonZero(const Value *V) {
8722 if (auto *C = dyn_cast<ConstantFP>(V))
8723 return !C->isZero();
8724
8725 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8726 if (!C->getElementType()->isFloatingPointTy())
8727 return false;
8728 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8729 if (C->getElementAsAPFloat(I).isZero())
8730 return false;
8731 }
8732 return true;
8733 }
8734
8735 return false;
8736}
8737
8738/// Match clamp pattern for float types without care about NaNs or signed zeros.
8739/// Given non-min/max outer cmp/select from the clamp pattern this
8740/// function recognizes if it can be substitued by a "canonical" min/max
8741/// pattern.
8743 Value *CmpLHS, Value *CmpRHS,
8744 Value *TrueVal, Value *FalseVal,
8745 Value *&LHS, Value *&RHS) {
8746 // Try to match
8747 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
8748 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
8749 // and return description of the outer Max/Min.
8750
8751 // First, check if select has inverse order:
8752 if (CmpRHS == FalseVal) {
8753 std::swap(TrueVal, FalseVal);
8754 Pred = CmpInst::getInversePredicate(Pred);
8755 }
8756
8757 // Assume success now. If there's no match, callers should not use these anyway.
8758 LHS = TrueVal;
8759 RHS = FalseVal;
8760
8761 const APFloat *FC1;
8762 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
8763 return {SPF_UNKNOWN, SPNB_NA, false};
8764
8765 const APFloat *FC2;
8766 switch (Pred) {
8767 case CmpInst::FCMP_OLT:
8768 case CmpInst::FCMP_OLE:
8769 case CmpInst::FCMP_ULT:
8770 case CmpInst::FCMP_ULE:
8771 if (match(FalseVal, m_OrdOrUnordFMin(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8772 *FC1 < *FC2)
8773 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8774 if (match(FalseVal, m_FMinNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8775 *FC1 < *FC2)
8776 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8777 break;
8778 case CmpInst::FCMP_OGT:
8779 case CmpInst::FCMP_OGE:
8780 case CmpInst::FCMP_UGT:
8781 case CmpInst::FCMP_UGE:
8782 if (match(FalseVal, m_OrdOrUnordFMax(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8783 *FC1 > *FC2)
8784 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8785 if (match(FalseVal, m_FMaxNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8786 *FC1 > *FC2)
8787 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8788 break;
8789 default:
8790 break;
8791 }
8792
8793 return {SPF_UNKNOWN, SPNB_NA, false};
8794}
8795
8796/// Recognize variations of:
8797/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
8799 Value *CmpLHS, Value *CmpRHS,
8800 Value *TrueVal, Value *FalseVal) {
8801 // Swap the select operands and predicate to match the patterns below.
8802 if (CmpRHS != TrueVal) {
8803 Pred = ICmpInst::getSwappedPredicate(Pred);
8804 std::swap(TrueVal, FalseVal);
8805 }
8806 const APInt *C1;
8807 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
8808 const APInt *C2;
8809 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
8810 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8811 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
8812 return {SPF_SMAX, SPNB_NA, false};
8813
8814 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
8815 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8816 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
8817 return {SPF_SMIN, SPNB_NA, false};
8818
8819 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
8820 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8821 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
8822 return {SPF_UMAX, SPNB_NA, false};
8823
8824 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
8825 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8826 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
8827 return {SPF_UMIN, SPNB_NA, false};
8828 }
8829 return {SPF_UNKNOWN, SPNB_NA, false};
8830}
8831
8832/// Recognize variations of:
8833/// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
8835 Value *CmpLHS, Value *CmpRHS,
8836 Value *TVal, Value *FVal,
8837 unsigned Depth) {
8838 // TODO: Allow FP min/max with nnan/nsz.
8839 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
8840
8841 Value *A = nullptr, *B = nullptr;
8842 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
8843 if (!SelectPatternResult::isMinOrMax(L.Flavor))
8844 return {SPF_UNKNOWN, SPNB_NA, false};
8845
8846 Value *C = nullptr, *D = nullptr;
8847 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
8848 if (L.Flavor != R.Flavor)
8849 return {SPF_UNKNOWN, SPNB_NA, false};
8850
8851 // We have something like: x Pred y ? min(a, b) : min(c, d).
8852 // Try to match the compare to the min/max operations of the select operands.
8853 // First, make sure we have the right compare predicate.
8854 switch (L.Flavor) {
8855 case SPF_SMIN:
8856 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
8857 Pred = ICmpInst::getSwappedPredicate(Pred);
8858 std::swap(CmpLHS, CmpRHS);
8859 }
8860 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
8861 break;
8862 return {SPF_UNKNOWN, SPNB_NA, false};
8863 case SPF_SMAX:
8864 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
8865 Pred = ICmpInst::getSwappedPredicate(Pred);
8866 std::swap(CmpLHS, CmpRHS);
8867 }
8868 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
8869 break;
8870 return {SPF_UNKNOWN, SPNB_NA, false};
8871 case SPF_UMIN:
8872 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
8873 Pred = ICmpInst::getSwappedPredicate(Pred);
8874 std::swap(CmpLHS, CmpRHS);
8875 }
8876 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
8877 break;
8878 return {SPF_UNKNOWN, SPNB_NA, false};
8879 case SPF_UMAX:
8880 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
8881 Pred = ICmpInst::getSwappedPredicate(Pred);
8882 std::swap(CmpLHS, CmpRHS);
8883 }
8884 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
8885 break;
8886 return {SPF_UNKNOWN, SPNB_NA, false};
8887 default:
8888 return {SPF_UNKNOWN, SPNB_NA, false};
8889 }
8890
8891 // If there is a common operand in the already matched min/max and the other
8892 // min/max operands match the compare operands (either directly or inverted),
8893 // then this is min/max of the same flavor.
8894
8895 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8896 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8897 if (D == B) {
8898 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8899 match(A, m_Not(m_Specific(CmpRHS)))))
8900 return {L.Flavor, SPNB_NA, false};
8901 }
8902 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8903 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8904 if (C == B) {
8905 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8906 match(A, m_Not(m_Specific(CmpRHS)))))
8907 return {L.Flavor, SPNB_NA, false};
8908 }
8909 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8910 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8911 if (D == A) {
8912 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8913 match(B, m_Not(m_Specific(CmpRHS)))))
8914 return {L.Flavor, SPNB_NA, false};
8915 }
8916 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8917 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8918 if (C == A) {
8919 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8920 match(B, m_Not(m_Specific(CmpRHS)))))
8921 return {L.Flavor, SPNB_NA, false};
8922 }
8923
8924 return {SPF_UNKNOWN, SPNB_NA, false};
8925}
8926
8927/// If the input value is the result of a 'not' op, constant integer, or vector
8928/// splat of a constant integer, return the bitwise-not source value.
8929/// TODO: This could be extended to handle non-splat vector integer constants.
8931 Value *NotV;
8932 if (match(V, m_Not(m_Value(NotV))))
8933 return NotV;
8934
8935 const APInt *C;
8936 if (match(V, m_APInt(C)))
8937 return ConstantInt::get(V->getType(), ~(*C));
8938
8939 return nullptr;
8940}
8941
8942/// Match non-obvious integer minimum and maximum sequences.
8944 Value *CmpLHS, Value *CmpRHS,
8945 Value *TrueVal, Value *FalseVal,
8946 Value *&LHS, Value *&RHS,
8947 unsigned Depth) {
8948 // Assume success. If there's no match, callers should not use these anyway.
8949 LHS = TrueVal;
8950 RHS = FalseVal;
8951
8952 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
8954 return SPR;
8955
8956 SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
8958 return SPR;
8959
8960 // Look through 'not' ops to find disguised min/max.
8961 // (X > Y) ? ~X : ~Y ==> (~X < ~Y) ? ~X : ~Y ==> MIN(~X, ~Y)
8962 // (X < Y) ? ~X : ~Y ==> (~X > ~Y) ? ~X : ~Y ==> MAX(~X, ~Y)
8963 if (CmpLHS == getNotValue(TrueVal) && CmpRHS == getNotValue(FalseVal)) {
8964 switch (Pred) {
8965 case CmpInst::ICMP_SGT: return {SPF_SMIN, SPNB_NA, false};
8966 case CmpInst::ICMP_SLT: return {SPF_SMAX, SPNB_NA, false};
8967 case CmpInst::ICMP_UGT: return {SPF_UMIN, SPNB_NA, false};
8968 case CmpInst::ICMP_ULT: return {SPF_UMAX, SPNB_NA, false};
8969 default: break;
8970 }
8971 }
8972
8973 // (X > Y) ? ~Y : ~X ==> (~X < ~Y) ? ~Y : ~X ==> MAX(~Y, ~X)
8974 // (X < Y) ? ~Y : ~X ==> (~X > ~Y) ? ~Y : ~X ==> MIN(~Y, ~X)
8975 if (CmpLHS == getNotValue(FalseVal) && CmpRHS == getNotValue(TrueVal)) {
8976 switch (Pred) {
8977 case CmpInst::ICMP_SGT: return {SPF_SMAX, SPNB_NA, false};
8978 case CmpInst::ICMP_SLT: return {SPF_SMIN, SPNB_NA, false};
8979 case CmpInst::ICMP_UGT: return {SPF_UMAX, SPNB_NA, false};
8980 case CmpInst::ICMP_ULT: return {SPF_UMIN, SPNB_NA, false};
8981 default: break;
8982 }
8983 }
8984
8985 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
8986 return {SPF_UNKNOWN, SPNB_NA, false};
8987
8988 const APInt *C1;
8989 if (!match(CmpRHS, m_APInt(C1)))
8990 return {SPF_UNKNOWN, SPNB_NA, false};
8991
8992 // An unsigned min/max can be written with a signed compare.
8993 const APInt *C2;
8994 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
8995 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
8996 // Is the sign bit set?
8997 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
8998 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
8999 if (Pred == CmpInst::ICMP_SLT && C1->isZero() && C2->isMaxSignedValue())
9000 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
9001
9002 // Is the sign bit clear?
9003 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
9004 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
9005 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnes() && C2->isMinSignedValue())
9006 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
9007 }
9008
9009 return {SPF_UNKNOWN, SPNB_NA, false};
9010}
9011
9012bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW,
9013 bool AllowPoison) {
9014 assert(X && Y && "Invalid operand");
9015
9016 auto IsNegationOf = [&](const Value *X, const Value *Y) {
9017 if (!match(X, m_Neg(m_Specific(Y))))
9018 return false;
9019
9020 auto *BO = cast<BinaryOperator>(X);
9021 if (NeedNSW && !BO->hasNoSignedWrap())
9022 return false;
9023
9024 auto *Zero = cast<Constant>(BO->getOperand(0));
9025 if (!AllowPoison && !Zero->isNullValue())
9026 return false;
9027
9028 return true;
9029 };
9030
9031 // X = -Y or Y = -X
9032 if (IsNegationOf(X, Y) || IsNegationOf(Y, X))
9033 return true;
9034
9035 // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
9036 Value *A, *B;
9037 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
9038 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
9039 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
9041}
9042
9043bool llvm::isKnownInversion(const Value *X, const Value *Y) {
9044 // Handle X = icmp pred A, B, Y = icmp pred A, C.
9045 Value *A, *B, *C;
9046 CmpPredicate Pred1, Pred2;
9047 if (!match(X, m_ICmp(Pred1, m_Value(A), m_Value(B))) ||
9048 !match(Y, m_c_ICmp(Pred2, m_Specific(A), m_Value(C))))
9049 return false;
9050
9051 // They must both have samesign flag or not.
9052 if (Pred1.hasSameSign() != Pred2.hasSameSign())
9053 return false;
9054
9055 if (B == C)
9056 return Pred1 == ICmpInst::getInversePredicate(Pred2);
9057
9058 // Try to infer the relationship from constant ranges.
9059 const APInt *RHSC1, *RHSC2;
9060 if (!match(B, m_APInt(RHSC1)) || !match(C, m_APInt(RHSC2)))
9061 return false;
9062
9063 // Sign bits of two RHSCs should match.
9064 if (Pred1.hasSameSign() && RHSC1->isNonNegative() != RHSC2->isNonNegative())
9065 return false;
9066
9067 const auto CR1 = ConstantRange::makeExactICmpRegion(Pred1, *RHSC1);
9068 const auto CR2 = ConstantRange::makeExactICmpRegion(Pred2, *RHSC2);
9069
9070 return CR1.inverse() == CR2;
9071}
9072
9074 SelectPatternNaNBehavior NaNBehavior,
9075 bool Ordered) {
9076 switch (Pred) {
9077 default:
9078 return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
9079 case ICmpInst::ICMP_UGT:
9080 case ICmpInst::ICMP_UGE:
9081 return {SPF_UMAX, SPNB_NA, false};
9082 case ICmpInst::ICMP_SGT:
9083 case ICmpInst::ICMP_SGE:
9084 return {SPF_SMAX, SPNB_NA, false};
9085 case ICmpInst::ICMP_ULT:
9086 case ICmpInst::ICMP_ULE:
9087 return {SPF_UMIN, SPNB_NA, false};
9088 case ICmpInst::ICMP_SLT:
9089 case ICmpInst::ICMP_SLE:
9090 return {SPF_SMIN, SPNB_NA, false};
9091 case FCmpInst::FCMP_UGT:
9092 case FCmpInst::FCMP_UGE:
9093 case FCmpInst::FCMP_OGT:
9094 case FCmpInst::FCMP_OGE:
9095 return {SPF_FMAXNUM, NaNBehavior, Ordered};
9096 case FCmpInst::FCMP_ULT:
9097 case FCmpInst::FCMP_ULE:
9098 case FCmpInst::FCMP_OLT:
9099 case FCmpInst::FCMP_OLE:
9100 return {SPF_FMINNUM, NaNBehavior, Ordered};
9101 }
9102}
9103
9104std::optional<std::pair<CmpPredicate, Constant *>>
9107 "Only for relational integer predicates.");
9108 if (isa<UndefValue>(C))
9109 return std::nullopt;
9110
9111 Type *Type = C->getType();
9112 bool IsSigned = ICmpInst::isSigned(Pred);
9113
9115 bool WillIncrement =
9116 UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
9117
9118 // Check if the constant operand can be safely incremented/decremented
9119 // without overflowing/underflowing.
9120 auto ConstantIsOk = [Pred, WillIncrement, IsSigned](ConstantInt *C) {
9121 if (WillIncrement ? C->isMaxValue(IsSigned) : C->isMinValue(IsSigned))
9122 return false;
9123
9124 if (!Pred.hasSameSign())
9125 return true;
9126
9127 // Crossing the corresponding boundary in the other ordering changes the
9128 // sign bit, and therefore changes the poison domain.
9129 return WillIncrement ? !C->isMaxValue(!IsSigned)
9130 : !C->isMinValue(!IsSigned);
9131 };
9132
9133 Constant *SafeReplacementConstant = nullptr;
9134 if (auto *CI = dyn_cast<ConstantInt>(C)) {
9135 // Bail out if the constant can't be safely incremented/decremented.
9136 if (!ConstantIsOk(CI))
9137 return std::nullopt;
9138 } else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) {
9139 unsigned NumElts = FVTy->getNumElements();
9140 for (unsigned i = 0; i != NumElts; ++i) {
9141 Constant *Elt = C->getAggregateElement(i);
9142 if (!Elt)
9143 return std::nullopt;
9144
9145 if (isa<UndefValue>(Elt))
9146 continue;
9147
9148 // Bail out if we can't determine if this constant is min/max or if we
9149 // know that this constant is min/max.
9150 auto *CI = dyn_cast<ConstantInt>(Elt);
9151 if (!CI || !ConstantIsOk(CI))
9152 return std::nullopt;
9153
9154 if (!SafeReplacementConstant)
9155 SafeReplacementConstant = CI;
9156 }
9157 } else if (isa<VectorType>(C->getType())) {
9158 // Handle scalable splat
9159 Value *SplatC = C->getSplatValue();
9160 auto *CI = dyn_cast_or_null<ConstantInt>(SplatC);
9161 // Bail out if the constant can't be safely incremented/decremented.
9162 if (!CI || !ConstantIsOk(CI))
9163 return std::nullopt;
9164 } else {
9165 // ConstantExpr?
9166 return std::nullopt;
9167 }
9168
9169 // It may not be safe to change a compare predicate in the presence of
9170 // undefined elements, so replace those elements with the first safe constant
9171 // that we found.
9172 // TODO: in case of poison, it is safe; let's replace undefs only.
9173 if (C->containsUndefOrPoisonElement()) {
9174 assert(SafeReplacementConstant && "Replacement constant not set");
9175 C = Constant::replaceUndefsWith(C, SafeReplacementConstant);
9176 }
9177
9179 Pred.hasSameSign());
9180
9181 // Increment or decrement the constant.
9182 Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
9183 Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
9184
9185 return std::make_pair(NewPred, NewC);
9186}
9187
9189 FastMathFlags FMF,
9190 Value *CmpLHS, Value *CmpRHS,
9191 Value *TrueVal, Value *FalseVal,
9192 Value *&LHS, Value *&RHS,
9193 unsigned Depth) {
9194 if (CmpInst::isFPPredicate(Pred)) {
9195 // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
9196 // 0.0 operand, set the compare's 0.0 operands to that same value for the
9197 // purpose of identifying min/max. Disregard vector constants with undefined
9198 // elements because those can not be back-propagated for analysis.
9199 Value *OutputZeroVal = nullptr;
9200 if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
9201 !cast<Constant>(TrueVal)->containsUndefOrPoisonElement())
9202 OutputZeroVal = TrueVal;
9203 else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
9204 !cast<Constant>(FalseVal)->containsUndefOrPoisonElement())
9205 OutputZeroVal = FalseVal;
9206
9207 if (OutputZeroVal) {
9208 if (match(CmpLHS, m_AnyZeroFP()) && CmpLHS != OutputZeroVal)
9209 CmpLHS = OutputZeroVal;
9210 if (match(CmpRHS, m_AnyZeroFP()) && CmpRHS != OutputZeroVal)
9211 CmpRHS = OutputZeroVal;
9212 }
9213 }
9214
9215 LHS = CmpLHS;
9216 RHS = CmpRHS;
9217
9218 // Signed zero may return inconsistent results between implementations.
9219 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
9220 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
9221 // Therefore, we behave conservatively and only proceed if at least one of the
9222 // operands is known to not be zero or if we don't care about signed zero.
9223 if (CmpInst::isFPPredicate(Pred)) {
9224 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9225 !isKnownNonZero(CmpRHS))
9226 return {SPF_UNKNOWN, SPNB_NA, false};
9227 }
9228
9229 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
9230 bool Ordered = false;
9231
9232 // When given one NaN and one non-NaN input:
9233 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
9234 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
9235 // ordered comparison fails), which could be NaN or non-NaN.
9236 // so here we discover exactly what NaN behavior is required/accepted.
9237 if (CmpInst::isFPPredicate(Pred)) {
9238 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
9239 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
9240
9241 if (LHSSafe && RHSSafe) {
9242 // Both operands are known non-NaN.
9243 NaNBehavior = SPNB_RETURNS_ANY;
9244 Ordered = CmpInst::isOrdered(Pred);
9245 } else if (CmpInst::isOrdered(Pred)) {
9246 // An ordered comparison will return false when given a NaN, so it
9247 // returns the RHS.
9248 Ordered = true;
9249 if (LHSSafe)
9250 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
9251 NaNBehavior = SPNB_RETURNS_NAN;
9252 else if (RHSSafe)
9253 NaNBehavior = SPNB_RETURNS_OTHER;
9254 else
9255 // Completely unsafe.
9256 return {SPF_UNKNOWN, SPNB_NA, false};
9257 } else {
9258 Ordered = false;
9259 // An unordered comparison will return true when given a NaN, so it
9260 // returns the LHS.
9261 if (LHSSafe)
9262 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
9263 NaNBehavior = SPNB_RETURNS_OTHER;
9264 else if (RHSSafe)
9265 NaNBehavior = SPNB_RETURNS_NAN;
9266 else
9267 // Completely unsafe.
9268 return {SPF_UNKNOWN, SPNB_NA, false};
9269 }
9270 }
9271
9272 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
9273 std::swap(CmpLHS, CmpRHS);
9274 Pred = CmpInst::getSwappedPredicate(Pred);
9275 if (NaNBehavior == SPNB_RETURNS_NAN)
9276 NaNBehavior = SPNB_RETURNS_OTHER;
9277 else if (NaNBehavior == SPNB_RETURNS_OTHER)
9278 NaNBehavior = SPNB_RETURNS_NAN;
9279 Ordered = !Ordered;
9280 }
9281
9282 // ([if]cmp X, Y) ? X : Y
9283 if (TrueVal == CmpLHS && FalseVal == CmpRHS)
9284 return getSelectPattern(Pred, NaNBehavior, Ordered);
9285
9286 if (isKnownNegation(TrueVal, FalseVal)) {
9287 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
9288 // match against either LHS or sign-preserving operations on LHS, like
9289 // sext(LHS), or binary ops that do not wrap in signed sense.
9290 auto CmpLHSOrSExt =
9291 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
9292 auto MaybeSExtOrMulCmpLHS =
9293 m_CombineOr(CmpLHSOrSExt, m_NSWMul(CmpLHSOrSExt, m_StrictlyPositive()),
9294 m_NSWShl(CmpLHSOrSExt, m_Value()));
9295 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
9296 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
9297 if (match(TrueVal, MaybeSExtOrMulCmpLHS)) {
9298 // Set the return values. If the compare uses the negated value (-X >s 0),
9299 // swap the return values because the negated value is always 'RHS'.
9300 LHS = TrueVal;
9301 RHS = FalseVal;
9302 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
9303 std::swap(LHS, RHS);
9304
9305 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
9306 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
9307 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9308 return {SPF_ABS, SPNB_NA, false};
9309
9310 // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
9311 if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
9312 return {SPF_ABS, SPNB_NA, false};
9313
9314 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
9315 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
9316 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9317 return {SPF_NABS, SPNB_NA, false};
9318 } else if (match(FalseVal, MaybeSExtOrMulCmpLHS)) {
9319 // Set the return values. If the compare uses the negated value (-X >s 0),
9320 // swap the return values because the negated value is always 'RHS'.
9321 LHS = FalseVal;
9322 RHS = TrueVal;
9323 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
9324 std::swap(LHS, RHS);
9325
9326 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
9327 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
9328 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9329 return {SPF_NABS, SPNB_NA, false};
9330
9331 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
9332 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
9333 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9334 return {SPF_ABS, SPNB_NA, false};
9335 }
9336 }
9337
9338 if (CmpInst::isIntPredicate(Pred))
9339 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
9340
9341 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
9342 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
9343 // semantics than minNum. Be conservative in such case.
9344 if (NaNBehavior != SPNB_RETURNS_ANY ||
9345 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9346 !isKnownNonZero(CmpRHS)))
9347 return {SPF_UNKNOWN, SPNB_NA, false};
9348
9349 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
9350}
9351
9353 Instruction::CastOps *CastOp) {
9354 const DataLayout &DL = CmpI->getDataLayout();
9355
9356 Constant *CastedTo = nullptr;
9357 switch (*CastOp) {
9358 case Instruction::ZExt:
9359 if (CmpI->isUnsigned())
9360 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
9361 break;
9362 case Instruction::SExt:
9363 if (CmpI->isSigned())
9364 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
9365 break;
9366 case Instruction::Trunc:
9367 Constant *CmpConst;
9368 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
9369 CmpConst->getType() == SrcTy) {
9370 // Here we have the following case:
9371 //
9372 // %cond = cmp iN %x, CmpConst
9373 // %tr = trunc iN %x to iK
9374 // %narrowsel = select i1 %cond, iK %t, iK C
9375 //
9376 // We can always move trunc after select operation:
9377 //
9378 // %cond = cmp iN %x, CmpConst
9379 // %widesel = select i1 %cond, iN %x, iN CmpConst
9380 // %tr = trunc iN %widesel to iK
9381 //
9382 // Note that C could be extended in any way because we don't care about
9383 // upper bits after truncation. It can't be abs pattern, because it would
9384 // look like:
9385 //
9386 // select i1 %cond, x, -x.
9387 //
9388 // So only min/max pattern could be matched. Such match requires widened C
9389 // == CmpConst. That is why set widened C = CmpConst, condition trunc
9390 // CmpConst == C is checked below.
9391 CastedTo = CmpConst;
9392 } else {
9393 unsigned ExtOp = CmpI->isSigned() ? Instruction::SExt : Instruction::ZExt;
9394 CastedTo = ConstantFoldCastOperand(ExtOp, C, SrcTy, DL);
9395 }
9396 break;
9397 case Instruction::FPTrunc:
9398 CastedTo = ConstantFoldCastOperand(Instruction::FPExt, C, SrcTy, DL);
9399 break;
9400 case Instruction::FPExt:
9401 CastedTo = ConstantFoldCastOperand(Instruction::FPTrunc, C, SrcTy, DL);
9402 break;
9403 case Instruction::FPToUI:
9404 CastedTo = ConstantFoldCastOperand(Instruction::UIToFP, C, SrcTy, DL);
9405 break;
9406 case Instruction::FPToSI:
9407 CastedTo = ConstantFoldCastOperand(Instruction::SIToFP, C, SrcTy, DL);
9408 break;
9409 case Instruction::UIToFP:
9410 CastedTo = ConstantFoldCastOperand(Instruction::FPToUI, C, SrcTy, DL);
9411 break;
9412 case Instruction::SIToFP:
9413 CastedTo = ConstantFoldCastOperand(Instruction::FPToSI, C, SrcTy, DL);
9414 break;
9415 default:
9416 break;
9417 }
9418
9419 if (!CastedTo)
9420 return nullptr;
9421
9422 // Make sure the cast doesn't lose any information.
9423 Constant *CastedBack =
9424 ConstantFoldCastOperand(*CastOp, CastedTo, C->getType(), DL);
9425 if (CastedBack && CastedBack != C)
9426 return nullptr;
9427
9428 return CastedTo;
9429}
9430
9431/// Helps to match a select pattern in case of a type mismatch.
9432///
9433/// The function processes the case when type of true and false values of a
9434/// select instruction differs from type of the cmp instruction operands because
9435/// of a cast instruction. The function checks if it is legal to move the cast
9436/// operation after "select". If yes, it returns the new second value of
9437/// "select" (with the assumption that cast is moved):
9438/// 1. As operand of cast instruction when both values of "select" are same cast
9439/// instructions.
9440/// 2. As restored constant (by applying reverse cast operation) when the first
9441/// value of the "select" is a cast operation and the second value is a
9442/// constant. It is implemented in lookThroughCastConst().
9443/// 3. As one operand is cast instruction and the other is not. The operands in
9444/// sel(cmp) are in different type integer.
9445/// NOTE: We return only the new second value because the first value could be
9446/// accessed as operand of cast instruction.
9448 Instruction::CastOps *CastOp) {
9449 auto *Cast1 = dyn_cast<CastInst>(V1);
9450 if (!Cast1)
9451 return nullptr;
9452
9453 *CastOp = Cast1->getOpcode();
9454 Type *SrcTy = Cast1->getSrcTy();
9455 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
9456 // If V1 and V2 are both the same cast from the same type, look through V1.
9457 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
9458 return Cast2->getOperand(0);
9459 return nullptr;
9460 }
9461
9462 auto *C = dyn_cast<Constant>(V2);
9463 if (C)
9464 return lookThroughCastConst(CmpI, SrcTy, C, CastOp);
9465
9466 Value *CastedTo = nullptr;
9467 if (*CastOp == Instruction::Trunc) {
9468 if (match(CmpI->getOperand(1), m_ZExtOrSExt(m_Specific(V2)))) {
9469 // Here we have the following case:
9470 // %y_ext = sext iK %y to iN
9471 // %cond = cmp iN %x, %y_ext
9472 // %tr = trunc iN %x to iK
9473 // %narrowsel = select i1 %cond, iK %tr, iK %y
9474 //
9475 // We can always move trunc after select operation:
9476 // %y_ext = sext iK %y to iN
9477 // %cond = cmp iN %x, %y_ext
9478 // %widesel = select i1 %cond, iN %x, iN %y_ext
9479 // %tr = trunc iN %widesel to iK
9480 assert(V2->getType() == Cast1->getType() &&
9481 "V2 and Cast1 should be the same type.");
9482 CastedTo = CmpI->getOperand(1);
9483 }
9484 }
9485
9486 return CastedTo;
9487}
9489 Instruction::CastOps *CastOp,
9490 unsigned Depth) {
9492 return {SPF_UNKNOWN, SPNB_NA, false};
9493
9495 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
9496
9497 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
9498 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
9499
9500 Value *TrueVal = SI->getTrueValue();
9501 Value *FalseVal = SI->getFalseValue();
9502
9503 return llvm::matchDecomposedSelectPattern(CmpI, TrueVal, FalseVal, LHS, RHS,
9504 SI->getFastMathFlagsOrNone(),
9505 CastOp, Depth);
9506}
9507
9509 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
9510 FastMathFlags FMF, Instruction::CastOps *CastOp, unsigned Depth) {
9511 CmpInst::Predicate Pred = CmpI->getPredicate();
9512 Value *CmpLHS = CmpI->getOperand(0);
9513 Value *CmpRHS = CmpI->getOperand(1);
9514 if (isa<FPMathOperator>(CmpI) && CmpI->hasNoNaNs())
9515 FMF.setNoNaNs();
9516
9517 // Bail out early.
9518 if (CmpI->isEquality())
9519 return {SPF_UNKNOWN, SPNB_NA, false};
9520
9521 // Deal with type mismatches.
9522 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
9523 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
9524 // If this is a potential fmin/fmax with a cast to integer, then ignore
9525 // -0.0 because there is no corresponding integer value.
9526 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9527 FMF.setNoSignedZeros();
9528 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9529 cast<CastInst>(TrueVal)->getOperand(0), C,
9530 LHS, RHS, Depth);
9531 }
9532 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
9533 // If this is a potential fmin/fmax with a cast to integer, then ignore
9534 // -0.0 because there is no corresponding integer value.
9535 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9536 FMF.setNoSignedZeros();
9537 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9538 C, cast<CastInst>(FalseVal)->getOperand(0),
9539 LHS, RHS, Depth);
9540 }
9541 }
9542 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
9543 LHS, RHS, Depth);
9544}
9545
9547 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
9548 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
9549 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
9550 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
9551 if (SPF == SPF_FMINNUM)
9552 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
9553 if (SPF == SPF_FMAXNUM)
9554 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
9555 llvm_unreachable("unhandled!");
9556}
9557
9559 switch (SPF) {
9561 return Intrinsic::umin;
9563 return Intrinsic::umax;
9565 return Intrinsic::smin;
9567 return Intrinsic::smax;
9568 default:
9569 llvm_unreachable("Unexpected SPF");
9570 }
9571}
9572
9574 if (SPF == SPF_SMIN) return SPF_SMAX;
9575 if (SPF == SPF_UMIN) return SPF_UMAX;
9576 if (SPF == SPF_SMAX) return SPF_SMIN;
9577 if (SPF == SPF_UMAX) return SPF_UMIN;
9578 llvm_unreachable("unhandled!");
9579}
9580
9582 switch (MinMaxID) {
9583 case Intrinsic::smax: return Intrinsic::smin;
9584 case Intrinsic::smin: return Intrinsic::smax;
9585 case Intrinsic::umax: return Intrinsic::umin;
9586 case Intrinsic::umin: return Intrinsic::umax;
9587 // Please note that next four intrinsics may produce the same result for
9588 // original and inverted case even if X != Y due to NaN is handled specially.
9589 case Intrinsic::maximum: return Intrinsic::minimum;
9590 case Intrinsic::minimum: return Intrinsic::maximum;
9591 case Intrinsic::maxnum: return Intrinsic::minnum;
9592 case Intrinsic::minnum: return Intrinsic::maxnum;
9593 case Intrinsic::maximumnum:
9594 return Intrinsic::minimumnum;
9595 case Intrinsic::minimumnum:
9596 return Intrinsic::maximumnum;
9597 default: llvm_unreachable("Unexpected intrinsic");
9598 }
9599}
9600
9602 switch (SPF) {
9605 case SPF_UMAX: return APInt::getMaxValue(BitWidth);
9606 case SPF_UMIN: return APInt::getMinValue(BitWidth);
9607 default: llvm_unreachable("Unexpected flavor");
9608 }
9609}
9610
9611std::pair<Intrinsic::ID, bool>
9613 // Check if VL contains select instructions that can be folded into a min/max
9614 // vector intrinsic and return the intrinsic if it is possible.
9615 // TODO: Support floating point min/max.
9616 bool AllCmpSingleUse = true;
9617 SelectPatternResult SelectPattern;
9618 SelectPattern.Flavor = SPF_UNKNOWN;
9619 if (all_of(VL, [&SelectPattern, &AllCmpSingleUse](Value *I) {
9620 Value *LHS, *RHS;
9621 auto CurrentPattern = matchSelectPattern(I, LHS, RHS);
9622 if (!SelectPatternResult::isMinOrMax(CurrentPattern.Flavor))
9623 return false;
9624 if (SelectPattern.Flavor != SPF_UNKNOWN &&
9625 SelectPattern.Flavor != CurrentPattern.Flavor)
9626 return false;
9627 SelectPattern = CurrentPattern;
9628 AllCmpSingleUse &=
9630 return true;
9631 })) {
9632 switch (SelectPattern.Flavor) {
9633 case SPF_SMIN:
9634 return {Intrinsic::smin, AllCmpSingleUse};
9635 case SPF_UMIN:
9636 return {Intrinsic::umin, AllCmpSingleUse};
9637 case SPF_SMAX:
9638 return {Intrinsic::smax, AllCmpSingleUse};
9639 case SPF_UMAX:
9640 return {Intrinsic::umax, AllCmpSingleUse};
9641 case SPF_FMAXNUM:
9642 return {Intrinsic::maxnum, AllCmpSingleUse};
9643 case SPF_FMINNUM:
9644 return {Intrinsic::minnum, AllCmpSingleUse};
9645 default:
9646 llvm_unreachable("unexpected select pattern flavor");
9647 }
9648 }
9649 return {Intrinsic::not_intrinsic, false};
9650}
9651
9652template <typename InstTy>
9653static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst,
9654 Value *&Init, Value *&OtherOp) {
9655 // Handle the case of a simple two-predecessor recurrence PHI.
9656 // There's a lot more that could theoretically be done here, but
9657 // this is sufficient to catch some interesting cases.
9658 // TODO: Expand list -- gep, uadd.sat etc.
9659 if (PN->getNumIncomingValues() != 2)
9660 return false;
9661
9662 for (unsigned I = 0; I != 2; ++I) {
9663 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9664 Operation && Operation->getNumOperands() >= 2) {
9665 Value *LHS = Operation->getOperand(0);
9666 Value *RHS = Operation->getOperand(1);
9667 if (LHS != PN && RHS != PN)
9668 continue;
9669
9670 Inst = Operation;
9671 Init = PN->getIncomingValue(!I);
9672 OtherOp = (LHS == PN) ? RHS : LHS;
9673 return true;
9674 }
9675 }
9676 return false;
9677}
9678
9679template <typename InstTy>
9680static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst,
9681 Value *&Init, Value *&OtherOp0,
9682 Value *&OtherOp1) {
9683 if (PN->getNumIncomingValues() != 2)
9684 return false;
9685
9686 for (unsigned I = 0; I != 2; ++I) {
9687 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9688 Operation && Operation->getNumOperands() >= 3) {
9689 Value *Op0 = Operation->getOperand(0);
9690 Value *Op1 = Operation->getOperand(1);
9691 Value *Op2 = Operation->getOperand(2);
9692
9693 if (Op0 != PN && Op1 != PN && Op2 != PN)
9694 continue;
9695
9696 Inst = Operation;
9697 Init = PN->getIncomingValue(!I);
9698 if (Op0 == PN) {
9699 OtherOp0 = Op1;
9700 OtherOp1 = Op2;
9701 } else if (Op1 == PN) {
9702 OtherOp0 = Op0;
9703 OtherOp1 = Op2;
9704 } else {
9705 OtherOp0 = Op0;
9706 OtherOp1 = Op1;
9707 }
9708 return true;
9709 }
9710 }
9711 return false;
9712}
9714 Value *&Start, Value *&Step) {
9715 // We try to match a recurrence of the form:
9716 // %iv = [Start, %entry], [%iv.next, %backedge]
9717 // %iv.next = binop %iv, Step
9718 // Or:
9719 // %iv = [Start, %entry], [%iv.next, %backedge]
9720 // %iv.next = binop Step, %iv
9721 return matchTwoInputRecurrence(P, BO, Start, Step);
9722}
9723
9725 Value *&Start, Value *&Step) {
9726 BinaryOperator *BO = nullptr;
9727 return match(I, m_c_BinOp(m_Phi(P), m_Value())) &&
9728 matchSimpleRecurrence(P, BO, Start, Step) && BO == I;
9729}
9730
9732 PHINode *&P, Value *&Init,
9733 Value *&OtherOp) {
9734 // Binary intrinsics only supported for now.
9735 if (I->arg_size() != 2 || I->getType() != I->getArgOperand(0)->getType() ||
9736 I->getType() != I->getArgOperand(1)->getType())
9737 return false;
9738
9739 IntrinsicInst *II = nullptr;
9740 P = dyn_cast<PHINode>(I->getArgOperand(0));
9741 if (!P)
9742 P = dyn_cast<PHINode>(I->getArgOperand(1));
9743
9744 return P && matchTwoInputRecurrence(P, II, Init, OtherOp) && II == I;
9745}
9746
9748 PHINode *&P, Value *&Init,
9749 Value *&OtherOp0,
9750 Value *&OtherOp1) {
9751 if (I->arg_size() != 3 || I->getType() != I->getArgOperand(0)->getType() ||
9752 I->getType() != I->getArgOperand(1)->getType() ||
9753 I->getType() != I->getArgOperand(2)->getType())
9754 return false;
9755 IntrinsicInst *II = nullptr;
9756 P = dyn_cast<PHINode>(I->getArgOperand(0));
9757 if (!P) {
9758 P = dyn_cast<PHINode>(I->getArgOperand(1));
9759 if (!P)
9760 P = dyn_cast<PHINode>(I->getArgOperand(2));
9761 }
9762 return P && matchThreeInputRecurrence(P, II, Init, OtherOp0, OtherOp1) &&
9763 II == I;
9764}
9765
9766/// Return true if "icmp Pred LHS RHS" is always true.
9768 const Value *RHS) {
9769 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
9770 return true;
9771
9772 switch (Pred) {
9773 default:
9774 return false;
9775
9776 case CmpInst::ICMP_SLE: {
9777 const APInt *C;
9778
9779 // LHS s<= LHS +_{nsw} C if C >= 0
9780 // LHS s<= LHS | C if C >= 0
9781 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))) ||
9783 return !C->isNegative();
9784
9785 // LHS s<= smax(LHS, V) for any V
9787 return true;
9788
9789 // smin(RHS, V) s<= RHS for any V
9791 return true;
9792
9793 // Match A to (X +_{nsw} CA) and B to (X +_{nsw} CB)
9794 const Value *X;
9795 const APInt *CLHS, *CRHS;
9796 if (match(LHS, m_NSWAddLike(m_Value(X), m_APInt(CLHS))) &&
9798 return CLHS->sle(*CRHS);
9799
9800 return false;
9801 }
9802
9803 case CmpInst::ICMP_ULE: {
9804 // LHS u<= LHS +_{nuw} V for any V
9805 if (match(RHS, m_c_Add(m_Specific(LHS), m_Value())) &&
9807 return true;
9808
9809 // LHS u<= LHS | V for any V
9810 if (match(RHS, m_c_Or(m_Specific(LHS), m_Value())))
9811 return true;
9812
9813 // LHS u<= umax(LHS, V) for any V
9815 return true;
9816
9817 // RHS >> V u<= RHS for any V
9818 if (match(LHS, m_LShr(m_Specific(RHS), m_Value())))
9819 return true;
9820
9821 // RHS u/ C_ugt_1 u<= RHS
9822 const APInt *C;
9823 if (match(LHS, m_UDiv(m_Specific(RHS), m_APInt(C))) && C->ugt(1))
9824 return true;
9825
9826 // RHS & V u<= RHS for any V
9828 return true;
9829
9830 // umin(RHS, V) u<= RHS for any V
9832 return true;
9833
9834 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
9835 const Value *X;
9836 const APInt *CLHS, *CRHS;
9837 if (match(LHS, m_NUWAddLike(m_Value(X), m_APInt(CLHS))) &&
9839 return CLHS->ule(*CRHS);
9840
9841 return false;
9842 }
9843 }
9844}
9845
9846/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
9847/// ALHS ARHS" is true. Otherwise, return std::nullopt.
9848static std::optional<bool>
9850 const Value *ARHS, const Value *BLHS, const Value *BRHS) {
9851 switch (Pred) {
9852 default:
9853 return std::nullopt;
9854
9855 case CmpInst::ICMP_SLT:
9856 case CmpInst::ICMP_SLE:
9857 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS) &&
9859 return true;
9860 return std::nullopt;
9861
9862 case CmpInst::ICMP_SGT:
9863 case CmpInst::ICMP_SGE:
9864 if (isTruePredicate(CmpInst::ICMP_SLE, ALHS, BLHS) &&
9866 return true;
9867 return std::nullopt;
9868
9869 case CmpInst::ICMP_ULT:
9870 case CmpInst::ICMP_ULE:
9871 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS) &&
9873 return true;
9874 return std::nullopt;
9875
9876 case CmpInst::ICMP_UGT:
9877 case CmpInst::ICMP_UGE:
9878 if (isTruePredicate(CmpInst::ICMP_ULE, ALHS, BLHS) &&
9880 return true;
9881 return std::nullopt;
9882 }
9883}
9884
9885/// Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
9886/// Return false if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is false.
9887/// Otherwise, return std::nullopt if we can't infer anything.
9888static std::optional<bool>
9890 CmpPredicate RPred, const ConstantRange &RCR) {
9891 auto CRImpliesPred = [&](ConstantRange CR,
9892 CmpInst::Predicate Pred) -> std::optional<bool> {
9893 // If all true values for lhs and true for rhs, lhs implies rhs
9894 if (CR.icmp(Pred, RCR))
9895 return true;
9896
9897 // If there is no overlap, lhs implies not rhs
9898 if (CR.icmp(CmpInst::getInversePredicate(Pred), RCR))
9899 return false;
9900
9901 return std::nullopt;
9902 };
9903 if (auto Res = CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9904 RPred))
9905 return Res;
9906 if (LPred.hasSameSign() ^ RPred.hasSameSign()) {
9908 : LPred.dropSameSign();
9910 : RPred.dropSameSign();
9911 return CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9912 RPred);
9913 }
9914 return std::nullopt;
9915}
9916
9917/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
9918/// is true. Return false if LHS implies RHS is false. Otherwise, return
9919/// std::nullopt if we can't infer anything.
9920static std::optional<bool>
9921isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1,
9922 CmpPredicate RPred, const Value *R0, const Value *R1,
9923 const DataLayout &DL, bool LHSIsTrue) {
9924 // The rest of the logic assumes the LHS condition is true. If that's not the
9925 // case, invert the predicate to make it so.
9926 if (!LHSIsTrue)
9927 LPred = ICmpInst::getInverseCmpPredicate(LPred);
9928
9929 // We can have non-canonical operands, so try to normalize any common operand
9930 // to L0/R0.
9931 if (L0 == R1) {
9932 std::swap(R0, R1);
9933 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9934 }
9935 if (R0 == L1) {
9936 std::swap(L0, L1);
9937 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9938 }
9939 if (L1 == R1) {
9940 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
9941 if (L0 != R0 || match(L0, m_ImmConstant())) {
9942 std::swap(L0, L1);
9943 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9944 std::swap(R0, R1);
9945 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9946 }
9947 }
9948
9949 // See if we can infer anything if operand-0 matches and we have at least one
9950 // constant.
9951 const APInt *Unused;
9952 if (L0 == R0 && (match(L1, m_APInt(Unused)) || match(R1, m_APInt(Unused)))) {
9953 // Potential TODO: We could also further use the constant range of L0/R0 to
9954 // further constraint the constant ranges. At the moment this leads to
9955 // several regressions related to not transforming `multi_use(A + C0) eq/ne
9956 // C1` (see discussion: D58633).
9957 SimplifyQuery SQ(DL);
9962
9963 // Even if L1/R1 are not both constant, we can still sometimes deduce
9964 // relationship from a single constant. For example X u> Y implies X != 0.
9965 if (auto R = isImpliedCondCommonOperandWithCR(LPred, LCR, RPred, RCR))
9966 return R;
9967 // If both L1/R1 were exact constant ranges and we didn't get anything
9968 // here, we won't be able to deduce this.
9969 if (match(L1, m_APInt(Unused)) && match(R1, m_APInt(Unused)))
9970 return std::nullopt;
9971 }
9972
9973 // Can we infer anything when the two compares have matching operands?
9974 if (L0 == R0 && L1 == R1)
9975 return ICmpInst::isImpliedByMatchingCmp(LPred, RPred);
9976
9977 // It only really makes sense in the context of signed comparison for "X - Y
9978 // must be positive if X >= Y and no overflow".
9979 // Take SGT as an example: L0:x > L1:y and C >= 0
9980 // ==> R0:(x -nsw y) < R1:(-C) is false
9981 CmpInst::Predicate SignedLPred = LPred.getPreferredSignedPredicate();
9982 if ((SignedLPred == ICmpInst::ICMP_SGT ||
9983 SignedLPred == ICmpInst::ICMP_SGE) &&
9984 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
9985 if (match(R1, m_NonPositive()) &&
9986 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == false)
9987 return false;
9988 }
9989
9990 // Take SLT as an example: L0:x < L1:y and C <= 0
9991 // ==> R0:(x -nsw y) < R1:(-C) is true
9992 if ((SignedLPred == ICmpInst::ICMP_SLT ||
9993 SignedLPred == ICmpInst::ICMP_SLE) &&
9994 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
9995 if (match(R1, m_NonNegative()) &&
9996 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == true)
9997 return true;
9998 }
9999
10000 // a - b == NonZero -> a != b
10001 // ptrtoint(a) - ptrtoint(b) == NonZero -> a != b
10002 const APInt *L1C;
10003 Value *A, *B;
10004 if (LPred == ICmpInst::ICMP_EQ && ICmpInst::isEquality(RPred) &&
10005 match(L1, m_APInt(L1C)) && !L1C->isZero() &&
10006 match(L0, m_Sub(m_Value(A), m_Value(B))) &&
10007 ((A == R0 && B == R1) || (A == R1 && B == R0) ||
10012 return RPred.dropSameSign() == ICmpInst::ICMP_NE;
10013 }
10014
10015 // L0 = R0 = L1 + R1, L0 >=u L1 implies R0 >=u R1, L0 <u L1 implies R0 <u R1
10016 if (L0 == R0 &&
10017 (LPred == ICmpInst::ICMP_ULT || LPred == ICmpInst::ICMP_UGE) &&
10018 (RPred == ICmpInst::ICMP_ULT || RPred == ICmpInst::ICMP_UGE) &&
10019 match(L0, m_c_Add(m_Specific(L1), m_Specific(R1))))
10020 return CmpPredicate::getMatching(LPred, RPred).has_value();
10021
10022 if (auto P = CmpPredicate::getMatching(LPred, RPred))
10023 return isImpliedCondOperands(*P, L0, L1, R0, R1);
10024
10025 // L0 u< C sets limits to L0's bits which may imply (L0 & Mask) pred RC
10026 // Example: L0 u< 13 => (L0 & 16) == 0
10027 const APInt *LC, *RC, *MaskC;
10028 if (match(L1, m_APInt(LC)) && match(R1, m_APInt(RC)) &&
10029 match(R0, m_And(m_Specific(L0), m_APInt(MaskC)))) {
10031 ConstantRange MaskedCRange = LCRange.binaryAnd(*MaskC);
10032 if (MaskedCRange.icmp(RPred, ConstantRange(*RC)))
10033 return true;
10034 if (MaskedCRange.icmp(ICmpInst::getInversePredicate(RPred),
10035 ConstantRange(*RC)))
10036 return false;
10037 }
10038
10039 return std::nullopt;
10040}
10041
10042/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
10043/// is true. Return false if LHS implies RHS is false. Otherwise, return
10044/// std::nullopt if we can't infer anything.
10045static std::optional<bool>
10047 FCmpInst::Predicate RPred, const Value *R0, const Value *R1,
10048 const DataLayout &DL, bool LHSIsTrue) {
10049 // The rest of the logic assumes the LHS condition is true. If that's not the
10050 // case, invert the predicate to make it so.
10051 if (!LHSIsTrue)
10052 LPred = FCmpInst::getInversePredicate(LPred);
10053
10054 // We can have non-canonical operands, so try to normalize any common operand
10055 // to L0/R0.
10056 if (L0 == R1) {
10057 std::swap(R0, R1);
10058 RPred = FCmpInst::getSwappedPredicate(RPred);
10059 }
10060 if (R0 == L1) {
10061 std::swap(L0, L1);
10062 LPred = FCmpInst::getSwappedPredicate(LPred);
10063 }
10064 if (L1 == R1) {
10065 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
10066 if (L0 != R0 || match(L0, m_ImmConstant())) {
10067 std::swap(L0, L1);
10068 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10069 std::swap(R0, R1);
10070 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10071 }
10072 }
10073
10074 // Can we infer anything when the two compares have matching operands?
10075 if (L0 == R0 && L1 == R1) {
10076 if ((LPred & RPred) == LPred)
10077 return true;
10078 if ((LPred & ~RPred) == LPred)
10079 return false;
10080 }
10081
10082 // See if we can infer anything if operand-0 matches and we have at least one
10083 // constant.
10084 const APFloat *L1C, *R1C;
10085 if (L0 == R0 && match(L1, m_APFloat(L1C)) && match(R1, m_APFloat(R1C))) {
10086 if (std::optional<ConstantFPRange> DomCR =
10088 if (std::optional<ConstantFPRange> ImpliedCR =
10090 if (ImpliedCR->contains(*DomCR))
10091 return true;
10092 }
10093 if (std::optional<ConstantFPRange> ImpliedCR =
10095 FCmpInst::getInversePredicate(RPred), *R1C)) {
10096 if (ImpliedCR->contains(*DomCR))
10097 return false;
10098 }
10099 }
10100 }
10101
10102 return std::nullopt;
10103}
10104
10105/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
10106/// false. Otherwise, return std::nullopt if we can't infer anything. We
10107/// expect the RHS to be an icmp and the LHS to be an 'and', 'or', or a 'select'
10108/// instruction.
10109static std::optional<bool>
10111 const Value *RHSOp0, const Value *RHSOp1,
10112 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10113 // The LHS must be an 'or', 'and', or a 'select' instruction.
10114 assert((LHS->getOpcode() == Instruction::And ||
10115 LHS->getOpcode() == Instruction::Or ||
10116 LHS->getOpcode() == Instruction::Select) &&
10117 "Expected LHS to be 'and', 'or', or 'select'.");
10118
10119 assert(Depth <= MaxAnalysisRecursionDepth && "Hit recursion limit");
10120
10121 // If the result of an 'or' is false, then we know both legs of the 'or' are
10122 // false. Similarly, if the result of an 'and' is true, then we know both
10123 // legs of the 'and' are true.
10124 const Value *ALHS, *ARHS;
10125 if ((!LHSIsTrue && match(LHS, m_LogicalOr(m_Value(ALHS), m_Value(ARHS)))) ||
10126 (LHSIsTrue && match(LHS, m_LogicalAnd(m_Value(ALHS), m_Value(ARHS))))) {
10127 // FIXME: Make this non-recursion.
10128 if (std::optional<bool> Implication = isImpliedCondition(
10129 ALHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10130 return Implication;
10131 if (std::optional<bool> Implication = isImpliedCondition(
10132 ARHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10133 return Implication;
10134 return std::nullopt;
10135 }
10136 return std::nullopt;
10137}
10138
10139std::optional<bool>
10141 const Value *RHSOp0, const Value *RHSOp1,
10142 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10143 // Bail out when we hit the limit.
10145 return std::nullopt;
10146
10147 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
10148 // example.
10149 if (RHSOp0->getType()->isVectorTy() != LHS->getType()->isVectorTy())
10150 return std::nullopt;
10151
10152 assert(LHS->getType()->isIntOrIntVectorTy(1) &&
10153 "Expected integer type only!");
10154
10155 // Match not
10156 if (match(LHS, m_Not(m_Value(LHS))))
10157 LHSIsTrue = !LHSIsTrue;
10158
10159 // Both LHS and RHS are icmps.
10160 if (RHSOp0->getType()->getScalarType()->isIntOrPtrTy()) {
10161 CmpPredicate LHSPred;
10162 Value *LHSOp0, *LHSOp1;
10163 if (match(LHS, m_ICmpLike(LHSPred, m_Value(LHSOp0), m_Value(LHSOp1))))
10164 return isImpliedCondICmps(LHSPred, LHSOp0, LHSOp1, RHSPred, RHSOp0,
10165 RHSOp1, DL, LHSIsTrue);
10166 } else {
10167 assert(RHSOp0->getType()->isFPOrFPVectorTy() &&
10168 "Expected floating point type only!");
10169 if (const auto *LHSCmp = dyn_cast<FCmpInst>(LHS))
10170 return isImpliedCondFCmps(LHSCmp->getPredicate(), LHSCmp->getOperand(0),
10171 LHSCmp->getOperand(1), RHSPred, RHSOp0, RHSOp1,
10172 DL, LHSIsTrue);
10173 }
10174
10175 /// The LHS should be an 'or', 'and', or a 'select' instruction. We expect
10176 /// the RHS to be an icmp.
10177 /// FIXME: Add support for and/or/select on the RHS.
10178 if (const Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
10179 if ((LHSI->getOpcode() == Instruction::And ||
10180 LHSI->getOpcode() == Instruction::Or ||
10181 LHSI->getOpcode() == Instruction::Select))
10182 return isImpliedCondAndOr(LHSI, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue,
10183 Depth);
10184 }
10185 return std::nullopt;
10186}
10187
10188std::optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
10189 const DataLayout &DL,
10190 bool LHSIsTrue, unsigned Depth) {
10191 // LHS ==> RHS by definition
10192 if (LHS == RHS)
10193 return LHSIsTrue;
10194
10195 // Match not
10196 bool InvertRHS = false;
10197 if (match(RHS, m_Not(m_Value(RHS)))) {
10198 if (LHS == RHS)
10199 return !LHSIsTrue;
10200 InvertRHS = true;
10201 }
10202
10203 CmpPredicate RHSPred;
10204 Value *RHSOp0, *RHSOp1;
10205 if (match(RHS, m_ICmpLike(RHSPred, m_Value(RHSOp0), m_Value(RHSOp1)))) {
10206 if (auto Implied = isImpliedCondition(LHS, RHSPred, RHSOp0, RHSOp1, DL,
10207 LHSIsTrue, Depth))
10208 return InvertRHS ? !*Implied : *Implied;
10209 return std::nullopt;
10210 }
10211 if (const FCmpInst *RHSCmp = dyn_cast<FCmpInst>(RHS)) {
10212 if (auto Implied = isImpliedCondition(
10213 LHS, RHSCmp->getPredicate(), RHSCmp->getOperand(0),
10214 RHSCmp->getOperand(1), DL, LHSIsTrue, Depth))
10215 return InvertRHS ? !*Implied : *Implied;
10216 return std::nullopt;
10217 }
10218
10220 return std::nullopt;
10221
10222 // LHS ==> (RHS1 || RHS2) if LHS ==> RHS1 or LHS ==> RHS2
10223 // LHS ==> !(RHS1 && RHS2) if LHS ==> !RHS1 or LHS ==> !RHS2
10224 const Value *RHS1, *RHS2;
10225 if (match(RHS, m_LogicalOr(m_Value(RHS1), m_Value(RHS2)))) {
10226 if (std::optional<bool> Imp =
10227 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10228 if (*Imp == true)
10229 return !InvertRHS;
10230 if (std::optional<bool> Imp =
10231 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10232 if (*Imp == true)
10233 return !InvertRHS;
10234 }
10235 if (match(RHS, m_LogicalAnd(m_Value(RHS1), m_Value(RHS2)))) {
10236 if (std::optional<bool> Imp =
10237 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10238 if (*Imp == false)
10239 return InvertRHS;
10240 if (std::optional<bool> Imp =
10241 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10242 if (*Imp == false)
10243 return InvertRHS;
10244 }
10245
10246 return std::nullopt;
10247}
10248
10249// Returns a pair (Condition, ConditionIsTrue), where Condition is a branch
10250// condition dominating ContextI or nullptr, if no condition is found.
10251static std::pair<Value *, bool>
10253 if (!ContextI || !ContextI->getParent())
10254 return {nullptr, false};
10255
10256 // TODO: This is a poor/cheap way to determine dominance. Should we use a
10257 // dominator tree (eg, from a SimplifyQuery) instead?
10258 const BasicBlock *ContextBB = ContextI->getParent();
10259 const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
10260 if (!PredBB)
10261 return {nullptr, false};
10262
10263 // We need a conditional branch in the predecessor.
10264 Value *PredCond;
10265 BasicBlock *TrueBB, *FalseBB;
10266 if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
10267 return {nullptr, false};
10268
10269 // The branch should get simplified. Don't bother simplifying this condition.
10270 if (TrueBB == FalseBB)
10271 return {nullptr, false};
10272
10273 assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
10274 "Predecessor block does not point to successor?");
10275
10276 // Is this condition implied by the predecessor condition?
10277 return {PredCond, TrueBB == ContextBB};
10278}
10279
10280std::optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
10281 const Instruction *ContextI,
10282 const DataLayout &DL) {
10283 assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
10284 auto PredCond = getDomPredecessorCondition(ContextI);
10285 if (PredCond.first)
10286 return isImpliedCondition(PredCond.first, Cond, DL, PredCond.second);
10287 return std::nullopt;
10288}
10289
10291 const Value *LHS,
10292 const Value *RHS,
10293 const Instruction *ContextI,
10294 const DataLayout &DL) {
10295 auto PredCond = getDomPredecessorCondition(ContextI);
10296 if (PredCond.first)
10297 return isImpliedCondition(PredCond.first, Pred, LHS, RHS, DL,
10298 PredCond.second);
10299 return std::nullopt;
10300}
10301
10303 APInt &Upper, const InstrInfoQuery &IIQ,
10304 bool PreferSignedRange) {
10305 unsigned Width = Lower.getBitWidth();
10306 const APInt *C;
10307 switch (BO.getOpcode()) {
10308 case Instruction::Sub:
10309 if (match(BO.getOperand(0), m_APInt(C))) {
10310 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10311 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10312
10313 // If the caller expects a signed compare, then try to use a signed range.
10314 // Otherwise if both no-wraps are set, use the unsigned range because it
10315 // is never larger than the signed range. Example:
10316 // "sub nuw nsw i8 -2, x" is unsigned [0, 254] vs. signed [-128, 126].
10317 // "sub nuw nsw i8 2, x" is unsigned [0, 2] vs. signed [-125, 127].
10318 if (PreferSignedRange && HasNSW && HasNUW)
10319 HasNUW = false;
10320
10321 if (HasNUW) {
10322 // 'sub nuw c, x' produces [0, C].
10323 Upper = *C + 1;
10324 } else if (HasNSW) {
10325 if (C->isNegative()) {
10326 // 'sub nsw -C, x' produces [SINT_MIN, -C - SINT_MIN].
10328 Upper = *C - APInt::getSignedMaxValue(Width);
10329 } else {
10330 // Note that sub 0, INT_MIN is not NSW. It techically is a signed wrap
10331 // 'sub nsw C, x' produces [C - SINT_MAX, SINT_MAX].
10332 Lower = *C - APInt::getSignedMaxValue(Width);
10334 }
10335 }
10336 }
10337 break;
10338 case Instruction::Add:
10339 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10340 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10341 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10342
10343 // If the caller expects a signed compare, then try to use a signed
10344 // range. Otherwise if both no-wraps are set, use the unsigned range
10345 // because it is never larger than the signed range. Example: "add nuw
10346 // nsw i8 X, -2" is unsigned [254,255] vs. signed [-128, 125].
10347 if (PreferSignedRange && HasNSW && HasNUW)
10348 HasNUW = false;
10349
10350 if (HasNUW) {
10351 // 'add nuw x, C' produces [C, UINT_MAX].
10352 Lower = *C;
10353 } else if (HasNSW) {
10354 if (C->isNegative()) {
10355 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
10357 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
10358 } else {
10359 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
10360 Lower = APInt::getSignedMinValue(Width) + *C;
10361 Upper = APInt::getSignedMaxValue(Width) + 1;
10362 }
10363 }
10364 }
10365 break;
10366
10367 case Instruction::And:
10368 if (match(BO.getOperand(1), m_APInt(C)))
10369 // 'and x, C' produces [0, C].
10370 Upper = *C + 1;
10371 // X & -X is a power of two or zero. So we can cap the value at max power of
10372 // two.
10373 if (match(BO.getOperand(0), m_Neg(m_Specific(BO.getOperand(1)))) ||
10374 match(BO.getOperand(1), m_Neg(m_Specific(BO.getOperand(0)))))
10375 Upper = APInt::getSignedMinValue(Width) + 1;
10376 break;
10377
10378 case Instruction::Or:
10379 if (match(BO.getOperand(1), m_APInt(C)))
10380 // 'or x, C' produces [C, UINT_MAX].
10381 Lower = *C;
10382 break;
10383
10384 case Instruction::AShr:
10385 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10386 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
10388 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
10389 } else if (match(BO.getOperand(0), m_APInt(C))) {
10390 unsigned ShiftAmount = Width - 1;
10391 if (!C->isZero() && IIQ.isExact(&BO))
10392 ShiftAmount = C->countr_zero();
10393 if (C->isNegative()) {
10394 // 'ashr C, x' produces [C, C >> (Width-1)]
10395 Lower = *C;
10396 Upper = C->ashr(ShiftAmount) + 1;
10397 } else {
10398 // 'ashr C, x' produces [C >> (Width-1), C]
10399 Lower = C->ashr(ShiftAmount);
10400 Upper = *C + 1;
10401 }
10402 }
10403 break;
10404
10405 case Instruction::LShr:
10406 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10407 // 'lshr x, C' produces [0, UINT_MAX >> C].
10408 Upper = APInt::getAllOnes(Width).lshr(*C) + 1;
10409 } else if (match(BO.getOperand(0), m_APInt(C))) {
10410 // 'lshr C, x' produces [C >> (Width-1), C].
10411 unsigned ShiftAmount = Width - 1;
10412 if (!C->isZero() && IIQ.isExact(&BO))
10413 ShiftAmount = C->countr_zero();
10414 Lower = C->lshr(ShiftAmount);
10415 Upper = *C + 1;
10416 }
10417 break;
10418
10419 case Instruction::Shl:
10420 if (match(BO.getOperand(0), m_APInt(C))) {
10421 if (IIQ.hasNoUnsignedWrap(&BO)) {
10422 // 'shl nuw C, x' produces [C, C << CLZ(C)]
10423 Lower = *C;
10424 Upper = Lower.shl(Lower.countl_zero()) + 1;
10425 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
10426 if (C->isNegative()) {
10427 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
10428 unsigned ShiftAmount = C->countl_one() - 1;
10429 Lower = C->shl(ShiftAmount);
10430 Upper = *C + 1;
10431 } else {
10432 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
10433 unsigned ShiftAmount = C->countl_zero() - 1;
10434 Lower = *C;
10435 Upper = C->shl(ShiftAmount) + 1;
10436 }
10437 } else {
10438 // If lowbit is set, value can never be zero.
10439 if ((*C)[0])
10440 Lower = APInt::getOneBitSet(Width, 0);
10441 // If we are shifting a constant the largest it can be is if the longest
10442 // sequence of consecutive ones is shifted to the highbits (breaking
10443 // ties for which sequence is higher). At the moment we take a liberal
10444 // upper bound on this by just popcounting the constant.
10445 // TODO: There may be a bitwise trick for it longest/highest
10446 // consecutative sequence of ones (naive method is O(Width) loop).
10447 Upper = APInt::getHighBitsSet(Width, C->popcount()) + 1;
10448 }
10449 } else if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10450 Upper = APInt::getBitsSetFrom(Width, C->getZExtValue()) + 1;
10451 }
10452 break;
10453
10454 case Instruction::SDiv:
10455 if (match(BO.getOperand(1), m_APInt(C))) {
10456 APInt IntMin = APInt::getSignedMinValue(Width);
10457 APInt IntMax = APInt::getSignedMaxValue(Width);
10458 if (C->isAllOnes()) {
10459 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
10460 // where C != -1 and C != 0 and C != 1
10461 Lower = IntMin + 1;
10462 Upper = IntMax + 1;
10463 } else if (C->countl_zero() < Width - 1) {
10464 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
10465 // where C != -1 and C != 0 and C != 1
10466 Lower = IntMin.sdiv(*C);
10467 Upper = IntMax.sdiv(*C);
10468 if (Lower.sgt(Upper))
10470 Upper = Upper + 1;
10471 assert(Upper != Lower && "Upper part of range has wrapped!");
10472 }
10473 } else if (match(BO.getOperand(0), m_APInt(C))) {
10474 if (C->isMinSignedValue()) {
10475 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
10476 Lower = *C;
10477 Upper = Lower.lshr(1) + 1;
10478 } else {
10479 // 'sdiv C, x' produces [-|C|, |C|].
10480 Upper = C->abs() + 1;
10481 Lower = (-Upper) + 1;
10482 }
10483 }
10484 break;
10485
10486 case Instruction::UDiv:
10487 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10488 // 'udiv x, C' produces [0, UINT_MAX / C].
10489 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
10490 } else if (match(BO.getOperand(0), m_APInt(C))) {
10491 // 'udiv C, x' produces [0, C].
10492 Upper = *C + 1;
10493 }
10494 break;
10495
10496 case Instruction::SRem:
10497 if (match(BO.getOperand(1), m_APInt(C))) {
10498 // 'srem x, C' produces (-|C|, |C|).
10499 Upper = C->abs();
10500 Lower = (-Upper) + 1;
10501 } else if (match(BO.getOperand(0), m_APInt(C))) {
10502 if (C->isNegative()) {
10503 // 'srem -|C|, x' produces [-|C|, 0].
10504 Upper = 1;
10505 Lower = *C;
10506 } else {
10507 // 'srem |C|, x' produces [0, |C|].
10508 Upper = *C + 1;
10509 }
10510 }
10511 break;
10512
10513 case Instruction::URem:
10514 if (match(BO.getOperand(1), m_APInt(C)))
10515 // 'urem x, C' produces [0, C).
10516 Upper = *C;
10517 else if (match(BO.getOperand(0), m_APInt(C)))
10518 // 'urem C, x' produces [0, C].
10519 Upper = *C + 1;
10520 break;
10521
10522 default:
10523 break;
10524 }
10525}
10526
10528 bool UseInstrInfo) {
10529 unsigned Width = II.getType()->getScalarSizeInBits();
10530 const APInt *C;
10531 switch (II.getIntrinsicID()) {
10532 case Intrinsic::ctlz:
10533 case Intrinsic::cttz: {
10534 APInt Upper(Width, Width);
10535 if (!UseInstrInfo || !match(II.getArgOperand(1), m_One()))
10536 Upper += 1;
10537 // Maximum of set/clear bits is the bit width.
10539 }
10540 case Intrinsic::ctpop:
10541 // Maximum of set/clear bits is the bit width.
10543 APInt(Width, Width) + 1);
10544 case Intrinsic::uadd_sat:
10545 // uadd.sat(x, C) produces [C, UINT_MAX].
10546 if (match(II.getOperand(0), m_APInt(C)) ||
10547 match(II.getOperand(1), m_APInt(C)))
10549 break;
10550 case Intrinsic::sadd_sat:
10551 if (match(II.getOperand(0), m_APInt(C)) ||
10552 match(II.getOperand(1), m_APInt(C))) {
10553 if (C->isNegative())
10554 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
10556 APInt::getSignedMaxValue(Width) + *C +
10557 1);
10558
10559 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
10561 APInt::getSignedMaxValue(Width) + 1);
10562 }
10563 break;
10564 case Intrinsic::usub_sat:
10565 // usub.sat(C, x) produces [0, C].
10566 if (match(II.getOperand(0), m_APInt(C)))
10567 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10568
10569 // usub.sat(x, C) produces [0, UINT_MAX - C].
10570 if (match(II.getOperand(1), m_APInt(C)))
10572 APInt::getMaxValue(Width) - *C + 1);
10573 break;
10574 case Intrinsic::ssub_sat:
10575 if (match(II.getOperand(0), m_APInt(C))) {
10576 if (C->isNegative())
10577 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
10579 *C - APInt::getSignedMinValue(Width) +
10580 1);
10581
10582 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
10584 APInt::getSignedMaxValue(Width) + 1);
10585 } else if (match(II.getOperand(1), m_APInt(C))) {
10586 if (C->isNegative())
10587 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
10589 APInt::getSignedMaxValue(Width) + 1);
10590
10591 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
10593 APInt::getSignedMaxValue(Width) - *C +
10594 1);
10595 }
10596 break;
10597 case Intrinsic::umin:
10598 case Intrinsic::umax:
10599 case Intrinsic::smin:
10600 case Intrinsic::smax:
10601 if (!match(II.getOperand(0), m_APInt(C)) &&
10602 !match(II.getOperand(1), m_APInt(C)))
10603 break;
10604
10605 switch (II.getIntrinsicID()) {
10606 case Intrinsic::umin:
10607 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10608 case Intrinsic::umax:
10610 case Intrinsic::smin:
10612 *C + 1);
10613 case Intrinsic::smax:
10615 APInt::getSignedMaxValue(Width) + 1);
10616 default:
10617 llvm_unreachable("Must be min/max intrinsic");
10618 }
10619 break;
10620 case Intrinsic::abs:
10621 // If abs of SIGNED_MIN is poison, then the result is [0..SIGNED_MAX],
10622 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10623 if (match(II.getOperand(1), m_One()))
10625 APInt::getSignedMaxValue(Width) + 1);
10626
10628 APInt::getSignedMinValue(Width) + 1);
10629 case Intrinsic::vscale:
10630 if (!II.getParent() || !II.getFunction())
10631 break;
10632 return getVScaleRange(II.getFunction(), Width);
10633 case Intrinsic::read_register:
10634 case Intrinsic::read_volatile_register: {
10635 const Module *M = II.getModule();
10636 if (!M || !M->getTargetTriple().isRISCV())
10637 break;
10638 if (II.getFunction() && isReadVLENB(II))
10639 return getRISCVVLENBRange(II, Width);
10640 break;
10641 }
10642 default:
10643 break;
10644 }
10645
10646 return ConstantRange::getFull(Width);
10647}
10648
10650 const InstrInfoQuery &IIQ) {
10651 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
10652 const Value *LHS = nullptr, *RHS = nullptr;
10654 if (R.Flavor == SPF_UNKNOWN)
10655 return ConstantRange::getFull(BitWidth);
10656
10657 if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
10658 // If the negation part of the abs (in RHS) has the NSW flag,
10659 // then the result of abs(X) is [0..SIGNED_MAX],
10660 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10661 if (match(RHS, m_Neg(m_Specific(LHS))) &&
10665
10668 }
10669
10670 if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
10671 // The result of -abs(X) is <= 0.
10673 APInt(BitWidth, 1));
10674 }
10675
10676 const APInt *C;
10677 if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
10678 return ConstantRange::getFull(BitWidth);
10679
10680 switch (R.Flavor) {
10681 case SPF_UMIN:
10683 case SPF_UMAX:
10685 case SPF_SMIN:
10687 *C + 1);
10688 case SPF_SMAX:
10691 default:
10692 return ConstantRange::getFull(BitWidth);
10693 }
10694}
10695
10697 // The maximum representable value of a half is 65504. For floats the maximum
10698 // value is 3.4e38 which requires roughly 129 bits.
10699 unsigned BitWidth = I->getType()->getScalarSizeInBits();
10700 if (!I->getOperand(0)->getType()->getScalarType()->isHalfTy())
10701 return;
10702 if (isa<FPToSIInst>(I) && BitWidth >= 17) {
10703 Lower = APInt(BitWidth, -65504, true);
10704 Upper = APInt(BitWidth, 65505);
10705 }
10706
10707 if (isa<FPToUIInst>(I) && BitWidth >= 16) {
10708 // For a fptoui the lower limit is left as 0.
10709 Upper = APInt(BitWidth, 65505);
10710 }
10711}
10712
10714 const SimplifyQuery &SQ,
10715 unsigned Depth) {
10716 assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
10717
10719 return ConstantRange::getFull(V->getType()->getScalarSizeInBits());
10720
10721 if (auto *C = dyn_cast<Constant>(V))
10722 return C->toConstantRange();
10723
10724 unsigned BitWidth = V->getType()->getScalarSizeInBits();
10725 ConstantRange CR = ConstantRange::getFull(BitWidth);
10726 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
10727 APInt Lower = APInt(BitWidth, 0);
10728 APInt Upper = APInt(BitWidth, 0);
10729 // TODO: Return ConstantRange.
10730 setLimitsForBinOp(*BO, Lower, Upper, SQ.IIQ, ForSigned);
10732 } else if (auto *II = dyn_cast<IntrinsicInst>(V))
10734 else if (auto *SI = dyn_cast<SelectInst>(V)) {
10735 ConstantRange CRTrue =
10736 computeConstantRange(SI->getTrueValue(), ForSigned, SQ, Depth + 1);
10737 ConstantRange CRFalse =
10738 computeConstantRange(SI->getFalseValue(), ForSigned, SQ, Depth + 1);
10739 CR = CRTrue.unionWith(CRFalse);
10741 } else if (auto *TI = dyn_cast<TruncInst>(V)) {
10742 ConstantRange SrcCR =
10743 computeConstantRange(TI->getOperand(0), ForSigned, SQ, Depth + 1);
10744 CR = SrcCR.truncate(BitWidth);
10745 } else if (isa<FPToUIInst>(V) || isa<FPToSIInst>(V)) {
10746 APInt Lower = APInt(BitWidth, 0);
10747 APInt Upper = APInt(BitWidth, 0);
10748 // TODO: Return ConstantRange.
10751 } else if (const auto *A = dyn_cast<Argument>(V))
10752 if (std::optional<ConstantRange> Range = A->getRange())
10753 CR = *Range;
10754
10755 if (auto *I = dyn_cast<Instruction>(V)) {
10756 if (auto *Range = SQ.IIQ.getMetadata(I, LLVMContext::MD_range))
10758
10759 Value *FrexpSrc;
10760 if (const auto *CB = dyn_cast<CallBase>(V)) {
10761 if (std::optional<ConstantRange> Range = CB->getRange())
10762 CR = CR.intersectWith(*Range);
10764 m_Value(FrexpSrc))))) {
10765 const fltSemantics &FltSem =
10766 FrexpSrc->getType()->getScalarType()->getFltSemantics();
10767 // It should be possible to implement this for any type, but this logic
10768 // only computes the range assuming standard subnormal handling.
10769 if (APFloat::isIEEELikeFP(FltSem)) {
10771 FrexpSrc, fcSubnormal | fcZero | fcNan | fcInf, SQ, Depth + 1);
10772
10773 // The exponent of frexp(NaN) and frexp(Inf) is unspecified. Only
10774 // constrain its range when the source can be neither.
10775 if (KnownSrc.isKnownNeverInfOrNaN()) {
10776 int MinExp = APFloat::semanticsMinExponent(FltSem) + 1;
10777
10778 // Offset to find the true minimum exponent value for a denormal.
10779 if (!KnownSrc.isKnownNeverSubnormal())
10780 MinExp -= (APFloat::semanticsPrecision(FltSem) - 1);
10781
10782 int MaxExp = APFloat::semanticsMaxExponent(FltSem) + 1;
10783
10784 auto [AdjustedMin, AdjustedMax, AdjustedMaxNonZero] =
10786
10787 DenormalMode Mode = I->getFunction()->getDenormalMode(FltSem);
10788 bool NeverLogicalZero = KnownSrc.isKnownNeverLogicalZero(Mode);
10789
10790 MinExp = std::max(AdjustedMin, MinExp);
10791 MaxExp = std::min(NeverLogicalZero ? AdjustedMaxNonZero : AdjustedMax,
10792 MaxExp);
10793
10795 APInt(BitWidth, static_cast<int64_t>(MinExp), /*isSigned=*/true),
10796 APInt(BitWidth, static_cast<int64_t>(MaxExp) + 1,
10797 /*isSigned=*/true));
10798 }
10799 }
10800 }
10801 }
10802
10803 if (SQ.CxtI && SQ.AC) {
10804 // Try to restrict the range based on information from assumptions.
10805 for (auto &AssumeVH : SQ.AC->assumptionsFor(V)) {
10806 if (!AssumeVH)
10807 continue;
10808 CallInst *I = cast<CallInst>(AssumeVH);
10809 assert(I->getParent()->getParent() == SQ.CxtI->getParent()->getParent() &&
10810 "Got assumption for the wrong function!");
10811 assert(I->getIntrinsicID() == Intrinsic::assume &&
10812 "must be an assume intrinsic");
10813
10814 if (!isValidAssumeForContext(I, SQ))
10815 continue;
10816 Value *Arg = I->getArgOperand(0);
10817 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
10818 // Currently we just use information from comparisons.
10819 if (!Cmp || Cmp->getOperand(0) != V)
10820 continue;
10821 // TODO: Set "ForSigned" parameter via Cmp->isSigned()?
10822 ConstantRange RHS =
10823 computeConstantRange(Cmp->getOperand(1), /*ForSigned=*/false,
10824 SQ.getWithInstruction(I), Depth + 1);
10825 CR = CR.intersectWith(
10826 ConstantRange::makeAllowedICmpRegion(Cmp->getCmpPredicate(), RHS));
10827 }
10828 }
10829
10830 return CR;
10831}
10832
10833static void
10835 function_ref<void(Value *)> InsertAffected) {
10836 assert(V != nullptr);
10837 if (isa<Argument>(V) || isa<GlobalValue>(V)) {
10838 InsertAffected(V);
10839 } else if (auto *I = dyn_cast<Instruction>(V)) {
10840 InsertAffected(V);
10841
10842 // Peek through unary operators to find the source of the condition.
10843 Value *Op;
10845 m_Trunc(m_Value(Op))))) {
10847 InsertAffected(Op);
10848 }
10849 }
10850}
10851
10853 Value *Cond, bool IsAssume, function_ref<void(Value *)> InsertAffected) {
10854 auto AddAffected = [&InsertAffected](Value *V) {
10855 addValueAffectedByCondition(V, InsertAffected);
10856 };
10857
10858 auto AddCmpOperands = [&AddAffected, IsAssume](Value *LHS, Value *RHS) {
10859 if (IsAssume) {
10860 AddAffected(LHS);
10861 AddAffected(RHS);
10862 } else if (match(RHS, m_Constant()))
10863 AddAffected(LHS);
10864 };
10865
10866 SmallVector<Value *, 8> Worklist;
10868 Worklist.push_back(Cond);
10869 while (!Worklist.empty()) {
10870 Value *V = Worklist.pop_back_val();
10871 if (!Visited.insert(V).second)
10872 continue;
10873
10874 CmpPredicate Pred;
10875 Value *A, *B, *X;
10876
10877 if (IsAssume) {
10878 AddAffected(V);
10879 if (match(V, m_Not(m_Value(X))))
10880 AddAffected(X);
10881 }
10882
10883 if (match(V, m_LogicalOp(m_Value(A), m_Value(B)))) {
10884 // assume(A && B) is split to -> assume(A); assume(B);
10885 // assume(!(A || B)) is split to -> assume(!A); assume(!B);
10886 // Finally, assume(A || B) / assume(!(A && B)) generally don't provide
10887 // enough information to be worth handling (intersection of information as
10888 // opposed to union).
10889 if (!IsAssume) {
10890 Worklist.push_back(A);
10891 Worklist.push_back(B);
10892 }
10893 } else if (match(V, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
10894 bool HasRHSC = match(B, m_ConstantInt());
10895 if (ICmpInst::isEquality(Pred)) {
10896 AddAffected(A);
10897 if (IsAssume)
10898 AddAffected(B);
10899 if (HasRHSC) {
10900 Value *Y;
10901 // (X << C) or (X >>_s C) or (X >>_u C).
10902 if (match(A, m_Shift(m_Value(X), m_ConstantInt())))
10903 AddAffected(X);
10904 // (X & C) or (X | C).
10905 else if (match(A, m_And(m_Value(X), m_Value(Y))) ||
10906 match(A, m_Or(m_Value(X), m_Value(Y)))) {
10907 AddAffected(X);
10908 AddAffected(Y);
10909 }
10910 // X - Y
10911 else if (match(A, m_Sub(m_Value(X), m_Value(Y)))) {
10912 AddAffected(X);
10913 AddAffected(Y);
10914 }
10915 }
10916 } else {
10917 AddCmpOperands(A, B);
10918 if (HasRHSC) {
10919 // Handle (A + C1) u< C2, which is the canonical form of
10920 // A > C3 && A < C4.
10922 AddAffected(X);
10923
10924 if (ICmpInst::isUnsigned(Pred)) {
10925 Value *Y;
10926 // X & Y u> C -> X >u C && Y >u C
10927 // X | Y u< C -> X u< C && Y u< C
10928 // X nuw+ Y u< C -> X u< C && Y u< C
10929 if (match(A, m_And(m_Value(X), m_Value(Y))) ||
10930 match(A, m_Or(m_Value(X), m_Value(Y))) ||
10931 match(A, m_NUWAdd(m_Value(X), m_Value(Y)))) {
10932 AddAffected(X);
10933 AddAffected(Y);
10934 }
10935 // X nuw- Y u> C -> X u> C
10936 if (match(A, m_NUWSub(m_Value(X), m_Value())))
10937 AddAffected(X);
10938 }
10939 }
10940
10941 // Handle icmp slt/sgt (bitcast X to int), 0/-1, which is supported
10942 // by computeKnownFPClass().
10944 if (Pred == ICmpInst::ICMP_SLT && match(B, m_Zero()))
10945 InsertAffected(X);
10946 else if (Pred == ICmpInst::ICMP_SGT && match(B, m_AllOnes()))
10947 InsertAffected(X);
10948 }
10949 }
10950
10951 auto AddNuwSquareOperand = [&AddAffected](Value *Op) {
10952 Value *SquareOp = nullptr;
10953 if (match(Op, m_NUWMul(m_Value(SquareOp), m_Deferred(SquareOp))))
10954 AddAffected(SquareOp);
10955 };
10956 AddNuwSquareOperand(A);
10957 AddNuwSquareOperand(B);
10958
10959 if (HasRHSC && match(A, m_Ctpop(m_Value(X))))
10960 AddAffected(X);
10961 } else if (match(V, m_FCmp(Pred, m_Value(A), m_Value(B)))) {
10962 AddCmpOperands(A, B);
10963
10964 // fcmp fneg(x), y
10965 // fcmp fabs(x), y
10966 // fcmp fneg(fabs(x)), y
10967 if (match(A, m_FNeg(m_Value(A))))
10968 AddAffected(A);
10969 if (match(A, m_FAbs(m_Value(A))))
10970 AddAffected(A);
10971
10973 m_Value()))) {
10974 // Handle patterns that computeKnownFPClass() support.
10975 AddAffected(A);
10976 } else if (!IsAssume && match(V, m_Trunc(m_Value(X)))) {
10977 // Assume is checked here as X is already added above for assumes in
10978 // addValueAffectedByCondition
10979 AddAffected(X);
10980 } else if (!IsAssume && match(V, m_Not(m_Value(X)))) {
10981 // Assume is checked here to avoid issues with ephemeral values
10982 Worklist.push_back(X);
10983 }
10984 }
10985}
10986
10988 // (X >> C) or/add (X & mask(C) != 0)
10989 if (const auto *BO = dyn_cast<BinaryOperator>(V)) {
10990 if (BO->getOpcode() == Instruction::Add ||
10991 BO->getOpcode() == Instruction::Or) {
10992 const Value *X;
10993 const APInt *C1, *C2;
10994 if (match(BO, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C1)),
10998 m_Zero())))) &&
10999 C2->popcount() == C1->getZExtValue())
11000 return X;
11001 }
11002 }
11003 return nullptr;
11004}
11005
11007 return const_cast<Value *>(stripNullTest(const_cast<const Value *>(V)));
11008}
11009
11012 unsigned MaxCount, bool AllowUndefOrPoison) {
11015 auto Push = [&](const Value *V) -> bool {
11016 Constant *C;
11017 if (match(const_cast<Value *>(V), m_ImmConstant(C))) {
11018 if (!AllowUndefOrPoison && !isGuaranteedNotToBeUndefOrPoison(C))
11019 return false;
11020 // Check existence first to avoid unnecessary allocations.
11021 if (Constants.contains(C))
11022 return true;
11023 if (Constants.size() == MaxCount)
11024 return false;
11025 Constants.insert(C);
11026 return true;
11027 }
11028
11029 if (auto *Inst = dyn_cast<Instruction>(V)) {
11030 if (Visited.insert(Inst).second)
11031 Worklist.push_back(Inst);
11032 return true;
11033 }
11034 return false;
11035 };
11036 if (!Push(V))
11037 return false;
11038 while (!Worklist.empty()) {
11039 const Instruction *CurInst = Worklist.pop_back_val();
11040 switch (CurInst->getOpcode()) {
11041 case Instruction::Select:
11042 if (!Push(CurInst->getOperand(1)))
11043 return false;
11044 if (!Push(CurInst->getOperand(2)))
11045 return false;
11046 break;
11047 case Instruction::PHI:
11048 for (Value *IncomingValue : cast<PHINode>(CurInst)->incoming_values()) {
11049 // Fast path for recurrence PHI.
11050 if (IncomingValue == CurInst)
11051 continue;
11052 if (!Push(IncomingValue))
11053 return false;
11054 }
11055 break;
11056 default:
11057 return false;
11058 }
11059 }
11060 return true;
11061}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
AMDGPU Register Bank Select
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Utilities for dealing with flags related to floating point properties and mode controls.
static Value * getCondition(Instruction *I)
Hexagon Common GEP
#define _
static MaybeAlign getAlign(Value *Ptr)
Module.h This file contains the declarations for the Module class.
static bool hasNoUnsignedWrap(BinaryOperator &I)
#define RegName(no)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
PowerPC Reduce CR logical Operation
R600 Clause Merge
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This file contains the UndefPoisonKind enum and helper functions.
static void computeKnownFPClassFromCond(const Value *V, Value *Cond, bool CondIsTrue, const Instruction *CxtI, KnownFPClass &KnownFromContext, unsigned Depth=0)
static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero, SimplifyQuery &Q, unsigned Depth)
Try to detect a recurrence that the value of the induction variable is always a power of two (or zero...
static cl::opt< unsigned > DomConditionsMaxUses("dom-conditions-max-uses", cl::Hidden, cl::init(20))
static unsigned computeNumSignBitsVectorConstant(const Value *V, const APInt &DemandedElts, unsigned TyBits)
For vector constants, loop over the elements and find the constant with the minimum number of sign bi...
static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS, const Value *RHS)
Return true if "icmp Pred LHS RHS" is always true.
static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V1 == (binop V2, X), where X is known non-zero.
static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q, unsigned Depth)
Test whether a GEP's result is known to be non-null.
static bool isNonEqualShl(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and the shift is nuw or nsw.
static bool isKnownNonNullFromDominatingCondition(const Value *V, const Instruction *CtxI, const DominatorTree *DT)
static const Value * getUnderlyingObjectFromInt(const Value *V)
This is the function that does the work of looking through basic ptrtoint+arithmetic+inttoptr sequenc...
static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, bool NSW, bool NUW, unsigned Depth)
static bool rangeMetadataExcludesValue(const MDNode *Ranges, const APInt &Value)
Does the 'Range' metadata (which must be a valid MD_range operand list) ensure that the value it's at...
static KnownBits getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &Q, unsigned Depth)
static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI, Value *&ValOut, Instruction *&CtxIOut, const PHINode **PhiOut=nullptr)
static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, unsigned Depth)
static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR)
Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
static void addValueAffectedByCondition(Value *V, function_ref< void(Value *)> InsertAffected)
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static void setLimitsForBinOp(const BinaryOperator &BO, APInt &Lower, APInt &Upper, const InstrInfoQuery &IIQ, bool PreferSignedRange)
static Value * lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2, Instruction::CastOps *CastOp)
Helps to match a select pattern in case of a type mismatch.
static std::pair< Value *, bool > getDomPredecessorCondition(const Instruction *ContextI)
static constexpr unsigned MaxInstrsToCheckForFree
Maximum number of instructions to check between assume and context instruction.
static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, const KnownBits &KnownVal, unsigned Depth)
static std::optional< bool > isImpliedCondFCmps(FCmpInst::Predicate LPred, const Value *L0, const Value *L1, FCmpInst::Predicate RPred, const Value *R0, const Value *R1, const DataLayout &DL, bool LHSIsTrue)
Return true if LHS implies RHS (expanded to its components as "R0 RPred R1") is true.
static ConstantRange getRISCVVLENBRange(const IntrinsicInst &II, unsigned Width)
Return the value range of a RISC-V vlenb CSR read.
static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2, const SimplifyQuery &Q, unsigned Depth)
static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS)
Match clamp pattern for float types without care about NaNs or signed zeros.
static std::optional< bool > isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1, CmpPredicate RPred, const Value *R0, const Value *R1, const DataLayout &DL, bool LHSIsTrue)
Return true if LHS implies RHS (expanded to its components as "R0 RPred R1") is true.
static std::optional< bool > isImpliedCondCommonOperandWithCR(CmpPredicate LPred, const ConstantRange &LCR, CmpPredicate RPred, const ConstantRange &RCR)
Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
static ConstantRange getRangeForSelectPattern(const SelectInst &SI, const InstrInfoQuery &IIQ)
static void computeKnownBitsFromOperator(const Operator *I, const APInt &DemandedElts, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth)
static uint64_t GetStringLengthH(const Value *V, SmallPtrSetImpl< const PHINode * > &PHIs, unsigned CharSize)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
static void computeKnownBitsFromShiftOperator(const Operator *I, const APInt &DemandedElts, KnownBits &Known, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth, function_ref< KnownBits(const KnownBits &, const KnownBits &, bool)> KF)
Compute known bits from a shift operator, including those with a non-constant shift amount.
static bool onlyUsedByLifetimeMarkersOrDroppableInstsHelper(const Value *V, bool AllowLifetime, bool AllowDroppable)
static std::optional< bool > isImpliedCondAndOr(const Instruction *LHS, CmpPredicate RHSPred, const Value *RHSOp0, const Value *RHSOp1, const DataLayout &DL, bool LHSIsTrue, unsigned Depth)
Return true if LHS implies RHS is true.
static std::tuple< int, int, int > computeKnownExponentRangeFromContext(const Value *V, const SimplifyQuery &Q)
Compute the minimum and maximum values (inclusive) for the exponent of V, assuming it is not nan.
static bool isSignedMinMaxClamp(const Value *Select, const Value *&In, const APInt *&CLow, const APInt *&CHigh)
static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, bool NSW, bool NUW, unsigned Depth)
static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V, unsigned Depth)
static bool isNonEqualSelect(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst, Value *&Init, Value *&OtherOp)
static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static void computeKnownBitsFromCmp(const Value *V, CmpInst::Predicate Pred, Value *LHS, Value *RHS, KnownBits &Known, const SimplifyQuery &Q)
static SelectPatternResult matchMinMaxOfMinMax(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TVal, Value *FVal, unsigned Depth)
Recognize variations of: a < c ?
static void unionWithMinMaxIntrinsicClamp(const IntrinsicInst *II, KnownBits &Known)
static void setLimitForFPToI(const Instruction *I, APInt &Lower, APInt &Upper)
static bool isSameUnderlyingObjectInLoop(const PHINode *PN, const LoopInfo *LI)
PN defines a loop-variant pointer to an object.
static bool isNonEqualPointersWithRecursiveGEP(const Value *A, const Value *B, const SimplifyQuery &Q)
static bool isSignedMinMaxIntrinsicClamp(const IntrinsicInst *II, const APInt *&CLow, const APInt *&CHigh)
static Value * lookThroughCastConst(CmpInst *CmpI, Type *SrcTy, Constant *C, Instruction::CastOps *CastOp)
static bool handleGuaranteedWellDefinedOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be undef or poison.
static bool isAbsoluteValueULEOne(const Value *V)
static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1, const APInt &DemandedElts, KnownBits &KnownOut, const SimplifyQuery &Q, unsigned Depth)
Try to detect the lerp pattern: a * (b - c) + c * d where a >= 0, b >= 0, c >= 0, d >= 0,...
static KnownFPClass computeKnownFPClassFromContext(const Value *V, const SimplifyQuery &Q)
static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &KnownOut, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth)
static Value * getNotValue(Value *V)
If the input value is the result of a 'not' op, constant integer, or vector splat of a constant integ...
static constexpr KnownFPClass::MinMaxKind getMinMaxKind(Intrinsic::ID IID)
static bool isReadVLENB(const IntrinsicInst &II)
Return true if II reads a register named "vlenb".
static unsigned ComputeNumSignBitsImpl(const Value *V, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return the number of times the sign bit of the register is replicated into the other bits.
static void computeKnownBitsFromICmpCond(const Value *V, ICmpInst *Cmp, KnownBits &Known, const SimplifyQuery &SQ, bool Invert)
static bool isKnownNonZeroFromOperator(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static bool matchOpWithOpEqZero(Value *Op0, Value *Op1)
static bool isNonZeroRecurrence(const PHINode *PN)
Try to detect a recurrence that monotonically increases/decreases from a non-zero starting value.
static SelectPatternResult matchClamp(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal)
Recognize variations of: CLAMP(v,l,h) ==> ((v) < (l) ?
static bool shiftAmountKnownInRange(const Value *ShiftAmount)
Shifts return poison if shiftwidth is larger than the bitwidth.
static bool isEphemeralValueOf(const Instruction *I, const Value *E)
static SelectPatternResult matchMinMax(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, unsigned Depth)
Match non-obvious integer minimum and maximum sequences.
static KnownBits computeKnownBitsForHorizontalOperation(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth, const function_ref< KnownBits(const KnownBits &, const KnownBits &)> KnownBitsFunc)
static bool handleGuaranteedNonPoisonOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be poison.
static std::optional< std::pair< Value *, Value * > > getInvertibleOperands(const Operator *Op1, const Operator *Op2)
If the pair of operators are the same invertible function, return the the operands of the function co...
static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS)
static void computeKnownBitsFromCond(const Value *V, Value *Cond, KnownBits &Known, const SimplifyQuery &SQ, bool Invert, unsigned Depth)
static NoCommonBitsSetResult haveNoCommonBitsSetSpecialCases(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q)
static std::optional< bool > isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, const Value *ARHS, const Value *BLHS, const Value *BRHS)
Return true if "icmp Pred BLHS BRHS" is true whenever "icmp PredALHS ARHS" is true.
static const Instruction * safeCxtI(const Value *V, const Instruction *CxtI)
static bool isNonEqualMul(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and the multiplication is nuw o...
static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero, const Value *Cond, bool CondIsTrue)
Return true if we can infer that V is known to be a power of 2 from dominating condition Cond (e....
static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &Known, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth)
static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst, Value *&Init, Value *&OtherOp0, Value *&OtherOp1)
static bool isKnownNonNaN(const Value *V, FastMathFlags FMF)
static bool isNonEqualURem(const Value *X, const Value *Rem, const SimplifyQuery &Q)
static ConstantRange getRangeForIntrinsic(const IntrinsicInst &II, bool UseInstrInfo)
static void computeKnownFPClassForFPTrunc(const Operator *Op, const APInt &DemandedElts, FPClassTest InterestedClasses, KnownFPClass &Known, const SimplifyQuery &Q, unsigned Depth)
static Value * BuildSubAggregate(Value *From, Value *To, Type *IndexedType, SmallVectorImpl< unsigned > &Idxs, unsigned IdxSkip, BasicBlock::iterator InsertBefore)
Value * RHS
Value * LHS
static LLVM_ABI bool semanticsHasInf(const fltSemantics &)
Definition APFloat.cpp:351
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:326
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
Definition APFloat.cpp:347
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:322
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:318
static LLVM_ABI bool semanticsHasNaN(const fltSemantics &)
Definition APFloat.cpp:355
static LLVM_ABI bool semanticsHasZero(const fltSemantics &)
Definition APFloat.cpp:343
static LLVM_ABI bool isRepresentableAsNormalIn(const fltSemantics &Src, const fltSemantics &Dst)
Definition APFloat.cpp:368
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:359
static LLVM_ABI const fltSemantics * getArbitraryFPSemantics(StringRef Format)
Returns the fltSemantics for a given arbitrary FP format string, or nullptr if invalid.
Definition APFloat.cpp:6131
LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.h:1639
bool isFinite() const
Definition APFloat.h:1588
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1242
bool isInteger() const
Definition APFloat.h:1600
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2009
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:231
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1427
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:420
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1561
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition APInt.h:1412
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1691
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:203
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1351
unsigned ceilLogBase2() const
Definition APInt.h:1785
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1206
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:368
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1187
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:377
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1509
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1116
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:206
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:213
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:326
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
Definition APInt.h:1254
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1673
LLVM_ABI APInt reverseBits() const
Definition APInt.cpp:786
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1171
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition APInt.h:1649
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1619
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:216
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1086
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:353
unsigned logBase2() const
Definition APInt.h:1782
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:830
bool getBoolValue() const
Convert APInt to a boolean value.
Definition APInt.h:468
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:402
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:331
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1155
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:876
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1262
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1135
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:293
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:197
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Definition APInt.h:1409
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1242
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:283
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:236
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:854
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1226
an instruction to allocate memory on the stack
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
Class to represent array types.
This represents the llvm.assume intrinsic.
A cache of @llvm.assume calls within a function.
MutableArrayRef< ResultElem > assumptionsFor(const Value *V)
Access the list of assumptions which affect this value.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
LLVM_ABI std::optional< unsigned > getVScaleRangeMax() const
Returns the maximum value for the vscale_range attribute or std::nullopt when unknown.
LLVM_ABI unsigned getVScaleRangeMin() const
Returns the minimum value for the vscale_range attribute.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:266
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
unsigned arg_size() const
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
static LLVM_ABI Predicate getFlippedStrictnessPredicate(Predicate pred)
This is a static version that you can use without an instruction available.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
bool isSigned() const
Definition InstrTypes.h:993
static LLVM_ABI bool isEquality(Predicate pred)
Determine if this is an equals/not equals predicate.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
static bool isFPPredicate(Predicate P)
Definition InstrTypes.h:833
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
static LLVM_ABI bool isOrdered(Predicate predicate)
Determine if the predicate is an ordered operation.
bool isUnsigned() const
Definition InstrTypes.h:999
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
LLVM_ABI CmpInst::Predicate getPreferredSignedPredicate() const
Attempts to return a signed CmpInst::Predicate from the CmpPredicate.
CmpInst::Predicate dropSameSign() const
Drops samesign information.
bool hasSameSign() const
Query samesign information, for optimizations.
Conditional Branch instruction.
An array constant whose element type is a simple 1/2/4/8-byte integer, bytes or float/double,...
Definition Constants.h:865
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition Constants.h:755
StringRef getAsString() const
If this array is isString(), then this method returns the array as a StringRef.
Definition Constants.h:831
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition Constants.h:951
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI std::optional< ConstantFPRange > makeExactFCmpRegion(FCmpInst::Predicate Pred, const APFloat &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
This class represents a range of values.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
static LLVM_ABI ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
LLVM_ABI OverflowResult unsignedSubMayOverflow(const ConstantRange &Other) const
Return whether unsigned sub of the two ranges always/never overflows.
LLVM_ABI bool isAllNegative() const
Return true if all values in this range are negative.
LLVM_ABI OverflowResult unsignedAddMayOverflow(const ConstantRange &Other) const
Return whether unsigned add of the two ranges always/never overflows.
LLVM_ABI KnownBits toKnownBits() const
Return known bits for values in this range.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
LLVM_ABI APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI OverflowResult unsignedMulMayOverflow(const ConstantRange &Other) const
Return whether unsigned mul of the two ranges always/never overflows.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI bool isAllNonNegative() const
Return true if all values in this range are non-negative.
static LLVM_ABI ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
LLVM_ABI ConstantRange multiply(const ConstantRange &Other, unsigned NoWrapKind=0) const
Return a new range representing the possible values resulting from a multiplication of a value in thi...
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI ConstantRange binaryAnd(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a binary-and of a value in this ra...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
LLVM_ABI OverflowResult signedAddMayOverflow(const ConstantRange &Other) const
Return whether signed add of the two ranges always/never overflows.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
OverflowResult
Represents whether an operation on the given constant range is known to always or never overflow.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
LLVM_ABI OverflowResult signedSubMayOverflow(const ConstantRange &Other) const
Return whether signed sub of the two ranges always/never overflows.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * replaceUndefsWith(Constant *C, Constant *Replacement)
Try to replace undefined constant C or undefined elements in C with Replacement.
LLVM_ABI Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:217
unsigned getAddressSizeInBits(unsigned AS) const
The size in bits of an address in for the given AS.
Definition DataLayout.h:518
LLVM_ABI const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
LLVM_ABI unsigned getPointerTypeSizeInBits(Type *) const
The pointer representation size in bits for this type.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:791
ArrayRef< CondBrInst * > conditionsFor(const Value *V) const
Access the list of branches which affect this value.
DomTreeNodeBase * getIDom() const
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction extracts a struct member or array element value from an aggregate value.
ArrayRef< unsigned > getIndices() const
unsigned getNumIndices() const
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
This instruction compares its operands according to the predicate given to the constructor.
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition Operator.h:202
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
bool noSignedZeros() const
Definition FMF.h:67
bool noInfs() const
Definition FMF.h:66
void setNoSignedZeros(bool B=true)
Definition FMF.h:84
void setNoNaNs(bool B=true)
Definition FMF.h:78
bool noNaNs() const
Definition FMF.h:65
const BasicBlock & getEntryBlock() const
Definition Function.h:794
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
PointerType * getType() const
Global values are always pointers.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
This instruction compares its operands according to the predicate given to the constructor.
CmpPredicate getSwappedCmpPredicate() const
CmpPredicate getInverseCmpPredicate() const
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
static LLVM_ABI std::optional< bool > isImpliedByMatchingCmp(CmpPredicate Pred1, CmpPredicate Pred2)
Determine if Pred1 implies Pred2 is true, false, or if nothing can be inferred about the implication,...
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
This instruction inserts a struct field of array element value into an aggregate value.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI bool hasNoNaNs() const LLVM_READONLY
Determine whether the no-NaNs flag is set.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
bool isBinaryOp() const
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
iterator_range< user_iterator > users()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isUnaryOp() const
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
An instruction for reading from memory.
Value * getPointerOperand()
Align getAlign() const
Return the alignment of the access that is being performed.
bool isLoopHeader(const BlockT *BB) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1079
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1436
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
This is a utility class that provides an abstraction for the common functionality between Instruction...
Definition Operator.h:33
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
iterator_range< const_block_iterator > blocks() const
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A udiv, sdiv, lshr, or ashr instruction, which can be marked as "exact", indicating that no bits are ...
Definition Operator.h:156
bool isExact() const
Test whether this division is known to be exact, with zero remainder.
Definition Operator.h:175
This class represents the LLVM 'select' instruction.
const Value * getFalseValue() const
const Value * getCondition() const
const Value * getTrueValue() const
This instruction constructs a fixed permutation of two input vectors.
VectorType * getType() const
Overload to return most specific vector type.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:743
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
Class to represent struct types.
unsigned getNumElements() const
Random access to the elements.
Type * getElementType(unsigned N) const
Provides information about what library functions are available for the current target.
LibFunc getLibFunc(StringRef funcName) const
Searches for a particular function name.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI uint64_t getArrayNumElements() const
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
This is a wrapper around stripAndAccumulateConstantOffsets with the in-bounds requirement set to fals...
Definition Value.h:729
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
const KnownBits & getKnownBits(const SimplifyQuery &Q) const
Definition WithCache.h:59
PointerType getValue() const
Definition WithCache.h:57
Represents an op.with.overflow intrinsic.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
An efficient, type-erasing, non-owning reference to a callable.
TypeSize getSequentialElementStride(const DataLayout &DL) const
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
A range adaptor for a pair of iterators.
CallInst * Call
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt ScaleBitMask(const APInt &A, unsigned NewBitWidth, bool MatchAllBits=false)
Splat/Merge neighboring bits to widen/narrow the bitmask represented by.
Definition APInt.cpp:3043
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2290
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
match_bind< PHINode > m_Phi(PHINode *&PN)
Match a PHI node, capturing it if we match.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
PtrToIntSameSize_match< OpTy > m_PtrToIntSameSize(const DataLayout &DL, const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, FCmpInst > m_FCmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_c_UMax(const LHS &L, const RHS &R)
Matches a UMax with LHS and RHS in either order.
cst_pred_ty< is_sign_mask > m_SignMask()
Match an integer or vector with only the sign bit(s) set.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
auto m_PtrToIntOrAddr(const OpTy &Op)
Matches PtrToInt or PtrToAddr.
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
auto m_LogicalOp()
Matches either L && R or L || R where L and R are arbitrary values.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
cst_pred_ty< is_power2_or_zero > m_Power2OrZero()
Match an integer or vector of 0 or power-of-2 values.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_idiv_op > m_IDiv(const LHS &L, const RHS &R)
Matches integer division operations.
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
auto m_UMin(const Opnd0 &Op0, const Opnd1 &Op1)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
auto match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true > m_c_NUWAdd(const LHS &L, const RHS &R)
cstfp_pred_ty< is_finite > m_Finite()
Match a finite FP constant, i.e.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
auto m_SMax(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
ICmpLike_match< LHS, RHS > m_ICmpLike(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
auto m_Ctpop(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
cst_pred_ty< is_strictlypositive > m_StrictlyPositive()
Match an integer or vector of strictly positive values.
auto m_VScale()
Matches a call to llvm.vscale().
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
auto m_Ctlz(const Opnd0 &Op0, const Opnd1 &Op1)
match_combine_or< FMaxMin_match< LHS, RHS, ofmin_pred_ty >, FMaxMin_match< LHS, RHS, ufmin_pred_ty > > m_OrdOrUnordFMin(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point minimum function.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_c_MaxOrMin(const LHS &L, const RHS &R)
cstfp_pred_ty< custom_checkfn< APFloat > > m_CheckedFp(function_ref< bool(const APFloat &)> CheckFn)
Match a float or vector where CheckFn(ele) for each element is true.
auto m_FMinNum(const Opnd0 &Op0, const Opnd1 &Op1)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
auto m_SMin(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_FAbs(const Opnd0 &Op0)
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
match_combine_or< FMaxMin_match< LHS, RHS, ofmax_pred_ty >, FMaxMin_match< LHS, RHS, ufmax_pred_ty > > m_OrdOrUnordFMax(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point maximum function.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
BinOpPred_match< LHS, RHS, is_shift_op > m_Shift(const LHS &L, const RHS &R)
Matches shift operations.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinOpPred_match< LHS, RHS, is_irem_op > m_IRem(const LHS &L, const RHS &R)
Matches integer remainder operations.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
auto m_c_UMin(const LHS &L, const RHS &R)
Matches a UMin with LHS and RHS in either order.
auto m_c_SMax(const LHS &L, const RHS &R)
Matches an SMax with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
auto m_FMaxNum(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_nonpositive > m_NonPositive()
Match an integer or vector of non-positive values.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
auto m_c_SMin(const LHS &L, const RHS &R)
Matches an SMin with LHS and RHS in either order.
ElementWiseBitCast_match< OpTy > m_ElementWiseBitCast(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap > m_NSWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
static unsigned decodeVSEW(unsigned VSEW)
LLVM_ABI unsigned getSEWLMULRatio(unsigned SEW, VLMUL VLMul)
static constexpr unsigned RVVBitsPerBlock
static constexpr unsigned RVVBytesPerBlock
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:677
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool haveNoCommonBitsSet(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return true if LHS and RHS have no common bits set.
LLVM_ABI bool mustExecuteUBIfPoisonOnPathTo(Instruction *Root, Instruction *OnPathTo, DominatorTree *DT)
Return true if undefined behavior would provable be executed on the path to OnPathTo if Root produced...
LLVM_ABI Intrinsic::ID getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID)
LLVM_ABI bool willNotFreeBetween(const Instruction *Assume, const Instruction *CtxI)
Returns true, if no instruction between Assume and CtxI may free (including through synchronization).
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
@ NeverOverflows
Never overflows.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1669
LLVM_ABI bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
LLVM_ABI bool mustTriggerUB(const Instruction *I, const SmallPtrSetImpl< const Value * > &KnownPoison)
Return true if the given instruction must trigger undefined behavior when I is executed with any oper...
LLVM_ABI bool isKnownNeverInfinity(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not an infinity or if the floating-point vector val...
LLVM_ABI void computeKnownBitsFromContext(const Value *V, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Merge bits known from context-dependent facts into Known.
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
BundleAttr getBundleAttrFromOBU(OperandBundleUse OBU)
LLVM_ABI bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI)
LLVM_ABI bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, bool &TrueIfSigned)
Given an exploded icmp instruction, return true if the comparison only checks the sign bit.
NoCommonBitsSetResult
@ Known
Known to have no common set bits.
@ Unknown
Not known to have no common set bits.
@ OnlyIfUndefIgnored
Known to have no common set bits only if undef values are ignored.
LLVM_ABI bool isAssumeLikeIntrinsic(const Instruction *I)
Return true if it is an intrinsic that cannot be speculated but also cannot trap.
LLVM_ABI AllocaInst * findAllocaForValue(Value *V, bool OffsetZero=false)
Returns unique alloca where the value comes from, or nullptr.
LLVM_ABI APInt getMinMaxLimit(SelectPatternFlavor SPF, unsigned BitWidth)
Return the minimum or maximum constant value for the specified integer min/max flavor and type.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool isOnlyUsedInZeroComparison(const Instruction *CxtI)
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
LLVM_ABI bool onlyUsedByLifetimeMarkersOrDroppableInsts(const Value *V)
Return true if the only users of this pointer are lifetime markers or droppable instructions.
LLVM_ABI Constant * ReadByteArrayFromGlobal(const GlobalVariable *GV, uint64_t Offset)
LLVM_ABI Value * stripNullTest(Value *V)
Returns the inner value X if the expression has the form f(X) where f(X) == 0 if and only if X == 0,...
LLVM_ABI bool getUnderlyingObjectsForCodeGen(const Value *V, SmallVectorImpl< Value * > &Objects)
This is a wrapper around getUnderlyingObjects and adds support for basic ptrtoint+arithmetic+inttoptr...
LLVM_ABI std::pair< Intrinsic::ID, bool > canConvertToMinOrMaxIntrinsic(ArrayRef< Value * > VL)
Check if the values in VL are select instructions that can be converted to a min or max (vector) intr...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice, unsigned ElementSize, uint64_t Offset=0)
Returns true if the value V is a pointer into a ConstantDataArray.
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:325
LLVM_ABI bool isGuaranteedToExecuteForEveryIteration(const Instruction *I, const Loop *L)
Return true if this function can prove that the instruction I is executed for every iteration of the ...
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI bool isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(const CallBase *Call, bool MustPreserveOffset)
{launder,strip}.invariant.group returns pointer that aliases its argument, and it only captures point...
LLVM_ABI bool assumeBundleImpliesNonNull(const Value *Val, const Function *Context, OperandBundleUse OBU)
LLVM_ABI bool mustSuppressSpeculation(const LoadInst &LI)
Return true if speculation of the given load must be suppressed to avoid ordering or interfering with...
Definition Loads.cpp:452
@ O1
Optimize quickly without destroying debuggability.
@ O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
gep_type_iterator gep_type_end(const User *GEP)
LLVM_ABI const Value * getArgumentAliasingToReturnedPointer(const CallBase *Call, bool MustPreserveOffset)
This function returns call pointer argument that is considered the same by aliasing rules.
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h:1692
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI CmpInst::Predicate getMinMaxPred(SelectPatternFlavor SPF, bool Ordered=false)
Return the canonical comparison predicate for the specified minimum/maximum flavor.
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI bool canIgnoreSignBitOfZero(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is zero.
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
std::tuple< Value *, FPClassTest, FPClassTest > fcmpImpliesClass(CmpInst::Predicate Pred, const Function &F, Value *LHS, FPClassTest RHSClass, bool LookThroughSrc=true)
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO 's result is used only along the paths control dependen...
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ, bool IsNSW=false)
LLVM_ABI bool getShuffleDemandedElts(int SrcWidth, ArrayRef< int > Mask, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS, bool AllowUndefElts=false)
Transform a shuffle mask's output demanded element mask into demanded element masks for the 2 operand...
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
LLVM_ABI bool isGuard(const User *U)
Returns true iff U has semantics of a guard expressed in a form of call of llvm.experimental....
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
LLVM_ABI SelectPatternFlavor getInverseMinMaxFlavor(SelectPatternFlavor SPF)
Return the inverse minimum/maximum flavor of the specified flavor.
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI void adjustKnownBitsForSelectArm(KnownBits &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
LLVM_ABI bool isKnownNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be negative (i.e.
LLVM_ABI NoCommonBitsSetResult getNoCommonBitsSetResult(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return how strongly LHS and RHS are known to have no common set bits.
LLVM_ABI OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
SelectPatternFlavor
Specific patterns of select instructions we can match.
@ SPF_ABS
Floating point maxnum.
@ SPF_NABS
Absolute value.
@ SPF_FMAXNUM
Floating point minnum.
@ SPF_UMIN
Signed minimum.
@ SPF_UMAX
Signed maximum.
@ SPF_SMAX
Unsigned minimum.
@ SPF_UNKNOWN
@ SPF_FMINNUM
Unsigned maximum.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
LLVM_ABI void getHorizDemandedEltsForFirstOperand(unsigned VectorBitWidth, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS)
Compute the demanded elements mask of horizontal binary operations.
LLVM_ABI SelectPatternResult getSelectPattern(CmpInst::Predicate Pred, SelectPatternNaNBehavior NaNBehavior=SPNB_NA, bool Ordered=false)
Determine the pattern for predicate X Pred Y ? X : Y.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
LLVM_ABI bool matchSimpleBinaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI bool cannotBeNegativeZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is never equal to -0.0.
LLVM_ABI bool programUndefinedIfUndefOrPoison(const Instruction *Inst)
Return true if this function can prove that if Inst is executed and yields a poison value or undef bi...
LLVM_ABI void adjustKnownFPClassForSelectArm(KnownFPClass &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI bool collectPossibleValues(const Value *V, SmallPtrSetImpl< const Constant * > &Constants, unsigned MaxCount, bool AllowUndefOrPoison=true)
Enumerates all possible immediate values of V and inserts them into the set Constants.
LLVM_ABI uint64_t GetStringLength(const Value *V, unsigned CharSize=8)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
LLVM_ABI OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
LLVM_ABI bool canCreateUndefOrPoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
canCreateUndefOrPoison returns true if Op can create undef or poison from non-undef & non-poison oper...
LLVM_ABI bool matchSimpleTernaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp0, Value *&OtherOp1)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
LLVM_ABI bool isKnownInversion(const Value *X, const Value *Y)
Return true iff:
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool intrinsicPropagatesPoison(Intrinsic::ID IID)
Return whether this intrinsic propagates poison for all operands.
LLVM_ABI bool isNotCrossLaneOperation(const Instruction *I)
Return true if the instruction doesn't potentially cross vector lanes.
bool includesPoison(UndefPoisonKind Kind)
Returns true if Kind includes the Poison bit.
Definition UndefPoison.h:27
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr int PoisonMaskElem
LLVM_ABI RetainedKnowledge getKnowledgeValidInContext(const Value *V, ArrayRef< Attribute::AttrKind > AttrKinds, AssumptionCache &AC, const Instruction *CtxI, const DominatorTree *DT=nullptr)
Return a valid Knowledge associated to the Value V if its Attribute kind is in AttrKinds and the know...
LLVM_ABI bool isSafeToSpeculativelyExecuteWithOpcode(unsigned Opcode, const Instruction *Inst, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
This returns the same result as isSafeToSpeculativelyExecute if Opcode is the actual opcode of Inst.
LLVM_ABI bool onlyUsedByLifetimeMarkers(const Value *V)
Return true if the only users of this pointer are lifetime markers.
LLVM_ABI Intrinsic::ID getIntrinsicForCallSite(const CallBase &CB, const TargetLibraryInfo *TLI)
Map a call instruction to an intrinsic ID.
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
LLVM_ABI const Value * getUnderlyingObjectAggressive(const Value *V)
Like getUnderlyingObject(), but will try harder to find a single underlying object.
LLVM_ABI Intrinsic::ID getMinMaxIntrinsic(SelectPatternFlavor SPF)
Convert given SPF to equivalent min/max intrinsic.
LLVM_ABI SelectPatternResult matchDecomposedSelectPattern(CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, FastMathFlags FMF=FastMathFlags(), Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Determine the pattern that a select with the given compare as its predicate and given values as its t...
bool includesUndef(UndefPoisonKind Kind)
Returns true if Kind includes the Undef bit.
Definition UndefPoison.h:33
LLVM_ABI OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
LLVM_ABI bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
@ Add
Sum of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI ConstantRange computeConstantRangeIncludingKnownBits(const WithCache< const Value * > &V, bool ForSigned, const SimplifyQuery &SQ)
Combine constant ranges from computeConstantRange() and computeKnownBits().
SelectPatternNaNBehavior
Behavior when a floating point min/max is given one NaN and one non-NaN as input.
@ SPNB_RETURNS_NAN
NaN behavior not applicable.
@ SPNB_RETURNS_OTHER
Given one NaN input, returns the NaN.
@ SPNB_RETURNS_ANY
Given one NaN input, returns the non-NaN.
LLVM_ABI bool isKnownNonEqual(const Value *V1, const Value *V2, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the given values are known to be non-equal when defined.
DWARFExpression::Operation Op
LLVM_ABI bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const SimplifyQuery &Q, bool IgnoreFree=false)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
Definition Loads.cpp:244
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
constexpr unsigned BitWidth
LLVM_ABI KnownBits analyzeKnownBitsFromAndXorOr(const Operator *I, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &SQ, unsigned Depth=0)
Using KnownBits LHS/RHS produce the known bits for logic op (and/xor/or).
LLVM_ABI OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
LLVM_ABI bool isKnownNeverInfOrNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point value can never contain a NaN or infinity.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
gep_type_iterator gep_type_begin(const User *GEP)
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
LLVM_ABI Value * isBytewiseValue(Value *V, const DataLayout &DL)
If the specified value can be set by repeating the same byte in memory, return the i8 value that it i...
LLVM_ABI std::optional< std::pair< CmpPredicate, Constant * > > getFlippedStrictnessPredicateAndConstant(CmpPredicate Pred, Constant *C)
Convert an integer comparison with a constant RHS into an equivalent form with the strictness flipped...
LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Get the upper bound on bit size for this Value Op as a signed integer.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
LLVM_ABI bool isKnownIntegral(const Value *V, const SimplifyQuery &SQ, FastMathFlags FMF)
Return true if the floating-point value V is known to be an integer value.
LLVM_ABI AssumeAlignInfo getAssumeAlignInfo(OperandBundleUse)
LLVM_ABI OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:197
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
LLVM_ABI std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known)
Compute known bits from the range metadata.
LLVM_ABI Value * FindInsertedValue(Value *V, ArrayRef< unsigned > idx_range, std::optional< BasicBlock::iterator > InsertBefore=std::nullopt)
Given an aggregate and an sequence of indices, see if the scalar value indexed is already around as a...
LLVM_ABI bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false, bool AllowPoison=true)
Return true if the two given values are negation.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI bool isKnownPositive(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
LLVM_ABI Constant * ConstantFoldIntegerCast(Constant *C, Type *DestTy, bool IsSigned, const DataLayout &DL)
Constant fold a zext, sext or trunc, depending on IsSigned and whether the DestTy is wider or narrowe...
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI bool cannotBeOrderedLessThanZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is either NaN or never less than -0....
LLVM_ABI void getUnderlyingObjects(const Value *V, SmallVectorImpl< const Value * > &Objects, const LoopInfo *LI=nullptr, unsigned MaxLookup=MaxLookupSearchDepth)
This method is similar to getUnderlyingObject except that it can look through phi and select instruct...
LLVM_ABI bool mayHaveNonDefUseDependency(const Instruction &I)
Returns true if the result or effects of the given instructions I depend values not reachable through...
LLVM_ABI bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
LLVM_ABI std::optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
LLVM_ABI std::optional< bool > computeKnownFPSignBit(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return false if we can prove that the specified FP value's sign bit is 0.
LLVM_ABI bool canIgnoreSignBitOfNaN(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is NaN.
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
LLVM_ABI void findValuesAffectedByCondition(Value *Cond, bool IsAssume, function_ref< void(Value *)> InsertAffected)
Call InsertAffected on all Values whose known bits / value may be affected by the condition Cond.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
SmallPtrSet< Value *, 4 > AffectedValues
Represents offset+length into a ConstantDataArray.
const ConstantDataArray * Array
ConstantDataArray pointer.
Represent subnormal handling kind for floating point instruction inputs and outputs.
static constexpr DenormalMode getDynamic()
InstrInfoQuery provides an interface to query additional information for instructions like metadata o...
bool isExact(const BinaryOperator *Op) const
MDNode * getMetadata(const Instruction *I, unsigned KindID) const
bool hasNoSignedZeros(const InstT *Op) const
bool hasNoSignedWrap(const InstT *Op) const
bool hasNoUnsignedWrap(const InstT *Op) const
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits sadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.sadd.sat(LHS, RHS)
KnownBits anyextOrTrunc(unsigned BitWidth) const
Return known bits for an "any" extension or truncation of the value we're tracking.
Definition KnownBits.h:190
static LLVM_ABI KnownBits mulhu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from zero-extended multiply-hi.
unsigned countMinSignBits() const
Returns the number of times the sign bit is replicated into the other bits.
Definition KnownBits.h:269
static LLVM_ABI KnownBits smax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smax(LHS, RHS).
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
bool isZero() const
Returns true if value is all zero.
Definition KnownBits.h:78
LLVM_ABI KnownBits blsi() const
Compute known bits for X & -X, which has only the lowest bit set of X set.
void makeNonNegative()
Make this value non-negative.
Definition KnownBits.h:125
static LLVM_ABI KnownBits usub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.usub.sat(LHS, RHS)
unsigned countMinLeadingOnes() const
Returns the minimum number of leading one bits.
Definition KnownBits.h:265
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:256
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits ssub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.ssub.sat(LHS, RHS)
static LLVM_ABI KnownBits urem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for urem(LHS, RHS).
bool isUnknown() const
Returns true if we don't know any bits.
Definition KnownBits.h:64
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:288
LLVM_ABI KnownBits blsmsk() const
Compute known bits for X ^ (X - 1), which has all bits up to and including the lowest set bit of X se...
KnownBits byteSwap() const
Definition KnownBits.h:559
bool hasConflict() const
Returns true if there is conflicting information.
Definition KnownBits.h:51
static LLVM_ABI KnownBits fshl(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshl(LHS, RHS, Amt).
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
void setAllZero()
Make all bits known to be zero and discard any previous information.
Definition KnownBits.h:84
KnownBits reverseBits() const
Definition KnownBits.h:563
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
static LLVM_ABI KnownBits umax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umax(LHS, RHS).
KnownBits zext(unsigned BitWidth) const
Return known bits for a zero extension of the value we're tracking.
Definition KnownBits.h:176
bool isConstant() const
Returns true if we know the value of all bits.
Definition KnownBits.h:54
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
KnownBits unionWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for either this or RHS or both.
Definition KnownBits.h:335
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
bool isNonZero() const
Returns true if this value is known to be non-zero.
Definition KnownBits.h:109
bool isEven() const
Return if the value is known even (the low bit is 0).
Definition KnownBits.h:162
KnownBits extractBits(unsigned NumBits, unsigned BitPosition) const
Return a subset of the known bits from [bitPosition,bitPosition+numBits).
Definition KnownBits.h:239
static LLVM_ABI KnownBits pdep(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pdep(Val, Mask).
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
Definition KnownBits.h:325
unsigned countMinTrailingOnes() const
Returns the minimum number of trailing one bits.
Definition KnownBits.h:259
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
static LLVM_ABI KnownBits fshr(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshr(LHS, RHS, Amt).
static LLVM_ABI KnownBits smin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smin(LHS, RHS).
static LLVM_ABI KnownBits mulhs(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from sign-extended multiply-hi.
static LLVM_ABI KnownBits srem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for srem(LHS, RHS).
static LLVM_ABI KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
Definition KnownBits.h:130
static LLVM_ABI KnownBits computeForAddSub(bool Add, bool NSW, bool NUW, const KnownBits &LHS, const KnownBits &RHS)
Compute known bits resulting from adding LHS and RHS.
Definition KnownBits.cpp:61
static LLVM_ABI KnownBits sdiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for sdiv(LHS, RHS).
static bool haveNoCommonBitsSet(const KnownBits &LHS, const KnownBits &RHS)
Return true if LHS and RHS have no common bits set.
Definition KnownBits.h:340
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static KnownBits sub(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from subtraction of LHS and RHS.
Definition KnownBits.h:376
unsigned countMaxLeadingZeros() const
Returns the maximum number of leading zero bits possible.
Definition KnownBits.h:294
void setAllOnes()
Make all bits known to be one and discard any previous information.
Definition KnownBits.h:90
static LLVM_ABI KnownBits uadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.uadd.sat(LHS, RHS)
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
KnownBits anyext(unsigned BitWidth) const
Return known bits for an "any" extension of the value we're tracking, where we don't know anything ab...
Definition KnownBits.h:171
static LLVM_ABI KnownBits clmul(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for clmul(LHS, RHS).
LLVM_ABI KnownBits abs(bool IntMinIsPoison=false) const
Compute known bits for the absolute value.
static LLVM_ABI std::optional< bool > sgt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGT result.
static LLVM_ABI std::optional< bool > uge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGE result.
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
static LLVM_ABI KnownBits umin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umin(LHS, RHS).
static LLVM_ABI KnownBits pext(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pext(Val, Mask).
KnownBits sextOrTrunc(unsigned BitWidth) const
Return known bits for a sign extension or truncation of the value we're tracking.
Definition KnownBits.h:210
bool isKnownNeverInfOrNaN() const
Return true if it's known this can never be an infinity or nan.
static LLVM_ABI KnownFPClass sin(const KnownFPClass &Src)
Report known values for sin.
static LLVM_ABI KnownFPClass frem(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for frem.
static LLVM_ABI KnownFPClass fdiv_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv x, x.
static constexpr FPClassTest OrderedLessThanZeroMask
void knownNot(FPClassTest RuleOut)
static LLVM_ABI KnownFPClass fmul(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fmul.
static LLVM_ABI KnownFPClass fadd_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd x, x.
static KnownFPClass square(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
static LLVM_ABI KnownFPClass fsub(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fsub.
bool isKnownNeverSubnormal() const
Return true if it's known this can never be a subnormal.
KnownFPClass unionWith(const KnownFPClass &RHS) const
static LLVM_ABI KnownFPClass canonicalize(const KnownFPClass &Src, DenormalMode DenormMode=DenormalMode::getDynamic())
Apply the canonicalize intrinsic to this value.
LLVM_ABI bool isKnownNeverLogicalZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a zero.
static LLVM_ABI KnownFPClass log(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for log/log2/log10.
static LLVM_ABI KnownFPClass atan2(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for atan2.
static LLVM_ABI KnownFPClass atan(const KnownFPClass &Src)
Report known values for atan.
static LLVM_ABI KnownFPClass fdiv(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv.
static LLVM_ABI KnownFPClass roundToIntegral(const KnownFPClass &Src, bool IsTrunc, bool IsMultiUnitFPType)
Propagate known class for rounding intrinsics (trunc, floor, ceil, rint, nearbyint,...
static LLVM_ABI KnownFPClass cos(const KnownFPClass &Src)
Report known values for cos.
static LLVM_ABI KnownFPClass cosh(const KnownFPClass &Src)
Report known values for cosh.
static LLVM_ABI KnownFPClass minMaxLike(const KnownFPClass &LHS, const KnownFPClass &RHS, MinMaxKind Kind, DenormalMode DenormMode=DenormalMode::getDynamic())
bool isUnknown() const
static LLVM_ABI KnownFPClass exp(const KnownFPClass &Src)
Report known values for exp, exp2 and exp10.
static LLVM_ABI KnownFPClass frexp_mant(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for mantissa component of frexp.
static LLVM_ABI KnownFPClass asin(const KnownFPClass &Src)
Report known values for asin.
bool isKnownNeverNaN() const
Return true if it's known this can never be a nan.
bool isKnownNever(FPClassTest Mask) const
Return true if it's known this can never be one of the mask entries.
std::optional< bool > getSignBit() const
std::nullopt if the sign bit is unknown, true if the sign bit is definitely set or false if the sign ...
static LLVM_ABI KnownFPClass fpext(const KnownFPClass &KnownSrc, const fltSemantics &DstTy, const fltSemantics &SrcTy)
Propagate known class for fpext.
FPClassTest getKnownFPClasses() const
Floating-point classes the value could be one of.
static LLVM_ABI KnownFPClass fma(const KnownFPClass &LHS, const KnownFPClass &RHS, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma.
static LLVM_ABI KnownFPClass tan(const KnownFPClass &Src)
Report known values for tan.
static LLVM_ABI KnownFPClass fptrunc(const KnownFPClass &KnownSrc)
Propagate known class for fptrunc.
bool cannotBeOrderedLessThanZero() const
Return true if we can prove that the analyzed floating-point value is either NaN or never less than -...
void signBitMustBeOne()
Assume the sign bit is one.
void signBitMustBeZero()
Assume the sign bit is zero.
static LLVM_ABI KnownFPClass sqrt(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for sqrt.
LLVM_ABI bool isKnownNeverLogicalPosZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a positive zero.
bool isKnownNeverPosInfinity() const
Return true if it's known this can never be +infinity.
static LLVM_ABI KnownFPClass fadd(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd.
LLVM_ABI bool isKnownNeverLogicalNegZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a negative zero.
static LLVM_ABI KnownFPClass bitcast(const fltSemantics &FltSemantics, const KnownBits &Bits)
Report known values for a bitcast into a float with provided semantics.
static LLVM_ABI KnownFPClass fma_square(const KnownFPClass &Squared, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma squared, squared, addend.
static LLVM_ABI KnownFPClass acos(const KnownFPClass &Src)
Report known values for acos.
static LLVM_ABI KnownFPClass frem_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for frem x, x.
static LLVM_ABI KnownFPClass powi(const KnownFPClass &Src, const KnownBits &N)
Propagate known class for powi.
static LLVM_ABI KnownFPClass pow(const KnownFPClass &LHS, const KnownFPClass &RHS)
Propagate known class for pow.
static LLVM_ABI KnownFPClass ldexp(const KnownFPClass &Src, const APInt &ConstantRangeMin, const APInt &ConstantRangeMax, const fltSemantics &Flt, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for ldexp, assuming the exponent is known to be within [ConstantRangeMin,...
static LLVM_ABI KnownFPClass sinh(const KnownFPClass &Src)
Report known values for sinh.
static LLVM_ABI KnownFPClass tanh(const KnownFPClass &Src)
Report known values for tanh.
SelectPatternFlavor Flavor
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?
const DataLayout & DL
SimplifyQuery getWithoutCondContext() const
const Instruction * CxtI
const DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
const DomConditionCache * DC
const InstrInfoQuery IIQ
const CondContext * CC
fltNanEncoding nanEncoding
Definition APFloat.h:1041