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::FPTrunc:
1518 case Instruction::FPExt:
1519 case Instruction::FPToUI:
1520 case Instruction::FPToSI:
1521 case Instruction::SIToFP:
1522 case Instruction::UIToFP:
1523 break; // Can't work with floating point.
1524 case Instruction::PtrToInt:
1525 case Instruction::PtrToAddr:
1526 case Instruction::IntToPtr:
1527 // Fall through and handle them the same as zext/trunc.
1528 [[fallthrough]];
1529 case Instruction::ZExt:
1530 case Instruction::Trunc: {
1531 Type *SrcTy = I->getOperand(0)->getType();
1532
1533 unsigned SrcBitWidth;
1534 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1535 // which fall through here.
1536 Type *ScalarTy = SrcTy->getScalarType();
1537 SrcBitWidth = ScalarTy->isPointerTy() ?
1538 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
1539 Q.DL.getTypeSizeInBits(ScalarTy);
1540
1541 assert(SrcBitWidth && "SrcBitWidth can't be zero");
1542 Known = Known.anyextOrTrunc(SrcBitWidth);
1543 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1544 if (auto *Inst = dyn_cast<PossiblyNonNegInst>(I);
1545 Inst && Inst->hasNonNeg() && !Known.isNegative())
1546 Known.makeNonNegative();
1547 Known = Known.zextOrTrunc(BitWidth);
1548 break;
1549 }
1550 case Instruction::BitCast: {
1551 Type *SrcTy = I->getOperand(0)->getType();
1552 if (SrcTy->isIntOrPtrTy() &&
1553 // TODO: For now, not handling conversions like:
1554 // (bitcast i64 %x to <2 x i32>)
1555 !I->getType()->isVectorTy()) {
1556 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1557 break;
1558 }
1559
1560 const Value *V;
1561 // Handle bitcast from floating point to integer.
1562 if (match(I, m_ElementWiseBitCast(m_Value(V))) &&
1563 V->getType()->isFPOrFPVectorTy()) {
1564 Type *FPType = V->getType()->getScalarType();
1565 KnownFPClass Result =
1566 computeKnownFPClass(V, DemandedElts, fcAllFlags, Q, Depth + 1);
1567
1568 Known = Result.toKnownBits(FPType->getFltSemantics());
1569
1570 break;
1571 }
1572
1573 // Handle cast from vector integer type to scalar or vector integer.
1574 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcTy);
1575 if (!SrcVecTy || !SrcVecTy->getElementType()->isIntegerTy() ||
1576 !I->getType()->isIntOrIntVectorTy() ||
1577 isa<ScalableVectorType>(I->getType()))
1578 break;
1579
1580 unsigned NumElts = DemandedElts.getBitWidth();
1581 bool IsLE = Q.DL.isLittleEndian();
1582 // Look through a cast from narrow vector elements to wider type.
1583 // Examples: v4i32 -> v2i64, v3i8 -> v24
1584 unsigned SubBitWidth = SrcVecTy->getScalarSizeInBits();
1585 if (BitWidth % SubBitWidth == 0) {
1586 // Known bits are automatically intersected across demanded elements of a
1587 // vector. So for example, if a bit is computed as known zero, it must be
1588 // zero across all demanded elements of the vector.
1589 //
1590 // For this bitcast, each demanded element of the output is sub-divided
1591 // across a set of smaller vector elements in the source vector. To get
1592 // the known bits for an entire element of the output, compute the known
1593 // bits for each sub-element sequentially. This is done by shifting the
1594 // one-set-bit demanded elements parameter across the sub-elements for
1595 // consecutive calls to computeKnownBits. We are using the demanded
1596 // elements parameter as a mask operator.
1597 //
1598 // The known bits of each sub-element are then inserted into place
1599 // (dependent on endian) to form the full result of known bits.
1600 unsigned SubScale = BitWidth / SubBitWidth;
1601 APInt SubDemandedElts = APInt::getZero(NumElts * SubScale);
1602 for (unsigned i = 0; i != NumElts; ++i) {
1603 if (DemandedElts[i])
1604 SubDemandedElts.setBit(i * SubScale);
1605 }
1606
1607 KnownBits KnownSrc(SubBitWidth);
1608 for (unsigned i = 0; i != SubScale; ++i) {
1609 computeKnownBits(I->getOperand(0), SubDemandedElts.shl(i), KnownSrc, Q,
1610 Depth + 1);
1611 unsigned ShiftElt = IsLE ? i : SubScale - 1 - i;
1612 Known.insertBits(KnownSrc, ShiftElt * SubBitWidth);
1613 }
1614 }
1615 // Look through a cast from wider vector elements to narrow type.
1616 // Examples: v2i64 -> v4i32
1617 if (SubBitWidth % BitWidth == 0) {
1618 unsigned SubScale = SubBitWidth / BitWidth;
1619 KnownBits KnownSrc(SubBitWidth);
1620 APInt SubDemandedElts =
1621 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
1622 computeKnownBits(I->getOperand(0), SubDemandedElts, KnownSrc, Q,
1623 Depth + 1);
1624
1625 Known.setAllConflict();
1626 for (unsigned i = 0; i != NumElts; ++i) {
1627 if (DemandedElts[i]) {
1628 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
1629 unsigned Offset = (Shifts % SubScale) * BitWidth;
1630 Known = Known.intersectWith(KnownSrc.extractBits(BitWidth, Offset));
1631 if (Known.isUnknown())
1632 break;
1633 }
1634 }
1635 }
1636 break;
1637 }
1638 case Instruction::SExt: {
1639 // Compute the bits in the result that are not present in the input.
1640 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1641
1642 Known = Known.trunc(SrcBitWidth);
1643 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1644 // If the sign bit of the input is known set or clear, then we know the
1645 // top bits of the result.
1646 Known = Known.sext(BitWidth);
1647 break;
1648 }
1649 case Instruction::Shl: {
1652 auto KF = [NUW, NSW](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1653 bool ShAmtNonZero) {
1654 return KnownBits::shl(KnownVal, KnownAmt, NUW, NSW, ShAmtNonZero);
1655 };
1656 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1657 KF);
1658 // Trailing zeros of a right-shifted constant never decrease.
1659 const APInt *C;
1660 if (match(I->getOperand(0), m_APInt(C)))
1661 Known.Zero.setLowBits(C->countr_zero());
1662
1663 // shl X, sub(Y, xor(ctlz(X, true), BitWidth-1)) shifts X so that its MSB
1664 // lands at bit Y, when BitWidth is a power of 2.
1665 const APInt *YC;
1666 Value *X = I->getOperand(0);
1667 if (isPowerOf2_32(BitWidth) &&
1668 match(I->getOperand(1),
1670 m_SpecificInt(BitWidth - 1)))) &&
1671 YC->ult(BitWidth - 1)) {
1672 unsigned Y = YC->getZExtValue();
1673 Known.One.setBit(Y);
1674 Known.Zero.setBitsFrom(Y + 1);
1675 }
1676 break;
1677 }
1678 case Instruction::LShr: {
1679 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1680 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1681 bool ShAmtNonZero) {
1682 return KnownBits::lshr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1683 };
1684 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1685 KF);
1686 // Leading zeros of a left-shifted constant never decrease.
1687 const APInt *C;
1688 if (match(I->getOperand(0), m_APInt(C)))
1689 Known.Zero.setHighBits(C->countl_zero());
1690 break;
1691 }
1692 case Instruction::AShr: {
1693 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1694 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1695 bool ShAmtNonZero) {
1696 return KnownBits::ashr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1697 };
1698 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1699 KF);
1700 break;
1701 }
1702 case Instruction::Sub: {
1705 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW, NUW,
1706 DemandedElts, Known, Known2, Q, Depth);
1707 break;
1708 }
1709 case Instruction::Add: {
1712 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW, NUW,
1713 DemandedElts, Known, Known2, Q, Depth);
1714 break;
1715 }
1716 case Instruction::SRem:
1717 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1718 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1719 Known = KnownBits::srem(Known, Known2);
1720 break;
1721
1722 case Instruction::URem:
1723 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1724 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1725 Known = KnownBits::urem(Known, Known2);
1726 break;
1727 case Instruction::Alloca:
1728 Known.Zero.setLowBits(Log2(cast<AllocaInst>(I)->getAlign()));
1729 break;
1730 case Instruction::GetElementPtr: {
1731 // Analyze all of the subscripts of this getelementptr instruction
1732 // to determine if we can prove known low zero bits.
1733 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1734 // Accumulate the constant indices in a separate variable
1735 // to minimize the number of calls to computeForAddSub.
1736 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(I->getType());
1737 APInt AccConstIndices(IndexWidth, 0);
1738
1739 auto AddIndexToKnown = [&](KnownBits IndexBits) {
1740 if (IndexWidth == BitWidth) {
1741 // Note that inbounds does *not* guarantee nsw for the addition, as only
1742 // the offset is signed, while the base address is unsigned.
1743 Known = KnownBits::add(Known, IndexBits);
1744 } else {
1745 // If the index width is smaller than the pointer width, only add the
1746 // value to the low bits.
1747 assert(IndexWidth < BitWidth &&
1748 "Index width can't be larger than pointer width");
1749 Known.insertBits(KnownBits::add(Known.trunc(IndexWidth), IndexBits), 0);
1750 }
1751 };
1752
1754 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1755 // TrailZ can only become smaller, short-circuit if we hit zero.
1756 if (Known.isUnknown())
1757 break;
1758
1759 Value *Index = I->getOperand(i);
1760
1761 // Handle case when index is zero.
1762 Constant *CIndex = dyn_cast<Constant>(Index);
1763 if (CIndex && CIndex->isNullValue())
1764 continue;
1765
1766 if (StructType *STy = GTI.getStructTypeOrNull()) {
1767 // Handle struct member offset arithmetic.
1768
1769 assert(CIndex &&
1770 "Access to structure field must be known at compile time");
1771
1772 if (CIndex->getType()->isVectorTy())
1773 Index = CIndex->getSplatValue();
1774
1775 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1776 const StructLayout *SL = Q.DL.getStructLayout(STy);
1777 uint64_t Offset = SL->getElementOffset(Idx);
1778 AccConstIndices += Offset;
1779 continue;
1780 }
1781
1782 // Handle array index arithmetic.
1783 Type *IndexedTy = GTI.getIndexedType();
1784 if (!IndexedTy->isSized()) {
1785 Known.resetAll();
1786 break;
1787 }
1788
1789 TypeSize Stride = GTI.getSequentialElementStride(Q.DL);
1790 uint64_t StrideInBytes = Stride.getKnownMinValue();
1791 if (!Stride.isScalable()) {
1792 // Fast path for constant offset.
1793 if (auto *CI = dyn_cast<ConstantInt>(Index)) {
1794 AccConstIndices +=
1795 CI->getValue().sextOrTrunc(IndexWidth) * StrideInBytes;
1796 continue;
1797 }
1798 }
1799
1800 KnownBits IndexBits =
1801 computeKnownBits(Index, Q, Depth + 1).sextOrTrunc(IndexWidth);
1802 KnownBits ScalingFactor(IndexWidth);
1803 // Multiply by current sizeof type.
1804 // &A[i] == A + i * sizeof(*A[i]).
1805 if (Stride.isScalable()) {
1806 // For scalable types the only thing we know about sizeof is
1807 // that this is a multiple of the minimum size.
1808 ScalingFactor.Zero.setLowBits(llvm::countr_zero(StrideInBytes));
1809 } else {
1810 ScalingFactor =
1811 KnownBits::makeConstant(APInt(IndexWidth, StrideInBytes));
1812 }
1813 AddIndexToKnown(KnownBits::mul(IndexBits, ScalingFactor));
1814 }
1815 if (!Known.isUnknown() && !AccConstIndices.isZero())
1816 AddIndexToKnown(KnownBits::makeConstant(AccConstIndices));
1817 break;
1818 }
1819 case Instruction::PHI: {
1820 const PHINode *P = cast<PHINode>(I);
1821 BinaryOperator *BO = nullptr;
1822 Value *R = nullptr, *L = nullptr;
1823 if (matchSimpleRecurrence(P, BO, R, L)) {
1824 // Handle the case of a simple two-predecessor recurrence PHI.
1825 // There's a lot more that could theoretically be done here, but
1826 // this is sufficient to catch some interesting cases.
1827 unsigned Opcode = BO->getOpcode();
1828
1829 switch (Opcode) {
1830 // If this is a shift recurrence, we know the bits being shifted in. We
1831 // can combine that with information about the start value of the
1832 // recurrence to conclude facts about the result. If this is a udiv
1833 // recurrence, we know that the result can never exceed either the
1834 // numerator or the start value, whichever is greater.
1835 case Instruction::LShr:
1836 case Instruction::AShr:
1837 case Instruction::Shl:
1838 case Instruction::UDiv:
1839 if (BO->getOperand(0) != I)
1840 break;
1841 [[fallthrough]];
1842
1843 // For a urem recurrence, the result can never exceed the start value. The
1844 // phi could either be the numerator or the denominator.
1845 case Instruction::URem: {
1846 // We have matched a recurrence of the form:
1847 // %iv = [R, %entry], [%iv.next, %backedge]
1848 // %iv.next = shift_op %iv, L
1849
1850 // Recurse with the phi context to avoid concern about whether facts
1851 // inferred hold at original context instruction. TODO: It may be
1852 // correct to use the original context. IF warranted, explore and
1853 // add sufficient tests to cover.
1855 RecQ.CxtI = P;
1856 computeKnownBits(R, DemandedElts, Known2, RecQ, Depth + 1);
1857 switch (Opcode) {
1858 case Instruction::Shl:
1859 // A shl recurrence will only increase the tailing zeros
1860 Known.Zero.setLowBits(Known2.countMinTrailingZeros());
1861 break;
1862 case Instruction::LShr:
1863 case Instruction::UDiv:
1864 case Instruction::URem:
1865 // lshr, udiv, and urem recurrences will preserve the leading zeros of
1866 // the start value.
1867 Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1868 break;
1869 case Instruction::AShr:
1870 // An ashr recurrence will extend the initial sign bit
1871 Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1872 Known.One.setHighBits(Known2.countMinLeadingOnes());
1873 break;
1874 }
1875 break;
1876 }
1877
1878 // Check for operations that have the property that if
1879 // both their operands have low zero bits, the result
1880 // will have low zero bits.
1881 case Instruction::Add:
1882 case Instruction::Sub:
1883 case Instruction::And:
1884 case Instruction::Or:
1885 case Instruction::Mul: {
1886 // Change the context instruction to the "edge" that flows into the
1887 // phi. This is important because that is where the value is actually
1888 // "evaluated" even though it is used later somewhere else. (see also
1889 // D69571).
1891
1892 unsigned OpNum = P->getOperand(0) == R ? 0 : 1;
1893 Instruction *RInst = P->getIncomingBlock(OpNum)->getTerminator();
1894 Instruction *LInst = P->getIncomingBlock(1 - OpNum)->getTerminator();
1895
1896 // Ok, we have a PHI of the form L op= R. Check for low
1897 // zero bits.
1898 RecQ.CxtI = RInst;
1899 computeKnownBits(R, DemandedElts, Known2, RecQ, Depth + 1);
1900
1901 // We need to take the minimum number of known bits
1902 KnownBits Known3(BitWidth);
1903 RecQ.CxtI = LInst;
1904 computeKnownBits(L, DemandedElts, Known3, RecQ, Depth + 1);
1905
1906 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1907 Known3.countMinTrailingZeros()));
1908
1909 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO);
1910 if (!OverflowOp || !Q.IIQ.hasNoSignedWrap(OverflowOp))
1911 break;
1912
1913 switch (Opcode) {
1914 // If initial value of recurrence is nonnegative, and we are adding
1915 // a nonnegative number with nsw, the result can only be nonnegative
1916 // or poison value regardless of the number of times we execute the
1917 // add in phi recurrence. If initial value is negative and we are
1918 // adding a negative number with nsw, the result can only be
1919 // negative or poison value. Similar arguments apply to sub and mul.
1920 //
1921 // (add non-negative, non-negative) --> non-negative
1922 // (add negative, negative) --> negative
1923 case Instruction::Add: {
1924 if (Known2.isNonNegative() && Known3.isNonNegative())
1925 Known.makeNonNegative();
1926 else if (Known2.isNegative() && Known3.isNegative())
1927 Known.makeNegative();
1928 break;
1929 }
1930
1931 // (sub nsw non-negative, negative) --> non-negative
1932 // (sub nsw negative, non-negative) --> negative
1933 case Instruction::Sub: {
1934 if (BO->getOperand(0) != I)
1935 break;
1936 if (Known2.isNonNegative() && Known3.isNegative())
1937 Known.makeNonNegative();
1938 else if (Known2.isNegative() && Known3.isNonNegative())
1939 Known.makeNegative();
1940 break;
1941 }
1942
1943 // (mul nsw non-negative, non-negative) --> non-negative
1944 case Instruction::Mul:
1945 if (Known2.isNonNegative() && Known3.isNonNegative())
1946 Known.makeNonNegative();
1947 break;
1948
1949 default:
1950 break;
1951 }
1952 break;
1953 }
1954
1955 default:
1956 break;
1957 }
1958 }
1959
1960 // Unreachable blocks may have zero-operand PHI nodes.
1961 if (P->getNumIncomingValues() == 0)
1962 break;
1963
1964 // Otherwise take the unions of the known bit sets of the operands,
1965 // taking conservative care to avoid excessive recursion.
1966 if (Depth < MaxAnalysisRecursionDepth - 1 && Known.isUnknown()) {
1967 // Skip if every incoming value references to ourself.
1968 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
1969 break;
1970
1971 Known.setAllConflict();
1972 for (const Use &U : P->operands()) {
1973 Value *IncValue;
1974 const PHINode *CxtPhi;
1975 Instruction *CxtI;
1976 breakSelfRecursivePHI(&U, P, IncValue, CxtI, &CxtPhi);
1977 // Skip direct self references.
1978 if (IncValue == P)
1979 continue;
1980
1981 // Change the context instruction to the "edge" that flows into the
1982 // phi. This is important because that is where the value is actually
1983 // "evaluated" even though it is used later somewhere else. (see also
1984 // D69571).
1986
1987 Known2 = KnownBits(BitWidth);
1988
1989 // Recurse, but cap the recursion to one level, because we don't
1990 // want to waste time spinning around in loops.
1991 // TODO: See if we can base recursion limiter on number of incoming phi
1992 // edges so we don't overly clamp analysis.
1993 computeKnownBits(IncValue, DemandedElts, Known2, RecQ,
1995
1996 // See if we can further use a conditional branch into the phi
1997 // to help us determine the range of the value.
1998 if (!Known2.isConstant()) {
1999 CmpPredicate Pred;
2000 const APInt *RHSC;
2001 BasicBlock *TrueSucc, *FalseSucc;
2002 // TODO: Use RHS Value and compute range from its known bits.
2003 if (match(RecQ.CxtI,
2004 m_Br(m_c_ICmp(Pred, m_Specific(IncValue), m_APInt(RHSC)),
2005 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
2006 // Check for cases of duplicate successors.
2007 if ((TrueSucc == CxtPhi->getParent()) !=
2008 (FalseSucc == CxtPhi->getParent())) {
2009 // If we're using the false successor, invert the predicate.
2010 if (FalseSucc == CxtPhi->getParent())
2011 Pred = CmpInst::getInversePredicate(Pred);
2012 // Get the knownbits implied by the incoming phi condition.
2013 auto CR = ConstantRange::makeExactICmpRegion(Pred, *RHSC);
2014 KnownBits KnownUnion = Known2.unionWith(CR.toKnownBits());
2015 // We can have conflicts here if we are analyzing deadcode (its
2016 // impossible for us reach this BB based the icmp).
2017 if (KnownUnion.hasConflict()) {
2018 // No reason to continue analyzing in a known dead region, so
2019 // just resetAll and break. This will cause us to also exit the
2020 // outer loop.
2021 Known.resetAll();
2022 break;
2023 }
2024 Known2 = KnownUnion;
2025 }
2026 }
2027 }
2028
2029 Known = Known.intersectWith(Known2);
2030 // If all bits have been ruled out, there's no need to check
2031 // more operands.
2032 if (Known.isUnknown())
2033 break;
2034 }
2035 }
2036 break;
2037 }
2038 case Instruction::Call:
2039 case Instruction::Invoke: {
2040 // If range metadata is attached to this call, set known bits from that,
2041 // and then intersect with known bits based on other properties of the
2042 // function.
2043 if (MDNode *MD =
2044 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
2046
2047 const auto *CB = cast<CallBase>(I);
2048
2049 if (std::optional<ConstantRange> Range = CB->getRange())
2050 Known = Known.unionWith(Range->toKnownBits());
2051
2052 if (const Value *RV = CB->getReturnedArgOperand()) {
2053 if (RV->getType() == I->getType()) {
2054 computeKnownBits(RV, Known2, Q, Depth + 1);
2055 Known = Known.unionWith(Known2);
2056 // If the function doesn't return properly for all input values
2057 // (e.g. unreachable exits) then there might be conflicts between the
2058 // argument value and the range metadata. Simply discard the known bits
2059 // in case of conflicts.
2060 if (Known.hasConflict())
2061 Known.resetAll();
2062 }
2063 }
2064 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2065 switch (II->getIntrinsicID()) {
2066 default:
2067 break;
2068 case Intrinsic::abs: {
2069 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2070 bool IntMinIsPoison = match(II->getArgOperand(1), m_One());
2071 Known = Known.unionWith(Known2.abs(IntMinIsPoison));
2072 break;
2073 }
2074 case Intrinsic::bitreverse:
2075 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2076 Known = Known.unionWith(Known2.reverseBits());
2077 break;
2078 case Intrinsic::bswap:
2079 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2080 Known = Known.unionWith(Known2.byteSwap());
2081 break;
2082 case Intrinsic::ctlz: {
2083 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2084 // If we have a known 1, its position is our upper bound.
2085 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2086 // If this call is poison for 0 input, the result will be less than 2^n.
2087 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2088 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
2089 unsigned LowBits = llvm::bit_width(PossibleLZ);
2090 Known.Zero.setBitsFrom(LowBits);
2091 break;
2092 }
2093 case Intrinsic::cttz: {
2094 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2095 // If we have a known 1, its position is our upper bound.
2096 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2097 // If this call is poison for 0 input, the result will be less than 2^n.
2098 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2099 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
2100 unsigned LowBits = llvm::bit_width(PossibleTZ);
2101 Known.Zero.setBitsFrom(LowBits);
2102 break;
2103 }
2104 case Intrinsic::ctpop: {
2105 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2106 // We can bound the space the count needs. Also, bits known to be zero
2107 // can't contribute to the population.
2108 unsigned BitsPossiblySet = Known2.countMaxPopulation();
2109 unsigned LowBits = llvm::bit_width(BitsPossiblySet);
2110 Known.Zero.setBitsFrom(LowBits);
2111 // TODO: we could bound KnownOne using the lower bound on the number
2112 // of bits which might be set provided by popcnt KnownOne2.
2113 break;
2114 }
2115 case Intrinsic::fshr:
2116 case Intrinsic::fshl: {
2117 const APInt *SA;
2118 if (!match(I->getOperand(2), m_APInt(SA)))
2119 break;
2120
2121 KnownBits Known3(BitWidth);
2122 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2123 computeKnownBits(I->getOperand(1), DemandedElts, Known3, Q, Depth + 1);
2124 Known = II->getIntrinsicID() == Intrinsic::fshl
2125 ? KnownBits::fshl(Known2, Known3, *SA)
2126 : KnownBits::fshr(Known2, Known3, *SA);
2127 break;
2128 }
2129 case Intrinsic::clmul:
2130 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2131 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2132 Known = KnownBits::clmul(Known, Known2);
2133 break;
2134 case Intrinsic::pext:
2135 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2136 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2137 Known = KnownBits::pext(Known, Known2);
2138 break;
2139 case Intrinsic::pdep:
2140 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2141 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2142 Known = KnownBits::pdep(Known, Known2);
2143 break;
2144 case Intrinsic::uadd_sat:
2145 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2146 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2147 Known = KnownBits::uadd_sat(Known, Known2);
2148 break;
2149 case Intrinsic::usub_sat:
2150 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2151 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2152 Known = KnownBits::usub_sat(Known, Known2);
2153 break;
2154 case Intrinsic::sadd_sat:
2155 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2156 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2157 Known = KnownBits::sadd_sat(Known, Known2);
2158 break;
2159 case Intrinsic::ssub_sat:
2160 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2161 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2162 Known = KnownBits::ssub_sat(Known, Known2);
2163 break;
2164 // Vec reverse preserves bits from input vec.
2165 case Intrinsic::vector_reverse:
2166 computeKnownBits(I->getOperand(0), DemandedElts.reverseBits(), Known, Q,
2167 Depth + 1);
2168 break;
2169 // for min/max/and/or reduce, any bit common to each element in the
2170 // input vec is set in the output.
2171 case Intrinsic::vector_reduce_and:
2172 case Intrinsic::vector_reduce_or:
2173 case Intrinsic::vector_reduce_umax:
2174 case Intrinsic::vector_reduce_umin:
2175 case Intrinsic::vector_reduce_smax:
2176 case Intrinsic::vector_reduce_smin:
2177 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2178 break;
2179 case Intrinsic::vector_reduce_xor: {
2180 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2181 // The zeros common to all vecs are zero in the output.
2182 // If the number of elements is odd, then the common ones remain. If the
2183 // number of elements is even, then the common ones becomes zeros.
2184 auto *VecTy = cast<VectorType>(I->getOperand(0)->getType());
2185 // Even, so the ones become zeros.
2186 bool EvenCnt = VecTy->getElementCount().isKnownEven();
2187 if (EvenCnt)
2188 Known.Zero |= Known.One;
2189 // Maybe even element count so need to clear ones.
2190 if (VecTy->isScalableTy() || EvenCnt)
2191 Known.One.clearAllBits();
2192 break;
2193 }
2194 case Intrinsic::vector_reduce_add: {
2195 auto *VecTy = dyn_cast<FixedVectorType>(I->getOperand(0)->getType());
2196 if (!VecTy)
2197 break;
2198 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2199 Known = Known.reduceAdd(VecTy->getNumElements());
2200 break;
2201 }
2202 case Intrinsic::umin:
2203 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2204 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2205 Known = KnownBits::umin(Known, Known2);
2206 break;
2207 case Intrinsic::umax:
2208 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2209 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2210 Known = KnownBits::umax(Known, Known2);
2211 break;
2212 case Intrinsic::smin:
2213 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2214 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2215 Known = KnownBits::smin(Known, Known2);
2217 break;
2218 case Intrinsic::smax:
2219 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2220 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2221 Known = KnownBits::smax(Known, Known2);
2223 break;
2224 case Intrinsic::ptrmask: {
2225 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2226
2227 const Value *Mask = I->getOperand(1);
2228 Known2 = KnownBits(Mask->getType()->getScalarSizeInBits());
2229 computeKnownBits(Mask, DemandedElts, Known2, Q, Depth + 1);
2230 // TODO: 1-extend would be more precise.
2231 Known &= Known2.anyextOrTrunc(BitWidth);
2232 break;
2233 }
2234 case Intrinsic::x86_sse2_pmulh_w:
2235 case Intrinsic::x86_avx2_pmulh_w:
2236 case Intrinsic::x86_avx512_pmulh_w_512:
2237 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2238 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2239 Known = KnownBits::mulhs(Known, Known2);
2240 break;
2241 case Intrinsic::x86_sse2_pmulhu_w:
2242 case Intrinsic::x86_avx2_pmulhu_w:
2243 case Intrinsic::x86_avx512_pmulhu_w_512:
2244 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2245 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2246 Known = KnownBits::mulhu(Known, Known2);
2247 break;
2248 case Intrinsic::x86_sse42_crc32_64_64:
2249 Known.Zero.setBitsFrom(32);
2250 break;
2251 case Intrinsic::x86_ssse3_phadd_d_128:
2252 case Intrinsic::x86_ssse3_phadd_w_128:
2253 case Intrinsic::x86_avx2_phadd_d:
2254 case Intrinsic::x86_avx2_phadd_w: {
2256 I, DemandedElts, Q, Depth,
2257 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2258 return KnownBits::add(KnownLHS, KnownRHS);
2259 });
2260 break;
2261 }
2262 case Intrinsic::x86_ssse3_phadd_sw_128:
2263 case Intrinsic::x86_avx2_phadd_sw: {
2265 I, DemandedElts, Q, Depth, KnownBits::sadd_sat);
2266 break;
2267 }
2268 case Intrinsic::x86_ssse3_phsub_d_128:
2269 case Intrinsic::x86_ssse3_phsub_w_128:
2270 case Intrinsic::x86_avx2_phsub_d:
2271 case Intrinsic::x86_avx2_phsub_w: {
2273 I, DemandedElts, Q, Depth,
2274 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2275 return KnownBits::sub(KnownLHS, KnownRHS);
2276 });
2277 break;
2278 }
2279 case Intrinsic::x86_ssse3_phsub_sw_128:
2280 case Intrinsic::x86_avx2_phsub_sw: {
2282 I, DemandedElts, Q, Depth, KnownBits::ssub_sat);
2283 break;
2284 }
2285 case Intrinsic::riscv_vsetvli:
2286 case Intrinsic::riscv_vsetvlimax: {
2287 bool HasAVL = II->getIntrinsicID() == Intrinsic::riscv_vsetvli;
2288 const ConstantRange Range = getVScaleRange(II->getFunction(), BitWidth);
2290 cast<ConstantInt>(II->getArgOperand(HasAVL))->getZExtValue());
2291 RISCVVType::VLMUL VLMUL = static_cast<RISCVVType::VLMUL>(
2292 cast<ConstantInt>(II->getArgOperand(1 + HasAVL))->getZExtValue());
2293 uint64_t MaxVLEN =
2294 Range.getUnsignedMax().getZExtValue() * RISCV::RVVBitsPerBlock;
2295 uint64_t MaxVL = MaxVLEN / RISCVVType::getSEWLMULRatio(SEW, VLMUL);
2296
2297 // Result of vsetvli must be not larger than AVL.
2298 if (HasAVL)
2299 if (auto *CI = dyn_cast<ConstantInt>(II->getArgOperand(0)))
2300 MaxVL = std::min(MaxVL, CI->getZExtValue());
2301
2302 unsigned KnownZeroFirstBit = Log2_32(MaxVL) + 1;
2303 if (BitWidth > KnownZeroFirstBit)
2304 Known.Zero.setBitsFrom(KnownZeroFirstBit);
2305 break;
2306 }
2307 case Intrinsic::amdgcn_mbcnt_hi:
2308 case Intrinsic::amdgcn_mbcnt_lo: {
2309 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
2310 // most 31 + src1.
2311 Known.Zero.setBitsFrom(
2312 II->getIntrinsicID() == Intrinsic::amdgcn_mbcnt_lo ? 6 : 5);
2313 computeKnownBits(I->getOperand(1), Known2, Q, Depth + 1);
2314 Known = KnownBits::add(Known, Known2);
2315 break;
2316 }
2317 case Intrinsic::vscale: {
2318 if (!II->getParent() || !II->getFunction())
2319 break;
2320
2321 Known = getVScaleRange(II->getFunction(), BitWidth).toKnownBits();
2322 break;
2323 }
2324 case Intrinsic::stepvector: {
2325 auto *VecTy = cast<VectorType>(II->getType());
2326 unsigned MinNumElts = VecTy->getElementCount().getKnownMinValue();
2327 if (!isUIntN(BitWidth, MinNumElts))
2328 break;
2329
2330 bool Overflow = false;
2331 APInt MaxNumElts(BitWidth, MinNumElts);
2332 if (VecTy->isScalableTy()) {
2333 if (!II->getParent() || !II->getFunction())
2334 break;
2335 MaxNumElts = getVScaleRange(II->getFunction(), BitWidth)
2337 .umul_ov(MaxNumElts, Overflow);
2338 }
2339
2340 // Give up if the lane count could wrap. Stepvector truncates lane
2341 // indices that do not fit in the element type.
2342 if (Overflow)
2343 break;
2344
2345 Known.Zero.setHighBits((MaxNumElts - 1).countl_zero());
2346 break;
2347 }
2348 }
2349 }
2350 break;
2351 }
2352 case Instruction::ShuffleVector: {
2353 if (auto *Splat = getSplatValue(I)) {
2355 break;
2356 }
2357
2358 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
2359 // FIXME: Do we need to handle ConstantExpr involving shufflevectors?
2360 if (!Shuf) {
2361 Known.resetAll();
2362 return;
2363 }
2364 // For undef elements, we don't know anything about the common state of
2365 // the shuffle result.
2366 APInt DemandedLHS, DemandedRHS;
2367 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) {
2368 Known.resetAll();
2369 return;
2370 }
2371 Known.setAllConflict();
2372 if (!!DemandedLHS) {
2373 const Value *LHS = Shuf->getOperand(0);
2374 computeKnownBits(LHS, DemandedLHS, Known, Q, Depth + 1);
2375 // If we don't know any bits, early out.
2376 if (Known.isUnknown())
2377 break;
2378 }
2379 if (!!DemandedRHS) {
2380 const Value *RHS = Shuf->getOperand(1);
2381 computeKnownBits(RHS, DemandedRHS, Known2, Q, Depth + 1);
2382 Known = Known.intersectWith(Known2);
2383 }
2384 break;
2385 }
2386 case Instruction::InsertElement: {
2387 if (isa<ScalableVectorType>(I->getType())) {
2388 Known.resetAll();
2389 return;
2390 }
2391 const Value *Vec = I->getOperand(0);
2392 const Value *Elt = I->getOperand(1);
2393 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
2394 unsigned NumElts = DemandedElts.getBitWidth();
2395 APInt DemandedVecElts = DemandedElts;
2396 bool NeedsElt = true;
2397 // If we know the index we are inserting too, clear it from Vec check.
2398 if (CIdx && CIdx->getValue().ult(NumElts)) {
2399 DemandedVecElts.clearBit(CIdx->getZExtValue());
2400 NeedsElt = DemandedElts[CIdx->getZExtValue()];
2401 }
2402
2403 Known.setAllConflict();
2404 if (NeedsElt) {
2405 computeKnownBits(Elt, Known, Q, Depth + 1);
2406 // If we don't know any bits, early out.
2407 if (Known.isUnknown())
2408 break;
2409 }
2410
2411 if (!DemandedVecElts.isZero()) {
2412 computeKnownBits(Vec, DemandedVecElts, Known2, Q, Depth + 1);
2413 Known = Known.intersectWith(Known2);
2414 }
2415 break;
2416 }
2417 case Instruction::ExtractElement: {
2418 // Look through extract element. If the index is non-constant or
2419 // out-of-range demand all elements, otherwise just the extracted element.
2420 const Value *Vec = I->getOperand(0);
2421 const Value *Idx = I->getOperand(1);
2422 auto *CIdx = dyn_cast<ConstantInt>(Idx);
2423 if (isa<ScalableVectorType>(Vec->getType())) {
2424 // FIXME: there's probably *something* we can do with scalable vectors
2425 Known.resetAll();
2426 break;
2427 }
2428 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
2429 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
2430 if (CIdx && CIdx->getValue().ult(NumElts))
2431 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2432 computeKnownBits(Vec, DemandedVecElts, Known, Q, Depth + 1);
2433 break;
2434 }
2435 case Instruction::ExtractValue:
2436 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
2438 if (EVI->getNumIndices() != 1) break;
2439 if (EVI->getIndices()[0] == 0) {
2440 switch (II->getIntrinsicID()) {
2441 default: break;
2442 case Intrinsic::uadd_with_overflow:
2443 case Intrinsic::sadd_with_overflow:
2445 true, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2446 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2447 break;
2448 case Intrinsic::usub_with_overflow:
2449 case Intrinsic::ssub_with_overflow:
2451 false, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2452 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2453 break;
2454 case Intrinsic::umul_with_overflow:
2455 case Intrinsic::smul_with_overflow:
2456 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
2457 false, DemandedElts, Known, Known2, Q, Depth);
2458 break;
2459 }
2460 }
2461 }
2462 break;
2463 case Instruction::Freeze:
2464 if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
2465 Depth + 1))
2466 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2467 break;
2468 }
2469}
2470
2471/// Determine which bits of V are known to be either zero or one and return
2472/// them.
2473KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
2474 const SimplifyQuery &Q, unsigned Depth) {
2475 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2476 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
2477 return Known;
2478}
2479
2480/// Determine which bits of V are known to be either zero or one and return
2481/// them.
2483 unsigned Depth) {
2484 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2486 return Known;
2487}
2488
2489/// Determine which bits of V are known to be either zero or one and return
2490/// them in the Known bit set.
2491///
2492/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
2493/// we cannot optimize based on the assumption that it is zero without changing
2494/// it to be an explicit zero. If we don't change it to zero, other code could
2495/// optimized based on the contradictory assumption that it is non-zero.
2496/// Because instcombine aggressively folds operations with undef args anyway,
2497/// this won't lose us code quality.
2498///
2499/// This function is defined on values with integer type, values with pointer
2500/// type, and vectors of integers. In the case
2501/// where V is a vector, known zero, and known one values are the
2502/// same width as the vector element, and the bit is set only if it is true
2503/// for all of the demanded elements in the vector specified by DemandedElts.
2504void computeKnownBits(const Value *V, const APInt &DemandedElts,
2505 KnownBits &Known, const SimplifyQuery &Q,
2506 unsigned Depth) {
2507 if (!DemandedElts) {
2508 // No demanded elts, better to assume we don't know anything.
2509 Known.resetAll();
2510 return;
2511 }
2512
2513 assert(V && "No Value?");
2514 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2515
2516#ifndef NDEBUG
2517 Type *Ty = V->getType();
2518 unsigned BitWidth = Known.getBitWidth();
2519
2520 assert((Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) &&
2521 "Not integer or pointer type!");
2522
2523 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2524 assert(
2525 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
2526 "DemandedElt width should equal the fixed vector number of elements");
2527 } else {
2528 assert(DemandedElts == APInt(1, 1) &&
2529 "DemandedElt width should be 1 for scalars or scalable vectors");
2530 }
2531
2532 Type *ScalarTy = Ty->getScalarType();
2533 if (ScalarTy->isPointerTy()) {
2534 assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) &&
2535 "V and Known should have same BitWidth");
2536 } else {
2537 assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) &&
2538 "V and Known should have same BitWidth");
2539 }
2540#endif
2541
2542 const APInt *C;
2543 if (match(V, m_APInt(C))) {
2544 // We know all of the bits for a scalar constant or a splat vector constant!
2546 return;
2547 }
2548 // Null and aggregate-zero are all-zeros.
2550 Known.setAllZero();
2551 return;
2552 }
2553 // Handle a constant vector by taking the intersection of the known bits of
2554 // each element.
2556 assert(!isa<ScalableVectorType>(V->getType()));
2557 // We know that CDV must be a vector of integers. Take the intersection of
2558 // each element.
2559 Known.setAllConflict();
2560 for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
2561 if (!DemandedElts[i])
2562 continue;
2563 APInt Elt = CDV->getElementAsAPInt(i);
2564 Known.Zero &= ~Elt;
2565 Known.One &= Elt;
2566 }
2567 if (Known.hasConflict())
2568 Known.resetAll();
2569 return;
2570 }
2571
2572 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
2573 assert(!isa<ScalableVectorType>(V->getType()));
2574 // We know that CV must be a vector of integers. Take the intersection of
2575 // each element.
2576 Known.setAllConflict();
2577 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
2578 if (!DemandedElts[i])
2579 continue;
2580 Constant *Element = CV->getAggregateElement(i);
2581 if (isa<PoisonValue>(Element))
2582 continue;
2583 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
2584 if (!ElementCI) {
2585 Known.resetAll();
2586 return;
2587 }
2588 const APInt &Elt = ElementCI->getValue();
2589 Known.Zero &= ~Elt;
2590 Known.One &= Elt;
2591 }
2592 if (Known.hasConflict())
2593 Known.resetAll();
2594 return;
2595 }
2596
2597 // Start out not knowing anything.
2598 Known.resetAll();
2599
2600 // We can't imply anything about undefs.
2601 if (isa<UndefValue>(V))
2602 return;
2603
2604 // There's no point in looking through other users of ConstantData for
2605 // assumptions. Confirm that we've handled them all.
2606 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
2607
2608 if (const auto *A = dyn_cast<Argument>(V))
2609 if (std::optional<ConstantRange> Range = A->getRange())
2610 Known = Range->toKnownBits();
2611
2612 // All recursive calls that increase depth must come after this.
2614 return;
2615
2616 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
2617 // the bits of its aliasee.
2618 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2619 if (!GA->isInterposable())
2620 computeKnownBits(GA->getAliasee(), Known, Q, Depth + 1);
2621 return;
2622 }
2623
2624 if (const Operator *I = dyn_cast<Operator>(V))
2625 computeKnownBitsFromOperator(I, DemandedElts, Known, Q, Depth);
2626 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2627 if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange())
2628 Known = CR->toKnownBits();
2629 }
2630
2631 // Aligned pointers have trailing zeros - refine Known.Zero set
2632 if (isa<PointerType>(V->getType())) {
2633 Align Alignment = V->getPointerAlignment(Q.DL);
2634 Known.Zero.setLowBits(Log2(Alignment));
2635 }
2636
2637 // computeKnownBitsFromContext strictly refines Known.
2638 // Therefore, we run them after computeKnownBitsFromOperator.
2639
2640 // Check whether we can determine known bits from context such as assumes.
2642}
2643
2644/// Try to detect a recurrence that the value of the induction variable is
2645/// always a power of two (or zero).
2646static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero,
2647 SimplifyQuery &Q, unsigned Depth) {
2648 BinaryOperator *BO = nullptr;
2649 Value *Start = nullptr, *Step = nullptr;
2650 if (!matchSimpleRecurrence(PN, BO, Start, Step))
2651 return false;
2652
2653 // Initial value must be a power of two.
2654 for (const Use &U : PN->operands()) {
2655 if (U.get() == Start) {
2656 // Initial value comes from a different BB, need to adjust context
2657 // instruction for analysis.
2658 Q.CxtI = PN->getIncomingBlock(U)->getTerminator();
2659 if (!isKnownToBeAPowerOfTwo(Start, OrZero, Q, Depth))
2660 return false;
2661 }
2662 }
2663
2664 // Except for Mul, the induction variable must be on the left side of the
2665 // increment expression, otherwise its value can be arbitrary.
2666 if (BO->getOpcode() != Instruction::Mul && BO->getOperand(1) != Step)
2667 return false;
2668
2669 Q.CxtI = BO->getParent()->getTerminator();
2670 switch (BO->getOpcode()) {
2671 case Instruction::Mul:
2672 // Power of two is closed under multiplication.
2673 return (OrZero || Q.IIQ.hasNoUnsignedWrap(BO) ||
2674 Q.IIQ.hasNoSignedWrap(BO)) &&
2675 isKnownToBeAPowerOfTwo(Step, OrZero, Q, Depth);
2676 case Instruction::SDiv:
2677 // Start value must not be signmask for signed division, so simply being a
2678 // power of two is not sufficient, and it has to be a constant.
2679 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2680 return false;
2681 [[fallthrough]];
2682 case Instruction::UDiv:
2683 // Divisor must be a power of two.
2684 // If OrZero is false, cannot guarantee induction variable is non-zero after
2685 // division, same for Shr, unless it is exact division.
2686 return (OrZero || Q.IIQ.isExact(BO)) &&
2687 isKnownToBeAPowerOfTwo(Step, false, Q, Depth);
2688 case Instruction::Shl:
2689 return OrZero || Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO);
2690 case Instruction::AShr:
2691 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2692 return false;
2693 [[fallthrough]];
2694 case Instruction::LShr:
2695 return OrZero || Q.IIQ.isExact(BO);
2696 default:
2697 return false;
2698 }
2699}
2700
2701/// Return true if we can infer that \p V is known to be a power of 2 from
2702/// dominating condition \p Cond (e.g., ctpop(V) == 1).
2703static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero,
2704 const Value *Cond,
2705 bool CondIsTrue) {
2706 CmpPredicate Pred;
2707 const APInt *RHSC;
2708 if (!match(Cond, m_ICmp(Pred, m_Ctpop(m_Specific(V)), m_APInt(RHSC))))
2709 return false;
2710 if (!CondIsTrue)
2711 Pred = ICmpInst::getInversePredicate(Pred);
2712 // ctpop(V) u< 2
2713 if (OrZero && Pred == ICmpInst::ICMP_ULT && *RHSC == 2)
2714 return true;
2715 // ctpop(V) == 1
2716 return Pred == ICmpInst::ICMP_EQ && *RHSC == 1;
2717}
2718
2719/// Return true if the given value is known to have exactly one
2720/// bit set when defined. For vectors return true if every element is known to
2721/// be a power of two when defined. Supports values with integer or pointer
2722/// types and vectors of integers.
2723bool llvm::isKnownToBeAPowerOfTwo(const Value *V, bool OrZero,
2724 const SimplifyQuery &Q, unsigned Depth) {
2725 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2726
2727 if (isa<Constant>(V))
2728 return OrZero ? match(V, m_Power2OrZero()) : match(V, m_Power2());
2729
2730 // i1 is by definition a power of 2 or zero.
2731 if (OrZero && V->getType()->getScalarSizeInBits() == 1)
2732 return true;
2733
2734 // Try to infer from assumptions.
2735 if (Q.AC && Q.CxtI) {
2736 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
2737 if (!AssumeVH)
2738 continue;
2739 CallInst *I = cast<CallInst>(AssumeVH);
2740 if (isImpliedToBeAPowerOfTwoFromCond(V, OrZero, I->getArgOperand(0),
2741 /*CondIsTrue=*/true) &&
2743 return true;
2744 }
2745 }
2746
2747 // Handle dominating conditions.
2748 if (Q.DC && Q.CxtI && Q.DT) {
2749 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
2750 Value *Cond = BI->getCondition();
2751
2752 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
2754 /*CondIsTrue=*/true) &&
2755 Q.DT->dominates(Edge0, Q.CxtI->getParent()))
2756 return true;
2757
2758 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
2760 /*CondIsTrue=*/false) &&
2761 Q.DT->dominates(Edge1, Q.CxtI->getParent()))
2762 return true;
2763 }
2764 }
2765
2766 auto *I = dyn_cast<Instruction>(V);
2767 if (!I)
2768 return false;
2769
2770 if (Q.CxtI && match(V, m_VScale())) {
2771 const Function *F = Q.CxtI->getFunction();
2772 // The vscale_range indicates vscale is a power-of-two.
2773 return F->hasFnAttribute(Attribute::VScaleRange);
2774 }
2775
2776 // 1 << X is clearly a power of two if the one is not shifted off the end. If
2777 // it is shifted off the end then the result is undefined.
2778 if (match(I, m_Shl(m_One(), m_Value())))
2779 return true;
2780
2781 // (signmask) >>l X is clearly a power of two if the one is not shifted off
2782 // the bottom. If it is shifted off the bottom then the result is undefined.
2783 if (match(I, m_LShr(m_SignMask(), m_Value())))
2784 return true;
2785
2786 // The remaining tests are all recursive, so bail out if we hit the limit.
2788 return false;
2789
2790 switch (I->getOpcode()) {
2791 case Instruction::ZExt:
2792 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2793 case Instruction::Trunc:
2794 return OrZero && isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2795 case Instruction::Shl:
2796 if (OrZero || Q.IIQ.hasNoUnsignedWrap(I) || Q.IIQ.hasNoSignedWrap(I))
2797 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2798 return false;
2799 case Instruction::LShr:
2800 if (OrZero || Q.IIQ.isExact(cast<BinaryOperator>(I)))
2801 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2802 return false;
2803 case Instruction::UDiv:
2805 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2806 return false;
2807 case Instruction::Mul:
2808 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2809 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth) &&
2810 (OrZero || isKnownNonZero(I, Q, Depth));
2811 case Instruction::And:
2812 // A power of two and'd with anything is a power of two or zero.
2813 if (OrZero &&
2814 (isKnownToBeAPowerOfTwo(I->getOperand(1), /*OrZero*/ true, Q, Depth) ||
2815 isKnownToBeAPowerOfTwo(I->getOperand(0), /*OrZero*/ true, Q, Depth)))
2816 return true;
2817 // X & (-X) is always a power of two or zero.
2818 if (match(I->getOperand(0), m_Neg(m_Specific(I->getOperand(1)))) ||
2819 match(I->getOperand(1), m_Neg(m_Specific(I->getOperand(0)))))
2820 return OrZero || isKnownNonZero(I->getOperand(0), Q, Depth);
2821 return false;
2822 case Instruction::Add: {
2823 // Adding a power-of-two or zero to the same power-of-two or zero yields
2824 // either the original power-of-two, a larger power-of-two or zero.
2826 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
2827 Q.IIQ.hasNoSignedWrap(VOBO)) {
2828 if (match(I->getOperand(0),
2829 m_c_And(m_Specific(I->getOperand(1)), m_Value())) &&
2830 isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth))
2831 return true;
2832 if (match(I->getOperand(1),
2833 m_c_And(m_Specific(I->getOperand(0)), m_Value())) &&
2834 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth))
2835 return true;
2836
2837 unsigned BitWidth = V->getType()->getScalarSizeInBits();
2838 KnownBits LHSBits(BitWidth);
2839 computeKnownBits(I->getOperand(0), LHSBits, Q, Depth);
2840
2841 KnownBits RHSBits(BitWidth);
2842 computeKnownBits(I->getOperand(1), RHSBits, Q, Depth);
2843 // If i8 V is a power of two or zero:
2844 // ZeroBits: 1 1 1 0 1 1 1 1
2845 // ~ZeroBits: 0 0 0 1 0 0 0 0
2846 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
2847 // If OrZero isn't set, we cannot give back a zero result.
2848 // Make sure either the LHS or RHS has a bit set.
2849 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
2850 return true;
2851 }
2852
2853 // LShr(UINT_MAX, Y) + 1 is a power of two (if add is nuw) or zero.
2854 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO))
2855 if (match(I, m_Add(m_LShr(m_AllOnes(), m_Value()), m_One())))
2856 return true;
2857 return false;
2858 }
2859 case Instruction::Select:
2860 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2861 isKnownToBeAPowerOfTwo(I->getOperand(2), OrZero, Q, Depth);
2862 case Instruction::PHI: {
2863 // A PHI node is power of two if all incoming values are power of two, or if
2864 // it is an induction variable where in each step its value is a power of
2865 // two.
2866 auto *PN = cast<PHINode>(I);
2868
2869 // Check if it is an induction variable and always power of two.
2870 if (isPowerOfTwoRecurrence(PN, OrZero, RecQ, Depth))
2871 return true;
2872
2873 // Recursively check all incoming values. Limit recursion to 2 levels, so
2874 // that search complexity is limited to number of operands^2.
2875 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
2876 return llvm::all_of(PN->operands(), [&](const Use &U) {
2877 // Value is power of 2 if it is coming from PHI node itself by induction.
2878 if (U.get() == PN)
2879 return true;
2880
2881 // Change the context instruction to the incoming block where it is
2882 // evaluated.
2883 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
2884 return isKnownToBeAPowerOfTwo(U.get(), OrZero, RecQ, NewDepth);
2885 });
2886 }
2887 case Instruction::Invoke:
2888 case Instruction::Call: {
2889 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2890 switch (II->getIntrinsicID()) {
2891 case Intrinsic::umax:
2892 case Intrinsic::smax:
2893 case Intrinsic::umin:
2894 case Intrinsic::smin:
2895 return isKnownToBeAPowerOfTwo(II->getArgOperand(1), OrZero, Q, Depth) &&
2896 isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2897 // bswap/bitreverse just move around bits, but don't change any 1s/0s
2898 // thus dont change pow2/non-pow2 status.
2899 case Intrinsic::bitreverse:
2900 case Intrinsic::bswap:
2901 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2902 case Intrinsic::fshr:
2903 case Intrinsic::fshl:
2904 // If Op0 == Op1, this is a rotate. is_pow2(rotate(x, y)) == is_pow2(x)
2905 if (II->getArgOperand(0) == II->getArgOperand(1))
2906 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2907 break;
2908 case Intrinsic::riscv_vsetvlimax:
2909 // VLMAX is VLEN * LMUL / SEW, which is always a non-zero power of two
2910 // for any valid vtype, so it is a power of two regardless of OrZero.
2911 return true;
2912 case Intrinsic::read_register:
2913 case Intrinsic::read_volatile_register: {
2914 // The RISC-V vlenb CSR holds VLEN/8, which is always a non-zero power
2915 // of two, so it is a power of two regardless of OrZero.
2916 const Module *M = II->getModule();
2917 if (!M || !M->getTargetTriple().isRISCV())
2918 break;
2919 return isReadVLENB(*II);
2920 }
2921 default:
2922 break;
2923 }
2924 }
2925 return false;
2926 }
2927 default:
2928 return false;
2929 }
2930}
2931
2932/// Test whether a GEP's result is known to be non-null.
2933///
2934/// Uses properties inherent in a GEP to try to determine whether it is known
2935/// to be non-null.
2936///
2937/// Currently this routine does not support vector GEPs.
2938static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q,
2939 unsigned Depth) {
2940 const Function *F = nullptr;
2941 if (const Instruction *I = dyn_cast<Instruction>(GEP))
2942 F = I->getFunction();
2943
2944 // If the gep is nuw or inbounds with invalid null pointer, then the GEP
2945 // may be null iff the base pointer is null and the offset is zero.
2946 if (!GEP->hasNoUnsignedWrap() &&
2947 !(GEP->isInBounds() &&
2948 !NullPointerIsDefined(F, GEP->getPointerAddressSpace())))
2949 return false;
2950
2951 // FIXME: Support vector-GEPs.
2952 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
2953
2954 // If the base pointer is non-null, we cannot walk to a null address with an
2955 // inbounds GEP in address space zero.
2956 if (isKnownNonZero(GEP->getPointerOperand(), Q, Depth))
2957 return true;
2958
2959 // Walk the GEP operands and see if any operand introduces a non-zero offset.
2960 // If so, then the GEP cannot produce a null pointer, as doing so would
2961 // inherently violate the inbounds contract within address space zero.
2963 GTI != GTE; ++GTI) {
2964 // Struct types are easy -- they must always be indexed by a constant.
2965 if (StructType *STy = GTI.getStructTypeOrNull()) {
2966 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
2967 unsigned ElementIdx = OpC->getZExtValue();
2968 const StructLayout *SL = Q.DL.getStructLayout(STy);
2969 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
2970 if (ElementOffset > 0)
2971 return true;
2972 continue;
2973 }
2974
2975 // If we have a zero-sized type, the index doesn't matter. Keep looping.
2976 if (GTI.getSequentialElementStride(Q.DL).isZero())
2977 continue;
2978
2979 // Fast path the constant operand case both for efficiency and so we don't
2980 // increment Depth when just zipping down an all-constant GEP.
2981 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
2982 if (!OpC->isZero())
2983 return true;
2984 continue;
2985 }
2986
2987 // We post-increment Depth here because while isKnownNonZero increments it
2988 // as well, when we pop back up that increment won't persist. We don't want
2989 // to recurse 10k times just because we have 10k GEP operands. We don't
2990 // bail completely out because we want to handle constant GEPs regardless
2991 // of depth.
2993 continue;
2994
2995 if (isKnownNonZero(GTI.getOperand(), Q, Depth))
2996 return true;
2997 }
2998
2999 return false;
3000}
3001
3003 const Instruction *CtxI,
3004 const DominatorTree *DT) {
3005 assert(!isa<Constant>(V) && "Called for constant?");
3006
3007 if (!CtxI || !DT)
3008 return false;
3009
3010 unsigned NumUsesExplored = 0;
3011 for (auto &U : V->uses()) {
3012 // Avoid massive lists
3013 if (NumUsesExplored >= DomConditionsMaxUses)
3014 break;
3015 NumUsesExplored++;
3016
3017 const Instruction *UI = cast<Instruction>(U.getUser());
3018 // If the value is used as an argument to a call or invoke, then argument
3019 // attributes may provide an answer about null-ness.
3020 if (V->getType()->isPointerTy()) {
3021 if (const auto *CB = dyn_cast<CallBase>(UI)) {
3022 if (CB->isArgOperand(&U) &&
3023 CB->paramHasNonNullAttr(CB->getArgOperandNo(&U),
3024 /*AllowUndefOrPoison=*/false) &&
3025 DT->dominates(CB, CtxI))
3026 return true;
3027 }
3028 }
3029
3030 // If the value is used as a load/store, then the pointer must be non null.
3031 if (V == getLoadStorePointerOperand(UI)) {
3034 DT->dominates(UI, CtxI))
3035 return true;
3036 }
3037
3038 if ((match(UI, m_IDiv(m_Value(), m_Specific(V))) ||
3039 match(UI, m_IRem(m_Value(), m_Specific(V)))) &&
3040 isValidAssumeForContext(UI, CtxI, DT))
3041 return true;
3042
3043 // Consider only compare instructions uniquely controlling a branch
3044 Value *RHS;
3045 CmpPredicate Pred;
3046 if (!match(UI, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS))))
3047 continue;
3048
3049 bool NonNullIfTrue;
3050 if (cmpExcludesZero(Pred, RHS))
3051 NonNullIfTrue = true;
3053 NonNullIfTrue = false;
3054 else
3055 continue;
3056
3059 for (const auto *CmpU : UI->users()) {
3060 assert(WorkList.empty() && "Should be!");
3061 if (Visited.insert(CmpU).second)
3062 WorkList.push_back(CmpU);
3063
3064 while (!WorkList.empty()) {
3065 auto *Curr = WorkList.pop_back_val();
3066
3067 // If a user is an AND, add all its users to the work list. We only
3068 // propagate "pred != null" condition through AND because it is only
3069 // correct to assume that all conditions of AND are met in true branch.
3070 // TODO: Support similar logic of OR and EQ predicate?
3071 if (NonNullIfTrue)
3072 if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) {
3073 for (const auto *CurrU : Curr->users())
3074 if (Visited.insert(CurrU).second)
3075 WorkList.push_back(CurrU);
3076 continue;
3077 }
3078
3079 if (const CondBrInst *BI = dyn_cast<CondBrInst>(Curr)) {
3080 BasicBlock *NonNullSuccessor =
3081 BI->getSuccessor(NonNullIfTrue ? 0 : 1);
3082 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3083 if (DT->dominates(Edge, CtxI->getParent()))
3084 return true;
3085 } else if (NonNullIfTrue && isGuard(Curr) &&
3086 DT->dominates(cast<Instruction>(Curr), CtxI)) {
3087 return true;
3088 }
3089 }
3090 }
3091 }
3092
3093 return false;
3094}
3095
3096/// Does the 'Range' metadata (which must be a valid MD_range operand list)
3097/// ensure that the value it's attached to is never Value? 'RangeType' is
3098/// is the type of the value described by the range.
3099static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
3100 const unsigned NumRanges = Ranges->getNumOperands() / 2;
3101 assert(NumRanges >= 1);
3102 for (unsigned i = 0; i < NumRanges; ++i) {
3104 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
3106 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
3107 ConstantRange Range(Lower->getValue(), Upper->getValue());
3108 if (Range.contains(Value))
3109 return false;
3110 }
3111 return true;
3112}
3113
3114/// Try to detect a recurrence that monotonically increases/decreases from a
3115/// non-zero starting value. These are common as induction variables.
3116static bool isNonZeroRecurrence(const PHINode *PN) {
3117 BinaryOperator *BO = nullptr;
3118 Value *Start = nullptr, *Step = nullptr;
3119 const APInt *StartC, *StepC;
3120 if (!matchSimpleRecurrence(PN, BO, Start, Step) ||
3121 !match(Start, m_APInt(StartC)) || StartC->isZero())
3122 return false;
3123
3124 switch (BO->getOpcode()) {
3125 case Instruction::Add:
3126 // Starting from non-zero and stepping away from zero can never wrap back
3127 // to zero.
3128 return BO->hasNoUnsignedWrap() ||
3129 (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) &&
3130 StartC->isNegative() == StepC->isNegative());
3131 case Instruction::Mul:
3132 return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) &&
3133 match(Step, m_APInt(StepC)) && !StepC->isZero();
3134 case Instruction::Shl:
3135 return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap();
3136 case Instruction::AShr:
3137 case Instruction::LShr:
3138 return BO->isExact();
3139 default:
3140 return false;
3141 }
3142}
3143
3144static bool matchOpWithOpEqZero(Value *Op0, Value *Op1) {
3146 m_Specific(Op1), m_Zero()))) ||
3148 m_Specific(Op0), m_Zero())));
3149}
3150
3151static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q,
3152 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3153 bool NUW, unsigned Depth) {
3154 // (X + (X != 0)) is non zero
3155 if (matchOpWithOpEqZero(X, Y))
3156 return true;
3157
3158 if (NUW)
3159 return isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3160 isKnownNonZero(X, DemandedElts, Q, Depth);
3161
3162 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3163 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3164
3165 // If X and Y are both non-negative (as signed values) then their sum is not
3166 // zero unless both X and Y are zero.
3167 if (XKnown.isNonNegative() && YKnown.isNonNegative())
3168 if (isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3169 isKnownNonZero(X, DemandedElts, Q, Depth))
3170 return true;
3171
3172 // If X and Y are both negative (as signed values) then their sum is not
3173 // zero unless both X and Y equal INT_MIN.
3174 if (XKnown.isNegative() && YKnown.isNegative()) {
3176 // The sign bit of X is set. If some other bit is set then X is not equal
3177 // to INT_MIN.
3178 if (XKnown.One.intersects(Mask))
3179 return true;
3180 // The sign bit of Y is set. If some other bit is set then Y is not equal
3181 // to INT_MIN.
3182 if (YKnown.One.intersects(Mask))
3183 return true;
3184 }
3185
3186 // The sum of a non-negative number and a power of two is not zero.
3187 if (XKnown.isNonNegative() &&
3188 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Q, Depth))
3189 return true;
3190 if (YKnown.isNonNegative() &&
3191 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Q, Depth))
3192 return true;
3193
3194 return KnownBits::add(XKnown, YKnown, NSW, NUW).isNonZero();
3195}
3196
3197static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q,
3198 unsigned BitWidth, Value *X, Value *Y,
3199 unsigned Depth) {
3200 // (X - (X != 0)) is non zero
3201 // ((X != 0) - X) is non zero
3202 if (matchOpWithOpEqZero(X, Y))
3203 return true;
3204
3205 // TODO: Move this case into isKnownNonEqual().
3206 if (auto *C = dyn_cast<Constant>(X))
3207 if (C->isNullValue() && isKnownNonZero(Y, DemandedElts, Q, Depth))
3208 return true;
3209
3210 return ::isKnownNonEqual(X, Y, DemandedElts, Q, Depth);
3211}
3212
3213static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q,
3214 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3215 bool NUW, unsigned Depth) {
3216 // If X and Y are non-zero then so is X * Y as long as the multiplication
3217 // does not overflow.
3218 if (NSW || NUW)
3219 return isKnownNonZero(X, DemandedElts, Q, Depth) &&
3220 isKnownNonZero(Y, DemandedElts, Q, Depth);
3221
3222 // If either X or Y is odd, then if the other is non-zero the result can't
3223 // be zero.
3224 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3225 if (XKnown.One[0])
3226 return isKnownNonZero(Y, DemandedElts, Q, Depth);
3227
3228 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3229 if (YKnown.One[0])
3230 return XKnown.isNonZero() || isKnownNonZero(X, DemandedElts, Q, Depth);
3231
3232 // If there exists any subset of X (sX) and subset of Y (sY) s.t sX * sY is
3233 // non-zero, then X * Y is non-zero. We can find sX and sY by just taking
3234 // the lowest known One of X and Y. If they are non-zero, the result
3235 // must be non-zero. We can check if LSB(X) * LSB(Y) != 0 by doing
3236 // X.CountLeadingZeros + Y.CountLeadingZeros < BitWidth.
3237 return (XKnown.countMaxTrailingZeros() + YKnown.countMaxTrailingZeros()) <
3238 BitWidth;
3239}
3240
3241static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts,
3242 const SimplifyQuery &Q, const KnownBits &KnownVal,
3243 unsigned Depth) {
3244 auto ShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3245 switch (I->getOpcode()) {
3246 case Instruction::Shl:
3247 return Lhs.shl(Rhs);
3248 case Instruction::LShr:
3249 return Lhs.lshr(Rhs);
3250 case Instruction::AShr:
3251 return Lhs.ashr(Rhs);
3252 default:
3253 llvm_unreachable("Unknown Shift Opcode");
3254 }
3255 };
3256
3257 auto InvShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3258 switch (I->getOpcode()) {
3259 case Instruction::Shl:
3260 return Lhs.lshr(Rhs);
3261 case Instruction::LShr:
3262 case Instruction::AShr:
3263 return Lhs.shl(Rhs);
3264 default:
3265 llvm_unreachable("Unknown Shift Opcode");
3266 }
3267 };
3268
3269 if (KnownVal.isUnknown())
3270 return false;
3271
3272 KnownBits KnownCnt =
3273 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3274 APInt MaxShift = KnownCnt.getMaxValue();
3275 unsigned NumBits = KnownVal.getBitWidth();
3276 if (MaxShift.uge(NumBits))
3277 return false;
3278
3279 if (!ShiftOp(KnownVal.One, MaxShift).isZero())
3280 return true;
3281
3282 // If all of the bits shifted out are known to be zero, and Val is known
3283 // non-zero then at least one non-zero bit must remain.
3284 if (InvShiftOp(KnownVal.Zero, NumBits - MaxShift)
3285 .eq(InvShiftOp(APInt::getAllOnes(NumBits), NumBits - MaxShift)) &&
3286 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth))
3287 return true;
3288
3289 return false;
3290}
3291
3293 const APInt &DemandedElts,
3294 const SimplifyQuery &Q, unsigned Depth) {
3295 unsigned BitWidth = getBitWidth(I->getType()->getScalarType(), Q.DL);
3296 switch (I->getOpcode()) {
3297 case Instruction::Alloca:
3298 // Alloca never returns null, malloc might.
3299 return I->getType()->getPointerAddressSpace() == 0;
3300 case Instruction::GetElementPtr:
3301 if (I->getType()->isPointerTy())
3303 break;
3304 case Instruction::BitCast: {
3305 // We need to be a bit careful here. We can only peek through the bitcast
3306 // if the scalar size of elements in the operand are smaller than and a
3307 // multiple of the size they are casting too. Take three cases:
3308 //
3309 // 1) Unsafe:
3310 // bitcast <2 x i16> %NonZero to <4 x i8>
3311 //
3312 // %NonZero can have 2 non-zero i16 elements, but isKnownNonZero on a
3313 // <4 x i8> requires that all 4 i8 elements be non-zero which isn't
3314 // guranteed (imagine just sign bit set in the 2 i16 elements).
3315 //
3316 // 2) Unsafe:
3317 // bitcast <4 x i3> %NonZero to <3 x i4>
3318 //
3319 // Even though the scalar size of the src (`i3`) is smaller than the
3320 // scalar size of the dst `i4`, because `i3` is not a multiple of `i4`
3321 // its possible for the `3 x i4` elements to be zero because there are
3322 // some elements in the destination that don't contain any full src
3323 // element.
3324 //
3325 // 3) Safe:
3326 // bitcast <4 x i8> %NonZero to <2 x i16>
3327 //
3328 // This is always safe as non-zero in the 4 i8 elements implies
3329 // non-zero in the combination of any two adjacent ones. Since i8 is a
3330 // multiple of i16, each i16 is guranteed to have 2 full i8 elements.
3331 // This all implies the 2 i16 elements are non-zero.
3332 Type *FromTy = I->getOperand(0)->getType();
3333 if ((FromTy->isIntOrIntVectorTy() || FromTy->isPtrOrPtrVectorTy()) &&
3334 (BitWidth % getBitWidth(FromTy->getScalarType(), Q.DL)) == 0)
3335 return isKnownNonZero(I->getOperand(0), Q, Depth);
3336 } break;
3337 case Instruction::IntToPtr:
3338 // Note that we have to take special care to avoid looking through
3339 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
3340 // as casts that can alter the value, e.g., AddrSpaceCasts.
3341 if (!isa<ScalableVectorType>(I->getType()) &&
3342 Q.DL.getTypeSizeInBits(I->getOperand(0)->getType()).getFixedValue() <=
3343 Q.DL.getTypeSizeInBits(I->getType()).getFixedValue())
3344 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3345 break;
3346 case Instruction::PtrToAddr:
3347 // isKnownNonZero() for pointers refers to the address bits being non-zero,
3348 // so we can directly forward.
3349 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3350 case Instruction::PtrToInt:
3351 // For inttoptr, make sure the result size is >= the address size. If the
3352 // address is non-zero, any larger value is also non-zero.
3353 if (Q.DL.getAddressSizeInBits(I->getOperand(0)->getType()) <=
3354 I->getType()->getScalarSizeInBits())
3355 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3356 break;
3357 case Instruction::Trunc:
3358 // nuw/nsw trunc preserves zero/non-zero status of input.
3359 if (auto *TI = dyn_cast<TruncInst>(I))
3360 if (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap())
3361 return isKnownNonZero(TI->getOperand(0), DemandedElts, Q, Depth);
3362 break;
3363
3364 // Iff x - y != 0, then x ^ y != 0
3365 // Therefore we can do the same exact checks
3366 case Instruction::Xor:
3367 case Instruction::Sub:
3368 return isNonZeroSub(DemandedElts, Q, BitWidth, I->getOperand(0),
3369 I->getOperand(1), Depth);
3370 case Instruction::Or:
3371 // (X | (X != 0)) is non zero
3372 if (matchOpWithOpEqZero(I->getOperand(0), I->getOperand(1)))
3373 return true;
3374 // X | Y != 0 if X != Y.
3375 if (isKnownNonEqual(I->getOperand(0), I->getOperand(1), DemandedElts, Q,
3376 Depth))
3377 return true;
3378 // X | Y != 0 if X != 0 or Y != 0.
3379 return isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth) ||
3380 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3381 case Instruction::SExt:
3382 case Instruction::ZExt:
3383 // ext X != 0 if X != 0.
3384 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3385
3386 case Instruction::Shl: {
3387 // shl nsw/nuw can't remove any non-zero bits.
3389 if (Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO))
3390 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3391
3392 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
3393 // if the lowest bit is shifted off the end.
3395 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth);
3396 if (Known.One[0])
3397 return true;
3398
3399 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3400 }
3401 case Instruction::LShr:
3402 case Instruction::AShr: {
3403 // shr exact can only shift out zero bits.
3405 if (BO->isExact())
3406 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3407
3408 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
3409 // defined if the sign bit is shifted off the end.
3411 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3412 if (Known.isNegative())
3413 return true;
3414
3415 // shr (add nuw A, B), C is non-zero if A or B has a known-one bit at
3416 // position >= C, because the sum >= max(A, B).
3417 Value *A, *B;
3418 const APInt *C;
3419 if (Depth + 1 < MaxAnalysisRecursionDepth &&
3420 match(I->getOperand(0), m_NUWAdd(m_Value(A), m_Value(B))) &&
3421 match(I->getOperand(1), m_APInt(C)) && C->ult(BitWidth)) {
3422 KnownBits KnownA = computeKnownBits(A, DemandedElts, Q, Depth + 1);
3423 if (!KnownA.One.lshr(*C).isZero())
3424 return true;
3425 KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
3426 if (!KnownB.One.lshr(*C).isZero())
3427 return true;
3428 }
3429
3430 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3431 }
3432 case Instruction::UDiv:
3433 case Instruction::SDiv: {
3434 // X / Y
3435 // div exact can only produce a zero if the dividend is zero.
3436 if (cast<PossiblyExactOperator>(I)->isExact())
3437 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3438
3439 KnownBits XKnown =
3440 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3441 // If X is fully unknown we won't be able to figure anything out so don't
3442 // both computing knownbits for Y.
3443 if (XKnown.isUnknown())
3444 return false;
3445
3446 KnownBits YKnown =
3447 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3448 if (I->getOpcode() == Instruction::SDiv) {
3449 // For signed division need to compare abs value of the operands.
3450 XKnown = XKnown.abs(/*IntMinIsPoison*/ false);
3451 YKnown = YKnown.abs(/*IntMinIsPoison*/ false);
3452 }
3453 // If X u>= Y then div is non zero (0/0 is UB).
3454 std::optional<bool> XUgeY = KnownBits::uge(XKnown, YKnown);
3455 // If X is total unknown or X u< Y we won't be able to prove non-zero
3456 // with compute known bits so just return early.
3457 return XUgeY && *XUgeY;
3458 }
3459 case Instruction::Add: {
3460 // X + Y.
3461
3462 // If Add has nuw wrap flag, then if either X or Y is non-zero the result is
3463 // non-zero.
3465 return isNonZeroAdd(DemandedElts, Q, BitWidth, I->getOperand(0),
3466 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3467 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3468 }
3469 case Instruction::Mul: {
3471 return isNonZeroMul(DemandedElts, Q, BitWidth, I->getOperand(0),
3472 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3473 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3474 }
3475 case Instruction::Select: {
3476 // (C ? X : Y) != 0 if X != 0 and Y != 0.
3477
3478 // First check if the arm is non-zero using `isKnownNonZero`. If that fails,
3479 // then see if the select condition implies the arm is non-zero. For example
3480 // (X != 0 ? X : Y), we know the true arm is non-zero as the `X` "return" is
3481 // dominated by `X != 0`.
3482 auto SelectArmIsNonZero = [&](bool IsTrueArm) {
3483 Value *Op;
3484 Op = IsTrueArm ? I->getOperand(1) : I->getOperand(2);
3485 // Op is trivially non-zero.
3486 if (isKnownNonZero(Op, DemandedElts, Q, Depth))
3487 return true;
3488
3489 // The condition of the select dominates the true/false arm. Check if the
3490 // condition implies that a given arm is non-zero.
3491 Value *X;
3492 CmpPredicate Pred;
3493 if (!match(I->getOperand(0), m_c_ICmp(Pred, m_Specific(Op), m_Value(X))))
3494 return false;
3495
3496 if (!IsTrueArm)
3497 Pred = ICmpInst::getInversePredicate(Pred);
3498
3499 return cmpExcludesZero(Pred, X);
3500 };
3501
3502 if (SelectArmIsNonZero(/* IsTrueArm */ true) &&
3503 SelectArmIsNonZero(/* IsTrueArm */ false))
3504 return true;
3505 break;
3506 }
3507 case Instruction::PHI: {
3508 auto *PN = cast<PHINode>(I);
3510 return true;
3511
3512 // Check if all incoming values are non-zero using recursion.
3514 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
3515 return llvm::all_of(PN->operands(), [&](const Use &U) {
3516 if (U.get() == PN)
3517 return true;
3518 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
3519 // Check if the branch on the phi excludes zero.
3520 CmpPredicate Pred;
3521 Value *X;
3522 BasicBlock *TrueSucc, *FalseSucc;
3523 if (match(RecQ.CxtI,
3524 m_Br(m_c_ICmp(Pred, m_Specific(U.get()), m_Value(X)),
3525 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
3526 // Check for cases of duplicate successors.
3527 if ((TrueSucc == PN->getParent()) != (FalseSucc == PN->getParent())) {
3528 // If we're using the false successor, invert the predicate.
3529 if (FalseSucc == PN->getParent())
3530 Pred = CmpInst::getInversePredicate(Pred);
3531 if (cmpExcludesZero(Pred, X))
3532 return true;
3533 }
3534 }
3535 // Finally recurse on the edge and check it directly.
3536 return isKnownNonZero(U.get(), DemandedElts, RecQ, NewDepth);
3537 });
3538 }
3539 case Instruction::InsertElement: {
3540 if (isa<ScalableVectorType>(I->getType()))
3541 break;
3542
3543 const Value *Vec = I->getOperand(0);
3544 const Value *Elt = I->getOperand(1);
3545 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
3546
3547 unsigned NumElts = DemandedElts.getBitWidth();
3548 APInt DemandedVecElts = DemandedElts;
3549 bool SkipElt = false;
3550 // If we know the index we are inserting too, clear it from Vec check.
3551 if (CIdx && CIdx->getValue().ult(NumElts)) {
3552 DemandedVecElts.clearBit(CIdx->getZExtValue());
3553 SkipElt = !DemandedElts[CIdx->getZExtValue()];
3554 }
3555
3556 // Result is zero if Elt is non-zero and rest of the demanded elts in Vec
3557 // are non-zero.
3558 return (SkipElt || isKnownNonZero(Elt, Q, Depth)) &&
3559 (DemandedVecElts.isZero() ||
3560 isKnownNonZero(Vec, DemandedVecElts, Q, Depth));
3561 }
3562 case Instruction::ExtractElement:
3563 if (const auto *EEI = dyn_cast<ExtractElementInst>(I)) {
3564 const Value *Vec = EEI->getVectorOperand();
3565 const Value *Idx = EEI->getIndexOperand();
3566 auto *CIdx = dyn_cast<ConstantInt>(Idx);
3567 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
3568 unsigned NumElts = VecTy->getNumElements();
3569 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
3570 if (CIdx && CIdx->getValue().ult(NumElts))
3571 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
3572 return isKnownNonZero(Vec, DemandedVecElts, Q, Depth);
3573 }
3574 }
3575 break;
3576 case Instruction::ShuffleVector: {
3577 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
3578 if (!Shuf)
3579 break;
3580 APInt DemandedLHS, DemandedRHS;
3581 // For undef elements, we don't know anything about the common state of
3582 // the shuffle result.
3583 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
3584 break;
3585 // If demanded elements for both vecs are non-zero, the shuffle is non-zero.
3586 return (DemandedRHS.isZero() ||
3587 isKnownNonZero(Shuf->getOperand(1), DemandedRHS, Q, Depth)) &&
3588 (DemandedLHS.isZero() ||
3589 isKnownNonZero(Shuf->getOperand(0), DemandedLHS, Q, Depth));
3590 }
3591 case Instruction::Freeze:
3592 return isKnownNonZero(I->getOperand(0), Q, Depth) &&
3593 isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
3594 Depth);
3595 case Instruction::Load: {
3596 auto *LI = cast<LoadInst>(I);
3597 // A Load tagged with nonnull or dereferenceable with null pointer undefined
3598 // is never null.
3599 if (auto *PtrT = dyn_cast<PointerType>(I->getType())) {
3600 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull) ||
3601 (Q.IIQ.getMetadata(LI, LLVMContext::MD_dereferenceable) &&
3602 !NullPointerIsDefined(LI->getFunction(), PtrT->getAddressSpace())))
3603 return true;
3604 } else if (MDNode *Ranges = Q.IIQ.getMetadata(LI, LLVMContext::MD_range)) {
3606 }
3607
3608 // No need to fall through to computeKnownBits as range metadata is already
3609 // handled in isKnownNonZero.
3610 return false;
3611 }
3612 case Instruction::ExtractValue: {
3613 const WithOverflowInst *WO;
3615 switch (WO->getBinaryOp()) {
3616 default:
3617 break;
3618 case Instruction::Add:
3619 return isNonZeroAdd(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3620 WO->getArgOperand(1),
3621 /*NSW=*/false,
3622 /*NUW=*/false, Depth);
3623 case Instruction::Sub:
3624 return isNonZeroSub(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3625 WO->getArgOperand(1), Depth);
3626 case Instruction::Mul:
3627 return isNonZeroMul(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3628 WO->getArgOperand(1),
3629 /*NSW=*/false, /*NUW=*/false, Depth);
3630 break;
3631 }
3632 }
3633 break;
3634 }
3635 case Instruction::Call:
3636 case Instruction::Invoke: {
3637 const auto *Call = cast<CallBase>(I);
3638 if (I->getType()->isPointerTy()) {
3639 if (Call->isReturnNonNull())
3640 return true;
3641 if (const auto *RP = getArgumentAliasingToReturnedPointer(
3642 Call, /*MustPreserveOffset=*/true))
3643 return isKnownNonZero(RP, Q, Depth);
3644 } else {
3645 if (MDNode *Ranges = Q.IIQ.getMetadata(Call, LLVMContext::MD_range))
3647 if (std::optional<ConstantRange> Range = Call->getRange()) {
3648 const APInt ZeroValue(Range->getBitWidth(), 0);
3649 if (!Range->contains(ZeroValue))
3650 return true;
3651 }
3652 if (const Value *RV = Call->getReturnedArgOperand())
3653 if (RV->getType() == I->getType() && isKnownNonZero(RV, Q, Depth))
3654 return true;
3655 }
3656
3657 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
3658 switch (II->getIntrinsicID()) {
3659 case Intrinsic::sshl_sat:
3660 case Intrinsic::ushl_sat:
3661 case Intrinsic::abs:
3662 case Intrinsic::bitreverse:
3663 case Intrinsic::bswap:
3664 case Intrinsic::ctpop:
3665 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3666 // NB: We don't do usub_sat here as in any case we can prove its
3667 // non-zero, we will fold it to `sub nuw` in InstCombine.
3668 case Intrinsic::ssub_sat:
3669 // For most types, if x != y then ssub.sat x, y != 0. But
3670 // ssub.sat.i1 0, -1 = 0, because 1 saturates to 0. This means
3671 // isNonZeroSub will do the wrong thing for ssub.sat.i1.
3672 if (BitWidth == 1)
3673 return false;
3674 return isNonZeroSub(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3675 II->getArgOperand(1), Depth);
3676 case Intrinsic::sadd_sat:
3677 return isNonZeroAdd(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3678 II->getArgOperand(1),
3679 /*NSW=*/true, /* NUW=*/false, Depth);
3680 // Vec reverse preserves zero/non-zero status from input vec.
3681 case Intrinsic::vector_reverse:
3682 return isKnownNonZero(II->getArgOperand(0), DemandedElts.reverseBits(),
3683 Q, Depth);
3684 // umin/smin/smax/smin/or of all non-zero elements is always non-zero.
3685 case Intrinsic::vector_reduce_or:
3686 case Intrinsic::vector_reduce_umax:
3687 case Intrinsic::vector_reduce_umin:
3688 case Intrinsic::vector_reduce_smax:
3689 case Intrinsic::vector_reduce_smin:
3690 return isKnownNonZero(II->getArgOperand(0), Q, Depth);
3691 case Intrinsic::umax:
3692 case Intrinsic::uadd_sat:
3693 // umax(X, (X != 0)) is non zero
3694 // X +usat (X != 0) is non zero
3695 if (matchOpWithOpEqZero(II->getArgOperand(0), II->getArgOperand(1)))
3696 return true;
3697
3698 return isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth) ||
3699 isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3700 case Intrinsic::smax: {
3701 // If either arg is strictly positive the result is non-zero. Otherwise
3702 // the result is non-zero if both ops are non-zero.
3703 auto IsNonZero = [&](Value *Op, std::optional<bool> &OpNonZero,
3704 const KnownBits &OpKnown) {
3705 if (!OpNonZero.has_value())
3706 OpNonZero = OpKnown.isNonZero() ||
3707 isKnownNonZero(Op, DemandedElts, Q, Depth);
3708 return *OpNonZero;
3709 };
3710 // Avoid re-computing isKnownNonZero.
3711 std::optional<bool> Op0NonZero, Op1NonZero;
3712 KnownBits Op1Known =
3713 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3714 if (Op1Known.isNonNegative() &&
3715 IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known))
3716 return true;
3717 KnownBits Op0Known =
3718 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3719 if (Op0Known.isNonNegative() &&
3720 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known))
3721 return true;
3722 return IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known) &&
3723 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known);
3724 }
3725 case Intrinsic::smin: {
3726 // If either arg is negative the result is non-zero. Otherwise
3727 // the result is non-zero if both ops are non-zero.
3728 KnownBits Op1Known =
3729 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3730 if (Op1Known.isNegative())
3731 return true;
3732 KnownBits Op0Known =
3733 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3734 if (Op0Known.isNegative())
3735 return true;
3736
3737 if (Op1Known.isNonZero() && Op0Known.isNonZero())
3738 return true;
3739 }
3740 [[fallthrough]];
3741 case Intrinsic::umin:
3742 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth) &&
3743 isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth);
3744 case Intrinsic::cttz:
3745 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3746 .Zero[0];
3747 case Intrinsic::ctlz:
3748 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3749 .isNonNegative();
3750 case Intrinsic::fshr:
3751 case Intrinsic::fshl:
3752 // If Op0 == Op1, this is a rotate. rotate(x, y) != 0 iff x != 0.
3753 if (II->getArgOperand(0) == II->getArgOperand(1))
3754 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3755 break;
3756 case Intrinsic::vscale:
3757 return true;
3758 case Intrinsic::experimental_get_vector_length:
3759 return isKnownNonZero(I->getOperand(0), Q, Depth);
3760 default:
3761 break;
3762 }
3763 break;
3764 }
3765
3766 return false;
3767 }
3768 }
3769
3771 computeKnownBits(I, DemandedElts, Known, Q, Depth);
3772 return Known.One != 0;
3773}
3774
3775/// Return true if the given value is known to be non-zero when defined. For
3776/// vectors, return true if every demanded element is known to be non-zero when
3777/// defined. For pointers, if the context instruction and dominator tree are
3778/// specified, perform context-sensitive analysis and return true if the
3779/// pointer couldn't possibly be null at the specified instruction.
3780/// Supports values with integer or pointer type and vectors of integers.
3781bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
3782 const SimplifyQuery &Q, unsigned Depth) {
3783 Type *Ty = V->getType();
3784
3785#ifndef NDEBUG
3786 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
3787
3788 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
3789 assert(
3790 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
3791 "DemandedElt width should equal the fixed vector number of elements");
3792 } else {
3793 assert(DemandedElts == APInt(1, 1) &&
3794 "DemandedElt width should be 1 for scalars");
3795 }
3796#endif
3797
3798 if (auto *C = dyn_cast<Constant>(V)) {
3799 if (C->isNullValue())
3800 return false;
3801 if (isa<ConstantInt>(C))
3802 // Must be non-zero due to null test above.
3803 return true;
3804
3805 // For constant vectors, check that all elements are poison or known
3806 // non-zero to determine that the whole vector is known non-zero.
3807 if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
3808 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
3809 if (!DemandedElts[i])
3810 continue;
3811 Constant *Elt = C->getAggregateElement(i);
3812 if (!Elt || Elt->isNullValue())
3813 return false;
3814 if (!isa<PoisonValue>(Elt) && !isa<ConstantInt>(Elt))
3815 return false;
3816 }
3817 return true;
3818 }
3819
3820 // Constant ptrauth can be null, iff the base pointer can be.
3821 if (auto *CPA = dyn_cast<ConstantPtrAuth>(V))
3822 return isKnownNonZero(CPA->getPointer(), DemandedElts, Q, Depth);
3823
3824 // A global variable in address space 0 is non null unless extern weak
3825 // or an absolute symbol reference. Other address spaces may have null as a
3826 // valid address for a global, so we can't assume anything.
3827 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3828 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
3829 GV->getType()->getAddressSpace() == 0)
3830 return true;
3831 }
3832
3833 // For constant expressions, fall through to the Operator code below.
3834 if (!isa<ConstantExpr>(V))
3835 return false;
3836 }
3837
3838 if (const auto *A = dyn_cast<Argument>(V))
3839 if (std::optional<ConstantRange> Range = A->getRange()) {
3840 const APInt ZeroValue(Range->getBitWidth(), 0);
3841 if (!Range->contains(ZeroValue))
3842 return true;
3843 }
3844
3845 if (!isa<Constant>(V) && isKnownNonZeroFromAssume(V, Q))
3846 return true;
3847
3848 // Some of the tests below are recursive, so bail out if we hit the limit.
3850 return false;
3851
3852 // Check for pointer simplifications.
3853
3854 if (PointerType *PtrTy = dyn_cast<PointerType>(Ty)) {
3855 // A byval, inalloca may not be null in a non-default addres space. A
3856 // nonnull argument is assumed never 0.
3857 if (const Argument *A = dyn_cast<Argument>(V)) {
3858 if (((A->hasPassPointeeByValueCopyAttr() &&
3859 !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
3860 A->hasNonNullAttr()))
3861 return true;
3862 }
3863 }
3864
3865 if (const auto *I = dyn_cast<Operator>(V))
3866 if (isKnownNonZeroFromOperator(I, DemandedElts, Q, Depth))
3867 return true;
3868
3869 if (!isa<Constant>(V) &&
3871 return true;
3872
3873 if (const Value *Stripped = stripNullTest(V))
3874 return isKnownNonZero(Stripped, DemandedElts, Q, Depth);
3875
3876 return false;
3877}
3878
3880 unsigned Depth) {
3881 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
3882 APInt DemandedElts =
3883 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
3884 return ::isKnownNonZero(V, DemandedElts, Q, Depth);
3885}
3886
3887/// If the pair of operators are the same invertible function, return the
3888/// the operands of the function corresponding to each input. Otherwise,
3889/// return std::nullopt. An invertible function is one that is 1-to-1 and maps
3890/// every input value to exactly one output value. This is equivalent to
3891/// saying that Op1 and Op2 are equal exactly when the specified pair of
3892/// operands are equal, (except that Op1 and Op2 may be poison more often.)
3893static std::optional<std::pair<Value*, Value*>>
3895 const Operator *Op2) {
3896 if (Op1->getOpcode() != Op2->getOpcode())
3897 return std::nullopt;
3898
3899 auto getOperands = [&](unsigned OpNum) -> auto {
3900 return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
3901 };
3902
3903 switch (Op1->getOpcode()) {
3904 default:
3905 break;
3906 case Instruction::Or:
3907 if (!cast<PossiblyDisjointInst>(Op1)->isDisjoint() ||
3908 !cast<PossiblyDisjointInst>(Op2)->isDisjoint())
3909 break;
3910 [[fallthrough]];
3911 case Instruction::Xor:
3912 case Instruction::Add: {
3913 Value *Other;
3914 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(0)), m_Value(Other))))
3915 return std::make_pair(Op1->getOperand(1), Other);
3916 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(1)), m_Value(Other))))
3917 return std::make_pair(Op1->getOperand(0), Other);
3918 break;
3919 }
3920 case Instruction::Sub:
3921 if (Op1->getOperand(0) == Op2->getOperand(0))
3922 return getOperands(1);
3923 if (Op1->getOperand(1) == Op2->getOperand(1))
3924 return getOperands(0);
3925 break;
3926 case Instruction::Mul: {
3927 // invertible if A * B == (A * B) mod 2^N where A, and B are integers
3928 // and N is the bitwdith. The nsw case is non-obvious, but proven by
3929 // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
3930 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3931 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3932 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3933 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3934 break;
3935
3936 // Assume operand order has been canonicalized
3937 if (Op1->getOperand(1) == Op2->getOperand(1) &&
3938 isa<ConstantInt>(Op1->getOperand(1)) &&
3939 !cast<ConstantInt>(Op1->getOperand(1))->isZero())
3940 return getOperands(0);
3941 break;
3942 }
3943 case Instruction::Shl: {
3944 // Same as multiplies, with the difference that we don't need to check
3945 // for a non-zero multiply. Shifts always multiply by non-zero.
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 if (Op1->getOperand(1) == Op2->getOperand(1))
3953 return getOperands(0);
3954 break;
3955 }
3956 case Instruction::AShr:
3957 case Instruction::LShr: {
3958 auto *PEO1 = cast<PossiblyExactOperator>(Op1);
3959 auto *PEO2 = cast<PossiblyExactOperator>(Op2);
3960 if (!PEO1->isExact() || !PEO2->isExact())
3961 break;
3962
3963 if (Op1->getOperand(1) == Op2->getOperand(1))
3964 return getOperands(0);
3965 break;
3966 }
3967 case Instruction::SExt:
3968 case Instruction::ZExt:
3969 if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
3970 return getOperands(0);
3971 break;
3972 case Instruction::PHI: {
3973 const PHINode *PN1 = cast<PHINode>(Op1);
3974 const PHINode *PN2 = cast<PHINode>(Op2);
3975
3976 // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
3977 // are a single invertible function of the start values? Note that repeated
3978 // application of an invertible function is also invertible
3979 BinaryOperator *BO1 = nullptr;
3980 Value *Start1 = nullptr, *Step1 = nullptr;
3981 BinaryOperator *BO2 = nullptr;
3982 Value *Start2 = nullptr, *Step2 = nullptr;
3983 if (PN1->getParent() != PN2->getParent() ||
3984 !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
3985 !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
3986 break;
3987
3989 cast<Operator>(BO2));
3990 if (!Values)
3991 break;
3992
3993 // We have to be careful of mutually defined recurrences here. Ex:
3994 // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
3995 // * X_i = Y_i = X_(i-1) OP Y_(i-1)
3996 // The invertibility of these is complicated, and not worth reasoning
3997 // about (yet?).
3998 if (Values->first != PN1 || Values->second != PN2)
3999 break;
4000
4001 return std::make_pair(Start1, Start2);
4002 }
4003 }
4004 return std::nullopt;
4005}
4006
4007/// Return true if V1 == (binop V2, X), where X is known non-zero.
4008/// Only handle a small subset of binops where (binop V2, X) with non-zero X
4009/// implies V2 != V1.
4010static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2,
4011 const APInt &DemandedElts,
4012 const SimplifyQuery &Q, unsigned Depth) {
4014 if (!BO)
4015 return false;
4016 switch (BO->getOpcode()) {
4017 default:
4018 break;
4019 case Instruction::Or:
4020 if (!cast<PossiblyDisjointInst>(V1)->isDisjoint())
4021 break;
4022 [[fallthrough]];
4023 case Instruction::Xor:
4024 case Instruction::Add:
4025 Value *Op = nullptr;
4026 if (V2 == BO->getOperand(0))
4027 Op = BO->getOperand(1);
4028 else if (V2 == BO->getOperand(1))
4029 Op = BO->getOperand(0);
4030 else
4031 return false;
4032 return isKnownNonZero(Op, DemandedElts, Q, Depth + 1);
4033 }
4034 return false;
4035}
4036
4037/// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
4038/// the multiplication is nuw or nsw.
4039static bool isNonEqualMul(const Value *V1, const Value *V2,
4040 const APInt &DemandedElts, const SimplifyQuery &Q,
4041 unsigned Depth) {
4042 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4043 const APInt *C;
4044 return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
4045 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4046 !C->isZero() && !C->isOne() &&
4047 isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4048 }
4049 return false;
4050}
4051
4052/// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
4053/// the shift is nuw or nsw.
4054static bool isNonEqualShl(const Value *V1, const Value *V2,
4055 const APInt &DemandedElts, const SimplifyQuery &Q,
4056 unsigned Depth) {
4057 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4058 const APInt *C;
4059 return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
4060 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4061 !C->isZero() && isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4062 }
4063 return false;
4064}
4065
4066static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
4067 const APInt &DemandedElts, const SimplifyQuery &Q,
4068 unsigned Depth) {
4069 // Check two PHIs are in same block.
4070 if (PN1->getParent() != PN2->getParent())
4071 return false;
4072
4074 bool UsedFullRecursion = false;
4075 for (const BasicBlock *IncomBB : PN1->blocks()) {
4076 if (!VisitedBBs.insert(IncomBB).second)
4077 continue; // Don't reprocess blocks that we have dealt with already.
4078 const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
4079 const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
4080 const APInt *C1, *C2;
4081 if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
4082 continue;
4083
4084 // Only one pair of phi operands is allowed for full recursion.
4085 if (UsedFullRecursion)
4086 return false;
4087
4089 RecQ.CxtI = IncomBB->getTerminator();
4090 if (!isKnownNonEqual(IV1, IV2, DemandedElts, RecQ, Depth + 1))
4091 return false;
4092 UsedFullRecursion = true;
4093 }
4094 return true;
4095}
4096
4097static bool isNonEqualSelect(const Value *V1, const Value *V2,
4098 const APInt &DemandedElts, const SimplifyQuery &Q,
4099 unsigned Depth) {
4100 const SelectInst *SI1 = dyn_cast<SelectInst>(V1);
4101 if (!SI1)
4102 return false;
4103
4104 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) {
4105 const Value *Cond1 = SI1->getCondition();
4106 const Value *Cond2 = SI2->getCondition();
4107 if (Cond1 == Cond2)
4108 return isKnownNonEqual(SI1->getTrueValue(), SI2->getTrueValue(),
4109 DemandedElts, Q, Depth + 1) &&
4110 isKnownNonEqual(SI1->getFalseValue(), SI2->getFalseValue(),
4111 DemandedElts, Q, Depth + 1);
4112 }
4113 return isKnownNonEqual(SI1->getTrueValue(), V2, DemandedElts, Q, Depth + 1) &&
4114 isKnownNonEqual(SI1->getFalseValue(), V2, DemandedElts, Q, Depth + 1);
4115}
4116
4117// Check to see if A is both a GEP and is the incoming value for a PHI in the
4118// loop, and B is either a ptr or another GEP. If the PHI has 2 incoming values,
4119// one of them being the recursive GEP A and the other a ptr at same base and at
4120// the same/higher offset than B we are only incrementing the pointer further in
4121// loop if offset of recursive GEP is greater than 0.
4123 const SimplifyQuery &Q) {
4124 if (!A->getType()->isPointerTy() || !B->getType()->isPointerTy())
4125 return false;
4126
4127 auto *GEPA = dyn_cast<GEPOperator>(A);
4128 if (!GEPA || GEPA->getNumIndices() != 1 || !isa<Constant>(GEPA->idx_begin()))
4129 return false;
4130
4131 // Handle 2 incoming PHI values with one being a recursive GEP.
4132 auto *PN = dyn_cast<PHINode>(GEPA->getPointerOperand());
4133 if (!PN || PN->getNumIncomingValues() != 2)
4134 return false;
4135
4136 // Search for the recursive GEP as an incoming operand, and record that as
4137 // Step.
4138 Value *Start = nullptr;
4139 Value *Step = const_cast<Value *>(A);
4140 if (PN->getIncomingValue(0) == Step)
4141 Start = PN->getIncomingValue(1);
4142 else if (PN->getIncomingValue(1) == Step)
4143 Start = PN->getIncomingValue(0);
4144 else
4145 return false;
4146
4147 // Other incoming node base should match the B base.
4148 // StartOffset >= OffsetB && StepOffset > 0?
4149 // StartOffset <= OffsetB && StepOffset < 0?
4150 // Is non-equal if above are true.
4151 // We use stripAndAccumulateInBoundsConstantOffsets to restrict the
4152 // optimisation to inbounds GEPs only.
4153 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(Start->getType());
4154 APInt StartOffset(IndexWidth, 0);
4155 Start = Start->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StartOffset);
4156 APInt StepOffset(IndexWidth, 0);
4157 Step = Step->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StepOffset);
4158
4159 // Check if Base Pointer of Step matches the PHI.
4160 if (Step != PN)
4161 return false;
4162 APInt OffsetB(IndexWidth, 0);
4163 B = B->stripAndAccumulateInBoundsConstantOffsets(Q.DL, OffsetB);
4164 return Start == B &&
4165 ((StartOffset.sge(OffsetB) && StepOffset.isStrictlyPositive()) ||
4166 (StartOffset.sle(OffsetB) && StepOffset.isNegative()));
4167}
4168
4169static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2,
4170 const SimplifyQuery &Q, unsigned Depth) {
4171 if (!Q.CxtI)
4172 return false;
4173
4174 // Try to infer NonEqual based on information from dominating conditions.
4175 if (Q.DC && Q.DT) {
4176 auto IsKnownNonEqualFromDominatingCondition = [&](const Value *V) {
4177 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4178 Value *Cond = BI->getCondition();
4179 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
4180 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()) &&
4182 /*LHSIsTrue=*/true, Depth)
4183 .value_or(false))
4184 return true;
4185
4186 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
4187 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()) &&
4189 /*LHSIsTrue=*/false, Depth)
4190 .value_or(false))
4191 return true;
4192 }
4193
4194 return false;
4195 };
4196
4197 if (IsKnownNonEqualFromDominatingCondition(V1) ||
4198 IsKnownNonEqualFromDominatingCondition(V2))
4199 return true;
4200 }
4201
4202 if (!Q.AC)
4203 return false;
4204
4205 // Try to infer NonEqual based on information from assumptions.
4206 for (auto &AssumeVH : Q.AC->assumptionsFor(V1)) {
4207 if (!AssumeVH)
4208 continue;
4209 CallInst *I = cast<CallInst>(AssumeVH);
4210
4211 assert(I->getFunction() == Q.CxtI->getFunction() &&
4212 "Got assumption for the wrong function!");
4213 assert(I->getIntrinsicID() == Intrinsic::assume &&
4214 "must be an assume intrinsic");
4215
4216 if (isImpliedCondition(I->getArgOperand(0), ICmpInst::ICMP_NE, V1, V2, Q.DL,
4217 /*LHSIsTrue=*/true, Depth)
4218 .value_or(false) &&
4220 return true;
4221 }
4222
4223 return false;
4224}
4225
4226static bool isNonEqualURem(const Value *X, const Value *Rem,
4227 const SimplifyQuery &Q) {
4228 const Value *Y;
4229 if (!match(Rem, m_URem(m_Specific(X), m_Value(Y))))
4230 return false;
4231
4232 // For a defined urem, X != X urem Y exactly when X u>= Y.
4233 // isTruePredicate does not handle UGE, so use the equivalent Y u<= X.
4235 return true;
4236
4237 std::optional<bool> Implied =
4239 return Implied && *Implied;
4240}
4241
4242/// Return true if it is known that V1 != V2.
4243static bool isKnownNonEqual(const Value *V1, const Value *V2,
4244 const APInt &DemandedElts, const SimplifyQuery &Q,
4245 unsigned Depth) {
4246 if (V1 == V2)
4247 return false;
4248 if (V1->getType() != V2->getType())
4249 // We can't look through casts yet.
4250 return false;
4251
4253 return false;
4254
4255 // See if we can recurse through (exactly one of) our operands. This
4256 // requires our operation be 1-to-1 and map every input value to exactly
4257 // one output value. Such an operation is invertible.
4258 auto *O1 = dyn_cast<Operator>(V1);
4259 auto *O2 = dyn_cast<Operator>(V2);
4260 if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
4261 if (auto Values = getInvertibleOperands(O1, O2))
4262 return isKnownNonEqual(Values->first, Values->second, DemandedElts, Q,
4263 Depth + 1);
4264
4265 if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
4266 const PHINode *PN2 = cast<PHINode>(V2);
4267 // FIXME: This is missing a generalization to handle the case where one is
4268 // a PHI and another one isn't.
4269 if (isNonEqualPHIs(PN1, PN2, DemandedElts, Q, Depth))
4270 return true;
4271 };
4272 }
4273
4274 if (isModifyingBinopOfNonZero(V1, V2, DemandedElts, Q, Depth) ||
4275 isModifyingBinopOfNonZero(V2, V1, DemandedElts, Q, Depth))
4276 return true;
4277
4278 if (isNonEqualMul(V1, V2, DemandedElts, Q, Depth) ||
4279 isNonEqualMul(V2, V1, DemandedElts, Q, Depth))
4280 return true;
4281
4282 if (isNonEqualShl(V1, V2, DemandedElts, Q, Depth) ||
4283 isNonEqualShl(V2, V1, DemandedElts, Q, Depth))
4284 return true;
4285
4286 if (V1->getType()->isIntOrIntVectorTy()) {
4287 // Are any known bits in V1 contradictory to known bits in V2? If V1
4288 // has a known zero where V2 has a known one, they must not be equal.
4289 KnownBits Known1 = computeKnownBits(V1, DemandedElts, Q, Depth);
4290 if (!Known1.isUnknown()) {
4291 KnownBits Known2 = computeKnownBits(V2, DemandedElts, Q, Depth);
4292 if (Known1.Zero.intersects(Known2.One) ||
4293 Known2.Zero.intersects(Known1.One))
4294 return true;
4295 }
4296 }
4297
4298 if (isNonEqualSelect(V1, V2, DemandedElts, Q, Depth) ||
4299 isNonEqualSelect(V2, V1, DemandedElts, Q, Depth))
4300 return true;
4301
4304 return true;
4305
4306 Value *A, *B;
4307 // PtrToInts are NonEqual if their Ptrs are NonEqual.
4308 // Check PtrToInt type matches the pointer size.
4309 if (match(V1, m_PtrToIntSameSize(Q.DL, m_Value(A))) &&
4311 return isKnownNonEqual(A, B, DemandedElts, Q, Depth + 1);
4312
4313 if (isNonEqualURem(V1, V2, Q) || isNonEqualURem(V2, V1, Q))
4314 return true;
4315
4316 if (isKnownNonEqualFromContext(V1, V2, Q, Depth))
4317 return true;
4318
4319 return false;
4320}
4321
4322/// For vector constants, loop over the elements and find the constant with the
4323/// minimum number of sign bits. Return 0 if the value is not a vector constant
4324/// or if any element was not analyzed; otherwise, return the count for the
4325/// element with the minimum number of sign bits.
4327 const APInt &DemandedElts,
4328 unsigned TyBits) {
4329 const auto *CV = dyn_cast<Constant>(V);
4330 if (!CV || !isa<FixedVectorType>(CV->getType()))
4331 return 0;
4332
4333 unsigned MinSignBits = TyBits;
4334 unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
4335 for (unsigned i = 0; i != NumElts; ++i) {
4336 if (!DemandedElts[i])
4337 continue;
4338 // If we find a non-ConstantInt, bail out.
4339 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
4340 if (!Elt)
4341 return 0;
4342
4343 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
4344 }
4345
4346 return MinSignBits;
4347}
4348
4349static unsigned ComputeNumSignBitsImpl(const Value *V,
4350 const APInt &DemandedElts,
4351 const SimplifyQuery &Q, unsigned Depth);
4352
4353static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
4354 const SimplifyQuery &Q, unsigned Depth) {
4355 unsigned Result = ComputeNumSignBitsImpl(V, DemandedElts, Q, Depth);
4356 assert(Result > 0 && "At least one sign bit needs to be present!");
4357 return Result;
4358}
4359
4360/// Return the number of times the sign bit of the register is replicated into
4361/// the other bits. We know that at least 1 bit is always equal to the sign bit
4362/// (itself), but other cases can give us information. For example, immediately
4363/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
4364/// other, so we return 3. For vectors, return the number of sign bits for the
4365/// vector element with the minimum number of known sign bits of the demanded
4366/// elements in the vector specified by DemandedElts.
4367static unsigned ComputeNumSignBitsImpl(const Value *V,
4368 const APInt &DemandedElts,
4369 const SimplifyQuery &Q, unsigned Depth) {
4370 Type *Ty = V->getType();
4371#ifndef NDEBUG
4372 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
4373
4374 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
4375 assert(
4376 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
4377 "DemandedElt width should equal the fixed vector number of elements");
4378 } else {
4379 assert(DemandedElts == APInt(1, 1) &&
4380 "DemandedElt width should be 1 for scalars");
4381 }
4382#endif
4383
4384 // We return the minimum number of sign bits that are guaranteed to be present
4385 // in V, so for undef we have to conservatively return 1. We don't have the
4386 // same behavior for poison though -- that's a FIXME today.
4387
4388 Type *ScalarTy = Ty->getScalarType();
4389 unsigned TyBits = ScalarTy->isPointerTy() ?
4390 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
4391 Q.DL.getTypeSizeInBits(ScalarTy);
4392
4393 unsigned Tmp, Tmp2;
4394 unsigned FirstAnswer = 1;
4395
4396 // Note that ConstantInt is handled by the general computeKnownBits case
4397 // below.
4398
4400 return 1;
4401
4402 if (auto *U = dyn_cast<Operator>(V)) {
4403 switch (Operator::getOpcode(V)) {
4404 default: break;
4405 case Instruction::BitCast: {
4406 Value *Src = U->getOperand(0);
4407 Type *SrcTy = Src->getType();
4408
4409 // Skip if the source type is not an integer or integer vector type
4410 // This ensures we only process integer-like types
4411 if (!SrcTy->isIntOrIntVectorTy())
4412 break;
4413
4414 unsigned SrcBits = SrcTy->getScalarSizeInBits();
4415
4416 // Bitcast 'large element' scalar/vector to 'small element' vector.
4417 if ((SrcBits % TyBits) != 0)
4418 break;
4419
4420 // Only proceed if the destination type is a fixed-size vector
4421 if (isa<FixedVectorType>(Ty)) {
4422 // Fast case - sign splat can be simply split across the small elements.
4423 // This works for both vector and scalar sources
4424 Tmp = ComputeNumSignBits(Src, Q, Depth + 1);
4425 if (Tmp == SrcBits)
4426 return TyBits;
4427 }
4428 break;
4429 }
4430 case Instruction::SExt:
4431 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
4432 return ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1) +
4433 Tmp;
4434
4435 case Instruction::SDiv: {
4436 const APInt *Denominator;
4437 // sdiv X, C -> adds log(C) sign bits.
4438 if (match(U->getOperand(1), m_APInt(Denominator))) {
4439
4440 // Ignore non-positive denominator.
4441 if (!Denominator->isStrictlyPositive())
4442 break;
4443
4444 // Calculate the incoming numerator bits.
4445 unsigned NumBits =
4446 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4447
4448 // Add floor(log(C)) bits to the numerator bits.
4449 return std::min(TyBits, NumBits + Denominator->logBase2());
4450 }
4451 break;
4452 }
4453
4454 case Instruction::SRem: {
4455 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4456
4457 const APInt *Denominator;
4458 // srem X, C -> we know that the result is within [-C+1,C) when C is a
4459 // positive constant. This let us put a lower bound on the number of sign
4460 // bits.
4461 if (match(U->getOperand(1), m_APInt(Denominator))) {
4462
4463 // Ignore non-positive denominator.
4464 if (Denominator->isStrictlyPositive()) {
4465 // Calculate the leading sign bit constraints by examining the
4466 // denominator. Given that the denominator is positive, there are two
4467 // cases:
4468 //
4469 // 1. The numerator is positive. The result range is [0,C) and
4470 // [0,C) u< (1 << ceilLogBase2(C)).
4471 //
4472 // 2. The numerator is negative. Then the result range is (-C,0] and
4473 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
4474 //
4475 // Thus a lower bound on the number of sign bits is `TyBits -
4476 // ceilLogBase2(C)`.
4477
4478 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
4479 Tmp = std::max(Tmp, ResBits);
4480 }
4481 }
4482 return Tmp;
4483 }
4484
4485 case Instruction::AShr: {
4486 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4487 // ashr X, C -> adds C sign bits. Vectors too.
4488 const APInt *ShAmt;
4489 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4490 if (ShAmt->uge(TyBits))
4491 break; // Bad shift.
4492 unsigned ShAmtLimited = ShAmt->getZExtValue();
4493 Tmp += ShAmtLimited;
4494 if (Tmp > TyBits) Tmp = TyBits;
4495 }
4496 return Tmp;
4497 }
4498 case Instruction::Shl: {
4499 const APInt *ShAmt;
4500 Value *X = nullptr;
4501 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4502 // shl destroys sign bits.
4503 if (ShAmt->uge(TyBits))
4504 break; // Bad shift.
4505 // We can look through a zext (more or less treating it as a sext) if
4506 // all extended bits are shifted out.
4507 if (match(U->getOperand(0), m_ZExt(m_Value(X))) &&
4508 ShAmt->uge(TyBits - X->getType()->getScalarSizeInBits())) {
4509 Tmp = ComputeNumSignBits(X, DemandedElts, Q, Depth + 1);
4510 Tmp += TyBits - X->getType()->getScalarSizeInBits();
4511 } else
4512 Tmp =
4513 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4514 if (ShAmt->uge(Tmp))
4515 break; // Shifted all sign bits out.
4516 Tmp2 = ShAmt->getZExtValue();
4517 return Tmp - Tmp2;
4518 }
4519 break;
4520 }
4521 case Instruction::And:
4522 case Instruction::Or:
4523 case Instruction::Xor: // NOT is handled here.
4524 // Logical binary ops preserve the number of sign bits at the worst.
4525 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4526 if (Tmp != 1) {
4527 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4528 FirstAnswer = std::min(Tmp, Tmp2);
4529 // We computed what we know about the sign bits as our first
4530 // answer. Now proceed to the generic code that uses
4531 // computeKnownBits, and pick whichever answer is better.
4532 }
4533 break;
4534
4535 case Instruction::Select: {
4536 // If we have a clamp pattern, we know that the number of sign bits will
4537 // be the minimum of the clamp min/max range.
4538 const Value *X;
4539 const APInt *CLow, *CHigh;
4540 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
4541 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4542
4543 Tmp = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4544 if (Tmp == 1)
4545 break;
4546 Tmp2 = ComputeNumSignBits(U->getOperand(2), DemandedElts, Q, Depth + 1);
4547 return std::min(Tmp, Tmp2);
4548 }
4549
4550 case Instruction::Add:
4551 // Add can have at most one carry bit. Thus we know that the output
4552 // is, at worst, one more bit than the inputs.
4553 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4554 if (Tmp == 1) break;
4555
4556 // Special case decrementing a value (ADD X, -1):
4557 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
4558 if (CRHS->isAllOnesValue()) {
4559 KnownBits Known(TyBits);
4560 computeKnownBits(U->getOperand(0), DemandedElts, Known, Q, Depth + 1);
4561
4562 // If the input is known to be 0 or 1, the output is 0/-1, which is
4563 // all sign bits set.
4564 if ((Known.Zero | 1).isAllOnes())
4565 return TyBits;
4566
4567 // If we are subtracting one from a positive number, there is no carry
4568 // out of the result.
4569 if (Known.isNonNegative())
4570 return Tmp;
4571 }
4572
4573 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4574 if (Tmp2 == 1)
4575 break;
4576 return std::min(Tmp, Tmp2) - 1;
4577
4578 case Instruction::Sub:
4579 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4580 if (Tmp2 == 1)
4581 break;
4582
4583 // Handle NEG.
4584 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
4585 if (CLHS->isNullValue()) {
4586 KnownBits Known(TyBits);
4587 computeKnownBits(U->getOperand(1), DemandedElts, Known, Q, Depth + 1);
4588 // If the input is known to be 0 or 1, the output is 0/-1, which is
4589 // all sign bits set.
4590 if ((Known.Zero | 1).isAllOnes())
4591 return TyBits;
4592
4593 // If the input is known to be positive (the sign bit is known clear),
4594 // the output of the NEG has the same number of sign bits as the
4595 // input.
4596 if (Known.isNonNegative())
4597 return Tmp2;
4598
4599 // Otherwise, we treat this like a SUB.
4600 }
4601
4602 // Sub can have at most one carry bit. Thus we know that the output
4603 // is, at worst, one more bit than the inputs.
4604 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4605 if (Tmp == 1)
4606 break;
4607 return std::min(Tmp, Tmp2) - 1;
4608
4609 case Instruction::Mul: {
4610 // The output of the Mul can be at most twice the valid bits in the
4611 // inputs.
4612 unsigned SignBitsOp0 =
4613 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4614 if (SignBitsOp0 == 1)
4615 break;
4616 unsigned SignBitsOp1 =
4617 ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4618 if (SignBitsOp1 == 1)
4619 break;
4620 unsigned OutValidBits =
4621 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
4622 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
4623 }
4624
4625 case Instruction::PHI: {
4626 const PHINode *PN = cast<PHINode>(U);
4627 unsigned NumIncomingValues = PN->getNumIncomingValues();
4628 // Don't analyze large in-degree PHIs.
4629 if (NumIncomingValues > 4) break;
4630 // Unreachable blocks may have zero-operand PHI nodes.
4631 if (NumIncomingValues == 0) break;
4632
4633 // Take the minimum of all incoming values. This can't infinitely loop
4634 // because of our depth threshold.
4636 Tmp = TyBits;
4637 for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
4638 if (Tmp == 1) return Tmp;
4639 RecQ.CxtI = PN->getIncomingBlock(i)->getTerminator();
4640 Tmp = std::min(Tmp, ComputeNumSignBits(PN->getIncomingValue(i),
4641 DemandedElts, RecQ, Depth + 1));
4642 }
4643 return Tmp;
4644 }
4645
4646 case Instruction::Trunc: {
4647 // If the input contained enough sign bits that some remain after the
4648 // truncation, then we can make use of that. Otherwise we don't know
4649 // anything.
4650 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4651 unsigned OperandTyBits = U->getOperand(0)->getType()->getScalarSizeInBits();
4652 if (Tmp > (OperandTyBits - TyBits))
4653 return Tmp - (OperandTyBits - TyBits);
4654
4655 return 1;
4656 }
4657
4658 case Instruction::ExtractElement:
4659 // Look through extract element. At the moment we keep this simple and
4660 // skip tracking the specific element. But at least we might find
4661 // information valid for all elements of the vector (for example if vector
4662 // is sign extended, shifted, etc).
4663 return ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4664
4665 case Instruction::ShuffleVector: {
4666 // Collect the minimum number of sign bits that are shared by every vector
4667 // element referenced by the shuffle.
4668 auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
4669 if (!Shuf) {
4670 // FIXME: Add support for shufflevector constant expressions.
4671 return 1;
4672 }
4673 APInt DemandedLHS, DemandedRHS;
4674 // For undef elements, we don't know anything about the common state of
4675 // the shuffle result.
4676 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
4677 return 1;
4678 Tmp = std::numeric_limits<unsigned>::max();
4679 if (!!DemandedLHS) {
4680 const Value *LHS = Shuf->getOperand(0);
4681 Tmp = ComputeNumSignBits(LHS, DemandedLHS, Q, Depth + 1);
4682 }
4683 // If we don't know anything, early out and try computeKnownBits
4684 // fall-back.
4685 if (Tmp == 1)
4686 break;
4687 if (!!DemandedRHS) {
4688 const Value *RHS = Shuf->getOperand(1);
4689 Tmp2 = ComputeNumSignBits(RHS, DemandedRHS, Q, Depth + 1);
4690 Tmp = std::min(Tmp, Tmp2);
4691 }
4692 // If we don't know anything, early out and try computeKnownBits
4693 // fall-back.
4694 if (Tmp == 1)
4695 break;
4696 assert(Tmp <= TyBits && "Failed to determine minimum sign bits");
4697 return Tmp;
4698 }
4699 case Instruction::Call: {
4700 if (const auto *II = dyn_cast<IntrinsicInst>(U)) {
4701 switch (II->getIntrinsicID()) {
4702 default:
4703 break;
4704 case Intrinsic::abs:
4705 Tmp =
4706 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4707 if (Tmp == 1)
4708 break;
4709
4710 // Absolute value reduces number of sign bits by at most 1.
4711 return Tmp - 1;
4712 case Intrinsic::smin:
4713 case Intrinsic::smax: {
4714 const APInt *CLow, *CHigh;
4715 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
4716 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4717 }
4718 }
4719 }
4720 }
4721 }
4722 }
4723
4724 // Finally, if we can prove that the top bits of the result are 0's or 1's,
4725 // use this information.
4726
4727 // If we can examine all elements of a vector constant successfully, we're
4728 // done (we can't do any better than that). If not, keep trying.
4729 if (unsigned VecSignBits =
4730 computeNumSignBitsVectorConstant(V, DemandedElts, TyBits))
4731 return VecSignBits;
4732
4733 KnownBits Known(TyBits);
4734 computeKnownBits(V, DemandedElts, Known, Q, Depth);
4735
4736 // If we know that the sign bit is either zero or one, determine the number of
4737 // identical bits in the top of the input value.
4738 return std::max(FirstAnswer, Known.countMinSignBits());
4739}
4740
4742 const TargetLibraryInfo *TLI) {
4743 const Function *F = CB.getCalledFunction();
4744 if (!F)
4746
4747 if (F->isIntrinsic())
4748 return F->getIntrinsicID();
4749
4750 // We are going to infer semantics of a library function based on mapping it
4751 // to an LLVM intrinsic. Check that the library function is available from
4752 // this callbase and in this environment.
4753 if (F->hasLocalLinkage() || !TLI || !CB.onlyReadsMemory())
4755
4756 LibFunc Func = TLI->getLibFunc(CB);
4757 if (Func == NotLibFunc)
4759
4760 switch (Func) {
4761 default:
4762 break;
4763 case LibFunc_sin:
4764 case LibFunc_sinf:
4765 case LibFunc_sinl:
4766 return Intrinsic::sin;
4767 case LibFunc_cos:
4768 case LibFunc_cosf:
4769 case LibFunc_cosl:
4770 return Intrinsic::cos;
4771 case LibFunc_tan:
4772 case LibFunc_tanf:
4773 case LibFunc_tanl:
4774 return Intrinsic::tan;
4775 case LibFunc_asin:
4776 case LibFunc_asinf:
4777 case LibFunc_asinl:
4778 return Intrinsic::asin;
4779 case LibFunc_acos:
4780 case LibFunc_acosf:
4781 case LibFunc_acosl:
4782 return Intrinsic::acos;
4783 case LibFunc_atan:
4784 case LibFunc_atanf:
4785 case LibFunc_atanl:
4786 return Intrinsic::atan;
4787 case LibFunc_atan2:
4788 case LibFunc_atan2f:
4789 case LibFunc_atan2l:
4790 return Intrinsic::atan2;
4791 case LibFunc_sinh:
4792 case LibFunc_sinhf:
4793 case LibFunc_sinhl:
4794 return Intrinsic::sinh;
4795 case LibFunc_cosh:
4796 case LibFunc_coshf:
4797 case LibFunc_coshl:
4798 return Intrinsic::cosh;
4799 case LibFunc_tanh:
4800 case LibFunc_tanhf:
4801 case LibFunc_tanhl:
4802 return Intrinsic::tanh;
4803 case LibFunc_exp:
4804 case LibFunc_expf:
4805 case LibFunc_expl:
4806 return Intrinsic::exp;
4807 case LibFunc_exp2:
4808 case LibFunc_exp2f:
4809 case LibFunc_exp2l:
4810 return Intrinsic::exp2;
4811 case LibFunc_exp10:
4812 case LibFunc_exp10f:
4813 case LibFunc_exp10l:
4814 return Intrinsic::exp10;
4815 case LibFunc_log:
4816 case LibFunc_logf:
4817 case LibFunc_logl:
4818 return Intrinsic::log;
4819 case LibFunc_log10:
4820 case LibFunc_log10f:
4821 case LibFunc_log10l:
4822 return Intrinsic::log10;
4823 case LibFunc_log2:
4824 case LibFunc_log2f:
4825 case LibFunc_log2l:
4826 return Intrinsic::log2;
4827 case LibFunc_fabs:
4828 case LibFunc_fabsf:
4829 case LibFunc_fabsl:
4830 return Intrinsic::fabs;
4831 case LibFunc_fmin:
4832 case LibFunc_fminf:
4833 case LibFunc_fminl:
4834 return Intrinsic::minnum;
4835 case LibFunc_fmax:
4836 case LibFunc_fmaxf:
4837 case LibFunc_fmaxl:
4838 return Intrinsic::maxnum;
4839 case LibFunc_copysign:
4840 case LibFunc_copysignf:
4841 case LibFunc_copysignl:
4842 return Intrinsic::copysign;
4843 case LibFunc_floor:
4844 case LibFunc_floorf:
4845 case LibFunc_floorl:
4846 return Intrinsic::floor;
4847 case LibFunc_ceil:
4848 case LibFunc_ceilf:
4849 case LibFunc_ceill:
4850 return Intrinsic::ceil;
4851 case LibFunc_trunc:
4852 case LibFunc_truncf:
4853 case LibFunc_truncl:
4854 return Intrinsic::trunc;
4855 case LibFunc_rint:
4856 case LibFunc_rintf:
4857 case LibFunc_rintl:
4858 return Intrinsic::rint;
4859 case LibFunc_nearbyint:
4860 case LibFunc_nearbyintf:
4861 case LibFunc_nearbyintl:
4862 return Intrinsic::nearbyint;
4863 case LibFunc_round:
4864 case LibFunc_roundf:
4865 case LibFunc_roundl:
4866 return Intrinsic::round;
4867 case LibFunc_roundeven:
4868 case LibFunc_roundevenf:
4869 case LibFunc_roundevenl:
4870 return Intrinsic::roundeven;
4871 case LibFunc_pow:
4872 case LibFunc_powf:
4873 case LibFunc_powl:
4874 return Intrinsic::pow;
4875 case LibFunc_sqrt:
4876 case LibFunc_sqrtf:
4877 case LibFunc_sqrtl:
4878 return Intrinsic::sqrt;
4879 }
4880
4882}
4883
4884/// Given an exploded icmp instruction, return true if the comparison only
4885/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if
4886/// the result of the comparison is true when the input value is signed.
4888 bool &TrueIfSigned) {
4889 switch (Pred) {
4890 case ICmpInst::ICMP_SLT: // True if LHS s< 0
4891 TrueIfSigned = true;
4892 return RHS.isZero();
4893 case ICmpInst::ICMP_SLE: // True if LHS s<= -1
4894 TrueIfSigned = true;
4895 return RHS.isAllOnes();
4896 case ICmpInst::ICMP_SGT: // True if LHS s> -1
4897 TrueIfSigned = false;
4898 return RHS.isAllOnes();
4899 case ICmpInst::ICMP_SGE: // True if LHS s>= 0
4900 TrueIfSigned = false;
4901 return RHS.isZero();
4902 case ICmpInst::ICMP_UGT:
4903 // True if LHS u> RHS and RHS == sign-bit-mask - 1
4904 TrueIfSigned = true;
4905 return RHS.isMaxSignedValue();
4906 case ICmpInst::ICMP_UGE:
4907 // True if LHS u>= RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4908 TrueIfSigned = true;
4909 return RHS.isMinSignedValue();
4910 case ICmpInst::ICMP_ULT:
4911 // True if LHS u< RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4912 TrueIfSigned = false;
4913 return RHS.isMinSignedValue();
4914 case ICmpInst::ICMP_ULE:
4915 // True if LHS u<= RHS and RHS == sign-bit-mask - 1
4916 TrueIfSigned = false;
4917 return RHS.isMaxSignedValue();
4918 default:
4919 return false;
4920 }
4921}
4922
4924 bool CondIsTrue,
4925 const Instruction *CxtI,
4926 KnownFPClass &KnownFromContext,
4927 unsigned Depth = 0) {
4928 Value *A, *B;
4930 (CondIsTrue ? match(Cond, m_LogicalAnd(m_Value(A), m_Value(B)))
4931 : match(Cond, m_LogicalOr(m_Value(A), m_Value(B))))) {
4932 computeKnownFPClassFromCond(V, A, CondIsTrue, CxtI, KnownFromContext,
4933 Depth + 1);
4934 computeKnownFPClassFromCond(V, B, CondIsTrue, CxtI, KnownFromContext,
4935 Depth + 1);
4936 return;
4937 }
4939 computeKnownFPClassFromCond(V, A, !CondIsTrue, CxtI, KnownFromContext,
4940 Depth + 1);
4941 return;
4942 }
4943 CmpPredicate Pred;
4944 Value *LHS;
4945 uint64_t ClassVal = 0;
4946 const APFloat *CRHS;
4947 const APInt *RHS;
4948 if (match(Cond, m_FCmp(Pred, m_Value(LHS), m_APFloat(CRHS)))) {
4949 auto [CmpVal, MaskIfTrue, MaskIfFalse] = fcmpImpliesClass(
4950 Pred, *cast<Instruction>(Cond)->getParent()->getParent(), LHS, *CRHS,
4951 LHS != V);
4952 if (CmpVal == V)
4953 KnownFromContext.knownNot(~(CondIsTrue ? MaskIfTrue : MaskIfFalse));
4955 m_Specific(V), m_ConstantInt(ClassVal)))) {
4956 FPClassTest Mask = static_cast<FPClassTest>(ClassVal);
4957 KnownFromContext.knownNot(CondIsTrue ? ~Mask : Mask);
4958 } else if (match(Cond, m_ICmp(Pred, m_ElementWiseBitCast(m_Specific(V)),
4959 m_APInt(RHS)))) {
4960 bool TrueIfSigned;
4961 if (!isSignBitCheck(Pred, *RHS, TrueIfSigned))
4962 return;
4963 if (TrueIfSigned == CondIsTrue)
4964 KnownFromContext.signBitMustBeOne();
4965 else
4966 KnownFromContext.signBitMustBeZero();
4967 }
4968}
4969
4970/// Compute the minimum and maximum values (inclusive) for the exponent of \p V,
4971/// assuming it is not nan. Returns {min, max, max-assuming-nonzero}. A value
4972/// frexp(0) = 0, so the tighter max-assuming-nonzero bound is only usable when
4973/// \p V is known not to be a logical zero (e.g., for fabs(x) < 0.25, the non-0
4974/// exponent range is [-149, -2], but the 0 edge case is above this range).
4975static std::tuple<int, int, int>
4977 if (!Q.CxtI || !Q.DC || !Q.DT)
4979
4980 // Intersect the bounds implied by every dominating condition, keeping the
4981 // tightest maximum. A value may participate in multiple compares
4982 // (e.g. fabs(x) < 2.0 and fabs(x) < 1.0), and the tighter one wins.
4983 int MaxExp = APFloat::IEK_Inf;
4984 int MaxExpNonZero = APFloat::IEK_Inf;
4985
4986 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4987 CmpPredicate Pred;
4988 const APFloat *LimitC;
4989 if (!match(BI->getCondition(),
4990 m_FCmp(Pred, m_FAbs(m_Specific(V)), m_Finite(LimitC))))
4991 continue;
4992
4993 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO ||
4994 Pred == FCmpInst::FCMP_TRUE || Pred == FCmpInst::FCMP_FALSE)
4995 continue;
4996
4997 // If fabs(x) <= K, implies the exponent min exp range.
4998 // if fabs(x) >= K, swap the successor
4999 bool IsLessEqual =
5000 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
5001 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE ||
5002 Pred == FCmpInst::FCMP_OEQ || Pred == FCmpInst::FCMP_UEQ;
5003
5004 bool KnownStrictlyLess =
5005 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT ||
5006 Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
5007
5008 BasicBlockEdge Edge1(BI->getParent(),
5009 BI->getSuccessor(IsLessEqual ? 0 : 1));
5010 if (Q.DT->dominates(Edge1, Q.CxtI->getParent())) {
5011 // frexp returns an exponent one greater than ilogb.
5012 int Exp = ilogb(*LimitC) + 1;
5013
5014 // A strict bound fabs(V) < 2^n forces ilogb(V) <= n - 1, so the max frexp
5015 // exponent drops by one when K is exact power of two.
5016 if (KnownStrictlyLess && LimitC->getExactLog2Abs() != INT_MIN)
5017 --Exp;
5018
5019 // frexp(0) = 0, which the bound above (assuming a normal nonzero value)
5020 // may exclude.
5021
5022 // TODO: Figure out lower bound to detect no-underflow.
5023 MaxExpNonZero = std::min(MaxExpNonZero, Exp);
5024 MaxExp = std::min(MaxExp, std::max(Exp, 0));
5025 }
5026 }
5027
5028 return {APFloat::IEK_NaN, MaxExp, MaxExpNonZero};
5029}
5030
5032 const SimplifyQuery &Q) {
5033 KnownFPClass KnownFromContext;
5034
5035 if (Q.CC && Q.CC->AffectedValues.contains(V))
5037 KnownFromContext);
5038
5039 if (!Q.CxtI)
5040 return KnownFromContext;
5041
5042 if (Q.DC && Q.DT) {
5043 // Handle dominating conditions.
5044 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5045 Value *Cond = BI->getCondition();
5046
5047 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
5048 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()))
5049 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/true, Q.CxtI,
5050 KnownFromContext);
5051
5052 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
5053 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()))
5054 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/false, Q.CxtI,
5055 KnownFromContext);
5056 }
5057 }
5058
5059 if (!Q.AC)
5060 return KnownFromContext;
5061
5062 // Try to restrict the floating-point classes based on information from
5063 // assumptions.
5064 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
5065 if (!AssumeVH)
5066 continue;
5067 CallInst *I = cast<CallInst>(AssumeVH);
5068
5069 assert(I->getFunction() == Q.CxtI->getParent()->getParent() &&
5070 "Got assumption for the wrong function!");
5071 assert(I->getIntrinsicID() == Intrinsic::assume &&
5072 "must be an assume intrinsic");
5073
5074 if (!isValidAssumeForContext(I, Q))
5075 continue;
5076
5077 computeKnownFPClassFromCond(V, I->getArgOperand(0),
5078 /*CondIsTrue=*/true, Q.CxtI, KnownFromContext);
5079 }
5080
5081 return KnownFromContext;
5082}
5083
5085 Value *Arm, bool Invert,
5086 const SimplifyQuery &SQ,
5087 unsigned Depth) {
5088
5089 KnownFPClass KnownSrc;
5091 /*CondIsTrue=*/!Invert, SQ.CxtI, KnownSrc,
5092 Depth + 1);
5093 KnownSrc = KnownSrc.unionWith(Known);
5094 if (KnownSrc.isUnknown())
5095 return;
5096
5097 if (isGuaranteedNotToBeUndef(Arm, SQ.AC, SQ.CxtI, SQ.DT, Depth + 1))
5098 Known = KnownSrc;
5099}
5100
5101void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5102 FPClassTest InterestedClasses, KnownFPClass &Known,
5103 const SimplifyQuery &Q, unsigned Depth);
5104
5106 FPClassTest InterestedClasses,
5107 const SimplifyQuery &Q, unsigned Depth) {
5108 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
5109 APInt DemandedElts =
5110 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
5111 computeKnownFPClass(V, DemandedElts, InterestedClasses, Known, Q, Depth);
5112}
5113
5115 const APInt &DemandedElts,
5116 FPClassTest InterestedClasses,
5118 const SimplifyQuery &Q,
5119 unsigned Depth) {
5120 if ((InterestedClasses &
5122 return;
5123
5124 KnownFPClass KnownSrc;
5125 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5126 KnownSrc, Q, Depth + 1);
5127 Known = KnownFPClass::fptrunc(KnownSrc);
5128}
5129
5131 switch (IID) {
5132 case Intrinsic::minimum:
5134 case Intrinsic::maximum:
5136 case Intrinsic::minimumnum:
5138 case Intrinsic::maximumnum:
5140 case Intrinsic::minnum:
5142 case Intrinsic::maxnum:
5144 default:
5145 llvm_unreachable("not a floating-point min-max intrinsic");
5146 }
5147}
5148
5149/// \return true if this is a floating point value that is known to have a
5150/// magnitude smaller than 1. i.e., fabs(X) <= 1.0 or is nan.
5151static bool isAbsoluteValueULEOne(const Value *V) {
5152 // TODO: Handle frexp
5153 // TODO: Other rounding intrinsics?
5154 // TODO: Try computeKnownExponentRangeFromContext
5155
5156 // fabs(x - floor(x)) <= 1
5157 const Value *SubFloorX;
5158 if (match(V, m_FSub(m_Value(SubFloorX),
5160 return true;
5161
5164}
5165
5166void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5167 FPClassTest InterestedClasses, KnownFPClass &Known,
5168 const SimplifyQuery &Q, unsigned Depth) {
5169 assert(Known.isUnknown() && "should not be called with known information");
5170
5171 if (!DemandedElts) {
5172 // No demanded elts, better to assume we don't know anything.
5173 Known.resetAll();
5174 return;
5175 }
5176
5177 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
5178
5179 if (auto *CFP = dyn_cast<ConstantFP>(V)) {
5180 Known = KnownFPClass(CFP->getValueAPF());
5181 return;
5182 }
5183
5185 Known.KnownFPClasses = fcPosZero;
5186 Known.setSignBit(false);
5187 return;
5188 }
5189
5190 if (isa<PoisonValue>(V)) {
5191 Known.KnownFPClasses = fcNone;
5192 Known.setSignBit(false);
5193 return;
5194 }
5195
5196 // Try to handle fixed width vector constants
5197 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
5198 const Constant *CV = dyn_cast<Constant>(V);
5199 if (VFVTy && CV) {
5200 Known.KnownFPClasses = fcNone;
5201 bool SignBitAllZero = true;
5202 bool SignBitAllOne = true;
5203
5204 // For vectors, verify that each element is not NaN.
5205 unsigned NumElts = VFVTy->getNumElements();
5206 for (unsigned i = 0; i != NumElts; ++i) {
5207 if (!DemandedElts[i])
5208 continue;
5209
5210 Constant *Elt = CV->getAggregateElement(i);
5211 if (!Elt) {
5212 Known = KnownFPClass();
5213 return;
5214 }
5215 if (isa<PoisonValue>(Elt))
5216 continue;
5217 auto *CElt = dyn_cast<ConstantFP>(Elt);
5218 if (!CElt) {
5219 Known = KnownFPClass();
5220 return;
5221 }
5222
5223 const APFloat &C = CElt->getValueAPF();
5224 Known.KnownFPClasses |= C.classify();
5225 if (C.isNegative())
5226 SignBitAllZero = false;
5227 else
5228 SignBitAllOne = false;
5229 }
5230 if (SignBitAllOne != SignBitAllZero)
5231 Known.setSignBit(SignBitAllOne);
5232 return;
5233 }
5234
5235 if (const auto *CDS = dyn_cast<ConstantDataSequential>(V)) {
5236 Known.KnownFPClasses = fcNone;
5237 for (size_t I = 0, E = CDS->getNumElements(); I != E; ++I)
5238 Known |= CDS->getElementAsAPFloat(I).classify();
5239 return;
5240 }
5241
5242 if (const auto *CA = dyn_cast<ConstantAggregate>(V)) {
5243 // TODO: Handle complex aggregates
5244 Known.KnownFPClasses = fcNone;
5245 for (const Use &Op : CA->operands()) {
5246 auto *CFP = dyn_cast<ConstantFP>(Op.get());
5247 if (!CFP) {
5248 Known = KnownFPClass();
5249 return;
5250 }
5251
5252 Known |= CFP->getValueAPF().classify();
5253 }
5254
5255 return;
5256 }
5257
5258 FPClassTest KnownNotFromFlags = fcNone;
5259 if (const auto *CB = dyn_cast<CallBase>(V))
5260 KnownNotFromFlags |= CB->getRetNoFPClass();
5261 else if (const auto *Arg = dyn_cast<Argument>(V))
5262 KnownNotFromFlags |= Arg->getNoFPClass();
5263
5264 const Operator *Op = dyn_cast<Operator>(V);
5266 if (FPOp->hasNoNaNs())
5267 KnownNotFromFlags |= fcNan;
5268 if (FPOp->hasNoInfs())
5269 KnownNotFromFlags |= fcInf;
5270 }
5271
5272 KnownFPClass AssumedClasses = computeKnownFPClassFromContext(V, Q);
5273 KnownNotFromFlags |= ~AssumedClasses.KnownFPClasses;
5274
5275 // We no longer need to find out about these bits from inputs if we can
5276 // assume this from flags/attributes.
5277 InterestedClasses &= ~KnownNotFromFlags;
5278
5279 llvm::scope_exit ClearClassesFromFlags([=, &Known] {
5280 Known.knownNot(KnownNotFromFlags);
5281 if (!Known.getSignBit() && AssumedClasses.getSignBit()) {
5282 if (*AssumedClasses.getSignBit())
5283 Known.signBitMustBeOne();
5284 else
5285 Known.signBitMustBeZero();
5286 }
5287 });
5288
5289 if (!Op)
5290 return;
5291
5292 // All recursive calls that increase depth must come after this.
5294 return;
5295
5296 const unsigned Opc = Op->getOpcode();
5297 switch (Opc) {
5298 case Instruction::FNeg: {
5299 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5300 Known, Q, Depth + 1);
5301 Known.fneg();
5302 break;
5303 }
5304 case Instruction::Select: {
5305 auto ComputeForArm = [&](Value *Arm, bool Invert) {
5306 KnownFPClass Res;
5307 computeKnownFPClass(Arm, DemandedElts, InterestedClasses, Res, Q,
5308 Depth + 1);
5309 adjustKnownFPClassForSelectArm(Res, Op->getOperand(0), Arm, Invert, Q,
5310 Depth);
5311 return Res;
5312 };
5313 // Only known if known in both the LHS and RHS.
5314 Known =
5315 ComputeForArm(Op->getOperand(1), /*Invert=*/false)
5316 .intersectWith(ComputeForArm(Op->getOperand(2), /*Invert=*/true));
5317 break;
5318 }
5319 case Instruction::Load: {
5320 const MDNode *NoFPClass =
5321 cast<LoadInst>(Op)->getMetadata(LLVMContext::MD_nofpclass);
5322 if (!NoFPClass)
5323 break;
5324
5325 ConstantInt *MaskVal =
5327 Known.knownNot(static_cast<FPClassTest>(MaskVal->getZExtValue()));
5328 break;
5329 }
5330 case Instruction::Call: {
5331 const CallInst *II = cast<CallInst>(Op);
5332 const Intrinsic::ID IID = II->getIntrinsicID();
5333 switch (IID) {
5334 case Intrinsic::fabs: {
5335 if ((InterestedClasses & (fcNan | fcPositive)) != fcNone) {
5336 // If we only care about the sign bit we don't need to inspect the
5337 // operand.
5338 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5339 InterestedClasses, Known, Q, Depth + 1);
5340 }
5341
5342 Known.fabs();
5343 break;
5344 }
5345 case Intrinsic::copysign: {
5346 KnownFPClass KnownSign;
5347
5348 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5349 Known, Q, Depth + 1);
5350 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5351 KnownSign, Q, Depth + 1);
5352 Known.copysign(KnownSign);
5353 break;
5354 }
5355 case Intrinsic::fma:
5356 case Intrinsic::fmuladd: {
5357 if ((InterestedClasses & fcNegative) == fcNone)
5358 break;
5359
5360 // FIXME: This should check isGuaranteedNotToBeUndef
5361 if (II->getArgOperand(0) == II->getArgOperand(1)) {
5362 KnownFPClass KnownSrc, KnownAddend;
5363 computeKnownFPClass(II->getArgOperand(2), DemandedElts,
5364 InterestedClasses, KnownAddend, Q, Depth + 1);
5365 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5366 InterestedClasses, KnownSrc, Q, Depth + 1);
5367
5368 const Function *F = II->getFunction();
5369 const fltSemantics &FltSem =
5370 II->getType()->getScalarType()->getFltSemantics();
5372 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5373
5374 if (KnownNotFromFlags & fcNan) {
5375 KnownSrc.knownNot(fcNan);
5376 KnownAddend.knownNot(fcNan);
5377 }
5378
5379 if (KnownNotFromFlags & fcInf) {
5380 KnownSrc.knownNot(fcInf);
5381 KnownAddend.knownNot(fcInf);
5382 }
5383
5384 Known = KnownFPClass::fma_square(KnownSrc, KnownAddend, Mode);
5385 break;
5386 }
5387
5388 KnownFPClass KnownSrc[3];
5389 for (int I = 0; I != 3; ++I) {
5390 computeKnownFPClass(II->getArgOperand(I), DemandedElts,
5391 InterestedClasses, KnownSrc[I], Q, Depth + 1);
5392 if (KnownSrc[I].isUnknown())
5393 return;
5394
5395 if (KnownNotFromFlags & fcNan)
5396 KnownSrc[I].knownNot(fcNan);
5397 if (KnownNotFromFlags & fcInf)
5398 KnownSrc[I].knownNot(fcInf);
5399 }
5400
5401 const Function *F = II->getFunction();
5402 const fltSemantics &FltSem =
5403 II->getType()->getScalarType()->getFltSemantics();
5405 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5406 Known = KnownFPClass::fma(KnownSrc[0], KnownSrc[1], KnownSrc[2], Mode);
5407 break;
5408 }
5409 case Intrinsic::sqrt:
5410 case Intrinsic::experimental_constrained_sqrt: {
5411 KnownFPClass KnownSrc;
5412 FPClassTest InterestedSrcs = InterestedClasses;
5413 if (InterestedClasses & fcNan)
5414 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5415
5416 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5417 KnownSrc, Q, Depth + 1);
5418
5420
5421 bool HasNSZ = Q.IIQ.hasNoSignedZeros(II);
5422 if (!HasNSZ) {
5423 const Function *F = II->getFunction();
5424 const fltSemantics &FltSem =
5425 II->getType()->getScalarType()->getFltSemantics();
5426 Mode = F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5427 }
5428
5429 Known = KnownFPClass::sqrt(KnownSrc, Mode);
5430 if (HasNSZ)
5431 Known.knownNot(fcNegZero);
5432
5433 break;
5434 }
5435 case Intrinsic::sin: {
5436 KnownFPClass KnownSrc;
5437 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5438 KnownSrc, Q, Depth + 1);
5439 Known = KnownFPClass::sin(KnownSrc);
5440 break;
5441 }
5442 case Intrinsic::cos: {
5443 KnownFPClass KnownSrc;
5444 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5445 KnownSrc, Q, Depth + 1);
5446 Known = KnownFPClass::cos(KnownSrc);
5447 break;
5448 }
5449 case Intrinsic::tan: {
5450 KnownFPClass KnownSrc;
5451 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5452 KnownSrc, Q, Depth + 1);
5453 Known = KnownFPClass::tan(KnownSrc);
5454 break;
5455 }
5456 case Intrinsic::sinh: {
5457 KnownFPClass KnownSrc;
5458 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5459 KnownSrc, Q, Depth + 1);
5460 Known = KnownFPClass::sinh(KnownSrc);
5461 break;
5462 }
5463 case Intrinsic::cosh: {
5464 KnownFPClass KnownSrc;
5465 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5466 KnownSrc, Q, Depth + 1);
5467 Known = KnownFPClass::cosh(KnownSrc);
5468 break;
5469 }
5470 case Intrinsic::tanh: {
5471 KnownFPClass KnownSrc;
5472 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5473 KnownSrc, Q, Depth + 1);
5474 Known = KnownFPClass::tanh(KnownSrc);
5475 break;
5476 }
5477 case Intrinsic::asin: {
5478 KnownFPClass KnownSrc;
5479 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5480 KnownSrc, Q, Depth + 1);
5481 Known = KnownFPClass::asin(KnownSrc);
5482 break;
5483 }
5484 case Intrinsic::acos: {
5485 KnownFPClass KnownSrc;
5486 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5487 KnownSrc, Q, Depth + 1);
5488 Known = KnownFPClass::acos(KnownSrc);
5489 break;
5490 }
5491 case Intrinsic::atan: {
5492 KnownFPClass KnownSrc;
5493 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5494 KnownSrc, Q, Depth + 1);
5495 Known = KnownFPClass::atan(KnownSrc);
5496 break;
5497 }
5498 case Intrinsic::atan2: {
5499 FPClassTest InterestedY = InterestedClasses;
5500 FPClassTest InterestedX = InterestedClasses;
5501
5502 // We can rule out zero and subnormal if x cannot have a positive value.
5503 if ((InterestedClasses & (fcZero | fcSubnormal)) != fcNone)
5504 InterestedX |= fcPositive | fcNegSubnormal;
5505
5506 KnownFPClass KnownY, KnownX;
5507 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedY,
5508 KnownY, Q, Depth + 1);
5509 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedX,
5510 KnownX, Q, Depth + 1);
5511
5512 const Function *F = II->getFunction();
5514 F ? F->getDenormalMode(
5515 II->getType()->getScalarType()->getFltSemantics())
5517 Known = KnownFPClass::atan2(KnownY, KnownX, Mode);
5518 break;
5519 }
5520 case Intrinsic::maxnum:
5521 case Intrinsic::minnum:
5522 case Intrinsic::minimum:
5523 case Intrinsic::maximum:
5524 case Intrinsic::minimumnum:
5525 case Intrinsic::maximumnum: {
5526 KnownFPClass KnownLHS, KnownRHS;
5527 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5528 KnownLHS, Q, Depth + 1);
5529 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5530 KnownRHS, Q, Depth + 1);
5531
5532 const Function *F = II->getFunction();
5533
5535 F ? F->getDenormalMode(
5536 II->getType()->getScalarType()->getFltSemantics())
5538
5539 Known = KnownFPClass::minMaxLike(KnownLHS, KnownRHS, getMinMaxKind(IID),
5540 Mode);
5541 break;
5542 }
5543 case Intrinsic::canonicalize: {
5544 KnownFPClass KnownSrc;
5545 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5546 KnownSrc, Q, Depth + 1);
5547
5548 const Function *F = II->getFunction();
5549 DenormalMode DenormMode =
5550 F ? F->getDenormalMode(
5551 II->getType()->getScalarType()->getFltSemantics())
5553 Known = KnownFPClass::canonicalize(KnownSrc, DenormMode);
5554 break;
5555 }
5556 case Intrinsic::vector_reduce_fmax:
5557 case Intrinsic::vector_reduce_fmin:
5558 case Intrinsic::vector_reduce_fmaximum:
5559 case Intrinsic::vector_reduce_fminimum:
5560 case Intrinsic::vector_reduce_fmaximumnum:
5561 case Intrinsic::vector_reduce_fminimumnum: {
5562 // reduce min/max will choose an element from one of the vector elements,
5563 // so we can infer and class information that is common to all elements.
5564 Known = computeKnownFPClass(II->getArgOperand(0), II->getFastMathFlags(),
5565 InterestedClasses, Q, Depth + 1);
5566 // Can only propagate sign if output is never NaN.
5567 if (!Known.isKnownNeverNaN())
5568 Known.setSignBit(std::nullopt);
5569 break;
5570 }
5571 // reverse preserves all characteristics of the input vec's element.
5572 case Intrinsic::vector_reverse:
5574 II->getArgOperand(0), DemandedElts.reverseBits(),
5575 II->getFastMathFlags(), InterestedClasses, Q, Depth + 1);
5576 break;
5577 case Intrinsic::trunc:
5578 case Intrinsic::floor:
5579 case Intrinsic::ceil:
5580 case Intrinsic::rint:
5581 case Intrinsic::nearbyint:
5582 case Intrinsic::round:
5583 case Intrinsic::roundeven: {
5584 KnownFPClass KnownSrc;
5585 FPClassTest InterestedSrcs = InterestedClasses;
5586 if (InterestedSrcs & fcPosFinite)
5587 InterestedSrcs |= fcPosFinite;
5588 if (InterestedSrcs & fcNegFinite)
5589 InterestedSrcs |= fcNegFinite;
5590 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5591 KnownSrc, Q, Depth + 1);
5592
5594 KnownSrc, IID == Intrinsic::trunc,
5595 V->getType()->getScalarType()->isMultiUnitFPType());
5596 break;
5597 }
5598 case Intrinsic::exp:
5599 case Intrinsic::exp2:
5600 case Intrinsic::exp10:
5601 case Intrinsic::amdgcn_exp2: {
5602 KnownFPClass KnownSrc;
5603 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5604 KnownSrc, Q, Depth + 1);
5605
5606 Known = KnownFPClass::exp(KnownSrc);
5607
5608 Type *EltTy = II->getType()->getScalarType();
5609 if (IID == Intrinsic::amdgcn_exp2 && EltTy->isFloatTy())
5610 Known.knownNot(fcSubnormal);
5611
5612 break;
5613 }
5614 case Intrinsic::fptrunc_round: {
5615 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known,
5616 Q, Depth);
5617 break;
5618 }
5619 case Intrinsic::log:
5620 case Intrinsic::log10:
5621 case Intrinsic::log2:
5622 case Intrinsic::experimental_constrained_log:
5623 case Intrinsic::experimental_constrained_log10:
5624 case Intrinsic::experimental_constrained_log2:
5625 case Intrinsic::amdgcn_log: {
5626 Type *EltTy = II->getType()->getScalarType();
5627
5628 // log(+inf) -> +inf
5629 // log([+-]0.0) -> -inf
5630 // log(-inf) -> nan
5631 // log(-x) -> nan
5632 if ((InterestedClasses & (fcNan | fcInf)) != fcNone) {
5633 FPClassTest InterestedSrcs = InterestedClasses;
5634 if ((InterestedClasses & fcNegInf) != fcNone)
5635 InterestedSrcs |= fcZero | fcSubnormal;
5636 if ((InterestedClasses & fcNan) != fcNone)
5637 InterestedSrcs |= fcNan | fcNegative;
5638
5639 KnownFPClass KnownSrc;
5640 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5641 KnownSrc, Q, Depth + 1);
5642
5643 const Function *F = II->getFunction();
5644 DenormalMode Mode = F ? F->getDenormalMode(EltTy->getFltSemantics())
5646 Known = KnownFPClass::log(KnownSrc, Mode);
5647 }
5648
5649 break;
5650 }
5651 case Intrinsic::pow: {
5652 const bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5653 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
5654 if (!WantNaN && !WantNegative)
5655 break;
5656
5657 FPClassTest InterestedLHS = fcNone;
5658 FPClassTest InterestedRHS = fcNone;
5659 if (WantNaN) {
5660 // pow may return NaN if one of the arguments is NaN. NaN may also be
5661 // produced from a negative, non-zero finite base and a non-integer
5662 // exponent.
5663 InterestedLHS |= fcNan | fcNegNormal | fcNegSubnormal;
5664 InterestedRHS |= fcNan;
5665 }
5666 if (WantNegative) {
5667 // A negative value is returned when a negative base is raised to an odd
5668 // integer power. Only normal values can be odd integers.
5669 InterestedLHS |= fcNegative;
5670 InterestedRHS |= fcNormal;
5671 }
5672
5673 KnownFPClass KnownLHS;
5674 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedLHS,
5675 KnownLHS, Q, Depth + 1);
5676
5677 // If the LHS is unknown, then querying the RHS is only useful for rare
5678 // edge cases.
5679 if (KnownLHS.isUnknown())
5680 break;
5681
5682 KnownFPClass KnownRHS;
5683 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedRHS,
5684 KnownRHS, Q, Depth + 1);
5685 Known = KnownFPClass::pow(KnownLHS, KnownRHS);
5686 break;
5687 }
5688 case Intrinsic::powi: {
5689 if ((InterestedClasses & (fcNan | fcInf | fcNegative)) == fcNone)
5690 break;
5691
5692 // The exponent is always a scalar, even when raising a vector to a power.
5693 const Value *Exp = II->getArgOperand(1);
5694 unsigned BitWidth = Exp->getType()->getIntegerBitWidth();
5695 KnownBits ExponentKnownBits(BitWidth);
5696 computeKnownBits(Exp, APInt(1, 1), ExponentKnownBits, Q, Depth + 1);
5697
5698 FPClassTest InterestedSrcs = fcNone;
5699 if (InterestedClasses & fcNan)
5700 InterestedSrcs |= fcNan;
5701 if (!ExponentKnownBits.isZero()) {
5702 if (InterestedClasses & fcInf)
5703 InterestedSrcs |= fcFinite | fcInf;
5704 if ((InterestedClasses & fcNegative) && !ExponentKnownBits.isEven())
5705 InterestedSrcs |= fcNegative;
5706 }
5707
5708 KnownFPClass KnownSrc;
5709 if (InterestedSrcs != fcNone)
5710 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5711 KnownSrc, Q, Depth + 1);
5712
5713 Known = KnownFPClass::powi(KnownSrc, ExponentKnownBits);
5714 break;
5715 }
5716 case Intrinsic::ldexp: {
5717 KnownFPClass KnownSrc;
5718 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5719 KnownSrc, Q, Depth + 1);
5720 // Can refine inf/zero handling based on the exponent operand.
5721 const FPClassTest ExpInfoMask = fcZero | fcSubnormal | fcInf;
5722
5723 const Value *ExpArg = II->getArgOperand(1);
5724 ConstantRange ExpKnownRange =
5725 ((KnownSrc.KnownFPClasses & ExpInfoMask) != fcNone)
5726 ? computeConstantRange(ExpArg, /*ForSigned=*/true, Q, Depth + 1)
5727 : ConstantRange::getFull(
5728 ExpArg->getType()->getScalarSizeInBits());
5729
5730 const fltSemantics &Flt =
5731 II->getType()->getScalarType()->getFltSemantics();
5732
5733 const Function *F = II->getFunction();
5735 F ? F->getDenormalMode(Flt) : DenormalMode::getDynamic();
5736
5737 Known = KnownFPClass::ldexp(KnownSrc, ExpKnownRange.getSignedMin(),
5738 ExpKnownRange.getSignedMax(), Flt, Mode);
5739 break;
5740 }
5741 case Intrinsic::arithmetic_fence: {
5742 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5743 Known, Q, Depth + 1);
5744 break;
5745 }
5746 case Intrinsic::experimental_constrained_sitofp:
5747 case Intrinsic::experimental_constrained_uitofp:
5748 // Cannot produce nan
5749 Known.knownNot(fcNan);
5750
5751 // sitofp and uitofp turn into +0.0 for zero.
5752 Known.knownNot(fcNegZero);
5753
5754 // Integers cannot be subnormal
5755 Known.knownNot(fcSubnormal);
5756
5757 if (IID == Intrinsic::experimental_constrained_uitofp)
5758 Known.signBitMustBeZero();
5759
5760 // TODO: Copy inf handling from instructions
5761 break;
5762
5763 case Intrinsic::amdgcn_fract: {
5764 Known.knownNot(fcInf);
5765
5766 if (InterestedClasses & fcNan) {
5767 KnownFPClass KnownSrc;
5768 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5769 InterestedClasses, KnownSrc, Q, Depth + 1);
5770
5771 if (KnownSrc.isKnownNeverInfOrNaN())
5772 Known.knownNot(fcNan);
5773 else if (KnownSrc.isKnownNever(fcSNan))
5774 Known.knownNot(fcSNan);
5775 }
5776
5777 break;
5778 }
5779 case Intrinsic::amdgcn_rcp: {
5780 KnownFPClass KnownSrc;
5781 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5782 KnownSrc, Q, Depth + 1);
5783
5784 Known.propagateNonNaN(KnownSrc);
5785
5786 Type *EltTy = II->getType()->getScalarType();
5787
5788 // f32 denormal always flushed.
5789 if (EltTy->isFloatTy()) {
5790 Known.knownNot(fcSubnormal);
5791 KnownSrc.knownNot(fcSubnormal);
5792 }
5793
5794 if (KnownSrc.isKnownNever(fcNegative))
5795 Known.knownNot(fcNegative);
5796 if (KnownSrc.isKnownNever(fcPositive))
5797 Known.knownNot(fcPositive);
5798
5799 if (const Function *F = II->getFunction()) {
5800 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5801 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5802 Known.knownNot(fcPosInf);
5803 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5804 Known.knownNot(fcNegInf);
5805 }
5806
5807 break;
5808 }
5809 case Intrinsic::amdgcn_rsq: {
5810 KnownFPClass KnownSrc;
5811 // The only negative value that can be returned is -inf for -0 inputs.
5813
5814 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5815 KnownSrc, Q, Depth + 1);
5816
5817 // Negative -> nan
5818 if (KnownSrc.isKnownNeverNaN() && KnownSrc.cannotBeOrderedLessThanZero())
5819 Known.knownNot(fcNan);
5820 else if (KnownSrc.isKnownNever(fcSNan))
5821 Known.knownNot(fcSNan);
5822
5823 // +inf -> +0
5824 if (KnownSrc.isKnownNeverPosInfinity())
5825 Known.knownNot(fcPosZero);
5826
5827 Type *EltTy = II->getType()->getScalarType();
5828
5829 // f32 denormal always flushed.
5830 if (EltTy->isFloatTy())
5831 Known.knownNot(fcPosSubnormal);
5832
5833 if (const Function *F = II->getFunction()) {
5834 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5835
5836 // -0 -> -inf
5837 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5838 Known.knownNot(fcNegInf);
5839
5840 // +0 -> +inf
5841 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5842 Known.knownNot(fcPosInf);
5843 }
5844
5845 break;
5846 }
5847 case Intrinsic::amdgcn_trig_preop: {
5848 // Always returns a value [0, 1)
5849 Known.knownNot(fcNan | fcInf | fcNegative);
5850 break;
5851 }
5852 case Intrinsic::convert_from_arbitrary_fp: {
5853 auto *MD = cast<MetadataAsValue>(II->getArgOperand(1))->getMetadata();
5854 StringRef FormatStr = cast<MDString>(MD)->getString();
5855
5856 const fltSemantics *SrcSemantics =
5858 if (!SrcSemantics)
5859 break;
5860
5861 const fltSemantics DstSemantics =
5862 II->getType()->getScalarType()->getFltSemantics();
5863
5864 if (!APFloat::semanticsHasNaN(*SrcSemantics))
5865 Known.knownNot(fcNan);
5866
5867 // fcInf can only be cleared if the source format has no Inf encoding
5868 // and the dst max exp can accommodate src max exp.
5869 if (!APFloat::semanticsHasInf(*SrcSemantics) &&
5870 APFloat::semanticsMaxExponent(*SrcSemantics) <=
5871 APFloat::semanticsMaxExponent(DstSemantics))
5872 Known.knownNot(fcInf);
5873
5874 // Check and clear all neg flags for formats that do not have signed
5875 // representation.
5876 if (!APFloat::semanticsHasSignedRepr(*SrcSemantics))
5877 Known.knownNot(fcNegative);
5878
5879 // Check if format has no zero at all (Float8E8M0FNU), or no negative
5880 // zero.
5881 if (!APFloat::semanticsHasZero(*SrcSemantics))
5882 Known.knownNot(fcZero);
5883 else if (SrcSemantics->nanEncoding == fltNanEncoding::NegativeZero)
5884 Known.knownNot(fcNegZero);
5885
5886 // If src lands normally in dest, the result can never be subnormal.
5887 if (APFloat::isRepresentableAsNormalIn(*SrcSemantics, DstSemantics))
5888 Known.knownNot(fcSubnormal);
5889 break;
5890 }
5891 default:
5892 break;
5893 }
5894
5895 break;
5896 }
5897 case Instruction::FAdd:
5898 case Instruction::FSub: {
5899 KnownFPClass KnownLHS, KnownRHS;
5900 bool WantNegative =
5901 Op->getOpcode() == Instruction::FAdd &&
5902 (InterestedClasses & KnownFPClass::OrderedLessThanZeroMask) != fcNone;
5903 bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5904 bool WantNegZero = (InterestedClasses & fcNegZero) != fcNone;
5905
5906 if (!WantNaN && !WantNegative && !WantNegZero)
5907 break;
5908
5909 FPClassTest InterestedSrcs = InterestedClasses;
5910 if (WantNegative)
5911 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5912 if (InterestedClasses & fcNan)
5913 InterestedSrcs |= fcInf;
5914 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedSrcs,
5915 KnownRHS, Q, Depth + 1);
5916
5917 // Special case fadd x, x, which is the canonical form of fmul x, 2.
5918 bool Self = Op->getOperand(0) == Op->getOperand(1) &&
5919 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT,
5920 Depth + 1);
5921 if (Self)
5922 KnownLHS = KnownRHS;
5923
5924 if ((WantNaN && KnownRHS.isKnownNeverNaN()) ||
5925 (WantNegative && KnownRHS.cannotBeOrderedLessThanZero()) ||
5926 WantNegZero || Opc == Instruction::FSub) {
5927
5928 // FIXME: Context function should always be passed in separately
5929 const Function *F = cast<Instruction>(Op)->getFunction();
5930 const fltSemantics &FltSem =
5931 Op->getType()->getScalarType()->getFltSemantics();
5933 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5934
5935 if (Self && Opc == Instruction::FAdd) {
5936 Known = KnownFPClass::fadd_self(KnownLHS, Mode);
5937 } else {
5938 // RHS is canonically cheaper to compute. Skip inspecting the LHS if
5939 // there's no point.
5940
5941 if (!Self) {
5942 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
5943 KnownLHS, Q, Depth + 1);
5944 }
5945
5946 Known = Opc == Instruction::FAdd
5947 ? KnownFPClass::fadd(KnownLHS, KnownRHS, Mode)
5948 : KnownFPClass::fsub(KnownLHS, KnownRHS, Mode);
5949 }
5950 }
5951
5952 break;
5953 }
5954 case Instruction::FMul: {
5955 const Function *F = cast<Instruction>(Op)->getFunction();
5957 F ? F->getDenormalMode(
5958 Op->getType()->getScalarType()->getFltSemantics())
5960
5961 Value *LHS = Op->getOperand(0);
5962 Value *RHS = Op->getOperand(1);
5963 // X * X is always non-negative or a NaN.
5964 // FIXME: Should check isGuaranteedNotToBeUndef
5965 if (LHS == RHS) {
5966 KnownFPClass KnownSrc;
5967 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownSrc, Q,
5968 Depth + 1);
5969 Known = KnownFPClass::square(KnownSrc, Mode);
5970 break;
5971 }
5972
5973 KnownFPClass KnownLHS, KnownRHS;
5974
5975 const APFloat *CRHS;
5976 if (match(RHS, m_APFloat(CRHS))) {
5977 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
5978 Depth + 1);
5979 Known = KnownFPClass::fmul(KnownLHS, *CRHS, Mode);
5980 } else {
5981 computeKnownFPClass(RHS, DemandedElts, fcAllFlags, KnownRHS, Q,
5982 Depth + 1);
5983 // TODO: Improve accuracy in unfused FMA pattern. We can prove an
5984 // additional not-nan if the addend is known-not negative infinity if the
5985 // multiply is known-not infinity.
5986
5987 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
5988 Depth + 1);
5989 Known = KnownFPClass::fmul(KnownLHS, KnownRHS, Mode);
5990 }
5991
5992 /// Propgate no-infs if the other source is known smaller than one, such
5993 /// that this cannot introduce overflow.
5994 if (KnownLHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(RHS))
5995 Known.knownNot(fcInf);
5996 else if (KnownRHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(LHS))
5997 Known.knownNot(fcInf);
5998
5999 break;
6000 }
6001 case Instruction::FDiv: {
6002 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
6003
6004 const Function *F = cast<Instruction>(Op)->getFunction();
6005 const fltSemantics &FltSem =
6006 Op->getType()->getScalarType()->getFltSemantics();
6008 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6009
6010 if (Op->getOperand(0) == Op->getOperand(1) &&
6011 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT)) {
6012 // X / X is always exactly 1.0 or a NaN.
6013 Known.KnownFPClasses = fcNan | fcPosNormal;
6014
6015 if (!WantNan)
6016 break;
6017
6018 KnownFPClass KnownSrc;
6019 computeKnownFPClass(Op->getOperand(0), DemandedElts,
6020 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
6021 Depth + 1);
6022
6023 Known = KnownFPClass::fdiv_self(KnownSrc, Mode);
6024 break;
6025 }
6026
6027 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
6028 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
6029 if (!WantNan && !WantNegative && !WantPositive)
6030 break;
6031
6032 KnownFPClass KnownLHS, KnownRHS;
6033 computeKnownFPClass(Op->getOperand(1), DemandedElts, fcAllFlags, KnownRHS,
6034 Q, Depth + 1);
6035
6036 bool KnowSomethingUseful =
6037 KnownRHS.isKnownNeverNaN() ||
6040
6041 if (KnowSomethingUseful)
6042 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
6043 Q, Depth + 1);
6044
6045 Known = KnownFPClass::fdiv(KnownLHS, KnownRHS, Mode);
6046 break;
6047 }
6048 case Instruction::FRem: {
6049 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
6050
6051 Known.knownNot(fcInf);
6052
6053 const Function *F = cast<Instruction>(Op)->getFunction();
6055 F ? F->getDenormalMode(
6056 Op->getType()->getScalarType()->getFltSemantics())
6058
6059 if (Op->getOperand(0) == Op->getOperand(1) &&
6060 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT)) {
6061 // X % X is always exactly [+-]0.0 or a NaN.
6062 Known.KnownFPClasses = fcNan | fcZero;
6063
6064 if (!WantNan)
6065 break;
6066
6067 KnownFPClass KnownSrc;
6068 computeKnownFPClass(Op->getOperand(0), DemandedElts,
6069 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
6070 Depth + 1);
6071
6072 Known = KnownFPClass::frem_self(KnownSrc, Mode);
6073 break;
6074 }
6075
6076 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
6077 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
6078 if (!WantNan && !WantNegative && !WantPositive)
6079 break;
6080
6081 KnownFPClass KnownLHS, KnownRHS;
6082 computeKnownFPClass(Op->getOperand(1), DemandedElts,
6083 fcNan | fcInf | fcZero | fcNegative, KnownRHS, Q,
6084 Depth + 1);
6085
6086 bool KnowSomethingUseful = KnownRHS.isKnownNeverNaN() ||
6087 KnownRHS.isKnownNever(fcNegative) ||
6088 KnownRHS.isKnownNever(fcPositive);
6089
6090 if (KnowSomethingUseful || WantPositive)
6091 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
6092 Q, Depth + 1);
6093
6094 Known = KnownFPClass::frem(KnownLHS, KnownRHS, Mode);
6095
6096 break;
6097 }
6098 case Instruction::FPExt: {
6099 KnownFPClass KnownSrc;
6100 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
6101 KnownSrc, Q, Depth + 1);
6102
6103 const fltSemantics &DstTy =
6104 Op->getType()->getScalarType()->getFltSemantics();
6105 const fltSemantics &SrcTy =
6106 Op->getOperand(0)->getType()->getScalarType()->getFltSemantics();
6107
6108 Known = KnownFPClass::fpext(KnownSrc, DstTy, SrcTy);
6109 break;
6110 }
6111 case Instruction::FPTrunc: {
6112 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known, Q,
6113 Depth);
6114 break;
6115 }
6116 case Instruction::SIToFP:
6117 case Instruction::UIToFP: {
6118 // Cannot produce nan
6119 Known.knownNot(fcNan);
6120
6121 // Integers cannot be subnormal
6122 Known.knownNot(fcSubnormal);
6123
6124 // sitofp and uitofp turn into +0.0 for zero.
6125 Known.knownNot(fcNegZero);
6126
6127 // UIToFP is always non-negative regardless of known bits.
6128 if (Op->getOpcode() == Instruction::UIToFP)
6129 Known.signBitMustBeZero();
6130
6131 // Only compute known bits if we can learn something useful from them.
6132 if (!(InterestedClasses & (fcPosZero | fcNormal | fcInf)))
6133 break;
6134
6135 KnownBits IntKnown =
6136 computeKnownBits(Op->getOperand(0), DemandedElts, Q, Depth + 1);
6137
6138 // If the integer is non-zero, the result cannot be +0.0
6139 if (IntKnown.isNonZero())
6140 Known.knownNot(fcPosZero);
6141
6142 if (Op->getOpcode() == Instruction::SIToFP) {
6143 // If the signed integer is known non-negative, the result is
6144 // non-negative. If the signed integer is known negative, the result is
6145 // negative.
6146 if (IntKnown.isNonNegative()) {
6147 Known.signBitMustBeZero();
6148 } else if (IntKnown.isNegative()) {
6149 Known.signBitMustBeOne();
6150 }
6151 }
6152
6153 // Guard kept for ilogb()
6154 if (InterestedClasses & fcInf) {
6155 // Get width of largest magnitude integer known.
6156 // This still works for a signed minimum value because the largest FP
6157 // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx).
6158 int IntSize = IntKnown.getBitWidth();
6159 if (Op->getOpcode() == Instruction::UIToFP)
6160 IntSize -= IntKnown.countMinLeadingZeros();
6161 else if (Op->getOpcode() == Instruction::SIToFP)
6162 IntSize -= IntKnown.countMinSignBits();
6163
6164 // If the exponent of the largest finite FP value can hold the largest
6165 // integer, the result of the cast must be finite.
6166 Type *FPTy = Op->getType()->getScalarType();
6167 if (ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize)
6168 Known.knownNot(fcInf);
6169 }
6170
6171 break;
6172 }
6173 case Instruction::ExtractElement: {
6174 // Look through extract element. If the index is non-constant or
6175 // out-of-range demand all elements, otherwise just the extracted element.
6176 const Value *Vec = Op->getOperand(0);
6177
6178 APInt DemandedVecElts;
6179 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
6180 unsigned NumElts = VecTy->getNumElements();
6181 DemandedVecElts = APInt::getAllOnes(NumElts);
6182 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(1));
6183 if (CIdx && CIdx->getValue().ult(NumElts))
6184 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
6185 } else {
6186 DemandedVecElts = APInt(1, 1);
6187 }
6188
6189 return computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known,
6190 Q, Depth + 1);
6191 }
6192 case Instruction::InsertElement: {
6193 if (isa<ScalableVectorType>(Op->getType()))
6194 return;
6195
6196 const Value *Vec = Op->getOperand(0);
6197 const Value *Elt = Op->getOperand(1);
6198 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(2));
6199 unsigned NumElts = DemandedElts.getBitWidth();
6200 APInt DemandedVecElts = DemandedElts;
6201 bool NeedsElt = true;
6202 // If we know the index we are inserting to, clear it from Vec check.
6203 if (CIdx && CIdx->getValue().ult(NumElts)) {
6204 DemandedVecElts.clearBit(CIdx->getZExtValue());
6205 NeedsElt = DemandedElts[CIdx->getZExtValue()];
6206 }
6207
6208 // Do we demand the inserted element?
6209 if (NeedsElt) {
6210 computeKnownFPClass(Elt, Known, InterestedClasses, Q, Depth + 1);
6211 // If we don't know any bits, early out.
6212 if (Known.isUnknown())
6213 break;
6214 } else {
6215 Known.KnownFPClasses = fcNone;
6216 }
6217
6218 // Do we need anymore elements from Vec?
6219 if (!DemandedVecElts.isZero()) {
6220 KnownFPClass Known2;
6221 computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known2, Q,
6222 Depth + 1);
6223 Known |= Known2;
6224 }
6225
6226 break;
6227 }
6228 case Instruction::ShuffleVector: {
6229 // Handle vector splat idiom
6230 if (Value *Splat = getSplatValue(V)) {
6231 computeKnownFPClass(Splat, Known, InterestedClasses, Q, Depth + 1);
6232 break;
6233 }
6234
6235 // For undef elements, we don't know anything about the common state of
6236 // the shuffle result.
6237 APInt DemandedLHS, DemandedRHS;
6238 auto *Shuf = dyn_cast<ShuffleVectorInst>(Op);
6239 if (!Shuf || !getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
6240 return;
6241
6242 if (!!DemandedLHS) {
6243 const Value *LHS = Shuf->getOperand(0);
6244 computeKnownFPClass(LHS, DemandedLHS, InterestedClasses, Known, Q,
6245 Depth + 1);
6246
6247 // If we don't know any bits, early out.
6248 if (Known.isUnknown())
6249 break;
6250 } else {
6251 Known.KnownFPClasses = fcNone;
6252 }
6253
6254 if (!!DemandedRHS) {
6255 KnownFPClass Known2;
6256 const Value *RHS = Shuf->getOperand(1);
6257 computeKnownFPClass(RHS, DemandedRHS, InterestedClasses, Known2, Q,
6258 Depth + 1);
6259 Known |= Known2;
6260 }
6261
6262 break;
6263 }
6264 case Instruction::ExtractValue: {
6265 const ExtractValueInst *Extract = cast<ExtractValueInst>(Op);
6266 ArrayRef<unsigned> Indices = Extract->getIndices();
6267 const Value *Src = Extract->getAggregateOperand();
6268 if (isa<StructType>(Src->getType()) && Indices.size() == 1 &&
6269 Indices[0] == 0) {
6270 if (const auto *II = dyn_cast<IntrinsicInst>(Src)) {
6271 switch (II->getIntrinsicID()) {
6272 case Intrinsic::frexp: {
6273 Known.knownNot(fcSubnormal);
6274
6275 KnownFPClass KnownSrc;
6276 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
6277 InterestedClasses, KnownSrc, Q, Depth + 1);
6278
6279 const Function *F = cast<Instruction>(Op)->getFunction();
6280 const fltSemantics &FltSem =
6281 Op->getType()->getScalarType()->getFltSemantics();
6282
6284 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6285 Known = KnownFPClass::frexp_mant(KnownSrc, Mode);
6286 return;
6287 }
6288 default:
6289 break;
6290 }
6291 }
6292 }
6293
6294 computeKnownFPClass(Src, DemandedElts, InterestedClasses, Known, Q,
6295 Depth + 1);
6296 break;
6297 }
6298 case Instruction::PHI: {
6299 const PHINode *P = cast<PHINode>(Op);
6300 // Unreachable blocks may have zero-operand PHI nodes.
6301 if (P->getNumIncomingValues() == 0)
6302 break;
6303
6304 // Otherwise take the unions of the known bit sets of the operands,
6305 // taking conservative care to avoid excessive recursion.
6306 const unsigned PhiRecursionLimit = MaxAnalysisRecursionDepth - 2;
6307
6308 if (Depth < PhiRecursionLimit) {
6309 // Skip if every incoming value references to ourself.
6310 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
6311 break;
6312
6313 bool First = true;
6314
6315 for (const Use &U : P->operands()) {
6316 Value *IncValue;
6317 Instruction *CxtI;
6318 breakSelfRecursivePHI(&U, P, IncValue, CxtI);
6319 // Skip direct self references.
6320 if (IncValue == P)
6321 continue;
6322
6323 KnownFPClass KnownSrc;
6324 // Recurse, but cap the recursion to two levels, because we don't want
6325 // to waste time spinning around in loops. We need at least depth 2 to
6326 // detect known sign bits.
6327 computeKnownFPClass(IncValue, DemandedElts, InterestedClasses, KnownSrc,
6329 PhiRecursionLimit);
6330
6331 if (First) {
6332 Known = KnownSrc;
6333 First = false;
6334 } else {
6335 Known |= KnownSrc;
6336 }
6337
6338 if (Known.KnownFPClasses == fcAllFlags)
6339 break;
6340 }
6341 }
6342
6343 // Look for the case of a for loop which has a positive
6344 // initial value and is incremented by a squared value.
6345 // This will propagate sign information out of such loops.
6346 if (P->getNumIncomingValues() != 2 || Known.cannotBeOrderedLessThanZero())
6347 break;
6348 for (unsigned I = 0; I < 2; I++) {
6349 Value *RecurValue = P->getIncomingValue(1 - I);
6351 if (!II)
6352 continue;
6353 Value *R, *L, *Init;
6354 PHINode *PN;
6356 PN == P) {
6357 switch (II->getIntrinsicID()) {
6358 case Intrinsic::fma:
6359 case Intrinsic::fmuladd: {
6360 KnownFPClass KnownStart;
6361 computeKnownFPClass(Init, DemandedElts, InterestedClasses, KnownStart,
6362 Q, Depth + 1);
6363 if (KnownStart.cannotBeOrderedLessThanZero() && L == R &&
6364 isGuaranteedNotToBeUndef(L, Q.AC, Q.CxtI, Q.DT, Depth + 1))
6366 break;
6367 }
6368 }
6369 }
6370 }
6371 break;
6372 }
6373 case Instruction::BitCast: {
6374 const Value *Src;
6375 if (!match(Op, m_ElementWiseBitCast(m_Value(Src))) ||
6376 !Src->getType()->isIntOrIntVectorTy())
6377 break;
6378
6379 const Type *Ty = Op->getType();
6380
6381 Value *CastLHS, *CastRHS;
6382
6383 // Match bitcast(umax(bitcast(a), bitcast(b)))
6384 if (match(Src, m_c_MaxOrMin(m_BitCast(m_Value(CastLHS)),
6385 m_BitCast(m_Value(CastRHS)))) &&
6386 CastLHS->getType() == Ty && CastRHS->getType() == Ty) {
6387 KnownFPClass KnownLHS, KnownRHS;
6388 computeKnownFPClass(CastRHS, DemandedElts, InterestedClasses, KnownRHS, Q,
6389 Depth + 1);
6390 if (!KnownRHS.isUnknown()) {
6391 computeKnownFPClass(CastLHS, DemandedElts, InterestedClasses, KnownLHS,
6392 Q, Depth + 1);
6393 Known = KnownLHS | KnownRHS;
6394 }
6395
6396 return;
6397 }
6398
6399 const Type *EltTy = Ty->getScalarType();
6400 KnownBits Bits(EltTy->getPrimitiveSizeInBits());
6401 computeKnownBits(Src, DemandedElts, Bits, Q, Depth + 1);
6402
6404 break;
6405 }
6406 default:
6407 break;
6408 }
6409}
6410
6412 const APInt &DemandedElts,
6413 FPClassTest InterestedClasses,
6414 const SimplifyQuery &SQ,
6415 unsigned Depth) {
6416 KnownFPClass KnownClasses;
6417 ::computeKnownFPClass(V, DemandedElts, InterestedClasses, KnownClasses, SQ,
6418 Depth);
6419 return KnownClasses;
6420}
6421
6423 FPClassTest InterestedClasses,
6424 const SimplifyQuery &SQ,
6425 unsigned Depth) {
6427 ::computeKnownFPClass(V, Known, InterestedClasses, SQ, Depth);
6428 return Known;
6429}
6430
6432 const Value *V, const DataLayout &DL, FPClassTest InterestedClasses,
6433 const TargetLibraryInfo *TLI, AssumptionCache *AC, const Instruction *CxtI,
6434 const DominatorTree *DT, bool UseInstrInfo, unsigned Depth) {
6435 return computeKnownFPClass(V, InterestedClasses,
6436 SimplifyQuery(DL, TLI, DT, AC, CxtI, UseInstrInfo),
6437 Depth);
6438}
6439
6441llvm::computeKnownFPClass(const Value *V, const APInt &DemandedElts,
6442 FastMathFlags FMF, FPClassTest InterestedClasses,
6443 const SimplifyQuery &SQ, unsigned Depth) {
6444 if (FMF.noNaNs())
6445 InterestedClasses &= ~fcNan;
6446 if (FMF.noInfs())
6447 InterestedClasses &= ~fcInf;
6448
6449 KnownFPClass Result =
6450 computeKnownFPClass(V, DemandedElts, InterestedClasses, SQ, Depth);
6451
6452 if (FMF.noNaNs())
6453 Result.KnownFPClasses &= ~fcNan;
6454 if (FMF.noInfs())
6455 Result.KnownFPClasses &= ~fcInf;
6456 return Result;
6457}
6458
6460 FPClassTest InterestedClasses,
6461 const SimplifyQuery &SQ,
6462 unsigned Depth) {
6463 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
6464 APInt DemandedElts =
6465 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
6466 return computeKnownFPClass(V, DemandedElts, FMF, InterestedClasses, SQ,
6467 Depth);
6468}
6469
6471 unsigned Depth) {
6473 return Known.isKnownNeverNegZero();
6474}
6475
6477 unsigned Depth) {
6480 return Known.cannotBeOrderedLessThanZero();
6481}
6482
6484 unsigned Depth) {
6486 return Known.isKnownNeverInfinity();
6487}
6488
6489/// Return true if the floating-point value can never contain a NaN or infinity.
6491 unsigned Depth) {
6493 return Known.isKnownNeverNaN() && Known.isKnownNeverInfinity();
6494}
6495
6496/// Return true if the floating-point scalar value is not a NaN or if the
6497/// floating-point vector value has no NaN elements. Return false if a value
6498/// could ever be NaN.
6500 unsigned Depth) {
6502 return Known.isKnownNeverNaN();
6503}
6504
6505/// Return false if we can prove that the specified FP value's sign bit is 0.
6506/// Return true if we can prove that the specified FP value's sign bit is 1.
6507/// Otherwise return std::nullopt.
6508std::optional<bool> llvm::computeKnownFPSignBit(const Value *V,
6509 const SimplifyQuery &SQ,
6510 unsigned Depth) {
6512 return Known.getSignBit();
6513}
6514
6516 auto *User = cast<Instruction>(U.getUser());
6517 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6518 if (FPOp->hasNoSignedZeros())
6519 return true;
6520 }
6521
6522 switch (User->getOpcode()) {
6523 case Instruction::FPToSI:
6524 case Instruction::FPToUI:
6525 return true;
6526 case Instruction::FCmp:
6527 // fcmp treats both positive and negative zero as equal.
6528 return true;
6529 case Instruction::Call:
6530 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6531 switch (II->getIntrinsicID()) {
6532 case Intrinsic::fabs:
6533 return true;
6534 case Intrinsic::copysign:
6535 return U.getOperandNo() == 0;
6536 case Intrinsic::is_fpclass: {
6537 auto Test =
6538 static_cast<FPClassTest>(
6539 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue()) &
6542 }
6543 default:
6544 return false;
6545 }
6546 }
6547 return false;
6548 default:
6549 return false;
6550 }
6551}
6552
6554 auto *User = cast<Instruction>(U.getUser());
6555 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6556 if (FPOp->hasNoNaNs())
6557 return true;
6558 }
6559
6560 switch (User->getOpcode()) {
6561 case Instruction::FPToSI:
6562 case Instruction::FPToUI:
6563 return true;
6564 // Proper FP math operations ignore the sign bit of NaN.
6565 case Instruction::FAdd:
6566 case Instruction::FSub:
6567 case Instruction::FMul:
6568 case Instruction::FDiv:
6569 case Instruction::FRem:
6570 case Instruction::FPTrunc:
6571 case Instruction::FPExt:
6572 case Instruction::FCmp:
6573 return true;
6574 // Bitwise FP operations should preserve the sign bit of NaN.
6575 case Instruction::FNeg:
6576 case Instruction::Select:
6577 case Instruction::PHI:
6578 return false;
6579 case Instruction::Ret:
6580 return User->getFunction()->getAttributes().getRetNoFPClass() &
6582 case Instruction::Call:
6583 case Instruction::Invoke: {
6584 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6585 switch (II->getIntrinsicID()) {
6586 case Intrinsic::fabs:
6587 return true;
6588 case Intrinsic::copysign:
6589 return U.getOperandNo() == 0;
6590 // Other proper FP math intrinsics ignore the sign bit of NaN.
6591 case Intrinsic::maxnum:
6592 case Intrinsic::minnum:
6593 case Intrinsic::maximum:
6594 case Intrinsic::minimum:
6595 case Intrinsic::maximumnum:
6596 case Intrinsic::minimumnum:
6597 case Intrinsic::canonicalize:
6598 case Intrinsic::fma:
6599 case Intrinsic::fmuladd:
6600 case Intrinsic::sqrt:
6601 case Intrinsic::pow:
6602 case Intrinsic::powi:
6603 case Intrinsic::fptoui_sat:
6604 case Intrinsic::fptosi_sat:
6605 case Intrinsic::is_fpclass:
6606 return true;
6607 default:
6608 return false;
6609 }
6610 }
6611
6612 FPClassTest NoFPClass =
6613 cast<CallBase>(User)->getParamNoFPClass(U.getOperandNo());
6614 return NoFPClass & FPClassTest::fcNan;
6615 }
6616 default:
6617 return false;
6618 }
6619}
6620
6622 FastMathFlags FMF) {
6623 if (isa<PoisonValue>(V))
6624 return true;
6625 if (isa<UndefValue>(V))
6626 return false;
6627
6628 if (match(V, m_CheckedFp([](const APFloat &Val) { return Val.isInteger(); })))
6629 return true;
6630
6632 if (!I)
6633 return false;
6634
6635 switch (I->getOpcode()) {
6636 case Instruction::SIToFP:
6637 case Instruction::UIToFP:
6638 // TODO: Could check nofpclass(inf) on incoming argument
6639 if (FMF.noInfs())
6640 return true;
6641
6642 // Need to check int size cannot produce infinity, which computeKnownFPClass
6643 // knows how to do already.
6644 return isKnownNeverInfinity(I, SQ);
6645 case Instruction::Call: {
6646 const CallInst *CI = cast<CallInst>(I);
6647 switch (CI->getIntrinsicID()) {
6648 case Intrinsic::trunc:
6649 case Intrinsic::floor:
6650 case Intrinsic::ceil:
6651 case Intrinsic::rint:
6652 case Intrinsic::nearbyint:
6653 case Intrinsic::round:
6654 case Intrinsic::roundeven:
6655 return (FMF.noInfs() && FMF.noNaNs()) || isKnownNeverInfOrNaN(I, SQ);
6656 default:
6657 break;
6658 }
6659
6660 break;
6661 }
6662 default:
6663 break;
6664 }
6665
6666 return false;
6667}
6668
6670
6671 // All byte-wide stores are splatable, even of arbitrary variables.
6672 if (V->getType()->isIntegerTy(8))
6673 return V;
6674
6675 LLVMContext &Ctx = V->getContext();
6676
6677 // Undef don't care.
6678 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
6679 if (isa<UndefValue>(V))
6680 return UndefInt8;
6681
6682 // Return poison for zero-sized type.
6683 if (DL.getTypeStoreSize(V->getType()).isZero())
6684 return PoisonValue::get(Type::getInt8Ty(Ctx));
6685
6687 if (!C) {
6688 // Conceptually, we could handle things like:
6689 // %a = zext i8 %X to i16
6690 // %b = shl i16 %a, 8
6691 // %c = or i16 %a, %b
6692 // but until there is an example that actually needs this, it doesn't seem
6693 // worth worrying about.
6694 return nullptr;
6695 }
6696
6697 // Handle 'null' ConstantArrayZero etc.
6698 if (C->isNullValue())
6700
6701 // Constant floating-point values can be handled as integer values if the
6702 // corresponding integer value is "byteable". An important case is 0.0.
6703 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
6704 Type *ScalarTy = CFP->getType()->getScalarType();
6705 if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
6706 return isBytewiseValue(
6707 ConstantInt::get(Ctx, CFP->getValue().bitcastToAPInt()), DL);
6708
6709 // Don't handle long double formats, which have strange constraints.
6710 return nullptr;
6711 }
6712
6713 // We can handle constant integers that are multiple of 8 bits.
6714 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
6715 if (CI->getBitWidth() % 8 == 0) {
6716 if (!CI->getValue().isSplat(8))
6717 return nullptr;
6718 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
6719 }
6720 }
6721
6722 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
6723 if (CE->getOpcode() == Instruction::IntToPtr) {
6724 if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
6725 unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
6727 CE->getOperand(0), Type::getIntNTy(Ctx, BitWidth), false, DL))
6728 return isBytewiseValue(Op, DL);
6729 }
6730 }
6731 }
6732
6733 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
6734 if (LHS == RHS)
6735 return LHS;
6736 if (!LHS || !RHS)
6737 return nullptr;
6738 if (LHS == UndefInt8)
6739 return RHS;
6740 if (RHS == UndefInt8)
6741 return LHS;
6742 return nullptr;
6743 };
6744
6746 Value *Val = UndefInt8;
6747 for (uint64_t I = 0, E = CA->getNumElements(); I != E; ++I)
6748 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
6749 return nullptr;
6750 return Val;
6751 }
6752
6754 Value *Val = UndefInt8;
6755 for (Value *Op : C->operands())
6756 if (!(Val = Merge(Val, isBytewiseValue(Op, DL))))
6757 return nullptr;
6758 return Val;
6759 }
6760
6761 // Don't try to handle the handful of other constants.
6762 return nullptr;
6763}
6764
6765// This is the recursive version of BuildSubAggregate. It takes a few different
6766// arguments. Idxs is the index within the nested struct From that we are
6767// looking at now (which is of type IndexedType). IdxSkip is the number of
6768// indices from Idxs that should be left out when inserting into the resulting
6769// struct. To is the result struct built so far, new insertvalue instructions
6770// build on that.
6771static Value *BuildSubAggregate(Value *From, Value *To, Type *IndexedType,
6773 unsigned IdxSkip,
6774 BasicBlock::iterator InsertBefore) {
6775 StructType *STy = dyn_cast<StructType>(IndexedType);
6776 if (STy) {
6777 // Save the original To argument so we can modify it
6778 Value *OrigTo = To;
6779 // General case, the type indexed by Idxs is a struct
6780 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
6781 // Process each struct element recursively
6782 Idxs.push_back(i);
6783 Value *PrevTo = To;
6784 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
6785 InsertBefore);
6786 Idxs.pop_back();
6787 if (!To) {
6788 // Couldn't find any inserted value for this index? Cleanup
6789 while (PrevTo != OrigTo) {
6791 PrevTo = Del->getAggregateOperand();
6792 Del->eraseFromParent();
6793 }
6794 // Stop processing elements
6795 break;
6796 }
6797 }
6798 // If we successfully found a value for each of our subaggregates
6799 if (To)
6800 return To;
6801 }
6802 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
6803 // the struct's elements had a value that was inserted directly. In the latter
6804 // case, perhaps we can't determine each of the subelements individually, but
6805 // we might be able to find the complete struct somewhere.
6806
6807 // Find the value that is at that particular spot
6808 Value *V = FindInsertedValue(From, Idxs);
6809
6810 if (!V)
6811 return nullptr;
6812
6813 // Insert the value in the new (sub) aggregate
6814 return InsertValueInst::Create(To, V, ArrayRef(Idxs).slice(IdxSkip), "tmp",
6815 InsertBefore);
6816}
6817
6818// This helper takes a nested struct and extracts a part of it (which is again a
6819// struct) into a new value. For example, given the struct:
6820// { a, { b, { c, d }, e } }
6821// and the indices "1, 1" this returns
6822// { c, d }.
6823//
6824// It does this by inserting an insertvalue for each element in the resulting
6825// struct, as opposed to just inserting a single struct. This will only work if
6826// each of the elements of the substruct are known (ie, inserted into From by an
6827// insertvalue instruction somewhere).
6828//
6829// All inserted insertvalue instructions are inserted before InsertBefore
6831 BasicBlock::iterator InsertBefore) {
6832 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
6833 idx_range);
6834 Value *To = PoisonValue::get(IndexedType);
6835 SmallVector<unsigned, 10> Idxs(idx_range);
6836 unsigned IdxSkip = Idxs.size();
6837
6838 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
6839}
6840
6841/// Given an aggregate and a sequence of indices, see if the scalar value
6842/// indexed is already around as a register, for example if it was inserted
6843/// directly into the aggregate.
6844///
6845/// If InsertBefore is not null, this function will duplicate (modified)
6846/// insertvalues when a part of a nested struct is extracted.
6847Value *
6849 std::optional<BasicBlock::iterator> InsertBefore) {
6850 // Nothing to index? Just return V then (this is useful at the end of our
6851 // recursion).
6852 if (idx_range.empty())
6853 return V;
6854 // We have indices, so V should have an indexable type.
6855 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
6856 "Not looking at a struct or array?");
6857 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
6858 "Invalid indices for type?");
6859
6860 if (Constant *C = dyn_cast<Constant>(V)) {
6861 C = C->getAggregateElement(idx_range[0]);
6862 if (!C) return nullptr;
6863 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
6864 }
6865
6867 // Loop the indices for the insertvalue instruction in parallel with the
6868 // requested indices
6869 const unsigned *req_idx = idx_range.begin();
6870 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
6871 i != e; ++i, ++req_idx) {
6872 if (req_idx == idx_range.end()) {
6873 // We can't handle this without inserting insertvalues
6874 if (!InsertBefore)
6875 return nullptr;
6876
6877 // The requested index identifies a part of a nested aggregate. Handle
6878 // this specially. For example,
6879 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
6880 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
6881 // %C = extractvalue {i32, { i32, i32 } } %B, 1
6882 // This can be changed into
6883 // %A = insertvalue {i32, i32 } undef, i32 10, 0
6884 // %C = insertvalue {i32, i32 } %A, i32 11, 1
6885 // which allows the unused 0,0 element from the nested struct to be
6886 // removed.
6887 return BuildSubAggregate(V, ArrayRef(idx_range.begin(), req_idx),
6888 *InsertBefore);
6889 }
6890
6891 // This insert value inserts something else than what we are looking for.
6892 // See if the (aggregate) value inserted into has the value we are
6893 // looking for, then.
6894 if (*req_idx != *i)
6895 return FindInsertedValue(I->getAggregateOperand(), idx_range,
6896 InsertBefore);
6897 }
6898 // If we end up here, the indices of the insertvalue match with those
6899 // requested (though possibly only partially). Now we recursively look at
6900 // the inserted value, passing any remaining indices.
6901 return FindInsertedValue(I->getInsertedValueOperand(),
6902 ArrayRef(req_idx, idx_range.end()), InsertBefore);
6903 }
6904
6906 // If we're extracting a value from an aggregate that was extracted from
6907 // something else, we can extract from that something else directly instead.
6908 // However, we will need to chain I's indices with the requested indices.
6909
6910 // Calculate the number of indices required
6911 unsigned size = I->getNumIndices() + idx_range.size();
6912 // Allocate some space to put the new indices in
6914 Idxs.reserve(size);
6915 // Add indices from the extract value instruction
6916 Idxs.append(I->idx_begin(), I->idx_end());
6917
6918 // Add requested indices
6919 Idxs.append(idx_range.begin(), idx_range.end());
6920
6921 assert(Idxs.size() == size
6922 && "Number of indices added not correct?");
6923
6924 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
6925 }
6926 // Otherwise, we don't know (such as, extracting from a function return value
6927 // or load instruction)
6928 return nullptr;
6929}
6930
6931// If V refers to an initialized global constant, set Slice either to
6932// its initializer if the size of its elements equals ElementSize, or,
6933// for ElementSize == 8, to its representation as an array of unsiged
6934// char. Return true on success.
6935// Offset is in the unit "nr of ElementSize sized elements".
6938 unsigned ElementSize, uint64_t Offset) {
6939 assert(V && "V should not be null.");
6940 assert((ElementSize % 8) == 0 &&
6941 "ElementSize expected to be a multiple of the size of a byte.");
6942 unsigned ElementSizeInBytes = ElementSize / 8;
6943
6944 // Drill down into the pointer expression V, ignoring any intervening
6945 // casts, and determine the identity of the object it references along
6946 // with the cumulative byte offset into it.
6947 const GlobalVariable *GV =
6949 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
6950 // Fail if V is not based on constant global object.
6951 return false;
6952
6953 const DataLayout &DL = GV->getDataLayout();
6954 APInt Off(DL.getIndexTypeSizeInBits(V->getType()), 0);
6955
6956 if (GV != V->stripAndAccumulateConstantOffsets(DL, Off,
6957 /*AllowNonInbounds*/ true))
6958 // Fail if a constant offset could not be determined.
6959 return false;
6960
6961 uint64_t StartIdx = Off.getLimitedValue();
6962 if (StartIdx == UINT64_MAX)
6963 // Fail if the constant offset is excessive.
6964 return false;
6965
6966 // Off/StartIdx is in the unit of bytes. So we need to convert to number of
6967 // elements. Simply bail out if that isn't possible.
6968 if ((StartIdx % ElementSizeInBytes) != 0)
6969 return false;
6970
6971 Offset += StartIdx / ElementSizeInBytes;
6972 ConstantDataArray *Array = nullptr;
6973 ArrayType *ArrayTy = nullptr;
6974
6975 if (GV->getInitializer()->isNullValue()) {
6976 Type *GVTy = GV->getValueType();
6977 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedValue();
6978 uint64_t Length = SizeInBytes / ElementSizeInBytes;
6979
6980 Slice.Array = nullptr;
6981 Slice.Offset = 0;
6982 // Return an empty Slice for undersized constants to let callers
6983 // transform even undefined library calls into simpler, well-defined
6984 // expressions. This is preferable to making the calls although it
6985 // prevents sanitizers from detecting such calls.
6986 Slice.Length = Length < Offset ? 0 : Length - Offset;
6987 return true;
6988 }
6989
6990 auto *Init = const_cast<Constant *>(GV->getInitializer());
6991 if (auto *ArrayInit = dyn_cast<ConstantDataArray>(Init)) {
6992 Type *InitElTy = ArrayInit->getElementType();
6993 if (InitElTy->isIntegerTy(ElementSize)) {
6994 // If Init is an initializer for an array of the expected type
6995 // and size, use it as is.
6996 Array = ArrayInit;
6997 ArrayTy = ArrayInit->getType();
6998 }
6999 }
7000
7001 if (!Array) {
7002 if (ElementSize != 8)
7003 // TODO: Handle conversions to larger integral types.
7004 return false;
7005
7006 // Otherwise extract the portion of the initializer starting
7007 // at Offset as an array of bytes, and reset Offset.
7009 if (!Init)
7010 return false;
7011
7012 Offset = 0;
7014 ArrayTy = dyn_cast<ArrayType>(Init->getType());
7015 }
7016
7017 uint64_t NumElts = ArrayTy->getArrayNumElements();
7018 if (Offset > NumElts)
7019 return false;
7020
7021 Slice.Array = Array;
7022 Slice.Offset = Offset;
7023 Slice.Length = NumElts - Offset;
7024 return true;
7025}
7026
7027/// Extract bytes from the initializer of the constant array V, which need
7028/// not be a nul-terminated string. On success, store the bytes in Str and
7029/// return true. When TrimAtNul is set, Str will contain only the bytes up
7030/// to but not including the first nul. Return false on failure.
7032 bool TrimAtNul) {
7034 if (!getConstantDataArrayInfo(V, Slice, 8))
7035 return false;
7036
7037 if (Slice.Array == nullptr) {
7038 if (TrimAtNul) {
7039 // Return a nul-terminated string even for an empty Slice. This is
7040 // safe because all existing SimplifyLibcalls callers require string
7041 // arguments and the behavior of the functions they fold is undefined
7042 // otherwise. Folding the calls this way is preferable to making
7043 // the undefined library calls, even though it prevents sanitizers
7044 // from reporting such calls.
7045 Str = StringRef();
7046 return true;
7047 }
7048 if (Slice.Length == 1) {
7049 Str = StringRef("", 1);
7050 return true;
7051 }
7052 // We cannot instantiate a StringRef as we do not have an appropriate string
7053 // of 0s at hand.
7054 return false;
7055 }
7056
7057 // Start out with the entire array in the StringRef.
7058 Str = Slice.Array->getAsString();
7059 // Skip over 'offset' bytes.
7060 Str = Str.substr(Slice.Offset);
7061
7062 if (TrimAtNul) {
7063 // Trim off the \0 and anything after it. If the array is not nul
7064 // terminated, we just return the whole end of string. The client may know
7065 // some other way that the string is length-bound.
7066 Str = Str.substr(0, Str.find('\0'));
7067 }
7068 return true;
7069}
7070
7071// These next two are very similar to the above, but also look through PHI
7072// nodes.
7073// TODO: See if we can integrate these two together.
7074
7075/// If we can compute the length of the string pointed to by
7076/// the specified pointer, return 'len+1'. If we can't, return 0.
7079 unsigned CharSize) {
7080 // Look through noop bitcast instructions.
7081 V = V->stripPointerCasts();
7082
7083 // If this is a PHI node, there are two cases: either we have already seen it
7084 // or we haven't.
7085 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
7086 if (!PHIs.insert(PN).second)
7087 return ~0ULL; // already in the set.
7088
7089 // If it was new, see if all the input strings are the same length.
7090 uint64_t LenSoFar = ~0ULL;
7091 for (Value *IncValue : PN->incoming_values()) {
7092 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
7093 if (Len == 0) return 0; // Unknown length -> unknown.
7094
7095 if (Len == ~0ULL) continue;
7096
7097 if (Len != LenSoFar && LenSoFar != ~0ULL)
7098 return 0; // Disagree -> unknown.
7099 LenSoFar = Len;
7100 }
7101
7102 // Success, all agree.
7103 return LenSoFar;
7104 }
7105
7106 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
7107 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
7108 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
7109 if (Len1 == 0) return 0;
7110 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
7111 if (Len2 == 0) return 0;
7112 if (Len1 == ~0ULL) return Len2;
7113 if (Len2 == ~0ULL) return Len1;
7114 if (Len1 != Len2) return 0;
7115 return Len1;
7116 }
7117
7118 // Otherwise, see if we can read the string.
7120 if (!getConstantDataArrayInfo(V, Slice, CharSize))
7121 return 0;
7122
7123 if (Slice.Array == nullptr)
7124 // Zeroinitializer (including an empty one).
7125 return 1;
7126
7127 // Search for the first nul character. Return a conservative result even
7128 // when there is no nul. This is safe since otherwise the string function
7129 // being folded such as strlen is undefined, and can be preferable to
7130 // making the undefined library call.
7131 unsigned NullIndex = 0;
7132 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
7133 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
7134 break;
7135 }
7136
7137 return NullIndex + 1;
7138}
7139
7140/// If we can compute the length of the string pointed to by
7141/// the specified pointer, return 'len+1'. If we can't, return 0.
7142uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
7143 if (!V->getType()->isPointerTy())
7144 return 0;
7145
7147 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
7148 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
7149 // an empty string as a length.
7150 return Len == ~0ULL ? 1 : Len;
7151}
7152
7153const Value *
7155 bool MustPreserveOffset) {
7156 assert(Call &&
7157 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
7158 if (const Value *RV = Call->getReturnedArgOperand())
7159 return RV;
7160 // This can be used only as a aliasing property.
7162 Call, MustPreserveOffset))
7163 return Call->getArgOperand(0);
7164 return nullptr;
7165}
7166
7168 const CallBase *Call, bool MustPreserveOffset) {
7169 switch (Call->getIntrinsicID()) {
7170 case Intrinsic::launder_invariant_group:
7171 case Intrinsic::strip_invariant_group:
7172 case Intrinsic::aarch64_irg:
7173 case Intrinsic::aarch64_tagp:
7174 // The amdgcn_make_buffer_rsrc function does not alter the address of the
7175 // input pointer (and thus preserves the byte offset, which is the property
7176 // the MustPreserveOffset flag selects). However, it will not necessarily
7177 // map ptr addrspace(N) null to ptr addrspace(8) null, aka the "null
7178 // descriptor", which has "all loads return 0, all stores are dropped"
7179 // semantics. Given the context of this intrinsic list, no one should be
7180 // relying on such a strict bit-exact null mapping (and, at time of
7181 // writing, they are not), but we document this fact out of an abundance
7182 // of caution.
7183 case Intrinsic::amdgcn_make_buffer_rsrc:
7184 return true;
7185 case Intrinsic::ptrmask:
7186 return !MustPreserveOffset;
7187 case Intrinsic::threadlocal_address:
7188 // The underlying variable changes with thread ID. The Thread ID may change
7189 // at coroutine suspend points.
7190 return !Call->getParent()->getParent()->isPresplitCoroutine();
7191 default:
7192 return false;
7193 }
7194}
7195
7196/// \p PN defines a loop-variant pointer to an object. Check if the
7197/// previous iteration of the loop was referring to the same object as \p PN.
7199 const LoopInfo *LI) {
7200 // Find the loop-defined value.
7201 Loop *L = LI->getLoopFor(PN->getParent());
7202 if (PN->getNumIncomingValues() != 2)
7203 return true;
7204
7205 // Find the value from previous iteration.
7206 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
7207 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7208 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
7209 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7210 return true;
7211
7212 // If a new pointer is loaded in the loop, the pointer references a different
7213 // object in every iteration. E.g.:
7214 // for (i)
7215 // int *p = a[i];
7216 // ...
7217 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
7218 if (!L->isLoopInvariant(Load->getPointerOperand()))
7219 return false;
7220 return true;
7221}
7222
7223const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup) {
7224 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
7225 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
7226 const Value *PtrOp = GEP->getPointerOperand();
7227 if (!PtrOp->getType()->isPointerTy()) // Only handle scalar pointer base.
7228 return V;
7229 V = PtrOp;
7230 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
7231 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
7232 Value *NewV = cast<Operator>(V)->getOperand(0);
7233 if (!NewV->getType()->isPointerTy())
7234 return V;
7235 V = NewV;
7236 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
7237 if (GA->isInterposable())
7238 return V;
7239 V = GA->getAliasee();
7240 } else {
7241 if (auto *PHI = dyn_cast<PHINode>(V)) {
7242 // Look through single-arg phi nodes created by LCSSA.
7243 if (PHI->getNumIncomingValues() == 1) {
7244 V = PHI->getIncomingValue(0);
7245 continue;
7246 }
7247 } else if (auto *Call = dyn_cast<CallBase>(V)) {
7248 // CaptureTracking can know about special capturing properties of some
7249 // intrinsics like launder.invariant.group, that can't be expressed with
7250 // the attributes, but have properties like returning aliasing pointer.
7251 // Because some analysis may assume that nocaptured pointer is not
7252 // returned from some special intrinsic (because function would have to
7253 // be marked with returns attribute), it is crucial to use this function
7254 // because it should be in sync with CaptureTracking. Not using it may
7255 // cause weird miscompilations where 2 aliasing pointers are assumed to
7256 // noalias.
7258 Call, /*MustPreserveOffset=*/false)) {
7259 V = RP;
7260 continue;
7261 }
7262 }
7263
7264 return V;
7265 }
7266 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
7267 }
7268 return V;
7269}
7270
7273 const LoopInfo *LI, unsigned MaxLookup) {
7276 Worklist.push_back(V);
7277 do {
7278 const Value *P = Worklist.pop_back_val();
7279 P = getUnderlyingObject(P, MaxLookup);
7280
7281 if (!Visited.insert(P).second)
7282 continue;
7283
7284 if (auto *SI = dyn_cast<SelectInst>(P)) {
7285 Worklist.push_back(SI->getTrueValue());
7286 Worklist.push_back(SI->getFalseValue());
7287 continue;
7288 }
7289
7290 if (auto *PN = dyn_cast<PHINode>(P)) {
7291 // If this PHI changes the underlying object in every iteration of the
7292 // loop, don't look through it. Consider:
7293 // int **A;
7294 // for (i) {
7295 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
7296 // Curr = A[i];
7297 // *Prev, *Curr;
7298 //
7299 // Prev is tracking Curr one iteration behind so they refer to different
7300 // underlying objects.
7301 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
7303 append_range(Worklist, PN->incoming_values());
7304 else
7305 Objects.push_back(P);
7306 continue;
7307 }
7308
7309 Objects.push_back(P);
7310 } while (!Worklist.empty());
7311}
7312
7314 const unsigned MaxVisited = 8;
7315
7318 Worklist.push_back(V);
7319 const Value *Object = nullptr;
7320 // Used as fallback if we can't find a common underlying object through
7321 // recursion.
7322 bool First = true;
7323 const Value *FirstObject = getUnderlyingObject(V);
7324 do {
7325 const Value *P = Worklist.pop_back_val();
7326 P = First ? FirstObject : getUnderlyingObject(P);
7327 First = false;
7328
7329 if (!Visited.insert(P).second)
7330 continue;
7331
7332 if (Visited.size() == MaxVisited)
7333 return FirstObject;
7334
7335 if (auto *SI = dyn_cast<SelectInst>(P)) {
7336 Worklist.push_back(SI->getTrueValue());
7337 Worklist.push_back(SI->getFalseValue());
7338 continue;
7339 }
7340
7341 if (auto *PN = dyn_cast<PHINode>(P)) {
7342 append_range(Worklist, PN->incoming_values());
7343 continue;
7344 }
7345
7346 if (!Object)
7347 Object = P;
7348 else if (Object != P)
7349 return FirstObject;
7350 } while (!Worklist.empty());
7351
7352 return Object ? Object : FirstObject;
7353}
7354
7355/// This is the function that does the work of looking through basic
7356/// ptrtoint+arithmetic+inttoptr sequences.
7357static const Value *getUnderlyingObjectFromInt(const Value *V) {
7358 do {
7359 if (const Operator *U = dyn_cast<Operator>(V)) {
7360 // If we find a ptrtoint, we can transfer control back to the
7361 // regular getUnderlyingObjectFromInt.
7362 if (U->getOpcode() == Instruction::PtrToInt)
7363 return U->getOperand(0);
7364 // If we find an add of a constant, a multiplied value, or a phi, it's
7365 // likely that the other operand will lead us to the base
7366 // object. We don't have to worry about the case where the
7367 // object address is somehow being computed by the multiply,
7368 // because our callers only care when the result is an
7369 // identifiable object.
7370 if (U->getOpcode() != Instruction::Add ||
7371 (!isa<ConstantInt>(U->getOperand(1)) &&
7372 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
7373 !isa<PHINode>(U->getOperand(1))))
7374 return V;
7375 V = U->getOperand(0);
7376 } else {
7377 return V;
7378 }
7379 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
7380 } while (true);
7381}
7382
7383/// This is a wrapper around getUnderlyingObjects and adds support for basic
7384/// ptrtoint+arithmetic+inttoptr sequences.
7385/// It returns false if unidentified object is found in getUnderlyingObjects.
7387 SmallVectorImpl<Value *> &Objects) {
7389 SmallVector<const Value *, 4> Working(1, V);
7390 do {
7391 V = Working.pop_back_val();
7392
7394 getUnderlyingObjects(V, Objs);
7395
7396 for (const Value *V : Objs) {
7397 if (!Visited.insert(V).second)
7398 continue;
7399 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
7400 const Value *O =
7401 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
7402 if (O->getType()->isPointerTy()) {
7403 Working.push_back(O);
7404 continue;
7405 }
7406 }
7407 // If getUnderlyingObjects fails to find an identifiable object,
7408 // getUnderlyingObjectsForCodeGen also fails for safety.
7409 if (!isIdentifiedObject(V)) {
7410 Objects.clear();
7411 return false;
7412 }
7413 Objects.push_back(const_cast<Value *>(V));
7414 }
7415 } while (!Working.empty());
7416 return true;
7417}
7418
7420 AllocaInst *Result = nullptr;
7422 SmallVector<Value *, 4> Worklist;
7423
7424 auto AddWork = [&](Value *V) {
7425 if (Visited.insert(V).second)
7426 Worklist.push_back(V);
7427 };
7428
7429 AddWork(V);
7430 do {
7431 V = Worklist.pop_back_val();
7432 assert(Visited.count(V));
7433
7434 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
7435 if (Result && Result != AI)
7436 return nullptr;
7437 Result = AI;
7438 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
7439 AddWork(CI->getOperand(0));
7440 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
7441 for (Value *IncValue : PN->incoming_values())
7442 AddWork(IncValue);
7443 } else if (auto *SI = dyn_cast<SelectInst>(V)) {
7444 AddWork(SI->getTrueValue());
7445 AddWork(SI->getFalseValue());
7447 if (OffsetZero && !GEP->hasAllZeroIndices())
7448 return nullptr;
7449 AddWork(GEP->getPointerOperand());
7450 } else if (CallBase *CB = dyn_cast<CallBase>(V)) {
7451 Value *Returned = CB->getReturnedArgOperand();
7452 if (Returned)
7453 AddWork(Returned);
7454 else
7455 return nullptr;
7456 } else {
7457 return nullptr;
7458 }
7459 } while (!Worklist.empty());
7460
7461 return Result;
7462}
7463
7465 const Value *V, bool AllowLifetime, bool AllowDroppable) {
7466 for (const User *U : V->users()) {
7468 if (!II)
7469 return false;
7470
7471 if (AllowLifetime && II->isLifetimeStartOrEnd())
7472 continue;
7473
7474 if (AllowDroppable && II->isDroppable())
7475 continue;
7476
7477 return false;
7478 }
7479 return true;
7480}
7481
7484 V, /* AllowLifetime */ true, /* AllowDroppable */ false);
7485}
7488 V, /* AllowLifetime */ true, /* AllowDroppable */ true);
7489}
7490
7492 if (auto *II = dyn_cast<IntrinsicInst>(I))
7493 return isTriviallyVectorizable(II->getIntrinsicID());
7494 auto *Shuffle = dyn_cast<ShuffleVectorInst>(I);
7495 return (!Shuffle || Shuffle->isSelect()) &&
7497}
7498
7500 const Instruction *Inst, const Instruction *CtxI, AssumptionCache *AC,
7501 const DominatorTree *DT, const TargetLibraryInfo *TLI, bool UseVariableInfo,
7502 bool IgnoreUBImplyingAttrs) {
7503 return isSafeToSpeculativelyExecuteWithOpcode(Inst->getOpcode(), Inst, CtxI,
7504 AC, DT, TLI, UseVariableInfo,
7505 IgnoreUBImplyingAttrs);
7506}
7507
7509 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI,
7510 AssumptionCache *AC, const DominatorTree *DT, const TargetLibraryInfo *TLI,
7511 bool UseVariableInfo, bool IgnoreUBImplyingAttrs) {
7512#ifndef NDEBUG
7513 if (Inst->getOpcode() != Opcode) {
7514 // Check that the operands are actually compatible with the Opcode override.
7515 auto hasEqualReturnAndLeadingOperandTypes =
7516 [](const Instruction *Inst, unsigned NumLeadingOperands) {
7517 if (Inst->getNumOperands() < NumLeadingOperands)
7518 return false;
7519 const Type *ExpectedType = Inst->getType();
7520 for (unsigned ItOp = 0; ItOp < NumLeadingOperands; ++ItOp)
7521 if (Inst->getOperand(ItOp)->getType() != ExpectedType)
7522 return false;
7523 return true;
7524 };
7526 hasEqualReturnAndLeadingOperandTypes(Inst, 2));
7527 assert(!Instruction::isUnaryOp(Opcode) ||
7528 hasEqualReturnAndLeadingOperandTypes(Inst, 1));
7529 }
7530#endif
7531
7532 switch (Opcode) {
7533 default:
7534 return true;
7535 case Instruction::UDiv:
7536 case Instruction::URem: {
7537 // x / y is undefined if y == 0.
7538 const APInt *V;
7539 if (match(Inst->getOperand(1), m_APInt(V)))
7540 return *V != 0;
7541 return false;
7542 }
7543 case Instruction::SDiv:
7544 case Instruction::SRem: {
7545 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
7546 const APInt *Numerator, *Denominator;
7547 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
7548 return false;
7549 // We cannot hoist this division if the denominator is 0.
7550 if (*Denominator == 0)
7551 return false;
7552 // It's safe to hoist if the denominator is not 0 or -1.
7553 if (!Denominator->isAllOnes())
7554 return true;
7555 // At this point we know that the denominator is -1. It is safe to hoist as
7556 // long we know that the numerator is not INT_MIN.
7557 if (match(Inst->getOperand(0), m_APInt(Numerator)))
7558 return !Numerator->isMinSignedValue();
7559 // The numerator *might* be MinSignedValue.
7560 return false;
7561 }
7562 case Instruction::Load: {
7563 if (!UseVariableInfo)
7564 return false;
7565
7566 const LoadInst *LI = dyn_cast<LoadInst>(Inst);
7567 if (!LI)
7568 return false;
7569 if (mustSuppressSpeculation(*LI))
7570 return false;
7571 const DataLayout &DL = LI->getDataLayout();
7573 LI->getPointerOperand(), LI->getType(), LI->getAlign(),
7574 SimplifyQuery(DL, TLI, DT, AC, CtxI));
7575 }
7576 case Instruction::Call: {
7577 auto *CI = dyn_cast<const CallInst>(Inst);
7578 if (!CI)
7579 return false;
7580 const Function *Callee = CI->getCalledFunction();
7581
7582 // The called function could have undefined behavior or side-effects, even
7583 // if marked readnone nounwind.
7584 if (!Callee || !Callee->isSpeculatable())
7585 return false;
7586 // Since the operands may be changed after hoisting, undefined behavior may
7587 // be triggered by some UB-implying attributes.
7588 return IgnoreUBImplyingAttrs || !CI->hasUBImplyingAttrs();
7589 }
7590 case Instruction::VAArg:
7591 case Instruction::Alloca:
7592 case Instruction::Invoke:
7593 case Instruction::CallBr:
7594 case Instruction::PHI:
7595 case Instruction::Store:
7596 case Instruction::Ret:
7597 case Instruction::UncondBr:
7598 case Instruction::CondBr:
7599 case Instruction::IndirectBr:
7600 case Instruction::Switch:
7601 case Instruction::Unreachable:
7602 case Instruction::Fence:
7603 case Instruction::AtomicRMW:
7604 case Instruction::AtomicCmpXchg:
7605 case Instruction::LandingPad:
7606 case Instruction::Resume:
7607 case Instruction::CatchSwitch:
7608 case Instruction::CatchPad:
7609 case Instruction::CatchRet:
7610 case Instruction::CleanupPad:
7611 case Instruction::CleanupRet:
7612 return false; // Misc instructions which have effects
7613 }
7614}
7615
7617 if (I.mayReadOrWriteMemory())
7618 // Memory dependency possible
7619 return true;
7621 // Can't move above a maythrow call or infinite loop. Or if an
7622 // inalloca alloca, above a stacksave call.
7623 return true;
7625 // 1) Can't reorder two inf-loop calls, even if readonly
7626 // 2) Also can't reorder an inf-loop call below a instruction which isn't
7627 // safe to speculative execute. (Inverse of above)
7628 return true;
7629 return false;
7630}
7631
7632/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
7646
7647/// Combine constant ranges from computeConstantRange() and computeKnownBits().
7650 bool ForSigned,
7651 const SimplifyQuery &SQ) {
7652 ConstantRange CR1 =
7653 ConstantRange::fromKnownBits(V.getKnownBits(SQ), ForSigned);
7654 ConstantRange CR2 = computeConstantRange(V, ForSigned, SQ);
7657 return CR1.intersectWith(CR2, RangeType);
7658}
7659
7661 const Value *RHS,
7662 const SimplifyQuery &SQ,
7663 bool IsNSW) {
7664 ConstantRange LHSRange =
7665 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7666 ConstantRange RHSRange =
7667 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7668
7669 // mul nsw of two non-negative numbers is also nuw.
7670 if (IsNSW && LHSRange.isAllNonNegative() && RHSRange.isAllNonNegative())
7672
7673 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
7674}
7675
7677 const Value *RHS,
7678 const SimplifyQuery &SQ) {
7679 // Multiplying n * m significant bits yields a result of n + m significant
7680 // bits. If the total number of significant bits does not exceed the
7681 // result bit width (minus 1), there is no overflow.
7682 // This means if we have enough leading sign bits in the operands
7683 // we can guarantee that the result does not overflow.
7684 // Ref: "Hacker's Delight" by Henry Warren
7685 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
7686
7687 // Note that underestimating the number of sign bits gives a more
7688 // conservative answer.
7689 unsigned SignBits =
7690 ::ComputeNumSignBits(LHS, SQ) + ::ComputeNumSignBits(RHS, SQ);
7691
7692 // First handle the easy case: if we have enough sign bits there's
7693 // definitely no overflow.
7694 if (SignBits > BitWidth + 1)
7696
7697 // There are two ambiguous cases where there can be no overflow:
7698 // SignBits == BitWidth + 1 and
7699 // SignBits == BitWidth
7700 // The second case is difficult to check, therefore we only handle the
7701 // first case.
7702 if (SignBits == BitWidth + 1) {
7703 // It overflows only when both arguments are negative and the true
7704 // product is exactly the minimum negative number.
7705 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
7706 // For simplicity we just check if at least one side is not negative.
7707 KnownBits LHSKnown = computeKnownBits(LHS, SQ);
7708 KnownBits RHSKnown = computeKnownBits(RHS, SQ);
7709 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
7711 }
7713}
7714
7717 const WithCache<const Value *> &RHS,
7718 const SimplifyQuery &SQ) {
7719 ConstantRange LHSRange =
7720 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7721 ConstantRange RHSRange =
7722 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7723 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
7724}
7725
7726static OverflowResult
7729 const AddOperator *Add, const SimplifyQuery &SQ) {
7730 if (Add && Add->hasNoSignedWrap()) {
7732 }
7733
7734 // If LHS and RHS each have at least two sign bits, the addition will look
7735 // like
7736 //
7737 // XX..... +
7738 // YY.....
7739 //
7740 // If the carry into the most significant position is 0, X and Y can't both
7741 // be 1 and therefore the carry out of the addition is also 0.
7742 //
7743 // If the carry into the most significant position is 1, X and Y can't both
7744 // be 0 and therefore the carry out of the addition is also 1.
7745 //
7746 // Since the carry into the most significant position is always equal to
7747 // the carry out of the addition, there is no signed overflow.
7748 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7750
7751 ConstantRange LHSRange =
7752 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7753 ConstantRange RHSRange =
7754 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7755 OverflowResult OR =
7756 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
7758 return OR;
7759
7760 // The remaining code needs Add to be available. Early returns if not so.
7761 if (!Add)
7763
7764 // If the sign of Add is the same as at least one of the operands, this add
7765 // CANNOT overflow. If this can be determined from the known bits of the
7766 // operands the above signedAddMayOverflow() check will have already done so.
7767 // The only other way to improve on the known bits is from an assumption, so
7768 // call computeKnownBitsFromContext() directly.
7769 bool LHSOrRHSKnownNonNegative =
7770 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
7771 bool LHSOrRHSKnownNegative =
7772 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
7773 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
7774 KnownBits AddKnown(LHSRange.getBitWidth());
7775 computeKnownBitsFromContext(Add, AddKnown, SQ);
7776 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
7777 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
7779 }
7780
7782}
7783
7785 const Value *RHS,
7786 const SimplifyQuery &SQ) {
7787 // X - (X % ?)
7788 // The remainder of a value can't have greater magnitude than itself,
7789 // so the subtraction can't overflow.
7790
7791 // X - (X -nuw ?)
7792 // In the minimal case, this would simplify to "?", so there's no subtract
7793 // at all. But if this analysis is used to peek through casts, for example,
7794 // then determining no-overflow may allow other transforms.
7795
7796 // TODO: There are other patterns like this.
7797 // See simplifyICmpWithBinOpOnLHS() for candidates.
7798 if (match(RHS, m_URem(m_Specific(LHS), m_Value())) ||
7799 match(RHS, m_NUWSub(m_Specific(LHS), m_Value())))
7800 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT))
7802
7803 if (auto C = isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, SQ.CxtI,
7804 SQ.DL)) {
7805 if (*C)
7808 }
7809
7810 ConstantRange LHSRange =
7811 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7812 ConstantRange RHSRange =
7813 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7814 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
7815}
7816
7818 const Value *RHS,
7819 const SimplifyQuery &SQ) {
7820 // X - (X % ?)
7821 // The remainder of a value can't have greater magnitude than itself,
7822 // so the subtraction can't overflow.
7823
7824 // X - (X -nsw ?)
7825 // In the minimal case, this would simplify to "?", so there's no subtract
7826 // at all. But if this analysis is used to peek through casts, for example,
7827 // then determining no-overflow may allow other transforms.
7828 if (match(RHS, m_SRem(m_Specific(LHS), m_Value())) ||
7829 match(RHS, m_NSWSub(m_Specific(LHS), m_Value())))
7830 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT))
7832
7833 // If LHS and RHS each have at least two sign bits, the subtraction
7834 // cannot overflow.
7835 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7837
7838 ConstantRange LHSRange =
7839 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7840 ConstantRange RHSRange =
7841 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7842 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
7843}
7844
7846 const DominatorTree &DT) {
7847 SmallVector<const CondBrInst *, 2> GuardingBranches;
7849
7850 for (const User *U : WO->users()) {
7851 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
7852 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
7853
7854 if (EVI->getIndices()[0] == 0)
7855 Results.push_back(EVI);
7856 else {
7857 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
7858
7859 for (const auto *U : EVI->users())
7860 if (const auto *B = dyn_cast<CondBrInst>(U))
7861 GuardingBranches.push_back(B);
7862 }
7863 } else {
7864 // We are using the aggregate directly in a way we don't want to analyze
7865 // here (storing it to a global, say).
7866 return false;
7867 }
7868 }
7869
7870 auto AllUsesGuardedByBranch = [&](const CondBrInst *BI) {
7871 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
7872
7873 // Check if all users of the add are provably no-wrap.
7874 for (const auto *Result : Results) {
7875 // If the extractvalue itself is not executed on overflow, the we don't
7876 // need to check each use separately, since domination is transitive.
7877 if (DT.dominates(NoWrapEdge, Result->getParent()))
7878 continue;
7879
7880 for (const auto &RU : Result->uses())
7881 if (!DT.dominates(NoWrapEdge, RU))
7882 return false;
7883 }
7884
7885 return true;
7886 };
7887
7888 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
7889}
7890
7891/// Shifts return poison if shiftwidth is larger than the bitwidth.
7892static bool shiftAmountKnownInRange(const Value *ShiftAmount) {
7893 auto *C = dyn_cast<Constant>(ShiftAmount);
7894 if (!C)
7895 return false;
7896
7897 // Shifts return poison if shiftwidth is larger than the bitwidth.
7899 if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
7900 unsigned NumElts = FVTy->getNumElements();
7901 for (unsigned i = 0; i < NumElts; ++i)
7902 ShiftAmounts.push_back(C->getAggregateElement(i));
7903 } else if (isa<ScalableVectorType>(C->getType()))
7904 return false; // Can't tell, just return false to be safe
7905 else
7906 ShiftAmounts.push_back(C);
7907
7908 bool Safe = llvm::all_of(ShiftAmounts, [](const Constant *C) {
7909 auto *CI = dyn_cast_or_null<ConstantInt>(C);
7910 return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
7911 });
7912
7913 return Safe;
7914}
7915
7917 bool ConsiderFlagsAndMetadata) {
7918
7919 if (ConsiderFlagsAndMetadata && includesPoison(Kind) &&
7920 Op->hasPoisonGeneratingAnnotations())
7921 return true;
7922
7923 unsigned Opcode = Op->getOpcode();
7924
7925 // Check whether opcode is a poison/undef-generating operation
7926 switch (Opcode) {
7927 case Instruction::Shl:
7928 case Instruction::AShr:
7929 case Instruction::LShr:
7930 return includesPoison(Kind) && !shiftAmountKnownInRange(Op->getOperand(1));
7931 case Instruction::FPToSI:
7932 case Instruction::FPToUI:
7933 // fptosi/ui yields poison if the resulting value does not fit in the
7934 // destination type.
7935 return true;
7936 case Instruction::Call:
7937 if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
7938 switch (II->getIntrinsicID()) {
7939 // NOTE: Use IntrNoCreateUndefOrPoison when possible.
7940 case Intrinsic::ctlz:
7941 case Intrinsic::cttz:
7942 case Intrinsic::abs:
7943 // We're not considering flags so it is safe to just return false.
7944 return false;
7945 case Intrinsic::sshl_sat:
7946 case Intrinsic::ushl_sat:
7947 if (!includesPoison(Kind) ||
7948 shiftAmountKnownInRange(II->getArgOperand(1)))
7949 return false;
7950 break;
7951 }
7952 }
7953 [[fallthrough]];
7954 case Instruction::CallBr:
7955 case Instruction::Invoke: {
7956 const auto *CB = cast<CallBase>(Op);
7957 return !CB->hasRetAttr(Attribute::NoUndef) &&
7958 !CB->hasFnAttr(Attribute::NoCreateUndefOrPoison);
7959 }
7960 case Instruction::InsertElement:
7961 case Instruction::ExtractElement: {
7962 // If index exceeds the length of the vector, it returns poison
7963 auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
7964 unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
7965 auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
7966 if (includesPoison(Kind))
7967 return !Idx ||
7968 Idx->getValue().uge(VTy->getElementCount().getKnownMinValue());
7969 return false;
7970 }
7971 case Instruction::ShuffleVector: {
7973 ? cast<ConstantExpr>(Op)->getShuffleMask()
7974 : cast<ShuffleVectorInst>(Op)->getShuffleMask();
7975 return includesPoison(Kind) && is_contained(Mask, PoisonMaskElem);
7976 }
7977 case Instruction::FNeg:
7978 case Instruction::PHI:
7979 case Instruction::Select:
7980 case Instruction::ExtractValue:
7981 case Instruction::InsertValue:
7982 case Instruction::Freeze:
7983 case Instruction::ICmp:
7984 case Instruction::FCmp:
7985 case Instruction::GetElementPtr:
7986 return false;
7987 case Instruction::AddrSpaceCast:
7988 return true;
7989 default: {
7990 const auto *CE = dyn_cast<ConstantExpr>(Op);
7991 if (isa<CastInst>(Op) || (CE && CE->isCast()))
7992 return false;
7993 else if (Instruction::isBinaryOp(Opcode))
7994 return false;
7995 // Be conservative and return true.
7996 return true;
7997 }
7998 }
7999}
8000
8002 bool ConsiderFlagsAndMetadata) {
8003 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::UndefOrPoison,
8004 ConsiderFlagsAndMetadata);
8005}
8006
8007bool llvm::canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata) {
8008 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::PoisonOnly,
8009 ConsiderFlagsAndMetadata);
8010}
8011
8012static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V,
8013 unsigned Depth) {
8014 if (ValAssumedPoison == V)
8015 return true;
8016
8017 const unsigned MaxDepth = 2;
8018 if (Depth >= MaxDepth)
8019 return false;
8020
8021 if (const auto *I = dyn_cast<Instruction>(V)) {
8022 if (any_of(I->operands(), [=](const Use &Op) {
8023 return propagatesPoison(Op) &&
8024 directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
8025 }))
8026 return true;
8027
8028 // V = extractvalue V0, idx
8029 // V2 = extractvalue V0, idx2
8030 // V0's elements are all poison or not. (e.g., add_with_overflow)
8031 const WithOverflowInst *II;
8033 (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
8034 llvm::is_contained(II->args(), ValAssumedPoison)))
8035 return true;
8036 }
8037 return false;
8038}
8039
8040static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
8041 unsigned Depth) {
8042 if (isGuaranteedNotToBePoison(ValAssumedPoison))
8043 return true;
8044
8045 if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
8046 return true;
8047
8048 const unsigned MaxDepth = 2;
8049 if (Depth >= MaxDepth)
8050 return false;
8051
8052 const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
8053 if (I && !canCreatePoison(cast<Operator>(I))) {
8054 return all_of(I->operands(), [=](const Value *Op) {
8055 return impliesPoison(Op, V, Depth + 1);
8056 });
8057 }
8058 return false;
8059}
8060
8061bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
8062 return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
8063}
8064
8065static bool programUndefinedIfUndefOrPoison(const Value *V, bool PoisonOnly);
8066
8068 const Value *V, AssumptionCache *AC, const Instruction *CtxI,
8069 const DominatorTree *DT, unsigned Depth, UndefPoisonKind Kind) {
8071 return false;
8072
8073 if (isa<MetadataAsValue>(V))
8074 return false;
8075
8076 if (const auto *A = dyn_cast<Argument>(V)) {
8077 if (A->hasAttribute(Attribute::NoUndef) ||
8078 A->hasAttribute(Attribute::Dereferenceable) ||
8079 A->hasAttribute(Attribute::DereferenceableOrNull))
8080 return true;
8081 }
8082
8083 if (auto *C = dyn_cast<Constant>(V)) {
8084 if (isa<PoisonValue>(C))
8085 return !includesPoison(Kind);
8086
8087 if (isa<UndefValue>(C))
8088 return !includesUndef(Kind);
8089
8092 return true;
8093
8094 if (C->getType()->isVectorTy()) {
8095 if (isa<ConstantExpr>(C)) {
8096 // Scalable vectors can use a ConstantExpr to build a splat.
8097 if (Constant *SplatC = C->getSplatValue())
8098 if (isa<ConstantInt>(SplatC) || isa<ConstantFP>(SplatC))
8099 return true;
8100 } else {
8101 if (includesUndef(Kind) && C->containsUndefElement())
8102 return false;
8103 if (includesPoison(Kind) && C->containsPoisonElement())
8104 return false;
8105 return !C->containsConstantExpression();
8106 }
8107 }
8108 }
8109
8110 // Strip cast operations from a pointer value.
8111 // Note that stripPointerCastsSameRepresentation can strip off getelementptr
8112 // inbounds with zero offset. To guarantee that the result isn't poison, the
8113 // stripped pointer is checked as it has to be pointing into an allocated
8114 // object or be null `null` to ensure `inbounds` getelement pointers with a
8115 // zero offset could not produce poison.
8116 // It can strip off addrspacecast that do not change bit representation as
8117 // well. We believe that such addrspacecast is equivalent to no-op.
8118 auto *StrippedV = V->stripPointerCastsSameRepresentation();
8119 if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
8120 isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
8121 return true;
8122
8123 auto OpCheck = [&](const Value *V) {
8124 return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1, Kind);
8125 };
8126
8127 if (auto *Opr = dyn_cast<Operator>(V)) {
8128 // If the value is a freeze instruction, then it can never
8129 // be undef or poison.
8130 if (isa<FreezeInst>(V))
8131 return true;
8132
8133 if (const auto *CB = dyn_cast<CallBase>(V)) {
8134 if (CB->hasRetAttr(Attribute::NoUndef) ||
8135 CB->hasRetAttr(Attribute::Dereferenceable) ||
8136 CB->hasRetAttr(Attribute::DereferenceableOrNull))
8137 return true;
8138 }
8139
8140 if (!::canCreateUndefOrPoison(Opr, Kind,
8141 /*ConsiderFlagsAndMetadata=*/true)) {
8142 if (const auto *PN = dyn_cast<PHINode>(V)) {
8143 unsigned Num = PN->getNumIncomingValues();
8144 bool IsWellDefined = true;
8145 for (unsigned i = 0; i < Num; ++i) {
8146 if (PN == PN->getIncomingValue(i))
8147 continue;
8148 auto *TI = PN->getIncomingBlock(i)->getTerminator();
8149 if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
8150 DT, Depth + 1, Kind)) {
8151 IsWellDefined = false;
8152 break;
8153 }
8154 }
8155 if (IsWellDefined)
8156 return true;
8157 } else if (auto *Splat = isa<ShuffleVectorInst>(Opr) ? getSplatValue(Opr)
8158 : nullptr) {
8159 // For splats we only need to check the value being splatted.
8160 if (OpCheck(Splat))
8161 return true;
8162 } else if (all_of(Opr->operands(), OpCheck))
8163 return true;
8164 }
8165 }
8166
8167 if (auto *I = dyn_cast<LoadInst>(V))
8168 if (I->hasMetadata(LLVMContext::MD_noundef) ||
8169 I->hasMetadata(LLVMContext::MD_dereferenceable) ||
8170 I->hasMetadata(LLVMContext::MD_dereferenceable_or_null))
8171 return true;
8172
8174 return true;
8175
8176 // CxtI may be null or a cloned instruction.
8177 if (!CtxI || !CtxI->getParent() || !DT)
8178 return false;
8179
8180 auto *DNode = DT->getNode(CtxI->getParent());
8181 if (!DNode)
8182 // Unreachable block
8183 return false;
8184
8185 // If V is used as a branch condition before reaching CtxI, V cannot be
8186 // undef or poison.
8187 // br V, BB1, BB2
8188 // BB1:
8189 // CtxI ; V cannot be undef or poison here
8190 auto *Dominator = DNode->getIDom();
8191 // This check is purely for compile time reasons: we can skip the IDom walk
8192 // if what we are checking for includes undef and the value is not an integer.
8193 if (!includesUndef(Kind) || V->getType()->isIntegerTy())
8194 while (Dominator) {
8195 auto *TI = Dominator->getBlock()->getTerminatorOrNull();
8196
8197 Value *Cond = nullptr;
8198 if (auto BI = dyn_cast_or_null<CondBrInst>(TI)) {
8199 Cond = BI->getCondition();
8200 } else if (auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
8201 Cond = SI->getCondition();
8202 }
8203
8204 if (Cond) {
8205 if (Cond == V)
8206 return true;
8207 else if (!includesUndef(Kind) && isa<Operator>(Cond)) {
8208 // For poison, we can analyze further
8209 auto *Opr = cast<Operator>(Cond);
8210 if (any_of(Opr->operands(), [V](const Use &U) {
8211 return V == U && propagatesPoison(U);
8212 }))
8213 return true;
8214 }
8215 }
8216
8217 Dominator = Dominator->getIDom();
8218 }
8219
8220 if (AC && getKnowledgeValidInContext(V, {Attribute::NoUndef}, *AC, CtxI, DT))
8221 return true;
8222
8223 return false;
8224}
8225
8227 const Instruction *CtxI,
8228 const DominatorTree *DT,
8229 unsigned Depth) {
8230 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8232}
8233
8235 const Instruction *CtxI,
8236 const DominatorTree *DT, unsigned Depth) {
8237 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8239}
8240
8242 const Instruction *CtxI,
8243 const DominatorTree *DT, unsigned Depth) {
8244 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8246}
8247
8248/// Return true if undefined behavior would provably be executed on the path to
8249/// OnPathTo if Root produced a posion result. Note that this doesn't say
8250/// anything about whether OnPathTo is actually executed or whether Root is
8251/// actually poison. This can be used to assess whether a new use of Root can
8252/// be added at a location which is control equivalent with OnPathTo (such as
8253/// immediately before it) without introducing UB which didn't previously
8254/// exist. Note that a false result conveys no information.
8256 Instruction *OnPathTo,
8257 DominatorTree *DT) {
8258 // Basic approach is to assume Root is poison, propagate poison forward
8259 // through all users we can easily track, and then check whether any of those
8260 // users are provable UB and must execute before out exiting block might
8261 // exit.
8262
8263 // The set of all recursive users we've visited (which are assumed to all be
8264 // poison because of said visit)
8267 Worklist.push_back(Root);
8268 while (!Worklist.empty()) {
8269 const Instruction *I = Worklist.pop_back_val();
8270
8271 // If we know this must trigger UB on a path leading our target.
8272 if (mustTriggerUB(I, KnownPoison) && DT->dominates(I, OnPathTo))
8273 return true;
8274
8275 // If we can't analyze propagation through this instruction, just skip it
8276 // and transitive users. Safe as false is a conservative result.
8277 if (I != Root && !any_of(I->operands(), [&KnownPoison](const Use &U) {
8278 return KnownPoison.contains(U) && propagatesPoison(U);
8279 }))
8280 continue;
8281
8282 if (KnownPoison.insert(I).second)
8283 for (const User *User : I->users())
8284 Worklist.push_back(cast<Instruction>(User));
8285 }
8286
8287 // Might be non-UB, or might have a path we couldn't prove must execute on
8288 // way to exiting bb.
8289 return false;
8290}
8291
8293 const SimplifyQuery &SQ) {
8294 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
8295 Add, SQ);
8296}
8297
8300 const WithCache<const Value *> &RHS,
8301 const SimplifyQuery &SQ) {
8302 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, SQ);
8303}
8304
8306 // Note: An atomic operation isn't guaranteed to return in a reasonable amount
8307 // of time because it's possible for another thread to interfere with it for an
8308 // arbitrary length of time, but programs aren't allowed to rely on that.
8309
8310 // If there is no successor, then execution can't transfer to it.
8311 if (isa<ReturnInst>(I))
8312 return false;
8314 return false;
8315
8316 // Note: Do not add new checks here; instead, change Instruction::mayThrow or
8317 // Instruction::willReturn.
8318 //
8319 // FIXME: Move this check into Instruction::willReturn.
8320 if (isa<CatchPadInst>(I)) {
8321 switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) {
8322 default:
8323 // A catchpad may invoke exception object constructors and such, which
8324 // in some languages can be arbitrary code, so be conservative by default.
8325 return false;
8327 // For CoreCLR, it just involves a type test.
8328 return true;
8329 }
8330 }
8331
8332 // An instruction that returns without throwing must transfer control flow
8333 // to a successor.
8334 return !I->mayThrow() && I->willReturn();
8335}
8336
8338 // TODO: This is slightly conservative for invoke instruction since exiting
8339 // via an exception *is* normal control for them.
8340 for (const Instruction &I : *BB)
8342 return false;
8343 return true;
8344}
8345
8352
8355 assert(ScanLimit && "scan limit must be non-zero");
8356 for (const Instruction &I : Range) {
8357 if (--ScanLimit == 0)
8358 return false;
8360 return false;
8361 }
8362 return true;
8363}
8364
8366 const Loop *L) {
8367 // The loop header is guaranteed to be executed for every iteration.
8368 //
8369 // FIXME: Relax this constraint to cover all basic blocks that are
8370 // guaranteed to be executed at every iteration.
8371 if (I->getParent() != L->getHeader()) return false;
8372
8373 for (const Instruction &LI : *L->getHeader()) {
8374 if (&LI == I) return true;
8375 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
8376 }
8377 llvm_unreachable("Instruction not contained in its own parent basic block.");
8378}
8379
8381 switch (IID) {
8382 // TODO: Add more intrinsics.
8383 case Intrinsic::sadd_with_overflow:
8384 case Intrinsic::ssub_with_overflow:
8385 case Intrinsic::smul_with_overflow:
8386 case Intrinsic::uadd_with_overflow:
8387 case Intrinsic::usub_with_overflow:
8388 case Intrinsic::umul_with_overflow:
8389 // If an input is a vector containing a poison element, the
8390 // two output vectors (calculated results, overflow bits)'
8391 // corresponding lanes are poison.
8392 return true;
8393 case Intrinsic::ctpop:
8394 case Intrinsic::ctlz:
8395 case Intrinsic::cttz:
8396 case Intrinsic::abs:
8397 case Intrinsic::smax:
8398 case Intrinsic::smin:
8399 case Intrinsic::umax:
8400 case Intrinsic::umin:
8401 case Intrinsic::scmp:
8402 case Intrinsic::is_fpclass:
8403 case Intrinsic::ptrmask:
8404 case Intrinsic::ucmp:
8405 case Intrinsic::bitreverse:
8406 case Intrinsic::bswap:
8407 case Intrinsic::sadd_sat:
8408 case Intrinsic::ssub_sat:
8409 case Intrinsic::sshl_sat:
8410 case Intrinsic::uadd_sat:
8411 case Intrinsic::usub_sat:
8412 case Intrinsic::ushl_sat:
8413 case Intrinsic::smul_fix:
8414 case Intrinsic::smul_fix_sat:
8415 case Intrinsic::umul_fix:
8416 case Intrinsic::umul_fix_sat:
8417 case Intrinsic::pow:
8418 case Intrinsic::powi:
8419 case Intrinsic::sin:
8420 case Intrinsic::sinh:
8421 case Intrinsic::cos:
8422 case Intrinsic::cosh:
8423 case Intrinsic::sincos:
8424 case Intrinsic::sincospi:
8425 case Intrinsic::tan:
8426 case Intrinsic::tanh:
8427 case Intrinsic::asin:
8428 case Intrinsic::acos:
8429 case Intrinsic::atan:
8430 case Intrinsic::atan2:
8431 case Intrinsic::canonicalize:
8432 case Intrinsic::sqrt:
8433 case Intrinsic::exp:
8434 case Intrinsic::exp2:
8435 case Intrinsic::exp10:
8436 case Intrinsic::log:
8437 case Intrinsic::log2:
8438 case Intrinsic::log10:
8439 case Intrinsic::modf:
8440 case Intrinsic::floor:
8441 case Intrinsic::ceil:
8442 case Intrinsic::trunc:
8443 case Intrinsic::rint:
8444 case Intrinsic::nearbyint:
8445 case Intrinsic::round:
8446 case Intrinsic::roundeven:
8447 case Intrinsic::lrint:
8448 case Intrinsic::llrint:
8449 case Intrinsic::fshl:
8450 case Intrinsic::fshr:
8451 case Intrinsic::frexp:
8452 case Intrinsic::get_active_lane_mask:
8453 return true;
8454 default:
8455 return false;
8456 }
8457}
8458
8459bool llvm::propagatesPoison(const Use &PoisonOp) {
8460 const Operator *I = cast<Operator>(PoisonOp.getUser());
8461 switch (I->getOpcode()) {
8462 case Instruction::Freeze:
8463 case Instruction::PHI:
8464 case Instruction::Invoke:
8465 return false;
8466 case Instruction::Select:
8467 return PoisonOp.getOperandNo() == 0;
8468 case Instruction::Call:
8469 if (auto *II = dyn_cast<IntrinsicInst>(I))
8470 return intrinsicPropagatesPoison(II->getIntrinsicID());
8471 return false;
8472 case Instruction::ICmp:
8473 case Instruction::FCmp:
8474 case Instruction::GetElementPtr:
8475 return true;
8476 default:
8478 return true;
8479
8480 // Be conservative and return false.
8481 return false;
8482 }
8483}
8484
8485/// Enumerates all operands of \p I that are guaranteed to not be undef or
8486/// poison. If the callback \p Handle returns true, stop processing and return
8487/// true. Otherwise, return false.
8488template <typename CallableT>
8490 const CallableT &Handle) {
8491 switch (I->getOpcode()) {
8492 case Instruction::Store:
8493 if (Handle(cast<StoreInst>(I)->getPointerOperand()))
8494 return true;
8495 break;
8496
8497 case Instruction::Load:
8498 if (Handle(cast<LoadInst>(I)->getPointerOperand()))
8499 return true;
8500 break;
8501
8502 // Since dereferenceable attribute imply noundef, atomic operations
8503 // also implicitly have noundef pointers too
8504 case Instruction::AtomicCmpXchg:
8506 return true;
8507 break;
8508
8509 case Instruction::AtomicRMW:
8510 if (Handle(cast<AtomicRMWInst>(I)->getPointerOperand()))
8511 return true;
8512 break;
8513
8514 case Instruction::Call:
8515 case Instruction::Invoke: {
8516 const CallBase *CB = cast<CallBase>(I);
8517 if (CB->isIndirectCall() && Handle(CB->getCalledOperand()))
8518 return true;
8519 for (unsigned i = 0; i < CB->arg_size(); ++i)
8520 if ((CB->paramHasAttr(i, Attribute::NoUndef) ||
8521 CB->paramHasAttr(i, Attribute::Dereferenceable) ||
8522 CB->paramHasAttr(i, Attribute::DereferenceableOrNull)) &&
8523 Handle(CB->getArgOperand(i)))
8524 return true;
8525 break;
8526 }
8527 case Instruction::Ret:
8528 if (I->getFunction()->hasRetAttribute(Attribute::NoUndef) &&
8529 Handle(I->getOperand(0)))
8530 return true;
8531 break;
8532 case Instruction::Switch:
8533 if (Handle(cast<SwitchInst>(I)->getCondition()))
8534 return true;
8535 break;
8536 case Instruction::CondBr:
8537 if (Handle(cast<CondBrInst>(I)->getCondition()))
8538 return true;
8539 break;
8540 default:
8541 break;
8542 }
8543
8544 return false;
8545}
8546
8547/// Enumerates all operands of \p I that are guaranteed to not be poison.
8548template <typename CallableT>
8550 const CallableT &Handle) {
8551 if (handleGuaranteedWellDefinedOps(I, Handle))
8552 return true;
8553 switch (I->getOpcode()) {
8554 // Divisors of these operations are allowed to be partially undef.
8555 case Instruction::UDiv:
8556 case Instruction::SDiv:
8557 case Instruction::URem:
8558 case Instruction::SRem:
8559 return Handle(I->getOperand(1));
8560 default:
8561 return false;
8562 }
8563}
8564
8566 const SmallPtrSetImpl<const Value *> &KnownPoison) {
8568 I, [&](const Value *V) { return KnownPoison.count(V); });
8569}
8570
8572 bool PoisonOnly) {
8573 // We currently only look for uses of values within the same basic
8574 // block, as that makes it easier to guarantee that the uses will be
8575 // executed given that Inst is executed.
8576 //
8577 // FIXME: Expand this to consider uses beyond the same basic block. To do
8578 // this, look out for the distinction between post-dominance and strong
8579 // post-dominance.
8580 const BasicBlock *BB = nullptr;
8582 if (const auto *Inst = dyn_cast<Instruction>(V)) {
8583 BB = Inst->getParent();
8584 Begin = Inst->getIterator();
8585 Begin++;
8586 } else if (const auto *Arg = dyn_cast<Argument>(V)) {
8587 if (Arg->getParent()->isDeclaration())
8588 return false;
8589 BB = &Arg->getParent()->getEntryBlock();
8590 Begin = BB->begin();
8591 } else {
8592 return false;
8593 }
8594
8595 // Limit number of instructions we look at, to avoid scanning through large
8596 // blocks. The current limit is chosen arbitrarily.
8597 unsigned ScanLimit = 32;
8598 BasicBlock::const_iterator End = BB->end();
8599
8600 if (!PoisonOnly) {
8601 // Since undef does not propagate eagerly, be conservative & just check
8602 // whether a value is directly passed to an instruction that must take
8603 // well-defined operands.
8604
8605 for (const auto &I : make_range(Begin, End)) {
8606 if (--ScanLimit == 0)
8607 break;
8608
8609 if (handleGuaranteedWellDefinedOps(&I, [V](const Value *WellDefinedOp) {
8610 return WellDefinedOp == V;
8611 }))
8612 return true;
8613
8615 break;
8616 }
8617 return false;
8618 }
8619
8620 // Set of instructions that we have proved will yield poison if Inst
8621 // does.
8622 SmallPtrSet<const Value *, 16> YieldsPoison;
8624
8625 YieldsPoison.insert(V);
8626 Visited.insert(BB);
8627
8628 while (true) {
8629 for (const auto &I : make_range(Begin, End)) {
8630 if (--ScanLimit == 0)
8631 return false;
8632 if (mustTriggerUB(&I, YieldsPoison))
8633 return true;
8635 return false;
8636
8637 // If an operand is poison and propagates it, mark I as yielding poison.
8638 for (const Use &Op : I.operands()) {
8639 if (YieldsPoison.count(Op) && propagatesPoison(Op)) {
8640 YieldsPoison.insert(&I);
8641 break;
8642 }
8643 }
8644
8645 // Special handling for select, which returns poison if its operand 0 is
8646 // poison (handled in the loop above) *or* if both its true/false operands
8647 // are poison (handled here).
8648 if (I.getOpcode() == Instruction::Select &&
8649 YieldsPoison.count(I.getOperand(1)) &&
8650 YieldsPoison.count(I.getOperand(2))) {
8651 YieldsPoison.insert(&I);
8652 }
8653 }
8654
8655 BB = BB->getSingleSuccessor();
8656 if (!BB || !Visited.insert(BB).second)
8657 break;
8658
8659 Begin = BB->getFirstNonPHIIt();
8660 End = BB->end();
8661 }
8662 return false;
8663}
8664
8666 return ::programUndefinedIfUndefOrPoison(Inst, false);
8667}
8668
8670 return ::programUndefinedIfUndefOrPoison(Inst, true);
8671}
8672
8673static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
8674 if (FMF.noNaNs())
8675 return true;
8676
8677 if (auto *C = dyn_cast<ConstantFP>(V))
8678 return !C->isNaN();
8679
8680 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8681 if (!C->getElementType()->isFloatingPointTy())
8682 return false;
8683 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8684 if (C->getElementAsAPFloat(I).isNaN())
8685 return false;
8686 }
8687 return true;
8688 }
8689
8691 return true;
8692
8693 return false;
8694}
8695
8696static bool isKnownNonZero(const Value *V) {
8697 if (auto *C = dyn_cast<ConstantFP>(V))
8698 return !C->isZero();
8699
8700 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8701 if (!C->getElementType()->isFloatingPointTy())
8702 return false;
8703 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8704 if (C->getElementAsAPFloat(I).isZero())
8705 return false;
8706 }
8707 return true;
8708 }
8709
8710 return false;
8711}
8712
8713/// Match clamp pattern for float types without care about NaNs or signed zeros.
8714/// Given non-min/max outer cmp/select from the clamp pattern this
8715/// function recognizes if it can be substitued by a "canonical" min/max
8716/// pattern.
8718 Value *CmpLHS, Value *CmpRHS,
8719 Value *TrueVal, Value *FalseVal,
8720 Value *&LHS, Value *&RHS) {
8721 // Try to match
8722 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
8723 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
8724 // and return description of the outer Max/Min.
8725
8726 // First, check if select has inverse order:
8727 if (CmpRHS == FalseVal) {
8728 std::swap(TrueVal, FalseVal);
8729 Pred = CmpInst::getInversePredicate(Pred);
8730 }
8731
8732 // Assume success now. If there's no match, callers should not use these anyway.
8733 LHS = TrueVal;
8734 RHS = FalseVal;
8735
8736 const APFloat *FC1;
8737 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
8738 return {SPF_UNKNOWN, SPNB_NA, false};
8739
8740 const APFloat *FC2;
8741 switch (Pred) {
8742 case CmpInst::FCMP_OLT:
8743 case CmpInst::FCMP_OLE:
8744 case CmpInst::FCMP_ULT:
8745 case CmpInst::FCMP_ULE:
8746 if (match(FalseVal, m_OrdOrUnordFMin(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8747 *FC1 < *FC2)
8748 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8749 if (match(FalseVal, m_FMinNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8750 *FC1 < *FC2)
8751 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8752 break;
8753 case CmpInst::FCMP_OGT:
8754 case CmpInst::FCMP_OGE:
8755 case CmpInst::FCMP_UGT:
8756 case CmpInst::FCMP_UGE:
8757 if (match(FalseVal, m_OrdOrUnordFMax(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8758 *FC1 > *FC2)
8759 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8760 if (match(FalseVal, m_FMaxNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8761 *FC1 > *FC2)
8762 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8763 break;
8764 default:
8765 break;
8766 }
8767
8768 return {SPF_UNKNOWN, SPNB_NA, false};
8769}
8770
8771/// Recognize variations of:
8772/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
8774 Value *CmpLHS, Value *CmpRHS,
8775 Value *TrueVal, Value *FalseVal) {
8776 // Swap the select operands and predicate to match the patterns below.
8777 if (CmpRHS != TrueVal) {
8778 Pred = ICmpInst::getSwappedPredicate(Pred);
8779 std::swap(TrueVal, FalseVal);
8780 }
8781 const APInt *C1;
8782 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
8783 const APInt *C2;
8784 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
8785 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8786 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
8787 return {SPF_SMAX, SPNB_NA, false};
8788
8789 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
8790 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8791 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
8792 return {SPF_SMIN, SPNB_NA, false};
8793
8794 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
8795 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8796 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
8797 return {SPF_UMAX, SPNB_NA, false};
8798
8799 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
8800 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8801 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
8802 return {SPF_UMIN, SPNB_NA, false};
8803 }
8804 return {SPF_UNKNOWN, SPNB_NA, false};
8805}
8806
8807/// Recognize variations of:
8808/// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
8810 Value *CmpLHS, Value *CmpRHS,
8811 Value *TVal, Value *FVal,
8812 unsigned Depth) {
8813 // TODO: Allow FP min/max with nnan/nsz.
8814 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
8815
8816 Value *A = nullptr, *B = nullptr;
8817 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
8818 if (!SelectPatternResult::isMinOrMax(L.Flavor))
8819 return {SPF_UNKNOWN, SPNB_NA, false};
8820
8821 Value *C = nullptr, *D = nullptr;
8822 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
8823 if (L.Flavor != R.Flavor)
8824 return {SPF_UNKNOWN, SPNB_NA, false};
8825
8826 // We have something like: x Pred y ? min(a, b) : min(c, d).
8827 // Try to match the compare to the min/max operations of the select operands.
8828 // First, make sure we have the right compare predicate.
8829 switch (L.Flavor) {
8830 case SPF_SMIN:
8831 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
8832 Pred = ICmpInst::getSwappedPredicate(Pred);
8833 std::swap(CmpLHS, CmpRHS);
8834 }
8835 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
8836 break;
8837 return {SPF_UNKNOWN, SPNB_NA, false};
8838 case SPF_SMAX:
8839 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
8840 Pred = ICmpInst::getSwappedPredicate(Pred);
8841 std::swap(CmpLHS, CmpRHS);
8842 }
8843 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
8844 break;
8845 return {SPF_UNKNOWN, SPNB_NA, false};
8846 case SPF_UMIN:
8847 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
8848 Pred = ICmpInst::getSwappedPredicate(Pred);
8849 std::swap(CmpLHS, CmpRHS);
8850 }
8851 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
8852 break;
8853 return {SPF_UNKNOWN, SPNB_NA, false};
8854 case SPF_UMAX:
8855 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
8856 Pred = ICmpInst::getSwappedPredicate(Pred);
8857 std::swap(CmpLHS, CmpRHS);
8858 }
8859 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
8860 break;
8861 return {SPF_UNKNOWN, SPNB_NA, false};
8862 default:
8863 return {SPF_UNKNOWN, SPNB_NA, false};
8864 }
8865
8866 // If there is a common operand in the already matched min/max and the other
8867 // min/max operands match the compare operands (either directly or inverted),
8868 // then this is min/max of the same flavor.
8869
8870 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8871 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8872 if (D == B) {
8873 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8874 match(A, m_Not(m_Specific(CmpRHS)))))
8875 return {L.Flavor, SPNB_NA, false};
8876 }
8877 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8878 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8879 if (C == B) {
8880 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8881 match(A, m_Not(m_Specific(CmpRHS)))))
8882 return {L.Flavor, SPNB_NA, false};
8883 }
8884 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8885 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8886 if (D == A) {
8887 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8888 match(B, m_Not(m_Specific(CmpRHS)))))
8889 return {L.Flavor, SPNB_NA, false};
8890 }
8891 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8892 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8893 if (C == A) {
8894 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8895 match(B, m_Not(m_Specific(CmpRHS)))))
8896 return {L.Flavor, SPNB_NA, false};
8897 }
8898
8899 return {SPF_UNKNOWN, SPNB_NA, false};
8900}
8901
8902/// If the input value is the result of a 'not' op, constant integer, or vector
8903/// splat of a constant integer, return the bitwise-not source value.
8904/// TODO: This could be extended to handle non-splat vector integer constants.
8906 Value *NotV;
8907 if (match(V, m_Not(m_Value(NotV))))
8908 return NotV;
8909
8910 const APInt *C;
8911 if (match(V, m_APInt(C)))
8912 return ConstantInt::get(V->getType(), ~(*C));
8913
8914 return nullptr;
8915}
8916
8917/// Match non-obvious integer minimum and maximum sequences.
8919 Value *CmpLHS, Value *CmpRHS,
8920 Value *TrueVal, Value *FalseVal,
8921 Value *&LHS, Value *&RHS,
8922 unsigned Depth) {
8923 // Assume success. If there's no match, callers should not use these anyway.
8924 LHS = TrueVal;
8925 RHS = FalseVal;
8926
8927 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
8929 return SPR;
8930
8931 SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
8933 return SPR;
8934
8935 // Look through 'not' ops to find disguised min/max.
8936 // (X > Y) ? ~X : ~Y ==> (~X < ~Y) ? ~X : ~Y ==> MIN(~X, ~Y)
8937 // (X < Y) ? ~X : ~Y ==> (~X > ~Y) ? ~X : ~Y ==> MAX(~X, ~Y)
8938 if (CmpLHS == getNotValue(TrueVal) && CmpRHS == getNotValue(FalseVal)) {
8939 switch (Pred) {
8940 case CmpInst::ICMP_SGT: return {SPF_SMIN, SPNB_NA, false};
8941 case CmpInst::ICMP_SLT: return {SPF_SMAX, SPNB_NA, false};
8942 case CmpInst::ICMP_UGT: return {SPF_UMIN, SPNB_NA, false};
8943 case CmpInst::ICMP_ULT: return {SPF_UMAX, SPNB_NA, false};
8944 default: break;
8945 }
8946 }
8947
8948 // (X > Y) ? ~Y : ~X ==> (~X < ~Y) ? ~Y : ~X ==> MAX(~Y, ~X)
8949 // (X < Y) ? ~Y : ~X ==> (~X > ~Y) ? ~Y : ~X ==> MIN(~Y, ~X)
8950 if (CmpLHS == getNotValue(FalseVal) && CmpRHS == getNotValue(TrueVal)) {
8951 switch (Pred) {
8952 case CmpInst::ICMP_SGT: return {SPF_SMAX, SPNB_NA, false};
8953 case CmpInst::ICMP_SLT: return {SPF_SMIN, SPNB_NA, false};
8954 case CmpInst::ICMP_UGT: return {SPF_UMAX, SPNB_NA, false};
8955 case CmpInst::ICMP_ULT: return {SPF_UMIN, SPNB_NA, false};
8956 default: break;
8957 }
8958 }
8959
8960 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
8961 return {SPF_UNKNOWN, SPNB_NA, false};
8962
8963 const APInt *C1;
8964 if (!match(CmpRHS, m_APInt(C1)))
8965 return {SPF_UNKNOWN, SPNB_NA, false};
8966
8967 // An unsigned min/max can be written with a signed compare.
8968 const APInt *C2;
8969 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
8970 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
8971 // Is the sign bit set?
8972 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
8973 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
8974 if (Pred == CmpInst::ICMP_SLT && C1->isZero() && C2->isMaxSignedValue())
8975 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
8976
8977 // Is the sign bit clear?
8978 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
8979 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
8980 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnes() && C2->isMinSignedValue())
8981 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
8982 }
8983
8984 return {SPF_UNKNOWN, SPNB_NA, false};
8985}
8986
8987bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW,
8988 bool AllowPoison) {
8989 assert(X && Y && "Invalid operand");
8990
8991 auto IsNegationOf = [&](const Value *X, const Value *Y) {
8992 if (!match(X, m_Neg(m_Specific(Y))))
8993 return false;
8994
8995 auto *BO = cast<BinaryOperator>(X);
8996 if (NeedNSW && !BO->hasNoSignedWrap())
8997 return false;
8998
8999 auto *Zero = cast<Constant>(BO->getOperand(0));
9000 if (!AllowPoison && !Zero->isNullValue())
9001 return false;
9002
9003 return true;
9004 };
9005
9006 // X = -Y or Y = -X
9007 if (IsNegationOf(X, Y) || IsNegationOf(Y, X))
9008 return true;
9009
9010 // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
9011 Value *A, *B;
9012 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
9013 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
9014 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
9016}
9017
9018bool llvm::isKnownInversion(const Value *X, const Value *Y) {
9019 // Handle X = icmp pred A, B, Y = icmp pred A, C.
9020 Value *A, *B, *C;
9021 CmpPredicate Pred1, Pred2;
9022 if (!match(X, m_ICmp(Pred1, m_Value(A), m_Value(B))) ||
9023 !match(Y, m_c_ICmp(Pred2, m_Specific(A), m_Value(C))))
9024 return false;
9025
9026 // They must both have samesign flag or not.
9027 if (Pred1.hasSameSign() != Pred2.hasSameSign())
9028 return false;
9029
9030 if (B == C)
9031 return Pred1 == ICmpInst::getInversePredicate(Pred2);
9032
9033 // Try to infer the relationship from constant ranges.
9034 const APInt *RHSC1, *RHSC2;
9035 if (!match(B, m_APInt(RHSC1)) || !match(C, m_APInt(RHSC2)))
9036 return false;
9037
9038 // Sign bits of two RHSCs should match.
9039 if (Pred1.hasSameSign() && RHSC1->isNonNegative() != RHSC2->isNonNegative())
9040 return false;
9041
9042 const auto CR1 = ConstantRange::makeExactICmpRegion(Pred1, *RHSC1);
9043 const auto CR2 = ConstantRange::makeExactICmpRegion(Pred2, *RHSC2);
9044
9045 return CR1.inverse() == CR2;
9046}
9047
9049 SelectPatternNaNBehavior NaNBehavior,
9050 bool Ordered) {
9051 switch (Pred) {
9052 default:
9053 return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
9054 case ICmpInst::ICMP_UGT:
9055 case ICmpInst::ICMP_UGE:
9056 return {SPF_UMAX, SPNB_NA, false};
9057 case ICmpInst::ICMP_SGT:
9058 case ICmpInst::ICMP_SGE:
9059 return {SPF_SMAX, SPNB_NA, false};
9060 case ICmpInst::ICMP_ULT:
9061 case ICmpInst::ICMP_ULE:
9062 return {SPF_UMIN, SPNB_NA, false};
9063 case ICmpInst::ICMP_SLT:
9064 case ICmpInst::ICMP_SLE:
9065 return {SPF_SMIN, SPNB_NA, false};
9066 case FCmpInst::FCMP_UGT:
9067 case FCmpInst::FCMP_UGE:
9068 case FCmpInst::FCMP_OGT:
9069 case FCmpInst::FCMP_OGE:
9070 return {SPF_FMAXNUM, NaNBehavior, Ordered};
9071 case FCmpInst::FCMP_ULT:
9072 case FCmpInst::FCMP_ULE:
9073 case FCmpInst::FCMP_OLT:
9074 case FCmpInst::FCMP_OLE:
9075 return {SPF_FMINNUM, NaNBehavior, Ordered};
9076 }
9077}
9078
9079std::optional<std::pair<CmpPredicate, Constant *>>
9082 "Only for relational integer predicates.");
9083 if (isa<UndefValue>(C))
9084 return std::nullopt;
9085
9086 Type *Type = C->getType();
9087 bool IsSigned = ICmpInst::isSigned(Pred);
9088
9090 bool WillIncrement =
9091 UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
9092
9093 // Check if the constant operand can be safely incremented/decremented
9094 // without overflowing/underflowing.
9095 auto ConstantIsOk = [Pred, WillIncrement, IsSigned](ConstantInt *C) {
9096 if (WillIncrement ? C->isMaxValue(IsSigned) : C->isMinValue(IsSigned))
9097 return false;
9098
9099 if (!Pred.hasSameSign())
9100 return true;
9101
9102 // Crossing the corresponding boundary in the other ordering changes the
9103 // sign bit, and therefore changes the poison domain.
9104 return WillIncrement ? !C->isMaxValue(!IsSigned)
9105 : !C->isMinValue(!IsSigned);
9106 };
9107
9108 Constant *SafeReplacementConstant = nullptr;
9109 if (auto *CI = dyn_cast<ConstantInt>(C)) {
9110 // Bail out if the constant can't be safely incremented/decremented.
9111 if (!ConstantIsOk(CI))
9112 return std::nullopt;
9113 } else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) {
9114 unsigned NumElts = FVTy->getNumElements();
9115 for (unsigned i = 0; i != NumElts; ++i) {
9116 Constant *Elt = C->getAggregateElement(i);
9117 if (!Elt)
9118 return std::nullopt;
9119
9120 if (isa<UndefValue>(Elt))
9121 continue;
9122
9123 // Bail out if we can't determine if this constant is min/max or if we
9124 // know that this constant is min/max.
9125 auto *CI = dyn_cast<ConstantInt>(Elt);
9126 if (!CI || !ConstantIsOk(CI))
9127 return std::nullopt;
9128
9129 if (!SafeReplacementConstant)
9130 SafeReplacementConstant = CI;
9131 }
9132 } else if (isa<VectorType>(C->getType())) {
9133 // Handle scalable splat
9134 Value *SplatC = C->getSplatValue();
9135 auto *CI = dyn_cast_or_null<ConstantInt>(SplatC);
9136 // Bail out if the constant can't be safely incremented/decremented.
9137 if (!CI || !ConstantIsOk(CI))
9138 return std::nullopt;
9139 } else {
9140 // ConstantExpr?
9141 return std::nullopt;
9142 }
9143
9144 // It may not be safe to change a compare predicate in the presence of
9145 // undefined elements, so replace those elements with the first safe constant
9146 // that we found.
9147 // TODO: in case of poison, it is safe; let's replace undefs only.
9148 if (C->containsUndefOrPoisonElement()) {
9149 assert(SafeReplacementConstant && "Replacement constant not set");
9150 C = Constant::replaceUndefsWith(C, SafeReplacementConstant);
9151 }
9152
9154 Pred.hasSameSign());
9155
9156 // Increment or decrement the constant.
9157 Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
9158 Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
9159
9160 return std::make_pair(NewPred, NewC);
9161}
9162
9164 FastMathFlags FMF,
9165 Value *CmpLHS, Value *CmpRHS,
9166 Value *TrueVal, Value *FalseVal,
9167 Value *&LHS, Value *&RHS,
9168 unsigned Depth) {
9169 if (CmpInst::isFPPredicate(Pred)) {
9170 // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
9171 // 0.0 operand, set the compare's 0.0 operands to that same value for the
9172 // purpose of identifying min/max. Disregard vector constants with undefined
9173 // elements because those can not be back-propagated for analysis.
9174 Value *OutputZeroVal = nullptr;
9175 if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
9176 !cast<Constant>(TrueVal)->containsUndefOrPoisonElement())
9177 OutputZeroVal = TrueVal;
9178 else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
9179 !cast<Constant>(FalseVal)->containsUndefOrPoisonElement())
9180 OutputZeroVal = FalseVal;
9181
9182 if (OutputZeroVal) {
9183 if (match(CmpLHS, m_AnyZeroFP()) && CmpLHS != OutputZeroVal)
9184 CmpLHS = OutputZeroVal;
9185 if (match(CmpRHS, m_AnyZeroFP()) && CmpRHS != OutputZeroVal)
9186 CmpRHS = OutputZeroVal;
9187 }
9188 }
9189
9190 LHS = CmpLHS;
9191 RHS = CmpRHS;
9192
9193 // Signed zero may return inconsistent results between implementations.
9194 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
9195 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
9196 // Therefore, we behave conservatively and only proceed if at least one of the
9197 // operands is known to not be zero or if we don't care about signed zero.
9198 if (CmpInst::isFPPredicate(Pred)) {
9199 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9200 !isKnownNonZero(CmpRHS))
9201 return {SPF_UNKNOWN, SPNB_NA, false};
9202 }
9203
9204 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
9205 bool Ordered = false;
9206
9207 // When given one NaN and one non-NaN input:
9208 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
9209 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
9210 // ordered comparison fails), which could be NaN or non-NaN.
9211 // so here we discover exactly what NaN behavior is required/accepted.
9212 if (CmpInst::isFPPredicate(Pred)) {
9213 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
9214 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
9215
9216 if (LHSSafe && RHSSafe) {
9217 // Both operands are known non-NaN.
9218 NaNBehavior = SPNB_RETURNS_ANY;
9219 Ordered = CmpInst::isOrdered(Pred);
9220 } else if (CmpInst::isOrdered(Pred)) {
9221 // An ordered comparison will return false when given a NaN, so it
9222 // returns the RHS.
9223 Ordered = true;
9224 if (LHSSafe)
9225 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
9226 NaNBehavior = SPNB_RETURNS_NAN;
9227 else if (RHSSafe)
9228 NaNBehavior = SPNB_RETURNS_OTHER;
9229 else
9230 // Completely unsafe.
9231 return {SPF_UNKNOWN, SPNB_NA, false};
9232 } else {
9233 Ordered = false;
9234 // An unordered comparison will return true when given a NaN, so it
9235 // returns the LHS.
9236 if (LHSSafe)
9237 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
9238 NaNBehavior = SPNB_RETURNS_OTHER;
9239 else if (RHSSafe)
9240 NaNBehavior = SPNB_RETURNS_NAN;
9241 else
9242 // Completely unsafe.
9243 return {SPF_UNKNOWN, SPNB_NA, false};
9244 }
9245 }
9246
9247 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
9248 std::swap(CmpLHS, CmpRHS);
9249 Pred = CmpInst::getSwappedPredicate(Pred);
9250 if (NaNBehavior == SPNB_RETURNS_NAN)
9251 NaNBehavior = SPNB_RETURNS_OTHER;
9252 else if (NaNBehavior == SPNB_RETURNS_OTHER)
9253 NaNBehavior = SPNB_RETURNS_NAN;
9254 Ordered = !Ordered;
9255 }
9256
9257 // ([if]cmp X, Y) ? X : Y
9258 if (TrueVal == CmpLHS && FalseVal == CmpRHS)
9259 return getSelectPattern(Pred, NaNBehavior, Ordered);
9260
9261 if (isKnownNegation(TrueVal, FalseVal)) {
9262 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
9263 // match against either LHS or sign-preserving operations on LHS, like
9264 // sext(LHS), or binary ops that do not wrap in signed sense.
9265 auto CmpLHSOrSExt =
9266 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
9267 auto MaybeSExtOrMulCmpLHS =
9268 m_CombineOr(CmpLHSOrSExt, m_NSWMul(CmpLHSOrSExt, m_StrictlyPositive()),
9269 m_NSWShl(CmpLHSOrSExt, m_Value()));
9270 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
9271 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
9272 if (match(TrueVal, MaybeSExtOrMulCmpLHS)) {
9273 // Set the return values. If the compare uses the negated value (-X >s 0),
9274 // swap the return values because the negated value is always 'RHS'.
9275 LHS = TrueVal;
9276 RHS = FalseVal;
9277 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
9278 std::swap(LHS, RHS);
9279
9280 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
9281 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
9282 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9283 return {SPF_ABS, SPNB_NA, false};
9284
9285 // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
9286 if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
9287 return {SPF_ABS, SPNB_NA, false};
9288
9289 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
9290 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
9291 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9292 return {SPF_NABS, SPNB_NA, false};
9293 } else if (match(FalseVal, MaybeSExtOrMulCmpLHS)) {
9294 // Set the return values. If the compare uses the negated value (-X >s 0),
9295 // swap the return values because the negated value is always 'RHS'.
9296 LHS = FalseVal;
9297 RHS = TrueVal;
9298 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
9299 std::swap(LHS, RHS);
9300
9301 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
9302 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
9303 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9304 return {SPF_NABS, SPNB_NA, false};
9305
9306 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
9307 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
9308 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9309 return {SPF_ABS, SPNB_NA, false};
9310 }
9311 }
9312
9313 if (CmpInst::isIntPredicate(Pred))
9314 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
9315
9316 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
9317 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
9318 // semantics than minNum. Be conservative in such case.
9319 if (NaNBehavior != SPNB_RETURNS_ANY ||
9320 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9321 !isKnownNonZero(CmpRHS)))
9322 return {SPF_UNKNOWN, SPNB_NA, false};
9323
9324 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
9325}
9326
9328 Instruction::CastOps *CastOp) {
9329 const DataLayout &DL = CmpI->getDataLayout();
9330
9331 Constant *CastedTo = nullptr;
9332 switch (*CastOp) {
9333 case Instruction::ZExt:
9334 if (CmpI->isUnsigned())
9335 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
9336 break;
9337 case Instruction::SExt:
9338 if (CmpI->isSigned())
9339 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
9340 break;
9341 case Instruction::Trunc:
9342 Constant *CmpConst;
9343 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
9344 CmpConst->getType() == SrcTy) {
9345 // Here we have the following case:
9346 //
9347 // %cond = cmp iN %x, CmpConst
9348 // %tr = trunc iN %x to iK
9349 // %narrowsel = select i1 %cond, iK %t, iK C
9350 //
9351 // We can always move trunc after select operation:
9352 //
9353 // %cond = cmp iN %x, CmpConst
9354 // %widesel = select i1 %cond, iN %x, iN CmpConst
9355 // %tr = trunc iN %widesel to iK
9356 //
9357 // Note that C could be extended in any way because we don't care about
9358 // upper bits after truncation. It can't be abs pattern, because it would
9359 // look like:
9360 //
9361 // select i1 %cond, x, -x.
9362 //
9363 // So only min/max pattern could be matched. Such match requires widened C
9364 // == CmpConst. That is why set widened C = CmpConst, condition trunc
9365 // CmpConst == C is checked below.
9366 CastedTo = CmpConst;
9367 } else {
9368 unsigned ExtOp = CmpI->isSigned() ? Instruction::SExt : Instruction::ZExt;
9369 CastedTo = ConstantFoldCastOperand(ExtOp, C, SrcTy, DL);
9370 }
9371 break;
9372 case Instruction::FPTrunc:
9373 CastedTo = ConstantFoldCastOperand(Instruction::FPExt, C, SrcTy, DL);
9374 break;
9375 case Instruction::FPExt:
9376 CastedTo = ConstantFoldCastOperand(Instruction::FPTrunc, C, SrcTy, DL);
9377 break;
9378 case Instruction::FPToUI:
9379 CastedTo = ConstantFoldCastOperand(Instruction::UIToFP, C, SrcTy, DL);
9380 break;
9381 case Instruction::FPToSI:
9382 CastedTo = ConstantFoldCastOperand(Instruction::SIToFP, C, SrcTy, DL);
9383 break;
9384 case Instruction::UIToFP:
9385 CastedTo = ConstantFoldCastOperand(Instruction::FPToUI, C, SrcTy, DL);
9386 break;
9387 case Instruction::SIToFP:
9388 CastedTo = ConstantFoldCastOperand(Instruction::FPToSI, C, SrcTy, DL);
9389 break;
9390 default:
9391 break;
9392 }
9393
9394 if (!CastedTo)
9395 return nullptr;
9396
9397 // Make sure the cast doesn't lose any information.
9398 Constant *CastedBack =
9399 ConstantFoldCastOperand(*CastOp, CastedTo, C->getType(), DL);
9400 if (CastedBack && CastedBack != C)
9401 return nullptr;
9402
9403 return CastedTo;
9404}
9405
9406/// Helps to match a select pattern in case of a type mismatch.
9407///
9408/// The function processes the case when type of true and false values of a
9409/// select instruction differs from type of the cmp instruction operands because
9410/// of a cast instruction. The function checks if it is legal to move the cast
9411/// operation after "select". If yes, it returns the new second value of
9412/// "select" (with the assumption that cast is moved):
9413/// 1. As operand of cast instruction when both values of "select" are same cast
9414/// instructions.
9415/// 2. As restored constant (by applying reverse cast operation) when the first
9416/// value of the "select" is a cast operation and the second value is a
9417/// constant. It is implemented in lookThroughCastConst().
9418/// 3. As one operand is cast instruction and the other is not. The operands in
9419/// sel(cmp) are in different type integer.
9420/// NOTE: We return only the new second value because the first value could be
9421/// accessed as operand of cast instruction.
9423 Instruction::CastOps *CastOp) {
9424 auto *Cast1 = dyn_cast<CastInst>(V1);
9425 if (!Cast1)
9426 return nullptr;
9427
9428 *CastOp = Cast1->getOpcode();
9429 Type *SrcTy = Cast1->getSrcTy();
9430 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
9431 // If V1 and V2 are both the same cast from the same type, look through V1.
9432 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
9433 return Cast2->getOperand(0);
9434 return nullptr;
9435 }
9436
9437 auto *C = dyn_cast<Constant>(V2);
9438 if (C)
9439 return lookThroughCastConst(CmpI, SrcTy, C, CastOp);
9440
9441 Value *CastedTo = nullptr;
9442 if (*CastOp == Instruction::Trunc) {
9443 if (match(CmpI->getOperand(1), m_ZExtOrSExt(m_Specific(V2)))) {
9444 // Here we have the following case:
9445 // %y_ext = sext iK %y to iN
9446 // %cond = cmp iN %x, %y_ext
9447 // %tr = trunc iN %x to iK
9448 // %narrowsel = select i1 %cond, iK %tr, iK %y
9449 //
9450 // We can always move trunc after select operation:
9451 // %y_ext = sext iK %y to iN
9452 // %cond = cmp iN %x, %y_ext
9453 // %widesel = select i1 %cond, iN %x, iN %y_ext
9454 // %tr = trunc iN %widesel to iK
9455 assert(V2->getType() == Cast1->getType() &&
9456 "V2 and Cast1 should be the same type.");
9457 CastedTo = CmpI->getOperand(1);
9458 }
9459 }
9460
9461 return CastedTo;
9462}
9464 Instruction::CastOps *CastOp,
9465 unsigned Depth) {
9467 return {SPF_UNKNOWN, SPNB_NA, false};
9468
9470 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
9471
9472 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
9473 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
9474
9475 Value *TrueVal = SI->getTrueValue();
9476 Value *FalseVal = SI->getFalseValue();
9477
9478 return llvm::matchDecomposedSelectPattern(CmpI, TrueVal, FalseVal, LHS, RHS,
9479 SI->getFastMathFlagsOrNone(),
9480 CastOp, Depth);
9481}
9482
9484 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
9485 FastMathFlags FMF, Instruction::CastOps *CastOp, unsigned Depth) {
9486 CmpInst::Predicate Pred = CmpI->getPredicate();
9487 Value *CmpLHS = CmpI->getOperand(0);
9488 Value *CmpRHS = CmpI->getOperand(1);
9489 if (isa<FPMathOperator>(CmpI) && CmpI->hasNoNaNs())
9490 FMF.setNoNaNs();
9491
9492 // Bail out early.
9493 if (CmpI->isEquality())
9494 return {SPF_UNKNOWN, SPNB_NA, false};
9495
9496 // Deal with type mismatches.
9497 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
9498 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
9499 // If this is a potential fmin/fmax with a cast to integer, then ignore
9500 // -0.0 because there is no corresponding integer value.
9501 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9502 FMF.setNoSignedZeros();
9503 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9504 cast<CastInst>(TrueVal)->getOperand(0), C,
9505 LHS, RHS, Depth);
9506 }
9507 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
9508 // If this is a potential fmin/fmax with a cast to integer, then ignore
9509 // -0.0 because there is no corresponding integer value.
9510 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9511 FMF.setNoSignedZeros();
9512 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9513 C, cast<CastInst>(FalseVal)->getOperand(0),
9514 LHS, RHS, Depth);
9515 }
9516 }
9517 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
9518 LHS, RHS, Depth);
9519}
9520
9522 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
9523 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
9524 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
9525 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
9526 if (SPF == SPF_FMINNUM)
9527 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
9528 if (SPF == SPF_FMAXNUM)
9529 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
9530 llvm_unreachable("unhandled!");
9531}
9532
9534 switch (SPF) {
9536 return Intrinsic::umin;
9538 return Intrinsic::umax;
9540 return Intrinsic::smin;
9542 return Intrinsic::smax;
9543 default:
9544 llvm_unreachable("Unexpected SPF");
9545 }
9546}
9547
9549 if (SPF == SPF_SMIN) return SPF_SMAX;
9550 if (SPF == SPF_UMIN) return SPF_UMAX;
9551 if (SPF == SPF_SMAX) return SPF_SMIN;
9552 if (SPF == SPF_UMAX) return SPF_UMIN;
9553 llvm_unreachable("unhandled!");
9554}
9555
9557 switch (MinMaxID) {
9558 case Intrinsic::smax: return Intrinsic::smin;
9559 case Intrinsic::smin: return Intrinsic::smax;
9560 case Intrinsic::umax: return Intrinsic::umin;
9561 case Intrinsic::umin: return Intrinsic::umax;
9562 // Please note that next four intrinsics may produce the same result for
9563 // original and inverted case even if X != Y due to NaN is handled specially.
9564 case Intrinsic::maximum: return Intrinsic::minimum;
9565 case Intrinsic::minimum: return Intrinsic::maximum;
9566 case Intrinsic::maxnum: return Intrinsic::minnum;
9567 case Intrinsic::minnum: return Intrinsic::maxnum;
9568 case Intrinsic::maximumnum:
9569 return Intrinsic::minimumnum;
9570 case Intrinsic::minimumnum:
9571 return Intrinsic::maximumnum;
9572 default: llvm_unreachable("Unexpected intrinsic");
9573 }
9574}
9575
9577 switch (SPF) {
9580 case SPF_UMAX: return APInt::getMaxValue(BitWidth);
9581 case SPF_UMIN: return APInt::getMinValue(BitWidth);
9582 default: llvm_unreachable("Unexpected flavor");
9583 }
9584}
9585
9586std::pair<Intrinsic::ID, bool>
9588 // Check if VL contains select instructions that can be folded into a min/max
9589 // vector intrinsic and return the intrinsic if it is possible.
9590 // TODO: Support floating point min/max.
9591 bool AllCmpSingleUse = true;
9592 SelectPatternResult SelectPattern;
9593 SelectPattern.Flavor = SPF_UNKNOWN;
9594 if (all_of(VL, [&SelectPattern, &AllCmpSingleUse](Value *I) {
9595 Value *LHS, *RHS;
9596 auto CurrentPattern = matchSelectPattern(I, LHS, RHS);
9597 if (!SelectPatternResult::isMinOrMax(CurrentPattern.Flavor))
9598 return false;
9599 if (SelectPattern.Flavor != SPF_UNKNOWN &&
9600 SelectPattern.Flavor != CurrentPattern.Flavor)
9601 return false;
9602 SelectPattern = CurrentPattern;
9603 AllCmpSingleUse &=
9605 return true;
9606 })) {
9607 switch (SelectPattern.Flavor) {
9608 case SPF_SMIN:
9609 return {Intrinsic::smin, AllCmpSingleUse};
9610 case SPF_UMIN:
9611 return {Intrinsic::umin, AllCmpSingleUse};
9612 case SPF_SMAX:
9613 return {Intrinsic::smax, AllCmpSingleUse};
9614 case SPF_UMAX:
9615 return {Intrinsic::umax, AllCmpSingleUse};
9616 case SPF_FMAXNUM:
9617 return {Intrinsic::maxnum, AllCmpSingleUse};
9618 case SPF_FMINNUM:
9619 return {Intrinsic::minnum, AllCmpSingleUse};
9620 default:
9621 llvm_unreachable("unexpected select pattern flavor");
9622 }
9623 }
9624 return {Intrinsic::not_intrinsic, false};
9625}
9626
9627template <typename InstTy>
9628static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst,
9629 Value *&Init, Value *&OtherOp) {
9630 // Handle the case of a simple two-predecessor recurrence PHI.
9631 // There's a lot more that could theoretically be done here, but
9632 // this is sufficient to catch some interesting cases.
9633 // TODO: Expand list -- gep, uadd.sat etc.
9634 if (PN->getNumIncomingValues() != 2)
9635 return false;
9636
9637 for (unsigned I = 0; I != 2; ++I) {
9638 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9639 Operation && Operation->getNumOperands() >= 2) {
9640 Value *LHS = Operation->getOperand(0);
9641 Value *RHS = Operation->getOperand(1);
9642 if (LHS != PN && RHS != PN)
9643 continue;
9644
9645 Inst = Operation;
9646 Init = PN->getIncomingValue(!I);
9647 OtherOp = (LHS == PN) ? RHS : LHS;
9648 return true;
9649 }
9650 }
9651 return false;
9652}
9653
9654template <typename InstTy>
9655static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst,
9656 Value *&Init, Value *&OtherOp0,
9657 Value *&OtherOp1) {
9658 if (PN->getNumIncomingValues() != 2)
9659 return false;
9660
9661 for (unsigned I = 0; I != 2; ++I) {
9662 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9663 Operation && Operation->getNumOperands() >= 3) {
9664 Value *Op0 = Operation->getOperand(0);
9665 Value *Op1 = Operation->getOperand(1);
9666 Value *Op2 = Operation->getOperand(2);
9667
9668 if (Op0 != PN && Op1 != PN && Op2 != PN)
9669 continue;
9670
9671 Inst = Operation;
9672 Init = PN->getIncomingValue(!I);
9673 if (Op0 == PN) {
9674 OtherOp0 = Op1;
9675 OtherOp1 = Op2;
9676 } else if (Op1 == PN) {
9677 OtherOp0 = Op0;
9678 OtherOp1 = Op2;
9679 } else {
9680 OtherOp0 = Op0;
9681 OtherOp1 = Op1;
9682 }
9683 return true;
9684 }
9685 }
9686 return false;
9687}
9689 Value *&Start, Value *&Step) {
9690 // We try to match a recurrence of the form:
9691 // %iv = [Start, %entry], [%iv.next, %backedge]
9692 // %iv.next = binop %iv, Step
9693 // Or:
9694 // %iv = [Start, %entry], [%iv.next, %backedge]
9695 // %iv.next = binop Step, %iv
9696 return matchTwoInputRecurrence(P, BO, Start, Step);
9697}
9698
9700 Value *&Start, Value *&Step) {
9701 BinaryOperator *BO = nullptr;
9702 return match(I, m_c_BinOp(m_Phi(P), m_Value())) &&
9703 matchSimpleRecurrence(P, BO, Start, Step) && BO == I;
9704}
9705
9707 PHINode *&P, Value *&Init,
9708 Value *&OtherOp) {
9709 // Binary intrinsics only supported for now.
9710 if (I->arg_size() != 2 || I->getType() != I->getArgOperand(0)->getType() ||
9711 I->getType() != I->getArgOperand(1)->getType())
9712 return false;
9713
9714 IntrinsicInst *II = nullptr;
9715 P = dyn_cast<PHINode>(I->getArgOperand(0));
9716 if (!P)
9717 P = dyn_cast<PHINode>(I->getArgOperand(1));
9718
9719 return P && matchTwoInputRecurrence(P, II, Init, OtherOp) && II == I;
9720}
9721
9723 PHINode *&P, Value *&Init,
9724 Value *&OtherOp0,
9725 Value *&OtherOp1) {
9726 if (I->arg_size() != 3 || I->getType() != I->getArgOperand(0)->getType() ||
9727 I->getType() != I->getArgOperand(1)->getType() ||
9728 I->getType() != I->getArgOperand(2)->getType())
9729 return false;
9730 IntrinsicInst *II = nullptr;
9731 P = dyn_cast<PHINode>(I->getArgOperand(0));
9732 if (!P) {
9733 P = dyn_cast<PHINode>(I->getArgOperand(1));
9734 if (!P)
9735 P = dyn_cast<PHINode>(I->getArgOperand(2));
9736 }
9737 return P && matchThreeInputRecurrence(P, II, Init, OtherOp0, OtherOp1) &&
9738 II == I;
9739}
9740
9741/// Return true if "icmp Pred LHS RHS" is always true.
9743 const Value *RHS) {
9744 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
9745 return true;
9746
9747 switch (Pred) {
9748 default:
9749 return false;
9750
9751 case CmpInst::ICMP_SLE: {
9752 const APInt *C;
9753
9754 // LHS s<= LHS +_{nsw} C if C >= 0
9755 // LHS s<= LHS | C if C >= 0
9756 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))) ||
9758 return !C->isNegative();
9759
9760 // LHS s<= smax(LHS, V) for any V
9762 return true;
9763
9764 // smin(RHS, V) s<= RHS for any V
9766 return true;
9767
9768 // Match A to (X +_{nsw} CA) and B to (X +_{nsw} CB)
9769 const Value *X;
9770 const APInt *CLHS, *CRHS;
9771 if (match(LHS, m_NSWAddLike(m_Value(X), m_APInt(CLHS))) &&
9773 return CLHS->sle(*CRHS);
9774
9775 return false;
9776 }
9777
9778 case CmpInst::ICMP_ULE: {
9779 // LHS u<= LHS +_{nuw} V for any V
9780 if (match(RHS, m_c_Add(m_Specific(LHS), m_Value())) &&
9782 return true;
9783
9784 // LHS u<= LHS | V for any V
9785 if (match(RHS, m_c_Or(m_Specific(LHS), m_Value())))
9786 return true;
9787
9788 // LHS u<= umax(LHS, V) for any V
9790 return true;
9791
9792 // RHS >> V u<= RHS for any V
9793 if (match(LHS, m_LShr(m_Specific(RHS), m_Value())))
9794 return true;
9795
9796 // RHS u/ C_ugt_1 u<= RHS
9797 const APInt *C;
9798 if (match(LHS, m_UDiv(m_Specific(RHS), m_APInt(C))) && C->ugt(1))
9799 return true;
9800
9801 // RHS & V u<= RHS for any V
9803 return true;
9804
9805 // umin(RHS, V) u<= RHS for any V
9807 return true;
9808
9809 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
9810 const Value *X;
9811 const APInt *CLHS, *CRHS;
9812 if (match(LHS, m_NUWAddLike(m_Value(X), m_APInt(CLHS))) &&
9814 return CLHS->ule(*CRHS);
9815
9816 return false;
9817 }
9818 }
9819}
9820
9821/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
9822/// ALHS ARHS" is true. Otherwise, return std::nullopt.
9823static std::optional<bool>
9825 const Value *ARHS, const Value *BLHS, const Value *BRHS) {
9826 switch (Pred) {
9827 default:
9828 return std::nullopt;
9829
9830 case CmpInst::ICMP_SLT:
9831 case CmpInst::ICMP_SLE:
9832 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS) &&
9834 return true;
9835 return std::nullopt;
9836
9837 case CmpInst::ICMP_SGT:
9838 case CmpInst::ICMP_SGE:
9839 if (isTruePredicate(CmpInst::ICMP_SLE, ALHS, BLHS) &&
9841 return true;
9842 return std::nullopt;
9843
9844 case CmpInst::ICMP_ULT:
9845 case CmpInst::ICMP_ULE:
9846 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS) &&
9848 return true;
9849 return std::nullopt;
9850
9851 case CmpInst::ICMP_UGT:
9852 case CmpInst::ICMP_UGE:
9853 if (isTruePredicate(CmpInst::ICMP_ULE, ALHS, BLHS) &&
9855 return true;
9856 return std::nullopt;
9857 }
9858}
9859
9860/// Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
9861/// Return false if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is false.
9862/// Otherwise, return std::nullopt if we can't infer anything.
9863static std::optional<bool>
9865 CmpPredicate RPred, const ConstantRange &RCR) {
9866 auto CRImpliesPred = [&](ConstantRange CR,
9867 CmpInst::Predicate Pred) -> std::optional<bool> {
9868 // If all true values for lhs and true for rhs, lhs implies rhs
9869 if (CR.icmp(Pred, RCR))
9870 return true;
9871
9872 // If there is no overlap, lhs implies not rhs
9873 if (CR.icmp(CmpInst::getInversePredicate(Pred), RCR))
9874 return false;
9875
9876 return std::nullopt;
9877 };
9878 if (auto Res = CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9879 RPred))
9880 return Res;
9881 if (LPred.hasSameSign() ^ RPred.hasSameSign()) {
9883 : LPred.dropSameSign();
9885 : RPred.dropSameSign();
9886 return CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9887 RPred);
9888 }
9889 return std::nullopt;
9890}
9891
9892/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
9893/// is true. Return false if LHS implies RHS is false. Otherwise, return
9894/// std::nullopt if we can't infer anything.
9895static std::optional<bool>
9896isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1,
9897 CmpPredicate RPred, const Value *R0, const Value *R1,
9898 const DataLayout &DL, bool LHSIsTrue) {
9899 // The rest of the logic assumes the LHS condition is true. If that's not the
9900 // case, invert the predicate to make it so.
9901 if (!LHSIsTrue)
9902 LPred = ICmpInst::getInverseCmpPredicate(LPred);
9903
9904 // We can have non-canonical operands, so try to normalize any common operand
9905 // to L0/R0.
9906 if (L0 == R1) {
9907 std::swap(R0, R1);
9908 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9909 }
9910 if (R0 == L1) {
9911 std::swap(L0, L1);
9912 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9913 }
9914 if (L1 == R1) {
9915 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
9916 if (L0 != R0 || match(L0, m_ImmConstant())) {
9917 std::swap(L0, L1);
9918 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9919 std::swap(R0, R1);
9920 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9921 }
9922 }
9923
9924 // See if we can infer anything if operand-0 matches and we have at least one
9925 // constant.
9926 const APInt *Unused;
9927 if (L0 == R0 && (match(L1, m_APInt(Unused)) || match(R1, m_APInt(Unused)))) {
9928 // Potential TODO: We could also further use the constant range of L0/R0 to
9929 // further constraint the constant ranges. At the moment this leads to
9930 // several regressions related to not transforming `multi_use(A + C0) eq/ne
9931 // C1` (see discussion: D58633).
9932 SimplifyQuery SQ(DL);
9937
9938 // Even if L1/R1 are not both constant, we can still sometimes deduce
9939 // relationship from a single constant. For example X u> Y implies X != 0.
9940 if (auto R = isImpliedCondCommonOperandWithCR(LPred, LCR, RPred, RCR))
9941 return R;
9942 // If both L1/R1 were exact constant ranges and we didn't get anything
9943 // here, we won't be able to deduce this.
9944 if (match(L1, m_APInt(Unused)) && match(R1, m_APInt(Unused)))
9945 return std::nullopt;
9946 }
9947
9948 // Can we infer anything when the two compares have matching operands?
9949 if (L0 == R0 && L1 == R1)
9950 return ICmpInst::isImpliedByMatchingCmp(LPred, RPred);
9951
9952 // It only really makes sense in the context of signed comparison for "X - Y
9953 // must be positive if X >= Y and no overflow".
9954 // Take SGT as an example: L0:x > L1:y and C >= 0
9955 // ==> R0:(x -nsw y) < R1:(-C) is false
9956 CmpInst::Predicate SignedLPred = LPred.getPreferredSignedPredicate();
9957 if ((SignedLPred == ICmpInst::ICMP_SGT ||
9958 SignedLPred == ICmpInst::ICMP_SGE) &&
9959 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
9960 if (match(R1, m_NonPositive()) &&
9961 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == false)
9962 return false;
9963 }
9964
9965 // Take SLT as an example: L0:x < L1:y and C <= 0
9966 // ==> R0:(x -nsw y) < R1:(-C) is true
9967 if ((SignedLPred == ICmpInst::ICMP_SLT ||
9968 SignedLPred == ICmpInst::ICMP_SLE) &&
9969 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
9970 if (match(R1, m_NonNegative()) &&
9971 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == true)
9972 return true;
9973 }
9974
9975 // a - b == NonZero -> a != b
9976 // ptrtoint(a) - ptrtoint(b) == NonZero -> a != b
9977 const APInt *L1C;
9978 Value *A, *B;
9979 if (LPred == ICmpInst::ICMP_EQ && ICmpInst::isEquality(RPred) &&
9980 match(L1, m_APInt(L1C)) && !L1C->isZero() &&
9981 match(L0, m_Sub(m_Value(A), m_Value(B))) &&
9982 ((A == R0 && B == R1) || (A == R1 && B == R0) ||
9987 return RPred.dropSameSign() == ICmpInst::ICMP_NE;
9988 }
9989
9990 // L0 = R0 = L1 + R1, L0 >=u L1 implies R0 >=u R1, L0 <u L1 implies R0 <u R1
9991 if (L0 == R0 &&
9992 (LPred == ICmpInst::ICMP_ULT || LPred == ICmpInst::ICMP_UGE) &&
9993 (RPred == ICmpInst::ICMP_ULT || RPred == ICmpInst::ICMP_UGE) &&
9994 match(L0, m_c_Add(m_Specific(L1), m_Specific(R1))))
9995 return CmpPredicate::getMatching(LPred, RPred).has_value();
9996
9997 if (auto P = CmpPredicate::getMatching(LPred, RPred))
9998 return isImpliedCondOperands(*P, L0, L1, R0, R1);
9999
10000 return std::nullopt;
10001}
10002
10003/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
10004/// is true. Return false if LHS implies RHS is false. Otherwise, return
10005/// std::nullopt if we can't infer anything.
10006static std::optional<bool>
10008 FCmpInst::Predicate RPred, const Value *R0, const Value *R1,
10009 const DataLayout &DL, bool LHSIsTrue) {
10010 // The rest of the logic assumes the LHS condition is true. If that's not the
10011 // case, invert the predicate to make it so.
10012 if (!LHSIsTrue)
10013 LPred = FCmpInst::getInversePredicate(LPred);
10014
10015 // We can have non-canonical operands, so try to normalize any common operand
10016 // to L0/R0.
10017 if (L0 == R1) {
10018 std::swap(R0, R1);
10019 RPred = FCmpInst::getSwappedPredicate(RPred);
10020 }
10021 if (R0 == L1) {
10022 std::swap(L0, L1);
10023 LPred = FCmpInst::getSwappedPredicate(LPred);
10024 }
10025 if (L1 == R1) {
10026 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
10027 if (L0 != R0 || match(L0, m_ImmConstant())) {
10028 std::swap(L0, L1);
10029 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10030 std::swap(R0, R1);
10031 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10032 }
10033 }
10034
10035 // Can we infer anything when the two compares have matching operands?
10036 if (L0 == R0 && L1 == R1) {
10037 if ((LPred & RPred) == LPred)
10038 return true;
10039 if ((LPred & ~RPred) == LPred)
10040 return false;
10041 }
10042
10043 // See if we can infer anything if operand-0 matches and we have at least one
10044 // constant.
10045 const APFloat *L1C, *R1C;
10046 if (L0 == R0 && match(L1, m_APFloat(L1C)) && match(R1, m_APFloat(R1C))) {
10047 if (std::optional<ConstantFPRange> DomCR =
10049 if (std::optional<ConstantFPRange> ImpliedCR =
10051 if (ImpliedCR->contains(*DomCR))
10052 return true;
10053 }
10054 if (std::optional<ConstantFPRange> ImpliedCR =
10056 FCmpInst::getInversePredicate(RPred), *R1C)) {
10057 if (ImpliedCR->contains(*DomCR))
10058 return false;
10059 }
10060 }
10061 }
10062
10063 return std::nullopt;
10064}
10065
10066/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
10067/// false. Otherwise, return std::nullopt if we can't infer anything. We
10068/// expect the RHS to be an icmp and the LHS to be an 'and', 'or', or a 'select'
10069/// instruction.
10070static std::optional<bool>
10072 const Value *RHSOp0, const Value *RHSOp1,
10073 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10074 // The LHS must be an 'or', 'and', or a 'select' instruction.
10075 assert((LHS->getOpcode() == Instruction::And ||
10076 LHS->getOpcode() == Instruction::Or ||
10077 LHS->getOpcode() == Instruction::Select) &&
10078 "Expected LHS to be 'and', 'or', or 'select'.");
10079
10080 assert(Depth <= MaxAnalysisRecursionDepth && "Hit recursion limit");
10081
10082 // If the result of an 'or' is false, then we know both legs of the 'or' are
10083 // false. Similarly, if the result of an 'and' is true, then we know both
10084 // legs of the 'and' are true.
10085 const Value *ALHS, *ARHS;
10086 if ((!LHSIsTrue && match(LHS, m_LogicalOr(m_Value(ALHS), m_Value(ARHS)))) ||
10087 (LHSIsTrue && match(LHS, m_LogicalAnd(m_Value(ALHS), m_Value(ARHS))))) {
10088 // FIXME: Make this non-recursion.
10089 if (std::optional<bool> Implication = isImpliedCondition(
10090 ALHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10091 return Implication;
10092 if (std::optional<bool> Implication = isImpliedCondition(
10093 ARHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10094 return Implication;
10095 return std::nullopt;
10096 }
10097 return std::nullopt;
10098}
10099
10100std::optional<bool>
10102 const Value *RHSOp0, const Value *RHSOp1,
10103 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10104 // Bail out when we hit the limit.
10106 return std::nullopt;
10107
10108 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
10109 // example.
10110 if (RHSOp0->getType()->isVectorTy() != LHS->getType()->isVectorTy())
10111 return std::nullopt;
10112
10113 assert(LHS->getType()->isIntOrIntVectorTy(1) &&
10114 "Expected integer type only!");
10115
10116 // Match not
10117 if (match(LHS, m_Not(m_Value(LHS))))
10118 LHSIsTrue = !LHSIsTrue;
10119
10120 // Both LHS and RHS are icmps.
10121 if (RHSOp0->getType()->getScalarType()->isIntOrPtrTy()) {
10122 CmpPredicate LHSPred;
10123 Value *LHSOp0, *LHSOp1;
10124 if (match(LHS, m_ICmpLike(LHSPred, m_Value(LHSOp0), m_Value(LHSOp1))))
10125 return isImpliedCondICmps(LHSPred, LHSOp0, LHSOp1, RHSPred, RHSOp0,
10126 RHSOp1, DL, LHSIsTrue);
10127 } else {
10128 assert(RHSOp0->getType()->isFPOrFPVectorTy() &&
10129 "Expected floating point type only!");
10130 if (const auto *LHSCmp = dyn_cast<FCmpInst>(LHS))
10131 return isImpliedCondFCmps(LHSCmp->getPredicate(), LHSCmp->getOperand(0),
10132 LHSCmp->getOperand(1), RHSPred, RHSOp0, RHSOp1,
10133 DL, LHSIsTrue);
10134 }
10135
10136 /// The LHS should be an 'or', 'and', or a 'select' instruction. We expect
10137 /// the RHS to be an icmp.
10138 /// FIXME: Add support for and/or/select on the RHS.
10139 if (const Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
10140 if ((LHSI->getOpcode() == Instruction::And ||
10141 LHSI->getOpcode() == Instruction::Or ||
10142 LHSI->getOpcode() == Instruction::Select))
10143 return isImpliedCondAndOr(LHSI, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue,
10144 Depth);
10145 }
10146 return std::nullopt;
10147}
10148
10149std::optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
10150 const DataLayout &DL,
10151 bool LHSIsTrue, unsigned Depth) {
10152 // LHS ==> RHS by definition
10153 if (LHS == RHS)
10154 return LHSIsTrue;
10155
10156 // Match not
10157 bool InvertRHS = false;
10158 if (match(RHS, m_Not(m_Value(RHS)))) {
10159 if (LHS == RHS)
10160 return !LHSIsTrue;
10161 InvertRHS = true;
10162 }
10163
10164 CmpPredicate RHSPred;
10165 Value *RHSOp0, *RHSOp1;
10166 if (match(RHS, m_ICmpLike(RHSPred, m_Value(RHSOp0), m_Value(RHSOp1)))) {
10167 if (auto Implied = isImpliedCondition(LHS, RHSPred, RHSOp0, RHSOp1, DL,
10168 LHSIsTrue, Depth))
10169 return InvertRHS ? !*Implied : *Implied;
10170 return std::nullopt;
10171 }
10172 if (const FCmpInst *RHSCmp = dyn_cast<FCmpInst>(RHS)) {
10173 if (auto Implied = isImpliedCondition(
10174 LHS, RHSCmp->getPredicate(), RHSCmp->getOperand(0),
10175 RHSCmp->getOperand(1), DL, LHSIsTrue, Depth))
10176 return InvertRHS ? !*Implied : *Implied;
10177 return std::nullopt;
10178 }
10179
10181 return std::nullopt;
10182
10183 // LHS ==> (RHS1 || RHS2) if LHS ==> RHS1 or LHS ==> RHS2
10184 // LHS ==> !(RHS1 && RHS2) if LHS ==> !RHS1 or LHS ==> !RHS2
10185 const Value *RHS1, *RHS2;
10186 if (match(RHS, m_LogicalOr(m_Value(RHS1), m_Value(RHS2)))) {
10187 if (std::optional<bool> Imp =
10188 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10189 if (*Imp == true)
10190 return !InvertRHS;
10191 if (std::optional<bool> Imp =
10192 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10193 if (*Imp == true)
10194 return !InvertRHS;
10195 }
10196 if (match(RHS, m_LogicalAnd(m_Value(RHS1), m_Value(RHS2)))) {
10197 if (std::optional<bool> Imp =
10198 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10199 if (*Imp == false)
10200 return InvertRHS;
10201 if (std::optional<bool> Imp =
10202 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10203 if (*Imp == false)
10204 return InvertRHS;
10205 }
10206
10207 return std::nullopt;
10208}
10209
10210// Returns a pair (Condition, ConditionIsTrue), where Condition is a branch
10211// condition dominating ContextI or nullptr, if no condition is found.
10212static std::pair<Value *, bool>
10214 if (!ContextI || !ContextI->getParent())
10215 return {nullptr, false};
10216
10217 // TODO: This is a poor/cheap way to determine dominance. Should we use a
10218 // dominator tree (eg, from a SimplifyQuery) instead?
10219 const BasicBlock *ContextBB = ContextI->getParent();
10220 const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
10221 if (!PredBB)
10222 return {nullptr, false};
10223
10224 // We need a conditional branch in the predecessor.
10225 Value *PredCond;
10226 BasicBlock *TrueBB, *FalseBB;
10227 if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
10228 return {nullptr, false};
10229
10230 // The branch should get simplified. Don't bother simplifying this condition.
10231 if (TrueBB == FalseBB)
10232 return {nullptr, false};
10233
10234 assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
10235 "Predecessor block does not point to successor?");
10236
10237 // Is this condition implied by the predecessor condition?
10238 return {PredCond, TrueBB == ContextBB};
10239}
10240
10241std::optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
10242 const Instruction *ContextI,
10243 const DataLayout &DL) {
10244 assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
10245 auto PredCond = getDomPredecessorCondition(ContextI);
10246 if (PredCond.first)
10247 return isImpliedCondition(PredCond.first, Cond, DL, PredCond.second);
10248 return std::nullopt;
10249}
10250
10252 const Value *LHS,
10253 const Value *RHS,
10254 const Instruction *ContextI,
10255 const DataLayout &DL) {
10256 auto PredCond = getDomPredecessorCondition(ContextI);
10257 if (PredCond.first)
10258 return isImpliedCondition(PredCond.first, Pred, LHS, RHS, DL,
10259 PredCond.second);
10260 return std::nullopt;
10261}
10262
10264 APInt &Upper, const InstrInfoQuery &IIQ,
10265 bool PreferSignedRange) {
10266 unsigned Width = Lower.getBitWidth();
10267 const APInt *C;
10268 switch (BO.getOpcode()) {
10269 case Instruction::Sub:
10270 if (match(BO.getOperand(0), m_APInt(C))) {
10271 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10272 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10273
10274 // If the caller expects a signed compare, then try to use a signed range.
10275 // Otherwise if both no-wraps are set, use the unsigned range because it
10276 // is never larger than the signed range. Example:
10277 // "sub nuw nsw i8 -2, x" is unsigned [0, 254] vs. signed [-128, 126].
10278 // "sub nuw nsw i8 2, x" is unsigned [0, 2] vs. signed [-125, 127].
10279 if (PreferSignedRange && HasNSW && HasNUW)
10280 HasNUW = false;
10281
10282 if (HasNUW) {
10283 // 'sub nuw c, x' produces [0, C].
10284 Upper = *C + 1;
10285 } else if (HasNSW) {
10286 if (C->isNegative()) {
10287 // 'sub nsw -C, x' produces [SINT_MIN, -C - SINT_MIN].
10289 Upper = *C - APInt::getSignedMaxValue(Width);
10290 } else {
10291 // Note that sub 0, INT_MIN is not NSW. It techically is a signed wrap
10292 // 'sub nsw C, x' produces [C - SINT_MAX, SINT_MAX].
10293 Lower = *C - APInt::getSignedMaxValue(Width);
10295 }
10296 }
10297 }
10298 break;
10299 case Instruction::Add:
10300 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10301 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10302 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10303
10304 // If the caller expects a signed compare, then try to use a signed
10305 // range. Otherwise if both no-wraps are set, use the unsigned range
10306 // because it is never larger than the signed range. Example: "add nuw
10307 // nsw i8 X, -2" is unsigned [254,255] vs. signed [-128, 125].
10308 if (PreferSignedRange && HasNSW && HasNUW)
10309 HasNUW = false;
10310
10311 if (HasNUW) {
10312 // 'add nuw x, C' produces [C, UINT_MAX].
10313 Lower = *C;
10314 } else if (HasNSW) {
10315 if (C->isNegative()) {
10316 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
10318 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
10319 } else {
10320 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
10321 Lower = APInt::getSignedMinValue(Width) + *C;
10322 Upper = APInt::getSignedMaxValue(Width) + 1;
10323 }
10324 }
10325 }
10326 break;
10327
10328 case Instruction::And:
10329 if (match(BO.getOperand(1), m_APInt(C)))
10330 // 'and x, C' produces [0, C].
10331 Upper = *C + 1;
10332 // X & -X is a power of two or zero. So we can cap the value at max power of
10333 // two.
10334 if (match(BO.getOperand(0), m_Neg(m_Specific(BO.getOperand(1)))) ||
10335 match(BO.getOperand(1), m_Neg(m_Specific(BO.getOperand(0)))))
10336 Upper = APInt::getSignedMinValue(Width) + 1;
10337 break;
10338
10339 case Instruction::Or:
10340 if (match(BO.getOperand(1), m_APInt(C)))
10341 // 'or x, C' produces [C, UINT_MAX].
10342 Lower = *C;
10343 break;
10344
10345 case Instruction::AShr:
10346 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10347 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
10349 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
10350 } else if (match(BO.getOperand(0), m_APInt(C))) {
10351 unsigned ShiftAmount = Width - 1;
10352 if (!C->isZero() && IIQ.isExact(&BO))
10353 ShiftAmount = C->countr_zero();
10354 if (C->isNegative()) {
10355 // 'ashr C, x' produces [C, C >> (Width-1)]
10356 Lower = *C;
10357 Upper = C->ashr(ShiftAmount) + 1;
10358 } else {
10359 // 'ashr C, x' produces [C >> (Width-1), C]
10360 Lower = C->ashr(ShiftAmount);
10361 Upper = *C + 1;
10362 }
10363 }
10364 break;
10365
10366 case Instruction::LShr:
10367 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10368 // 'lshr x, C' produces [0, UINT_MAX >> C].
10369 Upper = APInt::getAllOnes(Width).lshr(*C) + 1;
10370 } else if (match(BO.getOperand(0), m_APInt(C))) {
10371 // 'lshr C, x' produces [C >> (Width-1), C].
10372 unsigned ShiftAmount = Width - 1;
10373 if (!C->isZero() && IIQ.isExact(&BO))
10374 ShiftAmount = C->countr_zero();
10375 Lower = C->lshr(ShiftAmount);
10376 Upper = *C + 1;
10377 }
10378 break;
10379
10380 case Instruction::Shl:
10381 if (match(BO.getOperand(0), m_APInt(C))) {
10382 if (IIQ.hasNoUnsignedWrap(&BO)) {
10383 // 'shl nuw C, x' produces [C, C << CLZ(C)]
10384 Lower = *C;
10385 Upper = Lower.shl(Lower.countl_zero()) + 1;
10386 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
10387 if (C->isNegative()) {
10388 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
10389 unsigned ShiftAmount = C->countl_one() - 1;
10390 Lower = C->shl(ShiftAmount);
10391 Upper = *C + 1;
10392 } else {
10393 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
10394 unsigned ShiftAmount = C->countl_zero() - 1;
10395 Lower = *C;
10396 Upper = C->shl(ShiftAmount) + 1;
10397 }
10398 } else {
10399 // If lowbit is set, value can never be zero.
10400 if ((*C)[0])
10401 Lower = APInt::getOneBitSet(Width, 0);
10402 // If we are shifting a constant the largest it can be is if the longest
10403 // sequence of consecutive ones is shifted to the highbits (breaking
10404 // ties for which sequence is higher). At the moment we take a liberal
10405 // upper bound on this by just popcounting the constant.
10406 // TODO: There may be a bitwise trick for it longest/highest
10407 // consecutative sequence of ones (naive method is O(Width) loop).
10408 Upper = APInt::getHighBitsSet(Width, C->popcount()) + 1;
10409 }
10410 } else if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10411 Upper = APInt::getBitsSetFrom(Width, C->getZExtValue()) + 1;
10412 }
10413 break;
10414
10415 case Instruction::SDiv:
10416 if (match(BO.getOperand(1), m_APInt(C))) {
10417 APInt IntMin = APInt::getSignedMinValue(Width);
10418 APInt IntMax = APInt::getSignedMaxValue(Width);
10419 if (C->isAllOnes()) {
10420 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
10421 // where C != -1 and C != 0 and C != 1
10422 Lower = IntMin + 1;
10423 Upper = IntMax + 1;
10424 } else if (C->countl_zero() < Width - 1) {
10425 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
10426 // where C != -1 and C != 0 and C != 1
10427 Lower = IntMin.sdiv(*C);
10428 Upper = IntMax.sdiv(*C);
10429 if (Lower.sgt(Upper))
10431 Upper = Upper + 1;
10432 assert(Upper != Lower && "Upper part of range has wrapped!");
10433 }
10434 } else if (match(BO.getOperand(0), m_APInt(C))) {
10435 if (C->isMinSignedValue()) {
10436 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
10437 Lower = *C;
10438 Upper = Lower.lshr(1) + 1;
10439 } else {
10440 // 'sdiv C, x' produces [-|C|, |C|].
10441 Upper = C->abs() + 1;
10442 Lower = (-Upper) + 1;
10443 }
10444 }
10445 break;
10446
10447 case Instruction::UDiv:
10448 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10449 // 'udiv x, C' produces [0, UINT_MAX / C].
10450 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
10451 } else if (match(BO.getOperand(0), m_APInt(C))) {
10452 // 'udiv C, x' produces [0, C].
10453 Upper = *C + 1;
10454 }
10455 break;
10456
10457 case Instruction::SRem:
10458 if (match(BO.getOperand(1), m_APInt(C))) {
10459 // 'srem x, C' produces (-|C|, |C|).
10460 Upper = C->abs();
10461 Lower = (-Upper) + 1;
10462 } else if (match(BO.getOperand(0), m_APInt(C))) {
10463 if (C->isNegative()) {
10464 // 'srem -|C|, x' produces [-|C|, 0].
10465 Upper = 1;
10466 Lower = *C;
10467 } else {
10468 // 'srem |C|, x' produces [0, |C|].
10469 Upper = *C + 1;
10470 }
10471 }
10472 break;
10473
10474 case Instruction::URem:
10475 if (match(BO.getOperand(1), m_APInt(C)))
10476 // 'urem x, C' produces [0, C).
10477 Upper = *C;
10478 else if (match(BO.getOperand(0), m_APInt(C)))
10479 // 'urem C, x' produces [0, C].
10480 Upper = *C + 1;
10481 break;
10482
10483 default:
10484 break;
10485 }
10486}
10487
10489 bool UseInstrInfo) {
10490 unsigned Width = II.getType()->getScalarSizeInBits();
10491 const APInt *C;
10492 switch (II.getIntrinsicID()) {
10493 case Intrinsic::ctlz:
10494 case Intrinsic::cttz: {
10495 APInt Upper(Width, Width);
10496 if (!UseInstrInfo || !match(II.getArgOperand(1), m_One()))
10497 Upper += 1;
10498 // Maximum of set/clear bits is the bit width.
10500 }
10501 case Intrinsic::ctpop:
10502 // Maximum of set/clear bits is the bit width.
10504 APInt(Width, Width) + 1);
10505 case Intrinsic::uadd_sat:
10506 // uadd.sat(x, C) produces [C, UINT_MAX].
10507 if (match(II.getOperand(0), m_APInt(C)) ||
10508 match(II.getOperand(1), m_APInt(C)))
10510 break;
10511 case Intrinsic::sadd_sat:
10512 if (match(II.getOperand(0), m_APInt(C)) ||
10513 match(II.getOperand(1), m_APInt(C))) {
10514 if (C->isNegative())
10515 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
10517 APInt::getSignedMaxValue(Width) + *C +
10518 1);
10519
10520 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
10522 APInt::getSignedMaxValue(Width) + 1);
10523 }
10524 break;
10525 case Intrinsic::usub_sat:
10526 // usub.sat(C, x) produces [0, C].
10527 if (match(II.getOperand(0), m_APInt(C)))
10528 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10529
10530 // usub.sat(x, C) produces [0, UINT_MAX - C].
10531 if (match(II.getOperand(1), m_APInt(C)))
10533 APInt::getMaxValue(Width) - *C + 1);
10534 break;
10535 case Intrinsic::ssub_sat:
10536 if (match(II.getOperand(0), m_APInt(C))) {
10537 if (C->isNegative())
10538 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
10540 *C - APInt::getSignedMinValue(Width) +
10541 1);
10542
10543 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
10545 APInt::getSignedMaxValue(Width) + 1);
10546 } else if (match(II.getOperand(1), m_APInt(C))) {
10547 if (C->isNegative())
10548 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
10550 APInt::getSignedMaxValue(Width) + 1);
10551
10552 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
10554 APInt::getSignedMaxValue(Width) - *C +
10555 1);
10556 }
10557 break;
10558 case Intrinsic::umin:
10559 case Intrinsic::umax:
10560 case Intrinsic::smin:
10561 case Intrinsic::smax:
10562 if (!match(II.getOperand(0), m_APInt(C)) &&
10563 !match(II.getOperand(1), m_APInt(C)))
10564 break;
10565
10566 switch (II.getIntrinsicID()) {
10567 case Intrinsic::umin:
10568 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10569 case Intrinsic::umax:
10571 case Intrinsic::smin:
10573 *C + 1);
10574 case Intrinsic::smax:
10576 APInt::getSignedMaxValue(Width) + 1);
10577 default:
10578 llvm_unreachable("Must be min/max intrinsic");
10579 }
10580 break;
10581 case Intrinsic::abs:
10582 // If abs of SIGNED_MIN is poison, then the result is [0..SIGNED_MAX],
10583 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10584 if (match(II.getOperand(1), m_One()))
10586 APInt::getSignedMaxValue(Width) + 1);
10587
10589 APInt::getSignedMinValue(Width) + 1);
10590 case Intrinsic::vscale:
10591 if (!II.getParent() || !II.getFunction())
10592 break;
10593 return getVScaleRange(II.getFunction(), Width);
10594 case Intrinsic::read_register:
10595 case Intrinsic::read_volatile_register: {
10596 const Module *M = II.getModule();
10597 if (!M || !M->getTargetTriple().isRISCV())
10598 break;
10599 if (II.getFunction() && isReadVLENB(II))
10600 return getRISCVVLENBRange(II, Width);
10601 break;
10602 }
10603 default:
10604 break;
10605 }
10606
10607 return ConstantRange::getFull(Width);
10608}
10609
10611 const InstrInfoQuery &IIQ) {
10612 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
10613 const Value *LHS = nullptr, *RHS = nullptr;
10615 if (R.Flavor == SPF_UNKNOWN)
10616 return ConstantRange::getFull(BitWidth);
10617
10618 if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
10619 // If the negation part of the abs (in RHS) has the NSW flag,
10620 // then the result of abs(X) is [0..SIGNED_MAX],
10621 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10622 if (match(RHS, m_Neg(m_Specific(LHS))) &&
10626
10629 }
10630
10631 if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
10632 // The result of -abs(X) is <= 0.
10634 APInt(BitWidth, 1));
10635 }
10636
10637 const APInt *C;
10638 if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
10639 return ConstantRange::getFull(BitWidth);
10640
10641 switch (R.Flavor) {
10642 case SPF_UMIN:
10644 case SPF_UMAX:
10646 case SPF_SMIN:
10648 *C + 1);
10649 case SPF_SMAX:
10652 default:
10653 return ConstantRange::getFull(BitWidth);
10654 }
10655}
10656
10658 // The maximum representable value of a half is 65504. For floats the maximum
10659 // value is 3.4e38 which requires roughly 129 bits.
10660 unsigned BitWidth = I->getType()->getScalarSizeInBits();
10661 if (!I->getOperand(0)->getType()->getScalarType()->isHalfTy())
10662 return;
10663 if (isa<FPToSIInst>(I) && BitWidth >= 17) {
10664 Lower = APInt(BitWidth, -65504, true);
10665 Upper = APInt(BitWidth, 65505);
10666 }
10667
10668 if (isa<FPToUIInst>(I) && BitWidth >= 16) {
10669 // For a fptoui the lower limit is left as 0.
10670 Upper = APInt(BitWidth, 65505);
10671 }
10672}
10673
10675 const SimplifyQuery &SQ,
10676 unsigned Depth) {
10677 assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
10678
10680 return ConstantRange::getFull(V->getType()->getScalarSizeInBits());
10681
10682 if (auto *C = dyn_cast<Constant>(V))
10683 return C->toConstantRange();
10684
10685 unsigned BitWidth = V->getType()->getScalarSizeInBits();
10686 ConstantRange CR = ConstantRange::getFull(BitWidth);
10687 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
10688 APInt Lower = APInt(BitWidth, 0);
10689 APInt Upper = APInt(BitWidth, 0);
10690 // TODO: Return ConstantRange.
10691 setLimitsForBinOp(*BO, Lower, Upper, SQ.IIQ, ForSigned);
10693 } else if (auto *II = dyn_cast<IntrinsicInst>(V))
10695 else if (auto *SI = dyn_cast<SelectInst>(V)) {
10696 ConstantRange CRTrue =
10697 computeConstantRange(SI->getTrueValue(), ForSigned, SQ, Depth + 1);
10698 ConstantRange CRFalse =
10699 computeConstantRange(SI->getFalseValue(), ForSigned, SQ, Depth + 1);
10700 CR = CRTrue.unionWith(CRFalse);
10702 } else if (auto *TI = dyn_cast<TruncInst>(V)) {
10703 ConstantRange SrcCR =
10704 computeConstantRange(TI->getOperand(0), ForSigned, SQ, Depth + 1);
10705 CR = SrcCR.truncate(BitWidth);
10706 } else if (isa<FPToUIInst>(V) || isa<FPToSIInst>(V)) {
10707 APInt Lower = APInt(BitWidth, 0);
10708 APInt Upper = APInt(BitWidth, 0);
10709 // TODO: Return ConstantRange.
10712 } else if (const auto *A = dyn_cast<Argument>(V))
10713 if (std::optional<ConstantRange> Range = A->getRange())
10714 CR = *Range;
10715
10716 if (auto *I = dyn_cast<Instruction>(V)) {
10717 if (auto *Range = SQ.IIQ.getMetadata(I, LLVMContext::MD_range))
10719
10720 Value *FrexpSrc;
10721 if (const auto *CB = dyn_cast<CallBase>(V)) {
10722 if (std::optional<ConstantRange> Range = CB->getRange())
10723 CR = CR.intersectWith(*Range);
10725 m_Value(FrexpSrc))))) {
10726 const fltSemantics &FltSem =
10727 FrexpSrc->getType()->getScalarType()->getFltSemantics();
10728 // It should be possible to implement this for any type, but this logic
10729 // only computes the range assuming standard subnormal handling.
10730 if (APFloat::isIEEELikeFP(FltSem)) {
10732 FrexpSrc, fcSubnormal | fcZero | fcNan | fcInf, SQ, Depth + 1);
10733
10734 // The exponent of frexp(NaN) and frexp(Inf) is unspecified. Only
10735 // constrain its range when the source can be neither.
10736 if (KnownSrc.isKnownNeverInfOrNaN()) {
10737 int MinExp = APFloat::semanticsMinExponent(FltSem) + 1;
10738
10739 // Offset to find the true minimum exponent value for a denormal.
10740 if (!KnownSrc.isKnownNeverSubnormal())
10741 MinExp -= (APFloat::semanticsPrecision(FltSem) - 1);
10742
10743 int MaxExp = APFloat::semanticsMaxExponent(FltSem) + 1;
10744
10745 auto [AdjustedMin, AdjustedMax, AdjustedMaxNonZero] =
10747
10748 DenormalMode Mode = I->getFunction()->getDenormalMode(FltSem);
10749 bool NeverLogicalZero = KnownSrc.isKnownNeverLogicalZero(Mode);
10750
10751 MinExp = std::max(AdjustedMin, MinExp);
10752 MaxExp = std::min(NeverLogicalZero ? AdjustedMaxNonZero : AdjustedMax,
10753 MaxExp);
10754
10756 APInt(BitWidth, static_cast<int64_t>(MinExp), /*isSigned=*/true),
10757 APInt(BitWidth, static_cast<int64_t>(MaxExp) + 1,
10758 /*isSigned=*/true));
10759 }
10760 }
10761 }
10762 }
10763
10764 if (SQ.CxtI && SQ.AC) {
10765 // Try to restrict the range based on information from assumptions.
10766 for (auto &AssumeVH : SQ.AC->assumptionsFor(V)) {
10767 if (!AssumeVH)
10768 continue;
10769 CallInst *I = cast<CallInst>(AssumeVH);
10770 assert(I->getParent()->getParent() == SQ.CxtI->getParent()->getParent() &&
10771 "Got assumption for the wrong function!");
10772 assert(I->getIntrinsicID() == Intrinsic::assume &&
10773 "must be an assume intrinsic");
10774
10775 if (!isValidAssumeForContext(I, SQ))
10776 continue;
10777 Value *Arg = I->getArgOperand(0);
10778 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
10779 // Currently we just use information from comparisons.
10780 if (!Cmp || Cmp->getOperand(0) != V)
10781 continue;
10782 // TODO: Set "ForSigned" parameter via Cmp->isSigned()?
10783 ConstantRange RHS =
10784 computeConstantRange(Cmp->getOperand(1), /*ForSigned=*/false,
10785 SQ.getWithInstruction(I), Depth + 1);
10786 CR = CR.intersectWith(
10787 ConstantRange::makeAllowedICmpRegion(Cmp->getCmpPredicate(), RHS));
10788 }
10789 }
10790
10791 return CR;
10792}
10793
10794static void
10796 function_ref<void(Value *)> InsertAffected) {
10797 assert(V != nullptr);
10798 if (isa<Argument>(V) || isa<GlobalValue>(V)) {
10799 InsertAffected(V);
10800 } else if (auto *I = dyn_cast<Instruction>(V)) {
10801 InsertAffected(V);
10802
10803 // Peek through unary operators to find the source of the condition.
10804 Value *Op;
10806 m_Trunc(m_Value(Op))))) {
10808 InsertAffected(Op);
10809 }
10810 }
10811}
10812
10814 Value *Cond, bool IsAssume, function_ref<void(Value *)> InsertAffected) {
10815 auto AddAffected = [&InsertAffected](Value *V) {
10816 addValueAffectedByCondition(V, InsertAffected);
10817 };
10818
10819 auto AddCmpOperands = [&AddAffected, IsAssume](Value *LHS, Value *RHS) {
10820 if (IsAssume) {
10821 AddAffected(LHS);
10822 AddAffected(RHS);
10823 } else if (match(RHS, m_Constant()))
10824 AddAffected(LHS);
10825 };
10826
10827 SmallVector<Value *, 8> Worklist;
10829 Worklist.push_back(Cond);
10830 while (!Worklist.empty()) {
10831 Value *V = Worklist.pop_back_val();
10832 if (!Visited.insert(V).second)
10833 continue;
10834
10835 CmpPredicate Pred;
10836 Value *A, *B, *X;
10837
10838 if (IsAssume) {
10839 AddAffected(V);
10840 if (match(V, m_Not(m_Value(X))))
10841 AddAffected(X);
10842 }
10843
10844 if (match(V, m_LogicalOp(m_Value(A), m_Value(B)))) {
10845 // assume(A && B) is split to -> assume(A); assume(B);
10846 // assume(!(A || B)) is split to -> assume(!A); assume(!B);
10847 // Finally, assume(A || B) / assume(!(A && B)) generally don't provide
10848 // enough information to be worth handling (intersection of information as
10849 // opposed to union).
10850 if (!IsAssume) {
10851 Worklist.push_back(A);
10852 Worklist.push_back(B);
10853 }
10854 } else if (match(V, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
10855 bool HasRHSC = match(B, m_ConstantInt());
10856 if (ICmpInst::isEquality(Pred)) {
10857 AddAffected(A);
10858 if (IsAssume)
10859 AddAffected(B);
10860 if (HasRHSC) {
10861 Value *Y;
10862 // (X << C) or (X >>_s C) or (X >>_u C).
10863 if (match(A, m_Shift(m_Value(X), m_ConstantInt())))
10864 AddAffected(X);
10865 // (X & C) or (X | C).
10866 else if (match(A, m_And(m_Value(X), m_Value(Y))) ||
10867 match(A, m_Or(m_Value(X), m_Value(Y)))) {
10868 AddAffected(X);
10869 AddAffected(Y);
10870 }
10871 // X - Y
10872 else if (match(A, m_Sub(m_Value(X), m_Value(Y)))) {
10873 AddAffected(X);
10874 AddAffected(Y);
10875 }
10876 }
10877 } else {
10878 AddCmpOperands(A, B);
10879 if (HasRHSC) {
10880 // Handle (A + C1) u< C2, which is the canonical form of
10881 // A > C3 && A < C4.
10883 AddAffected(X);
10884
10885 if (ICmpInst::isUnsigned(Pred)) {
10886 Value *Y;
10887 // X & Y u> C -> X >u C && Y >u C
10888 // X | Y u< C -> X u< C && Y u< C
10889 // X nuw+ Y u< C -> X u< C && Y u< C
10890 if (match(A, m_And(m_Value(X), m_Value(Y))) ||
10891 match(A, m_Or(m_Value(X), m_Value(Y))) ||
10892 match(A, m_NUWAdd(m_Value(X), m_Value(Y)))) {
10893 AddAffected(X);
10894 AddAffected(Y);
10895 }
10896 // X nuw- Y u> C -> X u> C
10897 if (match(A, m_NUWSub(m_Value(X), m_Value())))
10898 AddAffected(X);
10899 }
10900 }
10901
10902 // Handle icmp slt/sgt (bitcast X to int), 0/-1, which is supported
10903 // by computeKnownFPClass().
10905 if (Pred == ICmpInst::ICMP_SLT && match(B, m_Zero()))
10906 InsertAffected(X);
10907 else if (Pred == ICmpInst::ICMP_SGT && match(B, m_AllOnes()))
10908 InsertAffected(X);
10909 }
10910 }
10911
10912 auto AddNuwSquareOperand = [&AddAffected](Value *Op) {
10913 Value *SquareOp = nullptr;
10914 if (match(Op, m_NUWMul(m_Value(SquareOp), m_Deferred(SquareOp))))
10915 AddAffected(SquareOp);
10916 };
10917 AddNuwSquareOperand(A);
10918 AddNuwSquareOperand(B);
10919
10920 if (HasRHSC && match(A, m_Ctpop(m_Value(X))))
10921 AddAffected(X);
10922 } else if (match(V, m_FCmp(Pred, m_Value(A), m_Value(B)))) {
10923 AddCmpOperands(A, B);
10924
10925 // fcmp fneg(x), y
10926 // fcmp fabs(x), y
10927 // fcmp fneg(fabs(x)), y
10928 if (match(A, m_FNeg(m_Value(A))))
10929 AddAffected(A);
10930 if (match(A, m_FAbs(m_Value(A))))
10931 AddAffected(A);
10932
10934 m_Value()))) {
10935 // Handle patterns that computeKnownFPClass() support.
10936 AddAffected(A);
10937 } else if (!IsAssume && match(V, m_Trunc(m_Value(X)))) {
10938 // Assume is checked here as X is already added above for assumes in
10939 // addValueAffectedByCondition
10940 AddAffected(X);
10941 } else if (!IsAssume && match(V, m_Not(m_Value(X)))) {
10942 // Assume is checked here to avoid issues with ephemeral values
10943 Worklist.push_back(X);
10944 }
10945 }
10946}
10947
10949 // (X >> C) or/add (X & mask(C) != 0)
10950 if (const auto *BO = dyn_cast<BinaryOperator>(V)) {
10951 if (BO->getOpcode() == Instruction::Add ||
10952 BO->getOpcode() == Instruction::Or) {
10953 const Value *X;
10954 const APInt *C1, *C2;
10955 if (match(BO, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C1)),
10959 m_Zero())))) &&
10960 C2->popcount() == C1->getZExtValue())
10961 return X;
10962 }
10963 }
10964 return nullptr;
10965}
10966
10968 return const_cast<Value *>(stripNullTest(const_cast<const Value *>(V)));
10969}
10970
10973 unsigned MaxCount, bool AllowUndefOrPoison) {
10976 auto Push = [&](const Value *V) -> bool {
10977 Constant *C;
10978 if (match(const_cast<Value *>(V), m_ImmConstant(C))) {
10979 if (!AllowUndefOrPoison && !isGuaranteedNotToBeUndefOrPoison(C))
10980 return false;
10981 // Check existence first to avoid unnecessary allocations.
10982 if (Constants.contains(C))
10983 return true;
10984 if (Constants.size() == MaxCount)
10985 return false;
10986 Constants.insert(C);
10987 return true;
10988 }
10989
10990 if (auto *Inst = dyn_cast<Instruction>(V)) {
10991 if (Visited.insert(Inst).second)
10992 Worklist.push_back(Inst);
10993 return true;
10994 }
10995 return false;
10996 };
10997 if (!Push(V))
10998 return false;
10999 while (!Worklist.empty()) {
11000 const Instruction *CurInst = Worklist.pop_back_val();
11001 switch (CurInst->getOpcode()) {
11002 case Instruction::Select:
11003 if (!Push(CurInst->getOperand(1)))
11004 return false;
11005 if (!Push(CurInst->getOperand(2)))
11006 return false;
11007 break;
11008 case Instruction::PHI:
11009 for (Value *IncomingValue : cast<PHINode>(CurInst)->incoming_values()) {
11010 // Fast path for recurrence PHI.
11011 if (IncomingValue == CurInst)
11012 continue;
11013 if (!Push(IncomingValue))
11014 return false;
11015 }
11016 break;
11017 default:
11018 return false;
11019 }
11020 }
11021 return true;
11022}
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:2007
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1600
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:1671
LLVM_ABI APInt reverseBits() const
Definition APInt.cpp:785
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:1085
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:105
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:261
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 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...
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:1069
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1426
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:288
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
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
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:326
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:232
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:285
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:270
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:313
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:227
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:106
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:255
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:727
iterator_range< user_iterator > users()
Definition Value.h:426
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:3041
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:668
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.
FPClassTest KnownFPClasses
Floating-point classes the value could be one of.
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.
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