LLVM 24.0.0git
ValueTracking.cpp
Go to the documentation of this file.
1//===- ValueTracking.cpp - Walk computations to compute properties --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains routines that help analyze properties that chains of
10// computations have.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/ScopeExit.h"
22#include "llvm/ADT/StringRef.h"
32#include "llvm/Analysis/Loads.h"
37#include "llvm/IR/Argument.h"
38#include "llvm/IR/Attributes.h"
39#include "llvm/IR/BasicBlock.h"
41#include "llvm/IR/Constant.h"
44#include "llvm/IR/Constants.h"
47#include "llvm/IR/Dominators.h"
49#include "llvm/IR/Function.h"
51#include "llvm/IR/GlobalAlias.h"
52#include "llvm/IR/GlobalValue.h"
54#include "llvm/IR/InstrTypes.h"
55#include "llvm/IR/Instruction.h"
58#include "llvm/IR/Intrinsics.h"
59#include "llvm/IR/IntrinsicsAArch64.h"
60#include "llvm/IR/IntrinsicsAMDGPU.h"
61#include "llvm/IR/IntrinsicsRISCV.h"
62#include "llvm/IR/IntrinsicsX86.h"
63#include "llvm/IR/LLVMContext.h"
64#include "llvm/IR/Metadata.h"
65#include "llvm/IR/Module.h"
66#include "llvm/IR/Operator.h"
68#include "llvm/IR/Type.h"
69#include "llvm/IR/User.h"
70#include "llvm/IR/Value.h"
80#include <algorithm>
81#include <cassert>
82#include <cstdint>
83#include <optional>
84#include <utility>
85
86using namespace llvm;
87using namespace llvm::PatternMatch;
88
89// Controls the number of uses of the value searched for possible
90// dominating comparisons.
91static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
92 cl::Hidden, cl::init(20));
93
94/// Maximum number of instructions to check between assume and context
95/// instruction.
96static constexpr unsigned MaxInstrsToCheckForFree = 32;
97
98/// Returns the bitwidth of the given scalar or pointer type. For vector types,
99/// returns the element type's bitwidth.
100static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
101 if (unsigned BitWidth = Ty->getScalarSizeInBits())
102 return BitWidth;
103
104 return DL.getPointerTypeSizeInBits(Ty);
105}
106
107// Given the provided Value and, potentially, a context instruction, return
108// the preferred context instruction (if any).
109static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
110 // If we've been provided with a context instruction, then use that (provided
111 // it has been inserted).
112 if (CxtI && CxtI->getParent())
113 return CxtI;
114
115 // If the value is really an already-inserted instruction, then use that.
116 CxtI = dyn_cast<Instruction>(V);
117 if (CxtI && CxtI->getParent())
118 return CxtI;
119
120 return nullptr;
121}
122
124 const APInt &DemandedElts,
125 APInt &DemandedLHS, APInt &DemandedRHS) {
126 if (isa<ScalableVectorType>(Shuf->getType())) {
127 assert(DemandedElts == APInt(1,1));
128 DemandedLHS = DemandedRHS = DemandedElts;
129 return true;
130 }
131
132 int NumElts =
133 cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
134 return llvm::getShuffleDemandedElts(NumElts, Shuf->getShuffleMask(),
135 DemandedElts, DemandedLHS, DemandedRHS);
136}
137
138static void computeKnownBits(const Value *V, const APInt &DemandedElts,
139 KnownBits &Known, const SimplifyQuery &Q,
140 unsigned Depth);
141
143 const SimplifyQuery &Q, unsigned Depth) {
144 // Since the number of lanes in a scalable vector is unknown at compile time,
145 // we track one bit which is implicitly broadcast to all lanes. This means
146 // that all lanes in a scalable vector are considered demanded.
147 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
148 APInt DemandedElts =
149 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
150 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
151}
152
154 const DataLayout &DL, AssumptionCache *AC,
155 const Instruction *CxtI, const DominatorTree *DT,
156 bool UseInstrInfo, unsigned Depth) {
158 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo),
159 Depth);
160}
161
163 AssumptionCache *AC, const Instruction *CxtI,
164 const DominatorTree *DT, bool UseInstrInfo,
165 unsigned Depth) {
166 return computeKnownBits(
167 V, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
168}
169
170KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
171 const DataLayout &DL, AssumptionCache *AC,
172 const Instruction *CxtI,
173 const DominatorTree *DT, bool UseInstrInfo,
174 unsigned Depth) {
175 return computeKnownBits(
176 V, DemandedElts,
177 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
178}
179
182 const SimplifyQuery &SQ) {
183 // Look for an inverted mask: (X & ~M) op (Y & M).
184 {
185 Value *M;
186 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
188 return isGuaranteedNotToBeUndef(M, SQ.AC, SQ.CxtI, SQ.DT)
191 }
192
193 // X op (Y & ~X)
195 return isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT)
198
199 // X op ((X & Y) ^ Y) -- this is the canonical form of the previous pattern
200 // for constant Y.
201 Value *Y;
202 if (match(RHS,
204 bool IsNoUndef = isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT) &&
205 isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CxtI, SQ.DT);
206 return IsNoUndef ? NoCommonBitsSetResult::Known
208 }
209
210 // Peek through extends to find a 'not' of the other side:
211 // (ext Y) op ext(~Y)
212 if (match(LHS, m_ZExtOrSExt(m_Value(Y))) &&
214 return isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CxtI, SQ.DT)
217
218 // Look for: (A & B) op ~(A | B)
219 {
220 Value *A, *B;
221 if (match(LHS, m_And(m_Value(A), m_Value(B))) &&
223 bool IsNoUndef = isGuaranteedNotToBeUndef(A, SQ.AC, SQ.CxtI, SQ.DT) &&
224 isGuaranteedNotToBeUndef(B, SQ.AC, SQ.CxtI, SQ.DT);
225 return IsNoUndef ? NoCommonBitsSetResult::Known
227 }
228 }
229
230 // Look for: (X << V) op (Y >> (BitWidth - V))
231 // or (X >> V) op (Y << (BitWidth - V))
232 {
233 const Value *V;
234 const APInt *R;
235 if (((match(RHS, m_Shl(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
236 match(LHS, m_LShr(m_Value(), m_Specific(V)))) ||
237 (match(RHS, m_LShr(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
238 match(LHS, m_Shl(m_Value(), m_Specific(V))))) &&
239 R->uge(LHS->getType()->getScalarSizeInBits()))
241 }
242
244}
245
248 const WithCache<const Value *> &RHSCache,
249 const SimplifyQuery &SQ) {
250 const Value *LHS = LHSCache.getValue();
251 const Value *RHS = RHSCache.getValue();
252
253 assert(LHS->getType() == RHS->getType() &&
254 "LHS and RHS should have the same type");
255 assert(LHS->getType()->isIntOrIntVectorTy() &&
256 "LHS and RHS should be integers");
257
259 if (Result == NoCommonBitsSetResult::Known)
261
262 NoCommonBitsSetResult CommuteResult =
264 if (CommuteResult == NoCommonBitsSetResult::Known)
266
268 RHSCache.getKnownBits(SQ)))
270
274
276}
277
279 const WithCache<const Value *> &RHSCache,
280 const SimplifyQuery &SQ) {
281 NoCommonBitsSetResult Result =
282 getNoCommonBitsSetResult(LHSCache, RHSCache, SQ);
283 return Result == NoCommonBitsSetResult::Known;
284}
285
287 return !I->user_empty() &&
288 all_of(I->users(), match_fn(m_ICmp(m_Value(), m_Zero())));
289}
290
292 return !I->user_empty() && all_of(I->users(), [](const User *U) {
293 CmpPredicate P;
294 return match(U, m_ICmp(P, m_Value(), m_Zero())) && ICmpInst::isEquality(P);
295 });
296}
297
299 bool OrZero, AssumptionCache *AC,
300 const Instruction *CxtI,
301 const DominatorTree *DT, bool UseInstrInfo,
302 unsigned Depth) {
303 return ::isKnownToBeAPowerOfTwo(
304 V, OrZero, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo),
305 Depth);
306}
307
308static bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
309 const SimplifyQuery &Q, unsigned Depth);
310
312 unsigned Depth) {
313 return computeKnownBits(V, SQ, Depth).isNonNegative();
314}
315
317 unsigned Depth) {
318 if (auto *CI = dyn_cast<ConstantInt>(V))
319 return CI->getValue().isStrictlyPositive();
320
321 // If `isKnownNonNegative` ever becomes more sophisticated, make sure to keep
322 // this updated.
324 return Known.isNonNegative() &&
325 (Known.isNonZero() || isKnownNonZero(V, SQ, Depth));
326}
327
329 unsigned Depth) {
330 return computeKnownBits(V, SQ, Depth).isNegative();
331}
332
333static bool isKnownNonEqual(const Value *V1, const Value *V2,
334 const APInt &DemandedElts, const SimplifyQuery &Q,
335 unsigned Depth);
336
337static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
338 const Value *RHS);
339
340bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
341 const SimplifyQuery &Q, unsigned Depth) {
342 // We don't support looking through casts.
343 if (V1 == V2 || V1->getType() != V2->getType())
344 return false;
345 auto *FVTy = dyn_cast<FixedVectorType>(V1->getType());
346 APInt DemandedElts =
347 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
348 return ::isKnownNonEqual(V1, V2, DemandedElts, Q, Depth);
349}
350
351bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
352 const SimplifyQuery &SQ, unsigned Depth) {
353 KnownBits Known(Mask.getBitWidth());
355 return Mask.isSubsetOf(Known.Zero);
356}
357
358static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
359 const SimplifyQuery &Q, unsigned Depth);
360
361static unsigned ComputeNumSignBits(const Value *V, const SimplifyQuery &Q,
362 unsigned Depth = 0) {
363 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
364 APInt DemandedElts =
365 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
366 return ComputeNumSignBits(V, DemandedElts, Q, Depth);
367}
368
369unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
370 AssumptionCache *AC, const Instruction *CxtI,
371 const DominatorTree *DT, bool UseInstrInfo,
372 unsigned Depth) {
373 return ::ComputeNumSignBits(
374 V, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
375}
376
378 AssumptionCache *AC,
379 const Instruction *CxtI,
380 const DominatorTree *DT,
381 unsigned Depth) {
382 unsigned SignBits = ComputeNumSignBits(V, DL, AC, CxtI, DT, Depth);
383 return V->getType()->getScalarSizeInBits() - SignBits + 1;
384}
385
386/// Try to detect the lerp pattern: a * (b - c) + c * d
387/// where a >= 0, b >= 0, c >= 0, d >= 0, and b >= c.
388///
389/// In that particular case, we can use the following chain of reasoning:
390///
391/// a * (b - c) + c * d <= a' * (b - c) + a' * c = a' * b where a' = max(a, d)
392///
393/// Since that is true for arbitrary a, b, c and d within our constraints, we
394/// can conclude that:
395///
396/// max(a * (b - c) + c * d) <= max(max(a), max(d)) * max(b) = U
397///
398/// Considering that any result of the lerp would be less or equal to U, it
399/// would have at least the number of leading 0s as in U.
400///
401/// While being quite a specific situation, it is fairly common in computer
402/// graphics in the shape of alpha blending.
403///
404/// Modifies given KnownOut in-place with the inferred information.
405static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1,
406 const APInt &DemandedElts,
407 KnownBits &KnownOut,
408 const SimplifyQuery &Q,
409 unsigned Depth) {
410
411 Type *Ty = Op0->getType();
412 const unsigned BitWidth = Ty->getScalarSizeInBits();
413
414 // Only handle scalar types for now
415 if (Ty->isVectorTy())
416 return;
417
418 // Try to match: a * (b - c) + c * d.
419 // When a == 1 => A == nullptr, the same applies to d/D as well.
420 const Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
421 const Instruction *SubBC = nullptr;
422
423 const auto MatchSubBC = [&]() {
424 // (b - c) can have two forms that interest us:
425 //
426 // 1. sub nuw %b, %c
427 // 2. xor %c, %b
428 //
429 // For the first case, nuw flag guarantees our requirement b >= c.
430 //
431 // The second case might happen when the analysis can infer that b is a mask
432 // for c and we can transform sub operation into xor (that is usually true
433 // for constant b's). Even though xor is symmetrical, canonicalization
434 // ensures that the constant will be the RHS. We have additional checks
435 // later on to ensure that this xor operation is equivalent to subtraction.
437 m_Xor(m_Value(C), m_Value(B))));
438 };
439
440 const auto MatchASubBC = [&]() {
441 // Cases:
442 // - a * (b - c)
443 // - (b - c) * a
444 // - (b - c) <- a implicitly equals 1
445 return m_CombineOr(m_c_Mul(m_Value(A), MatchSubBC()), MatchSubBC());
446 };
447
448 const auto MatchCD = [&]() {
449 // Cases:
450 // - d * c
451 // - c * d
452 // - c <- d implicitly equals 1
454 };
455
456 const auto Match = [&](const Value *LHS, const Value *RHS) {
457 // We do use m_Specific(C) in MatchCD, so we have to make sure that
458 // it's bound to anything and match(LHS, MatchASubBC()) absolutely
459 // has to evaluate first and return true.
460 //
461 // If Match returns true, it is guaranteed that B != nullptr, C != nullptr.
462 return match(LHS, MatchASubBC()) && match(RHS, MatchCD());
463 };
464
465 if (!Match(Op0, Op1) && !Match(Op1, Op0))
466 return;
467
468 const auto ComputeKnownBitsOrOne = [&](const Value *V) {
469 // For some of the values we use the convention of leaving
470 // it nullptr to signify an implicit constant 1.
471 return V ? computeKnownBits(V, DemandedElts, Q, Depth + 1)
473 };
474
475 // Check that all operands are non-negative
476 const KnownBits KnownA = ComputeKnownBitsOrOne(A);
477 if (!KnownA.isNonNegative())
478 return;
479
480 const KnownBits KnownD = ComputeKnownBitsOrOne(D);
481 if (!KnownD.isNonNegative())
482 return;
483
484 const KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
485 if (!KnownB.isNonNegative())
486 return;
487
488 const KnownBits KnownC = computeKnownBits(C, DemandedElts, Q, Depth + 1);
489 if (!KnownC.isNonNegative())
490 return;
491
492 // If we matched subtraction as xor, we need to actually check that xor
493 // is semantically equivalent to subtraction.
494 //
495 // For that to be true, b has to be a mask for c or that b's known
496 // ones cover all known and possible ones of c.
497 if (SubBC->getOpcode() == Instruction::Xor &&
498 !KnownC.getMaxValue().isSubsetOf(KnownB.getMinValue()))
499 return;
500
501 const APInt MaxA = KnownA.getMaxValue();
502 const APInt MaxD = KnownD.getMaxValue();
503 const APInt MaxAD = APIntOps::umax(MaxA, MaxD);
504 const APInt MaxB = KnownB.getMaxValue();
505
506 // We can't infer leading zeros info if the upper-bound estimate wraps.
507 bool Overflow;
508 const APInt UpperBound = MaxAD.umul_ov(MaxB, Overflow);
509
510 if (Overflow)
511 return;
512
513 // If we know that x <= y and both are positive than x has at least the same
514 // number of leading zeros as y.
515 const unsigned MinimumNumberOfLeadingZeros = UpperBound.countl_zero();
516 KnownOut.Zero.setHighBits(MinimumNumberOfLeadingZeros);
517}
518
519static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
520 bool NSW, bool NUW,
521 const APInt &DemandedElts,
522 KnownBits &KnownOut, KnownBits &Known2,
523 const SimplifyQuery &Q, unsigned Depth) {
524 computeKnownBits(Op1, DemandedElts, KnownOut, Q, Depth + 1);
525
526 // If one operand is unknown and we have no nowrap information,
527 // the result will be unknown independently of the second operand.
528 if (KnownOut.isUnknown() && !NSW && !NUW)
529 return;
530
531 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
532 KnownOut = KnownBits::computeForAddSub(Add, NSW, NUW, Known2, KnownOut);
533
534 if (!Add && NSW && !KnownOut.isNonNegative() &&
536 .value_or(false) ||
537 match(Op1, m_c_SMin(m_Specific(Op0), m_Value()))))
538 KnownOut.makeNonNegative();
539
540 if (Add)
541 // Try to match lerp pattern and combine results
542 computeKnownBitsFromLerpPattern(Op0, Op1, DemandedElts, KnownOut, Q, Depth);
543}
544
545static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
546 bool NUW, const APInt &DemandedElts,
547 KnownBits &Known, KnownBits &Known2,
548 const SimplifyQuery &Q, unsigned Depth) {
549 computeKnownBits(Op1, DemandedElts, Known, Q, Depth + 1);
550 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
551
552 bool isKnownNegative = false;
553 bool isKnownNonNegative = false;
554 // If the multiplication is known not to overflow, compute the sign bit.
555 if (NSW) {
556 if (Op0 == Op1) {
557 // The product of a number with itself is non-negative.
558 isKnownNonNegative = true;
559 } else {
560 bool isKnownNonNegativeOp1 = Known.isNonNegative();
561 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
562 bool isKnownNegativeOp1 = Known.isNegative();
563 bool isKnownNegativeOp0 = Known2.isNegative();
564 // The product of two numbers with the same sign is non-negative.
565 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
566 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
567 if (!isKnownNonNegative && NUW) {
568 // mul nuw nsw with a factor > 1 is non-negative.
569 KnownBits One = KnownBits::makeConstant(APInt(Known.getBitWidth(), 1));
570 isKnownNonNegative = KnownBits::sgt(Known, One).value_or(false) ||
571 KnownBits::sgt(Known2, One).value_or(false);
572 }
573
574 // The product of a negative number and a non-negative number is either
575 // negative or zero.
578 (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
579 Known2.isNonZero()) ||
580 (isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.isNonZero());
581 }
582 }
583
584 bool SelfMultiply = Op0 == Op1;
585 if (SelfMultiply)
586 SelfMultiply &=
587 isGuaranteedNotToBeUndef(Op0, Q.AC, Q.CxtI, Q.DT, Depth + 1);
588 Known = KnownBits::mul(Known, Known2, SelfMultiply);
589
590 if (SelfMultiply) {
591 unsigned SignBits = ComputeNumSignBits(Op0, DemandedElts, Q, Depth + 1);
592 unsigned TyBits = Op0->getType()->getScalarSizeInBits();
593 unsigned OutValidBits = 2 * (TyBits - SignBits + 1);
594
595 if (OutValidBits < TyBits) {
596 APInt KnownZeroMask =
597 APInt::getHighBitsSet(TyBits, TyBits - OutValidBits + 1);
598 Known.Zero |= KnownZeroMask;
599 }
600 }
601
602 // Only make use of no-wrap flags if we failed to compute the sign bit
603 // directly. This matters if the multiplication always overflows, in
604 // which case we prefer to follow the result of the direct computation,
605 // though as the program is invoking undefined behaviour we can choose
606 // whatever we like here.
607 if (isKnownNonNegative && !Known.isNegative())
608 Known.makeNonNegative();
609 else if (isKnownNegative && !Known.isNonNegative())
610 Known.makeNegative();
611}
612
614 KnownBits &Known) {
615 unsigned BitWidth = Known.getBitWidth();
616 unsigned NumRanges = Ranges.getNumOperands() / 2;
617 assert(NumRanges >= 1);
618
619 Known.setAllConflict();
620
621 for (unsigned i = 0; i < NumRanges; ++i) {
623 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
625 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
626 ConstantRange Range(Lower->getValue(), Upper->getValue());
627 // BitWidth must equal the Ranges BitWidth for the correct number of high
628 // bits to be set.
629 assert(BitWidth == Range.getBitWidth() &&
630 "Known bit width must match range bit width!");
631
632 // The first CommonPrefixBits of all values in Range are equal.
633 unsigned CommonPrefixBits =
634 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countl_zero();
635 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
636 APInt UnsignedMax = Range.getUnsignedMax().zextOrTrunc(BitWidth);
637 Known.One &= UnsignedMax & Mask;
638 Known.Zero &= ~UnsignedMax & Mask;
639 }
640}
641
642static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
643 // The instruction defining an assumption's condition itself is always
644 // considered ephemeral to that assumption (even if it has other
645 // non-ephemeral users). See r246696's test case for an example.
646 if (is_contained(I->operands(), E))
647 return true;
648
649 const auto *EI = dyn_cast<Instruction>(E);
650 if (!EI)
651 return false;
652
653 if (EI == I)
654 return true;
655
658 Visited.insert(EI);
659 WorkList.push_back(EI);
660 bool ReachesI = false;
661 while (!WorkList.empty()) {
662 const Instruction *V = WorkList.pop_back_val();
663 for (const User *U : V->users()) {
664 const auto *UI = cast<Instruction>(U);
665 if (UI == I) {
666 ReachesI = true;
667 continue;
668 }
669 if (UI->mayHaveSideEffects() || UI->isTerminator())
670 return false;
671 if (Visited.insert(UI).second)
672 WorkList.push_back(UI);
673 }
674 }
675 return ReachesI;
676}
677
678// Is this an intrinsic that cannot be speculated but also cannot trap?
680 if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(I))
681 return CI->isAssumeLikeIntrinsic();
682
683 return false;
684}
685
687 const Instruction *CxtI,
688 const DominatorTree *DT,
689 bool AllowEphemerals) {
690 // There are two restrictions on the use of an assume:
691 // 1. The assume must dominate the context (or the control flow must
692 // reach the assume whenever it reaches the context).
693 // 2. The context must not be in the assume's set of ephemeral values
694 // (otherwise we will use the assume to prove that the condition
695 // feeding the assume is trivially true, thus causing the removal of
696 // the assume).
697
698 if (Inv->getParent() == CxtI->getParent()) {
699 // If Inv and CtxI are in the same block, check if the assume (Inv) is first
700 // in the BB.
701 if (Inv->comesBefore(CxtI))
702 return true;
703
704 // Don't let an assume affect itself - this would cause the problems
705 // `isEphemeralValueOf` is trying to prevent, and it would also make
706 // the loop below go out of bounds.
707 if (!AllowEphemerals && Inv == CxtI)
708 return false;
709
710 // The context comes first, but they're both in the same block.
711 // Make sure there is nothing in between that might interrupt
712 // the control flow, not even CxtI itself.
713 // We limit the scan distance between the assume and its context instruction
714 // to avoid a compile-time explosion. This limit is chosen arbitrarily, so
715 // it can be adjusted if needed (could be turned into a cl::opt).
716 auto Range = make_range(CxtI->getIterator(), Inv->getIterator());
718 return false;
719
720 return AllowEphemerals || !isEphemeralValueOf(Inv, CxtI);
721 }
722
723 // Inv and CxtI are in different blocks.
724 if (DT) {
725 if (DT->dominates(Inv, CxtI))
726 return true;
727 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor() ||
728 Inv->getParent()->isEntryBlock()) {
729 // We don't have a DT, but this trivially dominates.
730 return true;
731 }
732
733 return false;
734}
735
737 const Instruction *CtxI) {
738 // Helper to check if there are any calls in the range that may free memory.
739 unsigned NumChecked = 0;
740 auto hasNoFreeInRange = [&NumChecked](auto Range) {
741 for (const Instruction &I : Range) {
742 if (NumChecked++ > MaxInstrsToCheckForFree)
743 return false;
744
745 if (auto *CB = dyn_cast<CallBase>(&I)) {
746 if (!CB->hasFnAttr(Attribute::NoFree))
747 return false;
748 } else if (I.maySynchronize())
749 return false;
750 }
751 return true;
752 };
753
754 const BasicBlock *CtxBB = CtxI->getParent();
755 const BasicBlock *AssumeBB = Assume->getParent();
756 BasicBlock::const_iterator CtxIter = CtxI->getIterator();
757 if (CtxBB == AssumeBB) {
758 // Same block case: check that Assume comes before CtxI.
759 if (Assume != CtxI && !Assume->comesBefore(CtxI))
760 return false;
761 return hasNoFreeInRange(make_range(Assume->getIterator(), CtxIter));
762 }
763
764 // Handle chain of single-predecessor blocks.
765 const BasicBlock *CurBB = CtxBB;
766 while (true) {
767 if (CurBB == AssumeBB)
768 return hasNoFreeInRange(
769 make_range(Assume->getIterator(), AssumeBB->end()));
770
771 const BasicBlock *PredBB = CurBB->getSinglePredecessor();
772 if (!PredBB)
773 return false;
774
775 if (!hasNoFreeInRange(make_range(CurBB->begin(),
776 CurBB == CtxBB ? CtxIter : CurBB->end())))
777 return false;
778 CurBB = PredBB;
779 }
780}
781
782// TODO: cmpExcludesZero misses many cases where `RHS` is non-constant but
783// we still have enough information about `RHS` to conclude non-zero. For
784// example Pred=EQ, RHS=isKnownNonZero. cmpExcludesZero is called in loops
785// so the extra compile time may not be worth it, but possibly a second API
786// should be created for use outside of loops.
787static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS) {
788 // v u> y implies v != 0.
789 if (Pred == ICmpInst::ICMP_UGT)
790 return true;
791
792 // Special-case v != 0 to also handle v != null.
793 if (Pred == ICmpInst::ICMP_NE)
794 return match(RHS, m_Zero());
795
796 // All other predicates - rely on generic ConstantRange handling.
797 const APInt *C;
798 auto Zero = APInt::getZero(RHS->getType()->getScalarSizeInBits());
799 if (match(RHS, m_APInt(C))) {
801 return !TrueValues.contains(Zero);
802 }
803
805 if (VC == nullptr)
806 return false;
807
808 for (unsigned ElemIdx = 0, NElem = VC->getNumElements(); ElemIdx < NElem;
809 ++ElemIdx) {
811 Pred, VC->getElementAsAPInt(ElemIdx));
812 if (TrueValues.contains(Zero))
813 return false;
814 }
815 return true;
816}
817
818static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI,
819 Value *&ValOut, Instruction *&CtxIOut,
820 const PHINode **PhiOut = nullptr) {
821 ValOut = U->get();
822 if (ValOut == PHI)
823 return;
824 CtxIOut = PHI->getIncomingBlock(*U)->getTerminator();
825 if (PhiOut)
826 *PhiOut = PHI;
827 Value *V;
828 // If the Use is a select of this phi, compute analysis on other arm to break
829 // recursion.
830 // TODO: Min/Max
831 if (match(ValOut, m_Select(m_Value(), m_Specific(PHI), m_Value(V))) ||
832 match(ValOut, m_Select(m_Value(), m_Value(V), m_Specific(PHI))))
833 ValOut = V;
834
835 // Same for select, if this phi is 2-operand phi, compute analysis on other
836 // incoming value to break recursion.
837 // TODO: We could handle any number of incoming edges as long as we only have
838 // two unique values.
839 if (auto *IncPhi = dyn_cast<PHINode>(ValOut);
840 IncPhi && IncPhi->getNumIncomingValues() == 2) {
841 for (int Idx = 0; Idx < 2; ++Idx) {
842 if (IncPhi->getIncomingValue(Idx) == PHI) {
843 ValOut = IncPhi->getIncomingValue(1 - Idx);
844 if (PhiOut)
845 *PhiOut = IncPhi;
846 CtxIOut = IncPhi->getIncomingBlock(1 - Idx)->getTerminator();
847 break;
848 }
849 }
850 }
851}
852
853static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q) {
854 // Use of assumptions is context-sensitive. If we don't have a context, we
855 // cannot use them!
856 if (!Q.AC || !Q.CxtI)
857 return false;
858
859 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
860 if (!Elem.Assume)
861 continue;
862
863 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
864 assert(I->getFunction() == Q.CxtI->getFunction() &&
865 "Got assumption for the wrong function!");
866
867 if (Elem.Index != AssumptionCache::ExprResultIdx) {
869 I->getOperandBundleAt(Elem.Index)) &&
871 return true;
872 continue;
873 }
874
875 // Warning: This loop can end up being somewhat performance sensitive.
876 // We're running this loop for once for each value queried resulting in a
877 // runtime of ~O(#assumes * #values).
878
879 Value *RHS;
880 CmpPredicate Pred;
881 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
882 if (!match(I->getArgOperand(0), m_c_ICmp(Pred, m_V, m_Value(RHS))))
883 continue;
884
886 return true;
887 }
888
889 return false;
890}
891
894 const SimplifyQuery &Q) {
895 if (RHS->getType()->isPointerTy()) {
896 // Handle comparison of pointer to null explicitly, as it will not be
897 // covered by the m_APInt() logic below.
898 if (LHS == V && match(RHS, m_Zero())) {
899 switch (Pred) {
901 Known.setAllZero();
902 break;
905 Known.makeNonNegative();
906 break;
908 Known.makeNegative();
909 break;
910 default:
911 break;
912 }
913 }
914 return;
915 }
916
917 unsigned BitWidth = Known.getBitWidth();
918 auto m_V =
920
921 Value *Y;
922 const APInt *Mask, *C;
923 if (!match(RHS, m_APInt(C)))
924 return;
925
926 uint64_t ShAmt;
927 switch (Pred) {
929 // assume(V = C)
930 if (match(LHS, m_V)) {
931 Known = Known.unionWith(KnownBits::makeConstant(*C));
932 // assume(V & Mask = C)
933 } else if (match(LHS, m_c_And(m_V, m_Value(Y)))) {
934 // For one bits in Mask, we can propagate bits from C to V.
935 Known.One |= *C;
936 if (match(Y, m_APInt(Mask)))
937 Known.Zero |= ~*C & *Mask;
938 // assume(V | Mask = C)
939 } else if (match(LHS, m_c_Or(m_V, m_Value(Y)))) {
940 // For zero bits in Mask, we can propagate bits from C to V.
941 Known.Zero |= ~*C;
942 if (match(Y, m_APInt(Mask)))
943 Known.One |= *C & ~*Mask;
944 // assume(V << ShAmt = C)
945 } else if (match(LHS, m_Shl(m_V, m_ConstantInt(ShAmt))) &&
946 ShAmt < BitWidth) {
947 // For those bits in C that are known, we can propagate them to known
948 // bits in V shifted to the right by ShAmt.
950 RHSKnown >>= ShAmt;
951 Known = Known.unionWith(RHSKnown);
952 // assume(V >> ShAmt = C)
953 } else if (match(LHS, m_Shr(m_V, m_ConstantInt(ShAmt))) &&
954 ShAmt < BitWidth) {
955 // For those bits in RHS that are known, we can propagate them to known
956 // bits in V shifted to the right by C.
958 RHSKnown <<= ShAmt;
959 Known = Known.unionWith(RHSKnown);
960 }
961 break;
962 case ICmpInst::ICMP_NE: {
963 // assume (V & B != 0) where B is a power of 2
964 const APInt *BPow2;
965 if (C->isZero() && match(LHS, m_And(m_V, m_Power2(BPow2))))
966 Known.One |= *BPow2;
967 break;
968 }
969 default: {
970 const APInt *Offset = nullptr;
971 if (match(LHS, m_CombineOr(m_V, m_AddLike(m_V, m_APInt(Offset))))) {
973 if (Offset)
974 LHSRange = LHSRange.sub(*Offset);
975 Known = Known.unionWith(LHSRange.toKnownBits());
976 }
977 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
978 // X & Y u> C -> X u> C && Y u> C
979 // X nuw- Y u> C -> X u> C
980 if (match(LHS, m_c_And(m_V, m_Value())) ||
981 match(LHS, m_NUWSub(m_V, m_Value())))
982 Known.One.setHighBits(
983 (*C + (Pred == ICmpInst::ICMP_UGT)).countLeadingOnes());
984 }
985 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
986 // X | Y u< C -> X u< C && Y u< C
987 // X nuw+ Y u< C -> X u< C && Y u< C
988 if (match(LHS, m_c_Or(m_V, m_Value())) ||
989 match(LHS, m_c_NUWAdd(m_V, m_Value()))) {
990 Known.Zero.setHighBits(
991 (*C - (Pred == ICmpInst::ICMP_ULT)).countLeadingZeros());
992 }
993 }
994 } break;
995 }
996}
997
998static void computeKnownBitsFromICmpCond(const Value *V, ICmpInst *Cmp,
1000 const SimplifyQuery &SQ, bool Invert) {
1001 ICmpInst::Predicate Pred =
1002 Invert ? Cmp->getInversePredicate() : Cmp->getPredicate();
1003 Value *LHS = Cmp->getOperand(0);
1004 Value *RHS = Cmp->getOperand(1);
1005
1006 // Handle icmp pred (trunc V), C
1007 if (match(LHS, m_Trunc(m_Specific(V)))) {
1008 KnownBits DstKnown(LHS->getType()->getScalarSizeInBits());
1009 computeKnownBitsFromCmp(LHS, Pred, LHS, RHS, DstKnown, SQ);
1011 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1012 else
1013 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1014 return;
1015 }
1016
1017 computeKnownBitsFromCmp(V, Pred, LHS, RHS, Known, SQ);
1018}
1019
1021 KnownBits &Known, const SimplifyQuery &SQ,
1022 bool Invert, unsigned Depth) {
1023 Value *A, *B;
1026 KnownBits Known2(Known.getBitWidth());
1027 KnownBits Known3(Known.getBitWidth());
1028 computeKnownBitsFromCond(V, A, Known2, SQ, Invert, Depth + 1);
1029 computeKnownBitsFromCond(V, B, Known3, SQ, Invert, Depth + 1);
1030 if (Invert ? match(Cond, m_LogicalOr(m_Value(), m_Value()))
1032 Known2 = Known2.unionWith(Known3);
1033 else
1034 Known2 = Known2.intersectWith(Known3);
1035 Known = Known.unionWith(Known2);
1036 return;
1037 }
1038
1039 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
1040 computeKnownBitsFromICmpCond(V, Cmp, Known, SQ, Invert);
1041 return;
1042 }
1043
1044 if (match(Cond, m_Trunc(m_Specific(V)))) {
1045 KnownBits DstKnown(1);
1046 if (Invert) {
1047 DstKnown.setAllZero();
1048 } else {
1049 DstKnown.setAllOnes();
1050 }
1052 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1053 return;
1054 }
1055 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1056 return;
1057 }
1058
1060 computeKnownBitsFromCond(V, A, Known, SQ, !Invert, Depth + 1);
1061}
1062
1064 const SimplifyQuery &Q, unsigned Depth) {
1065 // Handle injected condition.
1066 if (Q.CC && Q.CC->AffectedValues.contains(V))
1068
1069 if (!Q.CxtI)
1070 return;
1071
1072 if (Q.DC && Q.DT) {
1073 // Handle dominating conditions.
1074 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
1075 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1076 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()))
1077 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1078 /*Invert*/ false, Depth);
1079
1080 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1081 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()))
1082 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1083 /*Invert*/ true, Depth);
1084 }
1085
1086 if (Known.hasConflict())
1087 Known.resetAll();
1088 }
1089
1090 if (!Q.AC)
1091 return;
1092
1093 unsigned BitWidth = Known.getBitWidth();
1094
1095 // Note that the patterns below need to be kept in sync with the code
1096 // in AssumptionCache::updateAffectedValues.
1097
1098 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
1099 if (!Elem.Assume)
1100 continue;
1101
1102 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
1103 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
1104 "Got assumption for the wrong function!");
1105
1106 if (Elem.Index != AssumptionCache::ExprResultIdx) {
1107 if (auto OBU = I->getOperandBundleAt(Elem.Index);
1108 getBundleAttrFromOBU(OBU) == BundleAttr::Align) {
1109 auto [Ptr, _, _2, Alignment, Offset] = getAssumeAlignInfo(OBU);
1110 if (Ptr == V && Alignment && Offset && isPowerOf2_64(*Alignment) &&
1112 Known.Zero |= (*Alignment - 1) & ~*Offset;
1113 Known.One |= (*Alignment - 1) & *Offset;
1114 }
1115 }
1116 continue;
1117 }
1118
1119 // Warning: This loop can end up being somewhat performance sensitive.
1120 // We're running this loop for once for each value queried resulting in a
1121 // runtime of ~O(#assumes * #values).
1122
1123 Value *Arg = I->getArgOperand(0);
1124
1125 if (Arg == V && isValidAssumeForContext(I, Q)) {
1126 assert(BitWidth == 1 && "assume operand is not i1?");
1127 (void)BitWidth;
1128 Known.setAllOnes();
1129 return;
1130 }
1131 if (match(Arg, m_Not(m_Specific(V))) &&
1133 assert(BitWidth == 1 && "assume operand is not i1?");
1134 (void)BitWidth;
1135 Known.setAllZero();
1136 return;
1137 }
1138 auto *Trunc = dyn_cast<TruncInst>(Arg);
1139 if (Trunc && Trunc->getOperand(0) == V &&
1141 if (Trunc->hasNoUnsignedWrap()) {
1143 return;
1144 }
1145 Known.One.setBit(0);
1146 return;
1147 }
1148
1149 // The remaining tests are all recursive, so bail out if we hit the limit.
1151 continue;
1152
1153 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
1154 if (!Cmp)
1155 continue;
1156
1157 if (!isValidAssumeForContext(I, Q))
1158 continue;
1159
1160 computeKnownBitsFromICmpCond(V, Cmp, Known, Q, /*Invert=*/false);
1161 }
1162
1163 // Conflicting assumption: Undefined behavior will occur on this execution
1164 // path.
1165 if (Known.hasConflict())
1166 Known.resetAll();
1167}
1168
1169/// Compute known bits from a shift operator, including those with a
1170/// non-constant shift amount. Known is the output of this function. Known2 is a
1171/// pre-allocated temporary with the same bit width as Known and on return
1172/// contains the known bit of the shift value source. KF is an
1173/// operator-specific function that, given the known-bits and a shift amount,
1174/// compute the implied known-bits of the shift operator's result respectively
1175/// for that shift amount. The results from calling KF are conservatively
1176/// combined for all permitted shift amounts.
1178 const Operator *I, const APInt &DemandedElts, KnownBits &Known,
1179 KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth,
1180 function_ref<KnownBits(const KnownBits &, const KnownBits &, bool)> KF) {
1181 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1182 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1183 // To limit compile-time impact, only query isKnownNonZero() if we know at
1184 // least something about the shift amount.
1185 bool ShAmtNonZero =
1186 Known.isNonZero() ||
1187 (Known.getMaxValue().ult(Known.getBitWidth()) &&
1188 isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth + 1));
1189 Known = KF(Known2, Known, ShAmtNonZero);
1190}
1191
1192static KnownBits
1193getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts,
1194 const KnownBits &KnownLHS, const KnownBits &KnownRHS,
1195 const SimplifyQuery &Q, unsigned Depth) {
1196 unsigned BitWidth = KnownLHS.getBitWidth();
1197 KnownBits KnownOut(BitWidth);
1198 bool IsAnd = false;
1199 bool HasKnownOne = !KnownLHS.One.isZero() || !KnownRHS.One.isZero();
1200 Value *X = nullptr, *Y = nullptr;
1201
1202 switch (I->getOpcode()) {
1203 case Instruction::And:
1204 KnownOut = KnownLHS & KnownRHS;
1205 IsAnd = true;
1206 // and(x, -x) is common idioms that will clear all but lowest set
1207 // bit. If we have a single known bit in x, we can clear all bits
1208 // above it.
1209 // TODO: instcombine often reassociates independent `and` which can hide
1210 // this pattern. Try to match and(x, and(-x, y)) / and(and(x, y), -x).
1211 if (HasKnownOne && match(I, m_c_And(m_Value(X), m_Neg(m_Deferred(X))))) {
1212 // -(-x) == x so using whichever (LHS/RHS) gets us a better result.
1213 if (KnownLHS.countMaxTrailingZeros() <= KnownRHS.countMaxTrailingZeros())
1214 KnownOut = KnownLHS.blsi();
1215 else
1216 KnownOut = KnownRHS.blsi();
1217 }
1218 break;
1219 case Instruction::Or:
1220 KnownOut = KnownLHS | KnownRHS;
1221 break;
1222 case Instruction::Xor:
1223 KnownOut = KnownLHS ^ KnownRHS;
1224 // xor(x, x-1) is common idioms that will clear all but lowest set
1225 // bit. If we have a single known bit in x, we can clear all bits
1226 // above it.
1227 // TODO: xor(x, x-1) is often rewritting as xor(x, x-C) where C !=
1228 // -1 but for the purpose of demanded bits (xor(x, x-C) &
1229 // Demanded) == (xor(x, x-1) & Demanded). Extend the xor pattern
1230 // to use arbitrary C if xor(x, x-C) as the same as xor(x, x-1).
1231 if (HasKnownOne &&
1233 const KnownBits &XBits = I->getOperand(0) == X ? KnownLHS : KnownRHS;
1234 KnownOut = XBits.blsmsk();
1235 }
1236 break;
1237 default:
1238 llvm_unreachable("Invalid Op used in 'analyzeKnownBitsFromAndXorOr'");
1239 }
1240
1241 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
1242 // xor/or(x, add (x, -1)) is an idiom that will always set the low bit.
1243 // here we handle the more general case of adding any odd number by
1244 // matching the form and/xor/or(x, add(x, y)) where y is odd.
1245 // TODO: This could be generalized to clearing any bit set in y where the
1246 // following bit is known to be unset in y.
1247 if (!KnownOut.Zero[0] && !KnownOut.One[0] &&
1251 KnownBits KnownY(BitWidth);
1252 computeKnownBits(Y, DemandedElts, KnownY, Q, Depth + 1);
1253 if (KnownY.countMinTrailingOnes() > 0) {
1254 if (IsAnd)
1255 KnownOut.Zero.setBit(0);
1256 else
1257 KnownOut.One.setBit(0);
1258 }
1259 }
1260 return KnownOut;
1261}
1262
1264 const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q,
1265 unsigned Depth,
1266 const function_ref<KnownBits(const KnownBits &, const KnownBits &)>
1267 KnownBitsFunc) {
1268 APInt DemandedEltsLHS, DemandedEltsRHS;
1270 DemandedElts, DemandedEltsLHS,
1271 DemandedEltsRHS);
1272
1273 const auto ComputeForSingleOpFunc =
1274 [Depth, &Q, KnownBitsFunc](const Value *Op, APInt &DemandedEltsOp) {
1275 return KnownBitsFunc(
1276 computeKnownBits(Op, DemandedEltsOp, Q, Depth + 1),
1277 computeKnownBits(Op, DemandedEltsOp << 1, Q, Depth + 1));
1278 };
1279
1280 if (DemandedEltsRHS.isZero())
1281 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS);
1282 if (DemandedEltsLHS.isZero())
1283 return ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS);
1284
1285 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS)
1286 .intersectWith(ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS));
1287}
1288
1289// Public so this can be used in `SimplifyDemandedUseBits`.
1291 const KnownBits &KnownLHS,
1292 const KnownBits &KnownRHS,
1293 const SimplifyQuery &SQ,
1294 unsigned Depth) {
1295 auto *FVTy = dyn_cast<FixedVectorType>(I->getType());
1296 APInt DemandedElts =
1297 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
1298
1299 return getKnownBitsFromAndXorOr(I, DemandedElts, KnownLHS, KnownRHS, SQ,
1300 Depth);
1301}
1302
1304 Attribute Attr = F->getFnAttribute(Attribute::VScaleRange);
1305 // Without vscale_range, we only know that vscale is non-zero.
1306 if (!Attr.isValid())
1308
1309 unsigned AttrMin = Attr.getVScaleRangeMin();
1310 // Minimum is larger than vscale width, result is always poison.
1311 if ((unsigned)llvm::bit_width(AttrMin) > BitWidth)
1312 return ConstantRange::getEmpty(BitWidth);
1313
1314 APInt Min(BitWidth, AttrMin);
1315 std::optional<unsigned> AttrMax = Attr.getVScaleRangeMax();
1316 if (!AttrMax || (unsigned)llvm::bit_width(*AttrMax) > BitWidth)
1318
1319 return ConstantRange(Min, APInt(BitWidth, *AttrMax) + 1);
1320}
1321
1322/// Return true if \p II reads a register named "vlenb". On RISC-V this is the
1323/// VLENB CSR, which holds VLEN/8: a non-zero power of two bounded by the
1324/// target's VLEN range. Callers must ensure the target is RISC-V.
1325static bool isReadVLENB(const IntrinsicInst &II) {
1326 auto *MAV = dyn_cast<MetadataAsValue>(II.getArgOperand(0));
1327 if (!MAV)
1328 return false;
1329 auto *MD = dyn_cast<MDNode>(MAV->getMetadata());
1330 if (!MD || MD->getNumOperands() != 1)
1331 return false;
1332 auto *RegName = dyn_cast<MDString>(MD->getOperand(0));
1333 return RegName && RegName->getString() == "vlenb";
1334}
1335
1336/// Return the value range of a RISC-V vlenb CSR read. RVV requires VLEN to be a
1337/// power of two in [32, 65536] (Zvl32b is the smallest vector extension), so
1338/// VLENB = VLEN/8 is in [4, 8192]. This architectural bound is independent of
1339/// any function attribute and stays sound for Zvl32b, whose VLEN (32) is not
1340/// representable as an integer vscale (VLEN / RVVBitsPerBlock). A vscale_range
1341/// attribute, when present, pins the subtarget's VLEN in units of
1342/// RVVBitsPerBlock (64 bits) and so gives a tighter VLENB = vscale *
1343/// RVVBytesPerBlock.
1345 unsigned Width) {
1346 // Architectural bounds: VLEN in [32, 65536] => VLENB in [4, 8192].
1347 ConstantRange Range(APInt(Width, 32 / 8), APInt(Width, 65536 / 8) + 1);
1348
1349 const Function *F = II.getFunction();
1350 if (F->getFnAttribute(Attribute::VScaleRange).isValid()) {
1351 ConstantRange VScale = getVScaleRange(F, Width);
1352 Range = Range.intersectWith(
1354 }
1355 return Range;
1356}
1357
1359 Value *Arm, bool Invert,
1360 const SimplifyQuery &Q, unsigned Depth) {
1361 // If we have a constant arm, we are done.
1362 if (Known.isConstant())
1363 return;
1364
1365 // See what condition implies about the bits of the select arm.
1366 KnownBits CondRes(Known.getBitWidth());
1367 computeKnownBitsFromCond(Arm, Cond, CondRes, Q, Invert, Depth + 1);
1368 // If we don't get any information from the condition, no reason to
1369 // proceed.
1370 if (CondRes.isUnknown())
1371 return;
1372
1373 // We can have conflict if the condition is dead. I.e if we have
1374 // (x | 64) < 32 ? (x | 64) : y
1375 // we will have conflict at bit 6 from the condition/the `or`.
1376 // In that case just return. Its not particularly important
1377 // what we do, as this select is going to be simplified soon.
1378 CondRes = CondRes.unionWith(Known);
1379 if (CondRes.hasConflict())
1380 return;
1381
1382 // Finally make sure the information we found is valid. This is relatively
1383 // expensive so it's left for the very end.
1384 if (!isGuaranteedNotToBeUndef(Arm, Q.AC, Q.CxtI, Q.DT, Depth + 1))
1385 return;
1386
1387 // Finally, we know we get information from the condition and its valid,
1388 // so return it.
1389 Known = std::move(CondRes);
1390}
1391
1392// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
1393// Returns the input and lower/upper bounds.
1394static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
1395 const APInt *&CLow, const APInt *&CHigh) {
1397 cast<Operator>(Select)->getOpcode() == Instruction::Select &&
1398 "Input should be a Select!");
1399
1400 const Value *LHS = nullptr, *RHS = nullptr;
1402 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
1403 return false;
1404
1405 if (!match(RHS, m_APInt(CLow)))
1406 return false;
1407
1408 const Value *LHS2 = nullptr, *RHS2 = nullptr;
1410 if (getInverseMinMaxFlavor(SPF) != SPF2)
1411 return false;
1412
1413 if (!match(RHS2, m_APInt(CHigh)))
1414 return false;
1415
1416 if (SPF == SPF_SMIN)
1417 std::swap(CLow, CHigh);
1418
1419 In = LHS2;
1420 return CLow->sle(*CHigh);
1421}
1422
1424 const APInt *&CLow,
1425 const APInt *&CHigh) {
1426 assert((II->getIntrinsicID() == Intrinsic::smin ||
1427 II->getIntrinsicID() == Intrinsic::smax) &&
1428 "Must be smin/smax");
1429
1430 Intrinsic::ID InverseID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
1431 auto *InnerII = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
1432 if (!InnerII || InnerII->getIntrinsicID() != InverseID ||
1433 !match(II->getArgOperand(1), m_APInt(CLow)) ||
1434 !match(InnerII->getArgOperand(1), m_APInt(CHigh)))
1435 return false;
1436
1437 if (II->getIntrinsicID() == Intrinsic::smin)
1438 std::swap(CLow, CHigh);
1439 return CLow->sle(*CHigh);
1440}
1441
1443 KnownBits &Known) {
1444 const APInt *CLow, *CHigh;
1445 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
1446 Known = Known.unionWith(
1447 ConstantRange::getNonEmpty(*CLow, *CHigh + 1).toKnownBits());
1448}
1449
1451 const APInt &DemandedElts,
1453 const SimplifyQuery &Q,
1454 unsigned Depth) {
1455 unsigned BitWidth = Known.getBitWidth();
1456
1457 KnownBits Known2(BitWidth);
1458 switch (I->getOpcode()) {
1459 default: break;
1460 case Instruction::Load:
1461 if (MDNode *MD =
1462 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
1464 break;
1465 case Instruction::And:
1466 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1467 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1468
1469 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1470 break;
1471 case Instruction::Or:
1472 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1473 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1474
1475 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1476 break;
1477 case Instruction::Xor:
1478 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1479 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1480
1481 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1482 break;
1483 case Instruction::Mul: {
1486 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, NUW,
1487 DemandedElts, Known, Known2, Q, Depth);
1488 break;
1489 }
1490 case Instruction::UDiv: {
1491 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1492 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1493 Known =
1495 break;
1496 }
1497 case Instruction::SDiv: {
1498 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1499 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1500 Known =
1502 break;
1503 }
1504 case Instruction::Select: {
1505 auto ComputeForArm = [&](Value *Arm, bool Invert) {
1506 KnownBits Res(Known.getBitWidth());
1507 computeKnownBits(Arm, DemandedElts, Res, Q, Depth + 1);
1508 adjustKnownBitsForSelectArm(Res, I->getOperand(0), Arm, Invert, Q, Depth);
1509 return Res;
1510 };
1511 // Only known if known in both the LHS and RHS.
1512 Known =
1513 ComputeForArm(I->getOperand(1), /*Invert=*/false)
1514 .intersectWith(ComputeForArm(I->getOperand(2), /*Invert=*/true));
1515 break;
1516 }
1517 case Instruction::FPToSI: {
1518 // fptosi is poison if the rounded value doesn't fit in the result type,
1519 // so we can assume the conversion is well-defined and rounds towards
1520 // zero. +-Inf can never fit in an integer type, so it is always poison,
1521 // like NaN. Negative subnormals and negative zero round to 0. That
1522 // leaves negative normals as the only class that can produce a defined
1523 // negative result.
1524 KnownFPClass SrcFPClass = computeKnownFPClass(
1525 I->getOperand(0), DemandedElts, fcNegNormal, Q, Depth + 1);
1526 if (SrcFPClass.isKnownNever(fcNegNormal))
1527 Known.makeNonNegative();
1528 break;
1529 }
1530 case Instruction::FPTrunc:
1531 case Instruction::FPExt:
1532 case Instruction::FPToUI:
1533 case Instruction::SIToFP:
1534 case Instruction::UIToFP:
1535 break; // Can't work with floating point.
1536 case Instruction::PtrToInt:
1537 case Instruction::PtrToAddr:
1538 case Instruction::IntToPtr:
1539 // Fall through and handle them the same as zext/trunc.
1540 [[fallthrough]];
1541 case Instruction::ZExt:
1542 case Instruction::Trunc: {
1543 Type *SrcTy = I->getOperand(0)->getType();
1544
1545 unsigned SrcBitWidth;
1546 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1547 // which fall through here.
1548 Type *ScalarTy = SrcTy->getScalarType();
1549 SrcBitWidth = ScalarTy->isPointerTy() ?
1550 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
1551 Q.DL.getTypeSizeInBits(ScalarTy);
1552
1553 assert(SrcBitWidth && "SrcBitWidth can't be zero");
1554 Known = Known.anyextOrTrunc(SrcBitWidth);
1555 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1556 if (auto *Inst = dyn_cast<PossiblyNonNegInst>(I);
1557 Inst && Inst->hasNonNeg() && !Known.isNegative())
1558 Known.makeNonNegative();
1559 Known = Known.zextOrTrunc(BitWidth);
1560 break;
1561 }
1562 case Instruction::BitCast: {
1563 Type *SrcTy = I->getOperand(0)->getType();
1564 if (SrcTy->isIntOrPtrTy() &&
1565 // TODO: For now, not handling conversions like:
1566 // (bitcast i64 %x to <2 x i32>)
1567 !I->getType()->isVectorTy()) {
1568 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1569 break;
1570 }
1571
1572 const Value *V;
1573 // Handle bitcast from floating point to integer.
1574 if (match(I, m_ElementWiseBitCast(m_Value(V))) &&
1575 V->getType()->isFPOrFPVectorTy()) {
1576 Type *FPType = V->getType()->getScalarType();
1577 KnownFPClass Result =
1578 computeKnownFPClass(V, DemandedElts, fcAllFlags, Q, Depth + 1);
1579
1580 Known = Result.toKnownBits(FPType->getFltSemantics());
1581
1582 break;
1583 }
1584
1585 // Handle cast from vector integer type to scalar or vector integer.
1586 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcTy);
1587 if (!SrcVecTy || !SrcVecTy->getElementType()->isIntegerTy() ||
1588 !I->getType()->isIntOrIntVectorTy() ||
1589 isa<ScalableVectorType>(I->getType()))
1590 break;
1591
1592 unsigned NumElts = DemandedElts.getBitWidth();
1593 bool IsLE = Q.DL.isLittleEndian();
1594 // Look through a cast from narrow vector elements to wider type.
1595 // Examples: v4i32 -> v2i64, v3i8 -> v24
1596 unsigned SubBitWidth = SrcVecTy->getScalarSizeInBits();
1597 if (BitWidth % SubBitWidth == 0) {
1598 // Known bits are automatically intersected across demanded elements of a
1599 // vector. So for example, if a bit is computed as known zero, it must be
1600 // zero across all demanded elements of the vector.
1601 //
1602 // For this bitcast, each demanded element of the output is sub-divided
1603 // across a set of smaller vector elements in the source vector. To get
1604 // the known bits for an entire element of the output, compute the known
1605 // bits for each sub-element sequentially. This is done by shifting the
1606 // one-set-bit demanded elements parameter across the sub-elements for
1607 // consecutive calls to computeKnownBits. We are using the demanded
1608 // elements parameter as a mask operator.
1609 //
1610 // The known bits of each sub-element are then inserted into place
1611 // (dependent on endian) to form the full result of known bits.
1612 unsigned SubScale = BitWidth / SubBitWidth;
1613 APInt SubDemandedElts = APInt::getZero(NumElts * SubScale);
1614 for (unsigned i = 0; i != NumElts; ++i) {
1615 if (DemandedElts[i])
1616 SubDemandedElts.setBit(i * SubScale);
1617 }
1618
1619 KnownBits KnownSrc(SubBitWidth);
1620 for (unsigned i = 0; i != SubScale; ++i) {
1621 computeKnownBits(I->getOperand(0), SubDemandedElts.shl(i), KnownSrc, Q,
1622 Depth + 1);
1623 unsigned ShiftElt = IsLE ? i : SubScale - 1 - i;
1624 Known.insertBits(KnownSrc, ShiftElt * SubBitWidth);
1625 }
1626 }
1627 // Look through a cast from wider vector elements to narrow type.
1628 // Examples: v2i64 -> v4i32
1629 if (SubBitWidth % BitWidth == 0) {
1630 unsigned SubScale = SubBitWidth / BitWidth;
1631 KnownBits KnownSrc(SubBitWidth);
1632 APInt SubDemandedElts =
1633 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
1634 computeKnownBits(I->getOperand(0), SubDemandedElts, KnownSrc, Q,
1635 Depth + 1);
1636
1637 Known.setAllConflict();
1638 for (unsigned i = 0; i != NumElts; ++i) {
1639 if (DemandedElts[i]) {
1640 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
1641 unsigned Offset = (Shifts % SubScale) * BitWidth;
1642 Known = Known.intersectWith(KnownSrc.extractBits(BitWidth, Offset));
1643 if (Known.isUnknown())
1644 break;
1645 }
1646 }
1647 }
1648 break;
1649 }
1650 case Instruction::SExt: {
1651 // Compute the bits in the result that are not present in the input.
1652 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1653
1654 Known = Known.trunc(SrcBitWidth);
1655 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1656 // If the sign bit of the input is known set or clear, then we know the
1657 // top bits of the result.
1658 Known = Known.sext(BitWidth);
1659 break;
1660 }
1661 case Instruction::Shl: {
1664 auto KF = [NUW, NSW](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1665 bool ShAmtNonZero) {
1666 return KnownBits::shl(KnownVal, KnownAmt, NUW, NSW, ShAmtNonZero);
1667 };
1668 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1669 KF);
1670 // Trailing zeros of a right-shifted constant never decrease.
1671 const APInt *C;
1672 if (match(I->getOperand(0), m_APInt(C)))
1673 Known.Zero.setLowBits(C->countr_zero());
1674
1675 // shl X, sub(Y, xor(ctlz(X, true), BitWidth-1)) shifts X so that its MSB
1676 // lands at bit Y, when BitWidth is a power of 2.
1677 const APInt *YC;
1678 Value *X = I->getOperand(0);
1679 if (isPowerOf2_32(BitWidth) &&
1680 match(I->getOperand(1),
1682 m_SpecificInt(BitWidth - 1)))) &&
1683 YC->ult(BitWidth - 1)) {
1684 unsigned Y = YC->getZExtValue();
1685 Known.One.setBit(Y);
1686 Known.Zero.setBitsFrom(Y + 1);
1687 }
1688 break;
1689 }
1690 case Instruction::LShr: {
1691 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1692 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1693 bool ShAmtNonZero) {
1694 return KnownBits::lshr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1695 };
1696 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1697 KF);
1698 // Leading zeros of a left-shifted constant never decrease.
1699 const APInt *C;
1700 if (match(I->getOperand(0), m_APInt(C)))
1701 Known.Zero.setHighBits(C->countl_zero());
1702 break;
1703 }
1704 case Instruction::AShr: {
1705 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1706 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1707 bool ShAmtNonZero) {
1708 return KnownBits::ashr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1709 };
1710 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1711 KF);
1712 break;
1713 }
1714 case Instruction::Sub: {
1717 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW, NUW,
1718 DemandedElts, Known, Known2, Q, Depth);
1719 break;
1720 }
1721 case Instruction::Add: {
1724 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW, NUW,
1725 DemandedElts, Known, Known2, Q, Depth);
1726 break;
1727 }
1728 case Instruction::SRem:
1729 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1730 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1731 Known = KnownBits::srem(Known, Known2);
1732 break;
1733
1734 case Instruction::URem:
1735 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1736 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1737 Known = KnownBits::urem(Known, Known2);
1738 break;
1739 case Instruction::Alloca:
1740 Known.Zero.setLowBits(Log2(cast<AllocaInst>(I)->getAlign()));
1741 break;
1742 case Instruction::GetElementPtr: {
1743 // Analyze all of the subscripts of this getelementptr instruction
1744 // to determine if we can prove known low zero bits.
1745 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1746 // Accumulate the constant indices in a separate variable
1747 // to minimize the number of calls to computeForAddSub.
1748 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(I->getType());
1749 APInt AccConstIndices(IndexWidth, 0);
1750
1751 auto AddIndexToKnown = [&](KnownBits IndexBits) {
1752 if (IndexWidth == BitWidth) {
1753 // Note that inbounds does *not* guarantee nsw for the addition, as only
1754 // the offset is signed, while the base address is unsigned.
1755 Known = KnownBits::add(Known, IndexBits);
1756 } else {
1757 // If the index width is smaller than the pointer width, only add the
1758 // value to the low bits.
1759 assert(IndexWidth < BitWidth &&
1760 "Index width can't be larger than pointer width");
1761 Known.insertBits(KnownBits::add(Known.trunc(IndexWidth), IndexBits), 0);
1762 }
1763 };
1764
1766 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1767 // TrailZ can only become smaller, short-circuit if we hit zero.
1768 if (Known.isUnknown())
1769 break;
1770
1771 Value *Index = I->getOperand(i);
1772
1773 // Handle case when index is zero.
1774 Constant *CIndex = dyn_cast<Constant>(Index);
1775 if (CIndex && CIndex->isNullValue())
1776 continue;
1777
1778 if (StructType *STy = GTI.getStructTypeOrNull()) {
1779 // Handle struct member offset arithmetic.
1780
1781 assert(CIndex &&
1782 "Access to structure field must be known at compile time");
1783
1784 if (CIndex->getType()->isVectorTy())
1785 Index = CIndex->getSplatValue();
1786
1787 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1788 const StructLayout *SL = Q.DL.getStructLayout(STy);
1789 uint64_t Offset = SL->getElementOffset(Idx);
1790 AccConstIndices += Offset;
1791 continue;
1792 }
1793
1794 // Handle array index arithmetic.
1795 Type *IndexedTy = GTI.getIndexedType();
1796 if (!IndexedTy->isSized()) {
1797 Known.resetAll();
1798 break;
1799 }
1800
1801 TypeSize Stride = GTI.getSequentialElementStride(Q.DL);
1802 uint64_t StrideInBytes = Stride.getKnownMinValue();
1803 if (!Stride.isScalable()) {
1804 // Fast path for constant offset.
1805 if (auto *CI = dyn_cast<ConstantInt>(Index)) {
1806 AccConstIndices +=
1807 CI->getValue().sextOrTrunc(IndexWidth) * StrideInBytes;
1808 continue;
1809 }
1810 }
1811
1812 KnownBits IndexBits =
1813 computeKnownBits(Index, Q, Depth + 1).sextOrTrunc(IndexWidth);
1814 KnownBits ScalingFactor(IndexWidth);
1815 // Multiply by current sizeof type.
1816 // &A[i] == A + i * sizeof(*A[i]).
1817 if (Stride.isScalable()) {
1818 // For scalable types the only thing we know about sizeof is
1819 // that this is a multiple of the minimum size.
1820 ScalingFactor.Zero.setLowBits(llvm::countr_zero(StrideInBytes));
1821 } else {
1822 ScalingFactor =
1823 KnownBits::makeConstant(APInt(IndexWidth, StrideInBytes));
1824 }
1825 AddIndexToKnown(KnownBits::mul(IndexBits, ScalingFactor));
1826 }
1827 if (!Known.isUnknown() && !AccConstIndices.isZero())
1828 AddIndexToKnown(KnownBits::makeConstant(AccConstIndices));
1829 break;
1830 }
1831 case Instruction::PHI: {
1832 const PHINode *P = cast<PHINode>(I);
1833 BinaryOperator *BO = nullptr;
1834 Value *Start = nullptr, *Step = nullptr;
1835 KnownBits &KnownStart = Known2;
1836 if (matchSimpleRecurrence(P, BO, Start, Step)) {
1837 // Handle the case of a simple two-predecessor recurrence PHI.
1838 // There's a lot more that could theoretically be done here, but
1839 // this is sufficient to catch some interesting cases.
1840 unsigned Opcode = BO->getOpcode();
1841
1842 switch (Opcode) {
1843 // If this is a shift recurrence, we know the bits being shifted in. We
1844 // can combine that with information about the start value of the
1845 // recurrence to conclude facts about the result. If this is a udiv
1846 // recurrence, we know that the result can never exceed either the
1847 // numerator or the start value, whichever is greater.
1848 case Instruction::LShr:
1849 case Instruction::AShr:
1850 case Instruction::Shl:
1851 case Instruction::UDiv:
1852 if (BO->getOperand(0) != I)
1853 break;
1854 [[fallthrough]];
1855
1856 // For a urem recurrence, the result can never exceed the start value. The
1857 // phi could either be the numerator or the denominator.
1858 case Instruction::URem: {
1859 // We have matched a recurrence of the form:
1860 // %iv = [R, %entry], [%iv.next, %backedge]
1861 // %iv.next = shift_op %iv, L
1862
1863 // Recurse with the phi context to avoid concern about whether facts
1864 // inferred hold at original context instruction. TODO: It may be
1865 // correct to use the original context. IF warranted, explore and
1866 // add sufficient tests to cover.
1868 RecQ.CxtI = P;
1869 computeKnownBits(Start, DemandedElts, KnownStart, RecQ, Depth + 1);
1870 switch (Opcode) {
1871 case Instruction::Shl:
1872 // A shl recurrence will only increase the tailing zeros
1873 Known.Zero.setLowBits(KnownStart.countMinTrailingZeros());
1874 break;
1875 case Instruction::LShr:
1876 case Instruction::UDiv:
1877 case Instruction::URem:
1878 // lshr, udiv, and urem recurrences will preserve the leading zeros of
1879 // the start value.
1880 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
1881 break;
1882 case Instruction::AShr:
1883 // An ashr recurrence will extend the initial sign bit
1884 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
1885 Known.One.setHighBits(KnownStart.countMinLeadingOnes());
1886 break;
1887 }
1888 break;
1889 }
1890
1891 // Check for operations that have the property that if
1892 // both their operands have low zero bits, the result
1893 // will have low zero bits.
1894 case Instruction::Add:
1895 case Instruction::Sub:
1896 case Instruction::And:
1897 case Instruction::Or:
1898 case Instruction::Mul: {
1899 // Change the context instruction to the "edge" that flows into the
1900 // phi. This is important because that is where the value is actually
1901 // "evaluated" even though it is used later somewhere else. (see also
1902 // D69571).
1904
1905 unsigned OpNum = P->getOperand(0) == Start ? 0 : 1;
1906 Instruction *StartTerm = P->getIncomingBlock(OpNum)->getTerminator();
1907 Instruction *LatchTerm =
1908 P->getIncomingBlock(1 - OpNum)->getTerminator();
1909
1910 // Ok, we have a recurrence of the form {Start,op,Step}. Check for low
1911 // zero bits.
1912 RecQ.CxtI = StartTerm;
1913 computeKnownBits(Start, DemandedElts, KnownStart, RecQ, Depth + 1);
1914
1915 // We need to take the minimum number of known bits.
1916 // The step may be loop-variant, so make sure we don't make use of
1917 // any conditions that only hold on the last iteration.
1918 KnownBits KnownStep(BitWidth);
1919 RecQ.CxtI = LatchTerm;
1920 computeKnownBits(Step, DemandedElts, KnownStep, RecQ, Depth + 1);
1921
1922 Known.Zero.setLowBits(std::min(KnownStart.countMinTrailingZeros(),
1923 KnownStep.countMinTrailingZeros()));
1924
1925 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO);
1926 if (!OverflowOp || !Q.IIQ.hasNoSignedWrap(OverflowOp))
1927 break;
1928
1929 switch (Opcode) {
1930 // If initial value of recurrence is nonnegative, and we are adding
1931 // a nonnegative number with nsw, the result can only be nonnegative
1932 // or poison value regardless of the number of times we execute the
1933 // add in phi recurrence. If initial value is negative and we are
1934 // adding a negative number with nsw, the result can only be
1935 // negative or poison value. Similar arguments apply to sub and mul.
1936 //
1937 // (add non-negative, non-negative) --> non-negative
1938 // (add negative, negative) --> negative
1939 case Instruction::Add: {
1940 if (KnownStart.isNonNegative() && KnownStep.isNonNegative())
1941 Known.makeNonNegative();
1942 else if (KnownStart.isNegative() && KnownStep.isNegative())
1943 Known.makeNegative();
1944 break;
1945 }
1946
1947 // (sub nsw non-negative, negative) --> non-negative
1948 // (sub nsw negative, non-negative) --> negative
1949 case Instruction::Sub: {
1950 if (BO->getOperand(0) != I)
1951 break;
1952 if (KnownStart.isNonNegative() && KnownStep.isNegative())
1953 Known.makeNonNegative();
1954 else if (KnownStart.isNegative() && KnownStep.isNonNegative())
1955 Known.makeNegative();
1956 break;
1957 }
1958
1959 // (mul nsw non-negative, non-negative) --> non-negative
1960 case Instruction::Mul:
1961 if (KnownStart.isNonNegative() && KnownStep.isNonNegative())
1962 Known.makeNonNegative();
1963 break;
1964
1965 default:
1966 break;
1967 }
1968 break;
1969 }
1970
1971 default:
1972 break;
1973 }
1974 }
1975
1976 // Unreachable blocks may have zero-operand PHI nodes.
1977 if (P->getNumIncomingValues() == 0)
1978 break;
1979
1980 // Otherwise take the unions of the known bit sets of the operands,
1981 // taking conservative care to avoid excessive recursion.
1982 if (Depth < MaxAnalysisRecursionDepth - 1 && Known.isUnknown()) {
1983 // Skip if every incoming value references to ourself.
1984 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
1985 break;
1986
1987 Known.setAllConflict();
1988 for (const Use &U : P->operands()) {
1989 Value *IncValue;
1990 const PHINode *CxtPhi;
1991 Instruction *CxtI;
1992 breakSelfRecursivePHI(&U, P, IncValue, CxtI, &CxtPhi);
1993 // Skip direct self references.
1994 if (IncValue == P)
1995 continue;
1996
1997 // Change the context instruction to the "edge" that flows into the
1998 // phi. This is important because that is where the value is actually
1999 // "evaluated" even though it is used later somewhere else. (see also
2000 // D69571).
2002
2003 Known2 = KnownBits(BitWidth);
2004
2005 // Recurse, but cap the recursion to one level, because we don't
2006 // want to waste time spinning around in loops.
2007 // TODO: See if we can base recursion limiter on number of incoming phi
2008 // edges so we don't overly clamp analysis.
2009 computeKnownBits(IncValue, DemandedElts, Known2, RecQ,
2011
2012 // See if we can further use a conditional branch into the phi
2013 // to help us determine the range of the value.
2014 if (!Known2.isConstant()) {
2015 CmpPredicate Pred;
2016 const APInt *RHSC;
2017 BasicBlock *TrueSucc, *FalseSucc;
2018 // TODO: Use RHS Value and compute range from its known bits.
2019 if (match(RecQ.CxtI,
2020 m_Br(m_c_ICmp(Pred, m_Specific(IncValue), m_APInt(RHSC)),
2021 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
2022 // Check for cases of duplicate successors.
2023 if ((TrueSucc == CxtPhi->getParent()) !=
2024 (FalseSucc == CxtPhi->getParent())) {
2025 // If we're using the false successor, invert the predicate.
2026 if (FalseSucc == CxtPhi->getParent())
2027 Pred = CmpInst::getInversePredicate(Pred);
2028 // Get the knownbits implied by the incoming phi condition.
2029 auto CR = ConstantRange::makeExactICmpRegion(Pred, *RHSC);
2030 KnownBits KnownUnion = Known2.unionWith(CR.toKnownBits());
2031 // We can have conflicts here if we are analyzing deadcode (its
2032 // impossible for us reach this BB based the icmp).
2033 if (KnownUnion.hasConflict()) {
2034 // No reason to continue analyzing in a known dead region, so
2035 // just resetAll and break. This will cause us to also exit the
2036 // outer loop.
2037 Known.resetAll();
2038 break;
2039 }
2040 Known2 = KnownUnion;
2041 }
2042 }
2043 }
2044
2045 Known = Known.intersectWith(Known2);
2046 // If all bits have been ruled out, there's no need to check
2047 // more operands.
2048 if (Known.isUnknown())
2049 break;
2050 }
2051 }
2052 break;
2053 }
2054 case Instruction::Call:
2055 case Instruction::Invoke: {
2056 // If range metadata is attached to this call, set known bits from that,
2057 // and then intersect with known bits based on other properties of the
2058 // function.
2059 if (MDNode *MD =
2060 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
2062
2063 const auto *CB = cast<CallBase>(I);
2064
2065 if (std::optional<ConstantRange> Range = CB->getRange())
2066 Known = Known.unionWith(Range->toKnownBits());
2067
2068 if (const Value *RV = CB->getReturnedArgOperand()) {
2069 if (RV->getType() == I->getType()) {
2070 computeKnownBits(RV, Known2, Q, Depth + 1);
2071 Known = Known.unionWith(Known2);
2072 // If the function doesn't return properly for all input values
2073 // (e.g. unreachable exits) then there might be conflicts between the
2074 // argument value and the range metadata. Simply discard the known bits
2075 // in case of conflicts.
2076 if (Known.hasConflict())
2077 Known.resetAll();
2078 }
2079 }
2080 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2081 switch (II->getIntrinsicID()) {
2082 default:
2083 break;
2084 case Intrinsic::abs: {
2085 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2086 bool IntMinIsPoison = match(II->getArgOperand(1), m_One());
2087 Known = Known.unionWith(Known2.abs(IntMinIsPoison));
2088 break;
2089 }
2090 case Intrinsic::bitreverse:
2091 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2092 Known = Known.unionWith(Known2.reverseBits());
2093 break;
2094 case Intrinsic::bswap:
2095 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2096 Known = Known.unionWith(Known2.byteSwap());
2097 break;
2098 case Intrinsic::ctlz: {
2099 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2100 // If we have a known 1, its position is our upper bound.
2101 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2102 // If this call is poison for 0 input, the result will be less than 2^n.
2103 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2104 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
2105 unsigned LowBits = llvm::bit_width(PossibleLZ);
2106 Known.Zero.setBitsFrom(LowBits);
2107 break;
2108 }
2109 case Intrinsic::cttz: {
2110 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2111 // If we have a known 1, its position is our upper bound.
2112 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2113 // If this call is poison for 0 input, the result will be less than 2^n.
2114 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2115 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
2116 unsigned LowBits = llvm::bit_width(PossibleTZ);
2117 Known.Zero.setBitsFrom(LowBits);
2118 break;
2119 }
2120 case Intrinsic::ctpop: {
2121 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2122 // We can bound the space the count needs. Also, bits known to be zero
2123 // can't contribute to the population.
2124 unsigned BitsPossiblySet = Known2.countMaxPopulation();
2125 unsigned LowBits = llvm::bit_width(BitsPossiblySet);
2126 Known.Zero.setBitsFrom(LowBits);
2127 // TODO: we could bound KnownOne using the lower bound on the number
2128 // of bits which might be set provided by popcnt KnownOne2.
2129 break;
2130 }
2131 case Intrinsic::fshr:
2132 case Intrinsic::fshl: {
2133 const APInt *SA;
2134 if (!match(I->getOperand(2), m_APInt(SA)))
2135 break;
2136
2137 KnownBits Known3(BitWidth);
2138 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2139 computeKnownBits(I->getOperand(1), DemandedElts, Known3, Q, Depth + 1);
2140 Known = II->getIntrinsicID() == Intrinsic::fshl
2141 ? KnownBits::fshl(Known2, Known3, *SA)
2142 : KnownBits::fshr(Known2, Known3, *SA);
2143 break;
2144 }
2145 case Intrinsic::clmul:
2146 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2147 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2148 Known = KnownBits::clmul(Known, Known2);
2149 break;
2150 case Intrinsic::pext:
2151 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2152 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2153 Known = KnownBits::pext(Known, Known2);
2154 break;
2155 case Intrinsic::pdep:
2156 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2157 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2158 Known = KnownBits::pdep(Known, Known2);
2159 break;
2160 case Intrinsic::smulh:
2161 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2162 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2163 Known = KnownBits::mulhs(Known, Known2);
2164 break;
2165 case Intrinsic::umulh:
2166 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2167 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2168 Known = KnownBits::mulhu(Known, Known2);
2169 break;
2170 case Intrinsic::uadd_sat:
2171 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2172 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2173 Known = KnownBits::uadd_sat(Known, Known2);
2174 break;
2175 case Intrinsic::usub_sat:
2176 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2177 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2178 Known = KnownBits::usub_sat(Known, Known2);
2179 break;
2180 case Intrinsic::sadd_sat:
2181 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2182 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2183 Known = KnownBits::sadd_sat(Known, Known2);
2184 break;
2185 case Intrinsic::ssub_sat:
2186 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2187 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2188 Known = KnownBits::ssub_sat(Known, Known2);
2189 break;
2190 // Vec reverse preserves bits from input vec.
2191 case Intrinsic::vector_reverse:
2192 computeKnownBits(I->getOperand(0), DemandedElts.reverseBits(), Known, Q,
2193 Depth + 1);
2194 break;
2195 // for min/max/and/or reduce, any bit common to each element in the
2196 // input vec is set in the output.
2197 case Intrinsic::vector_reduce_and:
2198 case Intrinsic::vector_reduce_or:
2199 case Intrinsic::vector_reduce_umax:
2200 case Intrinsic::vector_reduce_umin:
2201 case Intrinsic::vector_reduce_smax:
2202 case Intrinsic::vector_reduce_smin:
2203 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2204 break;
2205 case Intrinsic::vector_reduce_xor: {
2206 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2207 // The zeros common to all vecs are zero in the output.
2208 // If the number of elements is odd, then the common ones remain. If the
2209 // number of elements is even, then the common ones becomes zeros.
2210 auto *VecTy = cast<VectorType>(I->getOperand(0)->getType());
2211 // Even, so the ones become zeros.
2212 bool EvenCnt = VecTy->getElementCount().isKnownEven();
2213 if (EvenCnt)
2214 Known.Zero |= Known.One;
2215 // Maybe even element count so need to clear ones.
2216 if (VecTy->isScalableTy() || EvenCnt)
2217 Known.One.clearAllBits();
2218 break;
2219 }
2220 case Intrinsic::vector_reduce_add: {
2221 auto *VecTy = dyn_cast<FixedVectorType>(I->getOperand(0)->getType());
2222 if (!VecTy)
2223 break;
2224 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2225 Known = Known.reduceAdd(VecTy->getNumElements());
2226 break;
2227 }
2228 case Intrinsic::umin:
2229 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2230 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2231 Known = KnownBits::umin(Known, Known2);
2232 break;
2233 case Intrinsic::umax:
2234 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2235 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2236 Known = KnownBits::umax(Known, Known2);
2237 break;
2238 case Intrinsic::smin:
2239 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2240 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2241 Known = KnownBits::smin(Known, Known2);
2243 break;
2244 case Intrinsic::smax:
2245 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2246 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2247 Known = KnownBits::smax(Known, Known2);
2249 break;
2250 case Intrinsic::ptrmask: {
2251 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2252
2253 const Value *Mask = I->getOperand(1);
2254 Known2 = KnownBits(Mask->getType()->getScalarSizeInBits());
2255 computeKnownBits(Mask, DemandedElts, Known2, Q, Depth + 1);
2256 // TODO: 1-extend would be more precise.
2257 Known &= Known2.anyextOrTrunc(BitWidth);
2258 break;
2259 }
2260 case Intrinsic::x86_sse2_pmulh_w:
2261 case Intrinsic::x86_avx2_pmulh_w:
2262 case Intrinsic::x86_avx512_pmulh_w_512:
2263 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2264 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2265 Known = KnownBits::mulhs(Known, Known2);
2266 break;
2267 case Intrinsic::x86_sse2_pmulhu_w:
2268 case Intrinsic::x86_avx2_pmulhu_w:
2269 case Intrinsic::x86_avx512_pmulhu_w_512:
2270 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2271 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2272 Known = KnownBits::mulhu(Known, Known2);
2273 break;
2274 case Intrinsic::x86_sse42_crc32_64_64:
2275 Known.Zero.setBitsFrom(32);
2276 break;
2277 case Intrinsic::x86_ssse3_phadd_d_128:
2278 case Intrinsic::x86_ssse3_phadd_w_128:
2279 case Intrinsic::x86_avx2_phadd_d:
2280 case Intrinsic::x86_avx2_phadd_w: {
2282 I, DemandedElts, Q, Depth,
2283 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2284 return KnownBits::add(KnownLHS, KnownRHS);
2285 });
2286 break;
2287 }
2288 case Intrinsic::x86_ssse3_phadd_sw_128:
2289 case Intrinsic::x86_avx2_phadd_sw: {
2291 I, DemandedElts, Q, Depth, KnownBits::sadd_sat);
2292 break;
2293 }
2294 case Intrinsic::x86_ssse3_phsub_d_128:
2295 case Intrinsic::x86_ssse3_phsub_w_128:
2296 case Intrinsic::x86_avx2_phsub_d:
2297 case Intrinsic::x86_avx2_phsub_w: {
2299 I, DemandedElts, Q, Depth,
2300 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2301 return KnownBits::sub(KnownLHS, KnownRHS);
2302 });
2303 break;
2304 }
2305 case Intrinsic::x86_ssse3_phsub_sw_128:
2306 case Intrinsic::x86_avx2_phsub_sw: {
2308 I, DemandedElts, Q, Depth, KnownBits::ssub_sat);
2309 break;
2310 }
2311 case Intrinsic::riscv_vsetvli:
2312 case Intrinsic::riscv_vsetvlimax: {
2313 bool HasAVL = II->getIntrinsicID() == Intrinsic::riscv_vsetvli;
2314 const ConstantRange Range = getVScaleRange(II->getFunction(), BitWidth);
2316 cast<ConstantInt>(II->getArgOperand(HasAVL))->getZExtValue());
2317 RISCVVType::VLMUL VLMUL = static_cast<RISCVVType::VLMUL>(
2318 cast<ConstantInt>(II->getArgOperand(1 + HasAVL))->getZExtValue());
2319 uint64_t MaxVLEN =
2320 Range.getUnsignedMax().getZExtValue() * RISCV::RVVBitsPerBlock;
2321 uint64_t MaxVL = MaxVLEN / RISCVVType::getSEWLMULRatio(SEW, VLMUL);
2322
2323 // Result of vsetvli must be not larger than AVL.
2324 if (HasAVL)
2325 if (auto *CI = dyn_cast<ConstantInt>(II->getArgOperand(0)))
2326 MaxVL = std::min(MaxVL, CI->getZExtValue());
2327
2328 unsigned KnownZeroFirstBit = Log2_32(MaxVL) + 1;
2329 if (BitWidth > KnownZeroFirstBit)
2330 Known.Zero.setBitsFrom(KnownZeroFirstBit);
2331 break;
2332 }
2333 case Intrinsic::amdgcn_mbcnt_hi:
2334 case Intrinsic::amdgcn_mbcnt_lo: {
2335 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
2336 // most 31 + src1.
2337 Known.Zero.setBitsFrom(
2338 II->getIntrinsicID() == Intrinsic::amdgcn_mbcnt_lo ? 6 : 5);
2339 computeKnownBits(I->getOperand(1), Known2, Q, Depth + 1);
2340 Known = KnownBits::add(Known, Known2);
2341 break;
2342 }
2343 case Intrinsic::vscale: {
2344 if (!II->getParent() || !II->getFunction())
2345 break;
2346
2347 Known = getVScaleRange(II->getFunction(), BitWidth).toKnownBits();
2348 break;
2349 }
2350 case Intrinsic::stepvector: {
2351 auto *VecTy = cast<VectorType>(II->getType());
2352 unsigned MinNumElts = VecTy->getElementCount().getKnownMinValue();
2353 if (!isUIntN(BitWidth, MinNumElts))
2354 break;
2355
2356 bool Overflow = false;
2357 APInt MaxNumElts(BitWidth, MinNumElts);
2358 if (VecTy->isScalableTy()) {
2359 if (!II->getParent() || !II->getFunction())
2360 break;
2361 MaxNumElts = getVScaleRange(II->getFunction(), BitWidth)
2363 .umul_ov(MaxNumElts, Overflow);
2364 }
2365
2366 // Give up if the lane count could wrap. Stepvector truncates lane
2367 // indices that do not fit in the element type.
2368 if (Overflow)
2369 break;
2370
2371 Known.Zero.setHighBits((MaxNumElts - 1).countl_zero());
2372 break;
2373 }
2374 }
2375 }
2376 break;
2377 }
2378 case Instruction::ShuffleVector: {
2379 if (auto *Splat = getSplatValue(I)) {
2381 break;
2382 }
2383
2384 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
2385 // FIXME: Do we need to handle ConstantExpr involving shufflevectors?
2386 if (!Shuf) {
2387 Known.resetAll();
2388 return;
2389 }
2390 // For undef elements, we don't know anything about the common state of
2391 // the shuffle result.
2392 APInt DemandedLHS, DemandedRHS;
2393 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) {
2394 Known.resetAll();
2395 return;
2396 }
2397 Known.setAllConflict();
2398 if (!!DemandedLHS) {
2399 const Value *LHS = Shuf->getOperand(0);
2400 computeKnownBits(LHS, DemandedLHS, Known, Q, Depth + 1);
2401 // If we don't know any bits, early out.
2402 if (Known.isUnknown())
2403 break;
2404 }
2405 if (!!DemandedRHS) {
2406 const Value *RHS = Shuf->getOperand(1);
2407 computeKnownBits(RHS, DemandedRHS, Known2, Q, Depth + 1);
2408 Known = Known.intersectWith(Known2);
2409 }
2410 break;
2411 }
2412 case Instruction::InsertElement: {
2413 if (isa<ScalableVectorType>(I->getType())) {
2414 Known.resetAll();
2415 return;
2416 }
2417 const Value *Vec = I->getOperand(0);
2418 const Value *Elt = I->getOperand(1);
2419 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
2420 unsigned NumElts = DemandedElts.getBitWidth();
2421 APInt DemandedVecElts = DemandedElts;
2422 bool NeedsElt = true;
2423 // If we know the index we are inserting too, clear it from Vec check.
2424 if (CIdx && CIdx->getValue().ult(NumElts)) {
2425 DemandedVecElts.clearBit(CIdx->getZExtValue());
2426 NeedsElt = DemandedElts[CIdx->getZExtValue()];
2427 }
2428
2429 Known.setAllConflict();
2430 if (NeedsElt) {
2431 computeKnownBits(Elt, Known, Q, Depth + 1);
2432 // If we don't know any bits, early out.
2433 if (Known.isUnknown())
2434 break;
2435 }
2436
2437 if (!DemandedVecElts.isZero()) {
2438 computeKnownBits(Vec, DemandedVecElts, Known2, Q, Depth + 1);
2439 Known = Known.intersectWith(Known2);
2440 }
2441 break;
2442 }
2443 case Instruction::ExtractElement: {
2444 // Look through extract element. If the index is non-constant or
2445 // out-of-range demand all elements, otherwise just the extracted element.
2446 const Value *Vec = I->getOperand(0);
2447 const Value *Idx = I->getOperand(1);
2448 auto *CIdx = dyn_cast<ConstantInt>(Idx);
2449 if (isa<ScalableVectorType>(Vec->getType())) {
2450 // FIXME: there's probably *something* we can do with scalable vectors
2451 Known.resetAll();
2452 break;
2453 }
2454 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
2455 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
2456 if (CIdx && CIdx->getValue().ult(NumElts))
2457 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2458 computeKnownBits(Vec, DemandedVecElts, Known, Q, Depth + 1);
2459 break;
2460 }
2461 case Instruction::ExtractValue:
2462 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
2464 if (EVI->getNumIndices() != 1) break;
2465 if (EVI->getIndices()[0] == 0) {
2466 switch (II->getIntrinsicID()) {
2467 default: break;
2468 case Intrinsic::uadd_with_overflow:
2469 case Intrinsic::sadd_with_overflow:
2471 true, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2472 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2473 break;
2474 case Intrinsic::usub_with_overflow:
2475 case Intrinsic::ssub_with_overflow:
2477 false, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2478 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2479 break;
2480 case Intrinsic::umul_with_overflow:
2481 case Intrinsic::smul_with_overflow:
2482 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
2483 false, DemandedElts, Known, Known2, Q, Depth);
2484 break;
2485 }
2486 }
2487 }
2488 break;
2489 case Instruction::Freeze:
2490 if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
2491 Depth + 1))
2492 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2493 break;
2494 }
2495}
2496
2497/// Determine which bits of V are known to be either zero or one and return
2498/// them.
2499KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
2500 const SimplifyQuery &Q, unsigned Depth) {
2501 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2502 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
2503 return Known;
2504}
2505
2506/// Determine which bits of V are known to be either zero or one and return
2507/// them.
2509 unsigned Depth) {
2510 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2512 return Known;
2513}
2514
2515/// Determine which bits of V are known to be either zero or one and return
2516/// them in the Known bit set.
2517///
2518/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
2519/// we cannot optimize based on the assumption that it is zero without changing
2520/// it to be an explicit zero. If we don't change it to zero, other code could
2521/// optimized based on the contradictory assumption that it is non-zero.
2522/// Because instcombine aggressively folds operations with undef args anyway,
2523/// this won't lose us code quality.
2524///
2525/// This function is defined on values with integer type, values with pointer
2526/// type, and vectors of integers. In the case
2527/// where V is a vector, known zero, and known one values are the
2528/// same width as the vector element, and the bit is set only if it is true
2529/// for all of the demanded elements in the vector specified by DemandedElts.
2530void computeKnownBits(const Value *V, const APInt &DemandedElts,
2531 KnownBits &Known, const SimplifyQuery &Q,
2532 unsigned Depth) {
2533 if (!DemandedElts) {
2534 // No demanded elts, better to assume we don't know anything.
2535 Known.resetAll();
2536 return;
2537 }
2538
2539 assert(V && "No Value?");
2540 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2541
2542#ifndef NDEBUG
2543 Type *Ty = V->getType();
2544 unsigned BitWidth = Known.getBitWidth();
2545
2546 assert((Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) &&
2547 "Not integer or pointer type!");
2548
2549 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2550 assert(
2551 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
2552 "DemandedElt width should equal the fixed vector number of elements");
2553 } else {
2554 assert(DemandedElts == APInt(1, 1) &&
2555 "DemandedElt width should be 1 for scalars or scalable vectors");
2556 }
2557
2558 Type *ScalarTy = Ty->getScalarType();
2559 if (ScalarTy->isPointerTy()) {
2560 assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) &&
2561 "V and Known should have same BitWidth");
2562 } else {
2563 assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) &&
2564 "V and Known should have same BitWidth");
2565 }
2566#endif
2567
2568 const APInt *C;
2569 if (match(V, m_APInt(C))) {
2570 // We know all of the bits for a scalar constant or a splat vector constant!
2572 return;
2573 }
2574 // Null and aggregate-zero are all-zeros.
2576 Known.setAllZero();
2577 return;
2578 }
2579 // Handle a constant vector by taking the intersection of the known bits of
2580 // each element.
2582 assert(!isa<ScalableVectorType>(V->getType()));
2583 // We know that CDV must be a vector of integers. Take the intersection of
2584 // each element.
2585 Known.setAllConflict();
2586 for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
2587 if (!DemandedElts[i])
2588 continue;
2589 APInt Elt = CDV->getElementAsAPInt(i);
2590 Known.Zero &= ~Elt;
2591 Known.One &= Elt;
2592 }
2593 if (Known.hasConflict())
2594 Known.resetAll();
2595 return;
2596 }
2597
2598 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
2599 assert(!isa<ScalableVectorType>(V->getType()));
2600 // We know that CV must be a vector of integers. Take the intersection of
2601 // each element.
2602 Known.setAllConflict();
2603 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
2604 if (!DemandedElts[i])
2605 continue;
2606 Constant *Element = CV->getAggregateElement(i);
2607 if (isa<PoisonValue>(Element))
2608 continue;
2609 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
2610 if (!ElementCI) {
2611 Known.resetAll();
2612 return;
2613 }
2614 const APInt &Elt = ElementCI->getValue();
2615 Known.Zero &= ~Elt;
2616 Known.One &= Elt;
2617 }
2618 if (Known.hasConflict())
2619 Known.resetAll();
2620 return;
2621 }
2622
2623 // Start out not knowing anything.
2624 Known.resetAll();
2625
2626 // We can't imply anything about undefs.
2627 if (isa<UndefValue>(V))
2628 return;
2629
2630 // There's no point in looking through other users of ConstantData for
2631 // assumptions. Confirm that we've handled them all.
2632 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
2633
2634 if (const auto *A = dyn_cast<Argument>(V))
2635 if (std::optional<ConstantRange> Range = A->getRange())
2636 Known = Range->toKnownBits();
2637
2638 // All recursive calls that increase depth must come after this.
2640 return;
2641
2642 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
2643 // the bits of its aliasee.
2644 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2645 if (!GA->isInterposable())
2646 computeKnownBits(GA->getAliasee(), Known, Q, Depth + 1);
2647 return;
2648 }
2649
2650 if (const Operator *I = dyn_cast<Operator>(V))
2651 computeKnownBitsFromOperator(I, DemandedElts, Known, Q, Depth);
2652 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2653 if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange())
2654 Known = CR->toKnownBits();
2655 }
2656
2657 // Aligned pointers have trailing zeros - refine Known.Zero set
2658 if (isa<PointerType>(V->getType())) {
2659 Align Alignment = V->getPointerAlignment(Q.DL);
2660 Known.Zero.setLowBits(Log2(Alignment));
2661 }
2662
2663 // computeKnownBitsFromContext strictly refines Known.
2664 // Therefore, we run them after computeKnownBitsFromOperator.
2665
2666 // Check whether we can determine known bits from context such as assumes.
2668}
2669
2670/// Try to detect a recurrence that the value of the induction variable is
2671/// always a power of two (or zero).
2672static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero,
2673 SimplifyQuery &Q, unsigned Depth) {
2674 BinaryOperator *BO = nullptr;
2675 Value *Start = nullptr, *Step = nullptr;
2676 if (!matchSimpleRecurrence(PN, BO, Start, Step))
2677 return false;
2678
2679 // Initial value must be a power of two.
2680 for (const Use &U : PN->operands()) {
2681 if (U.get() == Start) {
2682 // Initial value comes from a different BB, need to adjust context
2683 // instruction for analysis.
2684 Q.CxtI = PN->getIncomingBlock(U)->getTerminator();
2685 if (!isKnownToBeAPowerOfTwo(Start, OrZero, Q, Depth))
2686 return false;
2687 }
2688 }
2689
2690 // Except for Mul, the induction variable must be on the left side of the
2691 // increment expression, otherwise its value can be arbitrary.
2692 if (BO->getOpcode() != Instruction::Mul && BO->getOperand(1) != Step)
2693 return false;
2694
2695 Q.CxtI = BO->getParent()->getTerminator();
2696 switch (BO->getOpcode()) {
2697 case Instruction::Mul:
2698 // Power of two is closed under multiplication.
2699 return (OrZero || Q.IIQ.hasNoUnsignedWrap(BO) ||
2700 Q.IIQ.hasNoSignedWrap(BO)) &&
2701 isKnownToBeAPowerOfTwo(Step, OrZero, Q, Depth);
2702 case Instruction::SDiv:
2703 // Start value must not be signmask for signed division, so simply being a
2704 // power of two is not sufficient, and it has to be a constant.
2705 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2706 return false;
2707 [[fallthrough]];
2708 case Instruction::UDiv:
2709 // Divisor must be a power of two.
2710 // If OrZero is false, cannot guarantee induction variable is non-zero after
2711 // division, same for Shr, unless it is exact division.
2712 return (OrZero || Q.IIQ.isExact(BO)) &&
2713 isKnownToBeAPowerOfTwo(Step, false, Q, Depth);
2714 case Instruction::Shl:
2715 return OrZero || Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO);
2716 case Instruction::AShr:
2717 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2718 return false;
2719 [[fallthrough]];
2720 case Instruction::LShr:
2721 return OrZero || Q.IIQ.isExact(BO);
2722 default:
2723 return false;
2724 }
2725}
2726
2727/// Return true if we can infer that \p V is known to be a power of 2 from
2728/// dominating condition \p Cond (e.g., ctpop(V) == 1).
2729static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero,
2730 const Value *Cond,
2731 bool CondIsTrue) {
2732 CmpPredicate Pred;
2733 const APInt *RHSC;
2734 if (!match(Cond, m_ICmp(Pred, m_Ctpop(m_Specific(V)), m_APInt(RHSC))))
2735 return false;
2736 if (!CondIsTrue)
2737 Pred = ICmpInst::getInversePredicate(Pred);
2738 // ctpop(V) u< 2
2739 if (OrZero && Pred == ICmpInst::ICMP_ULT && *RHSC == 2)
2740 return true;
2741 // ctpop(V) == 1
2742 return Pred == ICmpInst::ICMP_EQ && *RHSC == 1;
2743}
2744
2745/// Return true if the given value is known to have exactly one
2746/// bit set when defined. For vectors return true if every element is known to
2747/// be a power of two when defined. Supports values with integer or pointer
2748/// types and vectors of integers.
2749bool llvm::isKnownToBeAPowerOfTwo(const Value *V, bool OrZero,
2750 const SimplifyQuery &Q, unsigned Depth) {
2751 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2752
2753 if (isa<Constant>(V))
2754 return OrZero ? match(V, m_Power2OrZero()) : match(V, m_Power2());
2755
2756 // i1 is by definition a power of 2 or zero.
2757 if (OrZero && V->getType()->getScalarSizeInBits() == 1)
2758 return true;
2759
2760 // Try to infer from assumptions.
2761 if (Q.AC && Q.CxtI) {
2762 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
2763 if (!AssumeVH)
2764 continue;
2765 CallInst *I = cast<CallInst>(AssumeVH);
2766 if (isImpliedToBeAPowerOfTwoFromCond(V, OrZero, I->getArgOperand(0),
2767 /*CondIsTrue=*/true) &&
2769 return true;
2770 }
2771 }
2772
2773 // Handle dominating conditions.
2774 if (Q.DC && Q.CxtI && Q.DT) {
2775 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
2776 Value *Cond = BI->getCondition();
2777
2778 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
2780 /*CondIsTrue=*/true) &&
2781 Q.DT->dominates(Edge0, Q.CxtI->getParent()))
2782 return true;
2783
2784 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
2786 /*CondIsTrue=*/false) &&
2787 Q.DT->dominates(Edge1, Q.CxtI->getParent()))
2788 return true;
2789 }
2790 }
2791
2792 auto *I = dyn_cast<Instruction>(V);
2793 if (!I)
2794 return false;
2795
2796 if (Q.CxtI && match(V, m_VScale())) {
2797 const Function *F = Q.CxtI->getFunction();
2798 // The vscale_range indicates vscale is a power-of-two.
2799 return F->hasFnAttribute(Attribute::VScaleRange);
2800 }
2801
2802 // 1 << X is clearly a power of two if the one is not shifted off the end. If
2803 // it is shifted off the end then the result is undefined.
2804 if (match(I, m_Shl(m_One(), m_Value())))
2805 return true;
2806
2807 // (signmask) >>l X is clearly a power of two if the one is not shifted off
2808 // the bottom. If it is shifted off the bottom then the result is undefined.
2809 if (match(I, m_LShr(m_SignMask(), m_Value())))
2810 return true;
2811
2812 // The remaining tests are all recursive, so bail out if we hit the limit.
2814 return false;
2815
2816 switch (I->getOpcode()) {
2817 case Instruction::ZExt:
2818 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2819 case Instruction::Trunc:
2820 return OrZero && isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2821 case Instruction::Shl:
2822 if (OrZero || Q.IIQ.hasNoUnsignedWrap(I) || Q.IIQ.hasNoSignedWrap(I))
2823 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2824 return false;
2825 case Instruction::LShr:
2826 if (OrZero || Q.IIQ.isExact(cast<BinaryOperator>(I)))
2827 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2828 return false;
2829 case Instruction::UDiv:
2831 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2832 return false;
2833 case Instruction::Mul:
2834 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2835 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth) &&
2836 (OrZero || isKnownNonZero(I, Q, Depth));
2837 case Instruction::And:
2838 // A power of two and'd with anything is a power of two or zero.
2839 if (OrZero &&
2840 (isKnownToBeAPowerOfTwo(I->getOperand(1), /*OrZero*/ true, Q, Depth) ||
2841 isKnownToBeAPowerOfTwo(I->getOperand(0), /*OrZero*/ true, Q, Depth)))
2842 return true;
2843 // X & (-X) is always a power of two or zero.
2844 if (match(I->getOperand(0), m_Neg(m_Specific(I->getOperand(1)))) ||
2845 match(I->getOperand(1), m_Neg(m_Specific(I->getOperand(0)))))
2846 return OrZero || isKnownNonZero(I->getOperand(0), Q, Depth);
2847 return false;
2848 case Instruction::Add: {
2849 // Adding a power-of-two or zero to the same power-of-two or zero yields
2850 // either the original power-of-two, a larger power-of-two or zero.
2852 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
2853 Q.IIQ.hasNoSignedWrap(VOBO)) {
2854 if (match(I->getOperand(0),
2855 m_c_And(m_Specific(I->getOperand(1)), m_Value())) &&
2856 isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth))
2857 return true;
2858 if (match(I->getOperand(1),
2859 m_c_And(m_Specific(I->getOperand(0)), m_Value())) &&
2860 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth))
2861 return true;
2862
2863 unsigned BitWidth = V->getType()->getScalarSizeInBits();
2864 KnownBits LHSBits(BitWidth);
2865 computeKnownBits(I->getOperand(0), LHSBits, Q, Depth);
2866
2867 KnownBits RHSBits(BitWidth);
2868 computeKnownBits(I->getOperand(1), RHSBits, Q, Depth);
2869 // If i8 V is a power of two or zero:
2870 // ZeroBits: 1 1 1 0 1 1 1 1
2871 // ~ZeroBits: 0 0 0 1 0 0 0 0
2872 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
2873 // If OrZero isn't set, we cannot give back a zero result.
2874 // Make sure either the LHS or RHS has a bit set.
2875 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
2876 return true;
2877 }
2878
2879 // LShr(UINT_MAX, Y) + 1 is a power of two (if add is nuw) or zero.
2880 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO))
2881 if (match(I, m_Add(m_LShr(m_AllOnes(), m_Value()), m_One())))
2882 return true;
2883 return false;
2884 }
2885 case Instruction::Select:
2886 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2887 isKnownToBeAPowerOfTwo(I->getOperand(2), OrZero, Q, Depth);
2888 case Instruction::PHI: {
2889 // A PHI node is power of two if all incoming values are power of two, or if
2890 // it is an induction variable where in each step its value is a power of
2891 // two.
2892 auto *PN = cast<PHINode>(I);
2894
2895 // Check if it is an induction variable and always power of two.
2896 if (isPowerOfTwoRecurrence(PN, OrZero, RecQ, Depth))
2897 return true;
2898
2899 // Recursively check all incoming values. Limit recursion to 2 levels, so
2900 // that search complexity is limited to number of operands^2.
2901 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
2902 return llvm::all_of(PN->operands(), [&](const Use &U) {
2903 // Value is power of 2 if it is coming from PHI node itself by induction.
2904 if (U.get() == PN)
2905 return true;
2906
2907 // Change the context instruction to the incoming block where it is
2908 // evaluated.
2909 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
2910 return isKnownToBeAPowerOfTwo(U.get(), OrZero, RecQ, NewDepth);
2911 });
2912 }
2913 case Instruction::Invoke:
2914 case Instruction::Call: {
2915 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2916 switch (II->getIntrinsicID()) {
2917 case Intrinsic::umax:
2918 case Intrinsic::smax:
2919 case Intrinsic::umin:
2920 case Intrinsic::smin:
2921 return isKnownToBeAPowerOfTwo(II->getArgOperand(1), OrZero, Q, Depth) &&
2922 isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2923 // bswap/bitreverse just move around bits, but don't change any 1s/0s
2924 // thus dont change pow2/non-pow2 status.
2925 case Intrinsic::bitreverse:
2926 case Intrinsic::bswap:
2927 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2928 case Intrinsic::fshr:
2929 case Intrinsic::fshl:
2930 // If Op0 == Op1, this is a rotate. is_pow2(rotate(x, y)) == is_pow2(x)
2931 if (II->getArgOperand(0) == II->getArgOperand(1))
2932 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2933 break;
2934 case Intrinsic::riscv_vsetvlimax:
2935 // VLMAX is VLEN * LMUL / SEW, which is always a non-zero power of two
2936 // for any valid vtype, so it is a power of two regardless of OrZero.
2937 return true;
2938 case Intrinsic::read_register:
2939 case Intrinsic::read_volatile_register: {
2940 // The RISC-V vlenb CSR holds VLEN/8, which is always a non-zero power
2941 // of two, so it is a power of two regardless of OrZero.
2942 const Module *M = II->getModule();
2943 if (!M || !M->getTargetTriple().isRISCV())
2944 break;
2945 return isReadVLENB(*II);
2946 }
2947 default:
2948 break;
2949 }
2950 }
2951 return false;
2952 }
2953 default:
2954 return false;
2955 }
2956}
2957
2958/// Test whether a GEP's result is known to be non-null.
2959///
2960/// Uses properties inherent in a GEP to try to determine whether it is known
2961/// to be non-null.
2962///
2963/// Currently this routine does not support vector GEPs.
2964static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q,
2965 unsigned Depth) {
2966 const Function *F = nullptr;
2967 if (const Instruction *I = dyn_cast<Instruction>(GEP))
2968 F = I->getFunction();
2969
2970 // If the gep is nuw or inbounds with invalid null pointer, then the GEP
2971 // may be null iff the base pointer is null and the offset is zero.
2972 if (!GEP->hasNoUnsignedWrap() &&
2973 !(GEP->isInBounds() &&
2974 !NullPointerIsDefined(F, GEP->getPointerAddressSpace())))
2975 return false;
2976
2977 // FIXME: Support vector-GEPs.
2978 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
2979
2980 // If the base pointer is non-null, we cannot walk to a null address with an
2981 // inbounds GEP in address space zero.
2982 if (isKnownNonZero(GEP->getPointerOperand(), Q, Depth))
2983 return true;
2984
2985 // Walk the GEP operands and see if any operand introduces a non-zero offset.
2986 // If so, then the GEP cannot produce a null pointer, as doing so would
2987 // inherently violate the inbounds contract within address space zero.
2989 GTI != GTE; ++GTI) {
2990 // Struct types are easy -- they must always be indexed by a constant.
2991 if (StructType *STy = GTI.getStructTypeOrNull()) {
2992 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
2993 unsigned ElementIdx = OpC->getZExtValue();
2994 const StructLayout *SL = Q.DL.getStructLayout(STy);
2995 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
2996 if (ElementOffset > 0)
2997 return true;
2998 continue;
2999 }
3000
3001 // If we have a zero-sized type, the index doesn't matter. Keep looping.
3002 if (GTI.getSequentialElementStride(Q.DL).isZero())
3003 continue;
3004
3005 // Fast path the constant operand case both for efficiency and so we don't
3006 // increment Depth when just zipping down an all-constant GEP.
3007 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
3008 if (!OpC->isZero())
3009 return true;
3010 continue;
3011 }
3012
3013 // We post-increment Depth here because while isKnownNonZero increments it
3014 // as well, when we pop back up that increment won't persist. We don't want
3015 // to recurse 10k times just because we have 10k GEP operands. We don't
3016 // bail completely out because we want to handle constant GEPs regardless
3017 // of depth.
3019 continue;
3020
3021 if (isKnownNonZero(GTI.getOperand(), Q, Depth))
3022 return true;
3023 }
3024
3025 return false;
3026}
3027
3029 const Instruction *CtxI,
3030 const DominatorTree *DT) {
3031 assert(!isa<Constant>(V) && "Called for constant?");
3032
3033 if (!CtxI || !DT)
3034 return false;
3035
3036 unsigned NumUsesExplored = 0;
3037 for (auto &U : V->uses()) {
3038 // Avoid massive lists
3039 if (NumUsesExplored >= DomConditionsMaxUses)
3040 break;
3041 NumUsesExplored++;
3042
3043 const Instruction *UI = cast<Instruction>(U.getUser());
3044 // If the value is used as an argument to a call or invoke, then argument
3045 // attributes may provide an answer about null-ness.
3046 if (V->getType()->isPointerTy()) {
3047 if (const auto *CB = dyn_cast<CallBase>(UI)) {
3048 if (CB->isArgOperand(&U) &&
3049 CB->paramHasNonNullAttr(CB->getArgOperandNo(&U),
3050 /*AllowUndefOrPoison=*/false) &&
3051 DT->dominates(CB, CtxI))
3052 return true;
3053 }
3054 }
3055
3056 // If the value is used as a load/store, then the pointer must be non null.
3057 if (V == getLoadStorePointerOperand(UI)) {
3060 DT->dominates(UI, CtxI))
3061 return true;
3062 }
3063
3064 if ((match(UI, m_IDiv(m_Value(), m_Specific(V))) ||
3065 match(UI, m_IRem(m_Value(), m_Specific(V)))) &&
3066 isValidAssumeForContext(UI, CtxI, DT))
3067 return true;
3068
3069 // Consider only compare instructions uniquely controlling a branch
3070 Value *RHS;
3071 CmpPredicate Pred;
3072 if (!match(UI, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS))))
3073 continue;
3074
3075 bool NonNullIfTrue;
3076 if (cmpExcludesZero(Pred, RHS))
3077 NonNullIfTrue = true;
3079 NonNullIfTrue = false;
3080 else
3081 continue;
3082
3085 for (const auto *CmpU : UI->users()) {
3086 assert(WorkList.empty() && "Should be!");
3087 if (Visited.insert(CmpU).second)
3088 WorkList.push_back(CmpU);
3089
3090 while (!WorkList.empty()) {
3091 auto *Curr = WorkList.pop_back_val();
3092
3093 // If a user is an AND, add all its users to the work list. We only
3094 // propagate "pred != null" condition through AND because it is only
3095 // correct to assume that all conditions of AND are met in true branch.
3096 // TODO: Support similar logic of OR and EQ predicate?
3097 if (NonNullIfTrue)
3098 if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) {
3099 for (const auto *CurrU : Curr->users())
3100 if (Visited.insert(CurrU).second)
3101 WorkList.push_back(CurrU);
3102 continue;
3103 }
3104
3105 if (const CondBrInst *BI = dyn_cast<CondBrInst>(Curr)) {
3106 BasicBlock *NonNullSuccessor =
3107 BI->getSuccessor(NonNullIfTrue ? 0 : 1);
3108 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3109 if (DT->dominates(Edge, CtxI->getParent()))
3110 return true;
3111 } else if (NonNullIfTrue && isGuard(Curr) &&
3112 DT->dominates(cast<Instruction>(Curr), CtxI)) {
3113 return true;
3114 }
3115 }
3116 }
3117 }
3118
3119 return false;
3120}
3121
3122/// Does the 'Range' metadata (which must be a valid MD_range operand list)
3123/// ensure that the value it's attached to is never Value? 'RangeType' is
3124/// is the type of the value described by the range.
3125static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
3126 const unsigned NumRanges = Ranges->getNumOperands() / 2;
3127 assert(NumRanges >= 1);
3128 for (unsigned i = 0; i < NumRanges; ++i) {
3130 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
3132 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
3133 ConstantRange Range(Lower->getValue(), Upper->getValue());
3134 if (Range.contains(Value))
3135 return false;
3136 }
3137 return true;
3138}
3139
3140/// Try to detect a recurrence that monotonically increases/decreases from a
3141/// non-zero starting value. These are common as induction variables.
3142static bool isNonZeroRecurrence(const PHINode *PN) {
3143 BinaryOperator *BO = nullptr;
3144 Value *Start = nullptr, *Step = nullptr;
3145 const APInt *StartC, *StepC;
3146 if (!matchSimpleRecurrence(PN, BO, Start, Step) ||
3147 !match(Start, m_APInt(StartC)) || StartC->isZero())
3148 return false;
3149
3150 switch (BO->getOpcode()) {
3151 case Instruction::Add:
3152 // Starting from non-zero and stepping away from zero can never wrap back
3153 // to zero.
3154 return BO->hasNoUnsignedWrap() ||
3155 (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) &&
3156 StartC->isNegative() == StepC->isNegative());
3157 case Instruction::Mul:
3158 return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) &&
3159 match(Step, m_APInt(StepC)) && !StepC->isZero();
3160 case Instruction::Shl:
3161 return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap();
3162 case Instruction::AShr:
3163 case Instruction::LShr:
3164 return BO->isExact();
3165 default:
3166 return false;
3167 }
3168}
3169
3170static bool matchOpWithOpEqZero(Value *Op0, Value *Op1) {
3172 m_Specific(Op1), m_Zero()))) ||
3174 m_Specific(Op0), m_Zero())));
3175}
3176
3177static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q,
3178 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3179 bool NUW, unsigned Depth) {
3180 // (X + (X != 0)) is non zero
3181 if (matchOpWithOpEqZero(X, Y))
3182 return true;
3183
3184 if (NUW)
3185 return isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3186 isKnownNonZero(X, DemandedElts, Q, Depth);
3187
3188 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3189 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3190
3191 // If X and Y are both non-negative (as signed values) then their sum is not
3192 // zero unless both X and Y are zero.
3193 if (XKnown.isNonNegative() && YKnown.isNonNegative())
3194 if (isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3195 isKnownNonZero(X, DemandedElts, Q, Depth))
3196 return true;
3197
3198 // If X and Y are both negative (as signed values) then their sum is not
3199 // zero unless both X and Y equal INT_MIN.
3200 if (XKnown.isNegative() && YKnown.isNegative()) {
3202 // The sign bit of X is set. If some other bit is set then X is not equal
3203 // to INT_MIN.
3204 if (XKnown.One.intersects(Mask))
3205 return true;
3206 // The sign bit of Y is set. If some other bit is set then Y is not equal
3207 // to INT_MIN.
3208 if (YKnown.One.intersects(Mask))
3209 return true;
3210 }
3211
3212 // The sum of a non-negative number and a power of two is not zero.
3213 if (XKnown.isNonNegative() &&
3214 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Q, Depth))
3215 return true;
3216 if (YKnown.isNonNegative() &&
3217 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Q, Depth))
3218 return true;
3219
3220 return KnownBits::add(XKnown, YKnown, NSW, NUW).isNonZero();
3221}
3222
3223static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q,
3224 unsigned BitWidth, Value *X, Value *Y,
3225 unsigned Depth) {
3226 // (X - (X != 0)) is non zero
3227 // ((X != 0) - X) is non zero
3228 if (matchOpWithOpEqZero(X, Y))
3229 return true;
3230
3231 // TODO: Move this case into isKnownNonEqual().
3232 if (auto *C = dyn_cast<Constant>(X))
3233 if (C->isNullValue() && isKnownNonZero(Y, DemandedElts, Q, Depth))
3234 return true;
3235
3236 return ::isKnownNonEqual(X, Y, DemandedElts, Q, Depth);
3237}
3238
3239static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q,
3240 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3241 bool NUW, unsigned Depth) {
3242 // If X and Y are non-zero then so is X * Y as long as the multiplication
3243 // does not overflow.
3244 if (NSW || NUW)
3245 return isKnownNonZero(X, DemandedElts, Q, Depth) &&
3246 isKnownNonZero(Y, DemandedElts, Q, Depth);
3247
3248 // If either X or Y is odd, then if the other is non-zero the result can't
3249 // be zero.
3250 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3251 if (XKnown.One[0])
3252 return isKnownNonZero(Y, DemandedElts, Q, Depth);
3253
3254 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3255 if (YKnown.One[0])
3256 return XKnown.isNonZero() || isKnownNonZero(X, DemandedElts, Q, Depth);
3257
3258 // If there exists any subset of X (sX) and subset of Y (sY) s.t sX * sY is
3259 // non-zero, then X * Y is non-zero. We can find sX and sY by just taking
3260 // the lowest known One of X and Y. If they are non-zero, the result
3261 // must be non-zero. We can check if LSB(X) * LSB(Y) != 0 by doing
3262 // X.CountLeadingZeros + Y.CountLeadingZeros < BitWidth.
3263 return (XKnown.countMaxTrailingZeros() + YKnown.countMaxTrailingZeros()) <
3264 BitWidth;
3265}
3266
3267static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts,
3268 const SimplifyQuery &Q, const KnownBits &KnownVal,
3269 unsigned Depth) {
3270 auto ShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3271 switch (I->getOpcode()) {
3272 case Instruction::Shl:
3273 return Lhs.shl(Rhs);
3274 case Instruction::LShr:
3275 return Lhs.lshr(Rhs);
3276 case Instruction::AShr:
3277 return Lhs.ashr(Rhs);
3278 default:
3279 llvm_unreachable("Unknown Shift Opcode");
3280 }
3281 };
3282
3283 auto InvShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3284 switch (I->getOpcode()) {
3285 case Instruction::Shl:
3286 return Lhs.lshr(Rhs);
3287 case Instruction::LShr:
3288 case Instruction::AShr:
3289 return Lhs.shl(Rhs);
3290 default:
3291 llvm_unreachable("Unknown Shift Opcode");
3292 }
3293 };
3294
3295 if (KnownVal.isUnknown())
3296 return false;
3297
3298 KnownBits KnownCnt =
3299 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3300 APInt MaxShift = KnownCnt.getMaxValue();
3301 unsigned NumBits = KnownVal.getBitWidth();
3302 if (MaxShift.uge(NumBits))
3303 return false;
3304
3305 if (!ShiftOp(KnownVal.One, MaxShift).isZero())
3306 return true;
3307
3308 // If all of the bits shifted out are known to be zero, and Val is known
3309 // non-zero then at least one non-zero bit must remain.
3310 if (InvShiftOp(KnownVal.Zero, NumBits - MaxShift)
3311 .eq(InvShiftOp(APInt::getAllOnes(NumBits), NumBits - MaxShift)) &&
3312 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth))
3313 return true;
3314
3315 return false;
3316}
3317
3319 const APInt &DemandedElts,
3320 const SimplifyQuery &Q, unsigned Depth) {
3321 unsigned BitWidth = getBitWidth(I->getType()->getScalarType(), Q.DL);
3322 switch (I->getOpcode()) {
3323 case Instruction::Alloca:
3324 // Alloca never returns null, malloc might.
3325 return I->getType()->getPointerAddressSpace() == 0;
3326 case Instruction::GetElementPtr:
3327 if (I->getType()->isPointerTy())
3329 break;
3330 case Instruction::BitCast: {
3331 // We need to be a bit careful here. We can only peek through the bitcast
3332 // if the scalar size of elements in the operand are smaller than and a
3333 // multiple of the size they are casting too. Take three cases:
3334 //
3335 // 1) Unsafe:
3336 // bitcast <2 x i16> %NonZero to <4 x i8>
3337 //
3338 // %NonZero can have 2 non-zero i16 elements, but isKnownNonZero on a
3339 // <4 x i8> requires that all 4 i8 elements be non-zero which isn't
3340 // guranteed (imagine just sign bit set in the 2 i16 elements).
3341 //
3342 // 2) Unsafe:
3343 // bitcast <4 x i3> %NonZero to <3 x i4>
3344 //
3345 // Even though the scalar size of the src (`i3`) is smaller than the
3346 // scalar size of the dst `i4`, because `i3` is not a multiple of `i4`
3347 // its possible for the `3 x i4` elements to be zero because there are
3348 // some elements in the destination that don't contain any full src
3349 // element.
3350 //
3351 // 3) Safe:
3352 // bitcast <4 x i8> %NonZero to <2 x i16>
3353 //
3354 // This is always safe as non-zero in the 4 i8 elements implies
3355 // non-zero in the combination of any two adjacent ones. Since i8 is a
3356 // multiple of i16, each i16 is guranteed to have 2 full i8 elements.
3357 // This all implies the 2 i16 elements are non-zero.
3358 Type *FromTy = I->getOperand(0)->getType();
3359 if ((FromTy->isIntOrIntVectorTy() || FromTy->isPtrOrPtrVectorTy()) &&
3360 (BitWidth % getBitWidth(FromTy->getScalarType(), Q.DL)) == 0)
3361 return isKnownNonZero(I->getOperand(0), Q, Depth);
3362 } break;
3363 case Instruction::IntToPtr:
3364 // Note that we have to take special care to avoid looking through
3365 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
3366 // as casts that can alter the value, e.g., AddrSpaceCasts.
3367 if (!isa<ScalableVectorType>(I->getType()) &&
3368 Q.DL.getTypeSizeInBits(I->getOperand(0)->getType()).getFixedValue() <=
3369 Q.DL.getTypeSizeInBits(I->getType()).getFixedValue())
3370 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3371 break;
3372 case Instruction::PtrToAddr:
3373 // isKnownNonZero() for pointers refers to the address bits being non-zero,
3374 // so we can directly forward.
3375 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3376 case Instruction::PtrToInt:
3377 // For inttoptr, make sure the result size is >= the address size. If the
3378 // address is non-zero, any larger value is also non-zero.
3379 if (Q.DL.getAddressSizeInBits(I->getOperand(0)->getType()) <=
3380 I->getType()->getScalarSizeInBits())
3381 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3382 break;
3383 case Instruction::Trunc:
3384 // nuw/nsw trunc preserves zero/non-zero status of input.
3385 if (auto *TI = dyn_cast<TruncInst>(I))
3386 if (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap())
3387 return isKnownNonZero(TI->getOperand(0), DemandedElts, Q, Depth);
3388 break;
3389
3390 // Iff x - y != 0, then x ^ y != 0
3391 // Therefore we can do the same exact checks
3392 case Instruction::Xor:
3393 case Instruction::Sub:
3394 return isNonZeroSub(DemandedElts, Q, BitWidth, I->getOperand(0),
3395 I->getOperand(1), Depth);
3396 case Instruction::Or:
3397 // (X | (X != 0)) is non zero
3398 if (matchOpWithOpEqZero(I->getOperand(0), I->getOperand(1)))
3399 return true;
3400 // X | Y != 0 if X != Y.
3401 if (isKnownNonEqual(I->getOperand(0), I->getOperand(1), DemandedElts, Q,
3402 Depth))
3403 return true;
3404 // X | Y != 0 if X != 0 or Y != 0.
3405 return isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth) ||
3406 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3407 case Instruction::SExt:
3408 case Instruction::ZExt:
3409 // ext X != 0 if X != 0.
3410 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3411
3412 case Instruction::Shl: {
3413 // shl nsw/nuw can't remove any non-zero bits.
3415 if (Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO))
3416 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3417
3418 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
3419 // if the lowest bit is shifted off the end.
3421 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth);
3422 if (Known.One[0])
3423 return true;
3424
3425 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3426 }
3427 case Instruction::LShr:
3428 case Instruction::AShr: {
3429 // shr exact can only shift out zero bits.
3431 if (BO->isExact())
3432 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3433
3434 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
3435 // defined if the sign bit is shifted off the end.
3437 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3438 if (Known.isNegative())
3439 return true;
3440
3441 // shr (add nuw A, B), C is non-zero if A or B has a known-one bit at
3442 // position >= C, because the sum >= max(A, B).
3443 Value *A, *B;
3444 const APInt *C;
3445 if (Depth + 1 < MaxAnalysisRecursionDepth &&
3446 match(I->getOperand(0), m_NUWAdd(m_Value(A), m_Value(B))) &&
3447 match(I->getOperand(1), m_APInt(C)) && C->ult(BitWidth)) {
3448 KnownBits KnownA = computeKnownBits(A, DemandedElts, Q, Depth + 1);
3449 if (!KnownA.One.lshr(*C).isZero())
3450 return true;
3451 KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
3452 if (!KnownB.One.lshr(*C).isZero())
3453 return true;
3454 }
3455
3456 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3457 }
3458 case Instruction::UDiv:
3459 case Instruction::SDiv: {
3460 // X / Y
3461 // div exact can only produce a zero if the dividend is zero.
3462 if (cast<PossiblyExactOperator>(I)->isExact())
3463 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3464
3465 KnownBits XKnown =
3466 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3467 // If X is fully unknown we won't be able to figure anything out so don't
3468 // both computing knownbits for Y.
3469 if (XKnown.isUnknown())
3470 return false;
3471
3472 KnownBits YKnown =
3473 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3474 if (I->getOpcode() == Instruction::SDiv) {
3475 // For signed division need to compare abs value of the operands.
3476 XKnown = XKnown.abs(/*IntMinIsPoison*/ false);
3477 YKnown = YKnown.abs(/*IntMinIsPoison*/ false);
3478 }
3479 // If X u>= Y then div is non zero (0/0 is UB).
3480 std::optional<bool> XUgeY = KnownBits::uge(XKnown, YKnown);
3481 // If X is total unknown or X u< Y we won't be able to prove non-zero
3482 // with compute known bits so just return early.
3483 return XUgeY && *XUgeY;
3484 }
3485 case Instruction::Add: {
3486 // X + Y.
3487
3488 // If Add has nuw wrap flag, then if either X or Y is non-zero the result is
3489 // non-zero.
3491 return isNonZeroAdd(DemandedElts, Q, BitWidth, I->getOperand(0),
3492 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3493 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3494 }
3495 case Instruction::Mul: {
3497 return isNonZeroMul(DemandedElts, Q, BitWidth, I->getOperand(0),
3498 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3499 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3500 }
3501 case Instruction::Select: {
3502 // (C ? X : Y) != 0 if X != 0 and Y != 0.
3503
3504 // First check if the arm is non-zero using `isKnownNonZero`. If that fails,
3505 // then see if the select condition implies the arm is non-zero. For example
3506 // (X != 0 ? X : Y), we know the true arm is non-zero as the `X` "return" is
3507 // dominated by `X != 0`.
3508 auto SelectArmIsNonZero = [&](bool IsTrueArm) {
3509 Value *Op;
3510 Op = IsTrueArm ? I->getOperand(1) : I->getOperand(2);
3511 // Op is trivially non-zero.
3512 if (isKnownNonZero(Op, DemandedElts, Q, Depth))
3513 return true;
3514
3515 // The condition of the select dominates the true/false arm. Check if the
3516 // condition implies that a given arm is non-zero.
3517 Value *X;
3518 CmpPredicate Pred;
3519 if (!match(I->getOperand(0), m_c_ICmp(Pred, m_Specific(Op), m_Value(X))))
3520 return false;
3521
3522 if (!IsTrueArm)
3523 Pred = ICmpInst::getInversePredicate(Pred);
3524
3525 return cmpExcludesZero(Pred, X);
3526 };
3527
3528 if (SelectArmIsNonZero(/* IsTrueArm */ true) &&
3529 SelectArmIsNonZero(/* IsTrueArm */ false))
3530 return true;
3531 break;
3532 }
3533 case Instruction::PHI: {
3534 auto *PN = cast<PHINode>(I);
3536 return true;
3537
3538 // Check if all incoming values are non-zero using recursion.
3540 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
3541 return llvm::all_of(PN->operands(), [&](const Use &U) {
3542 if (U.get() == PN)
3543 return true;
3544 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
3545 // Check if the branch on the phi excludes zero.
3546 CmpPredicate Pred;
3547 Value *X;
3548 BasicBlock *TrueSucc, *FalseSucc;
3549 if (match(RecQ.CxtI,
3550 m_Br(m_c_ICmp(Pred, m_Specific(U.get()), m_Value(X)),
3551 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
3552 // Check for cases of duplicate successors.
3553 if ((TrueSucc == PN->getParent()) != (FalseSucc == PN->getParent())) {
3554 // If we're using the false successor, invert the predicate.
3555 if (FalseSucc == PN->getParent())
3556 Pred = CmpInst::getInversePredicate(Pred);
3557 if (cmpExcludesZero(Pred, X))
3558 return true;
3559 }
3560 }
3561 // Finally recurse on the edge and check it directly.
3562 return isKnownNonZero(U.get(), DemandedElts, RecQ, NewDepth);
3563 });
3564 }
3565 case Instruction::InsertElement: {
3566 if (isa<ScalableVectorType>(I->getType()))
3567 break;
3568
3569 const Value *Vec = I->getOperand(0);
3570 const Value *Elt = I->getOperand(1);
3571 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
3572
3573 unsigned NumElts = DemandedElts.getBitWidth();
3574 APInt DemandedVecElts = DemandedElts;
3575 bool SkipElt = false;
3576 // If we know the index we are inserting too, clear it from Vec check.
3577 if (CIdx && CIdx->getValue().ult(NumElts)) {
3578 DemandedVecElts.clearBit(CIdx->getZExtValue());
3579 SkipElt = !DemandedElts[CIdx->getZExtValue()];
3580 }
3581
3582 // Result is zero if Elt is non-zero and rest of the demanded elts in Vec
3583 // are non-zero.
3584 return (SkipElt || isKnownNonZero(Elt, Q, Depth)) &&
3585 (DemandedVecElts.isZero() ||
3586 isKnownNonZero(Vec, DemandedVecElts, Q, Depth));
3587 }
3588 case Instruction::ExtractElement:
3589 if (const auto *EEI = dyn_cast<ExtractElementInst>(I)) {
3590 const Value *Vec = EEI->getVectorOperand();
3591 const Value *Idx = EEI->getIndexOperand();
3592 auto *CIdx = dyn_cast<ConstantInt>(Idx);
3593 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
3594 unsigned NumElts = VecTy->getNumElements();
3595 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
3596 if (CIdx && CIdx->getValue().ult(NumElts))
3597 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
3598 return isKnownNonZero(Vec, DemandedVecElts, Q, Depth);
3599 }
3600 }
3601 break;
3602 case Instruction::ShuffleVector: {
3603 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
3604 if (!Shuf)
3605 break;
3606 APInt DemandedLHS, DemandedRHS;
3607 // For undef elements, we don't know anything about the common state of
3608 // the shuffle result.
3609 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
3610 break;
3611 // If demanded elements for both vecs are non-zero, the shuffle is non-zero.
3612 return (DemandedRHS.isZero() ||
3613 isKnownNonZero(Shuf->getOperand(1), DemandedRHS, Q, Depth)) &&
3614 (DemandedLHS.isZero() ||
3615 isKnownNonZero(Shuf->getOperand(0), DemandedLHS, Q, Depth));
3616 }
3617 case Instruction::Freeze:
3618 return isKnownNonZero(I->getOperand(0), Q, Depth) &&
3619 isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
3620 Depth);
3621 case Instruction::Load: {
3622 auto *LI = cast<LoadInst>(I);
3623 // A Load tagged with nonnull or dereferenceable with null pointer undefined
3624 // is never null.
3625 if (auto *PtrT = dyn_cast<PointerType>(I->getType())) {
3626 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull) ||
3627 (Q.IIQ.getMetadata(LI, LLVMContext::MD_dereferenceable) &&
3628 !NullPointerIsDefined(LI->getFunction(), PtrT->getAddressSpace())))
3629 return true;
3630 } else if (MDNode *Ranges = Q.IIQ.getMetadata(LI, LLVMContext::MD_range)) {
3632 }
3633
3634 // No need to fall through to computeKnownBits as range metadata is already
3635 // handled in isKnownNonZero.
3636 return false;
3637 }
3638 case Instruction::ExtractValue: {
3639 const WithOverflowInst *WO;
3641 switch (WO->getBinaryOp()) {
3642 default:
3643 break;
3644 case Instruction::Add:
3645 return isNonZeroAdd(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3646 WO->getArgOperand(1),
3647 /*NSW=*/false,
3648 /*NUW=*/false, Depth);
3649 case Instruction::Sub:
3650 return isNonZeroSub(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3651 WO->getArgOperand(1), Depth);
3652 case Instruction::Mul:
3653 return isNonZeroMul(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3654 WO->getArgOperand(1),
3655 /*NSW=*/false, /*NUW=*/false, Depth);
3656 break;
3657 }
3658 }
3659 break;
3660 }
3661 case Instruction::Call:
3662 case Instruction::Invoke: {
3663 const auto *Call = cast<CallBase>(I);
3664 if (I->getType()->isPointerTy()) {
3665 if (Call->isReturnNonNull())
3666 return true;
3667 if (const auto *RP = getArgumentAliasingToReturnedPointer(
3668 Call, /*MustPreserveOffset=*/true))
3669 return isKnownNonZero(RP, Q, Depth);
3670 } else {
3671 if (MDNode *Ranges = Q.IIQ.getMetadata(Call, LLVMContext::MD_range))
3673 if (std::optional<ConstantRange> Range = Call->getRange()) {
3674 const APInt ZeroValue(Range->getBitWidth(), 0);
3675 if (!Range->contains(ZeroValue))
3676 return true;
3677 }
3678 if (const Value *RV = Call->getReturnedArgOperand())
3679 if (RV->getType() == I->getType() && isKnownNonZero(RV, Q, Depth))
3680 return true;
3681 }
3682
3683 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
3684 switch (II->getIntrinsicID()) {
3685 case Intrinsic::sshl_sat:
3686 case Intrinsic::ushl_sat:
3687 case Intrinsic::abs:
3688 case Intrinsic::bitreverse:
3689 case Intrinsic::bswap:
3690 case Intrinsic::ctpop:
3691 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3692 // NB: We don't do usub_sat here as in any case we can prove its
3693 // non-zero, we will fold it to `sub nuw` in InstCombine.
3694 case Intrinsic::ssub_sat:
3695 // For most types, if x != y then ssub.sat x, y != 0. But
3696 // ssub.sat.i1 0, -1 = 0, because 1 saturates to 0. This means
3697 // isNonZeroSub will do the wrong thing for ssub.sat.i1.
3698 if (BitWidth == 1)
3699 return false;
3700 return isNonZeroSub(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3701 II->getArgOperand(1), Depth);
3702 case Intrinsic::sadd_sat:
3703 return isNonZeroAdd(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3704 II->getArgOperand(1),
3705 /*NSW=*/true, /* NUW=*/false, Depth);
3706 // Vec reverse preserves zero/non-zero status from input vec.
3707 case Intrinsic::vector_reverse:
3708 return isKnownNonZero(II->getArgOperand(0), DemandedElts.reverseBits(),
3709 Q, Depth);
3710 // umin/smin/smax/smin/or of all non-zero elements is always non-zero.
3711 case Intrinsic::vector_reduce_or:
3712 case Intrinsic::vector_reduce_umax:
3713 case Intrinsic::vector_reduce_umin:
3714 case Intrinsic::vector_reduce_smax:
3715 case Intrinsic::vector_reduce_smin:
3716 return isKnownNonZero(II->getArgOperand(0), Q, Depth);
3717 case Intrinsic::umax:
3718 case Intrinsic::uadd_sat:
3719 // umax(X, (X != 0)) is non zero
3720 // X +usat (X != 0) is non zero
3721 if (matchOpWithOpEqZero(II->getArgOperand(0), II->getArgOperand(1)))
3722 return true;
3723
3724 return isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth) ||
3725 isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3726 case Intrinsic::smax: {
3727 // If either arg is strictly positive the result is non-zero. Otherwise
3728 // the result is non-zero if both ops are non-zero.
3729 auto IsNonZero = [&](Value *Op, std::optional<bool> &OpNonZero,
3730 const KnownBits &OpKnown) {
3731 if (!OpNonZero.has_value())
3732 OpNonZero = OpKnown.isNonZero() ||
3733 isKnownNonZero(Op, DemandedElts, Q, Depth);
3734 return *OpNonZero;
3735 };
3736 // Avoid re-computing isKnownNonZero.
3737 std::optional<bool> Op0NonZero, Op1NonZero;
3738 KnownBits Op1Known =
3739 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3740 if (Op1Known.isNonNegative() &&
3741 IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known))
3742 return true;
3743 KnownBits Op0Known =
3744 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3745 if (Op0Known.isNonNegative() &&
3746 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known))
3747 return true;
3748 return IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known) &&
3749 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known);
3750 }
3751 case Intrinsic::smin: {
3752 // If either arg is negative the result is non-zero. Otherwise
3753 // the result is non-zero if both ops are non-zero.
3754 KnownBits Op1Known =
3755 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3756 if (Op1Known.isNegative())
3757 return true;
3758 KnownBits Op0Known =
3759 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3760 if (Op0Known.isNegative())
3761 return true;
3762
3763 if (Op1Known.isNonZero() && Op0Known.isNonZero())
3764 return true;
3765 }
3766 [[fallthrough]];
3767 case Intrinsic::umin:
3768 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth) &&
3769 isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth);
3770 case Intrinsic::cttz:
3771 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3772 .Zero[0];
3773 case Intrinsic::ctlz:
3774 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3775 .isNonNegative();
3776 case Intrinsic::fshr:
3777 case Intrinsic::fshl:
3778 // If Op0 == Op1, this is a rotate. rotate(x, y) != 0 iff x != 0.
3779 if (II->getArgOperand(0) == II->getArgOperand(1))
3780 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3781 break;
3782 case Intrinsic::vscale:
3783 return true;
3784 case Intrinsic::experimental_get_vector_length:
3785 return isKnownNonZero(I->getOperand(0), Q, Depth);
3786 default:
3787 break;
3788 }
3789 break;
3790 }
3791
3792 return false;
3793 }
3794 }
3795
3797 computeKnownBits(I, DemandedElts, Known, Q, Depth);
3798 return Known.One != 0;
3799}
3800
3801/// Return true if the given value is known to be non-zero when defined. For
3802/// vectors, return true if every demanded element is known to be non-zero when
3803/// defined. For pointers, if the context instruction and dominator tree are
3804/// specified, perform context-sensitive analysis and return true if the
3805/// pointer couldn't possibly be null at the specified instruction.
3806/// Supports values with integer or pointer type and vectors of integers.
3807bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
3808 const SimplifyQuery &Q, unsigned Depth) {
3809 Type *Ty = V->getType();
3810
3811#ifndef NDEBUG
3812 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
3813
3814 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
3815 assert(
3816 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
3817 "DemandedElt width should equal the fixed vector number of elements");
3818 } else {
3819 assert(DemandedElts == APInt(1, 1) &&
3820 "DemandedElt width should be 1 for scalars");
3821 }
3822#endif
3823
3824 if (auto *C = dyn_cast<Constant>(V)) {
3825 if (C->isNullValue())
3826 return false;
3827 if (isa<ConstantInt>(C))
3828 // Must be non-zero due to null test above.
3829 return true;
3830
3831 // For constant vectors, check that all elements are poison or known
3832 // non-zero to determine that the whole vector is known non-zero.
3833 if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
3834 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
3835 if (!DemandedElts[i])
3836 continue;
3837 Constant *Elt = C->getAggregateElement(i);
3838 if (!Elt || Elt->isNullValue())
3839 return false;
3840 if (!isa<PoisonValue>(Elt) && !isa<ConstantInt>(Elt))
3841 return false;
3842 }
3843 return true;
3844 }
3845
3846 // Constant ptrauth can be null, iff the base pointer can be.
3847 if (auto *CPA = dyn_cast<ConstantPtrAuth>(V))
3848 return isKnownNonZero(CPA->getPointer(), DemandedElts, Q, Depth);
3849
3850 // A global variable in address space 0 is non null unless extern weak
3851 // or an absolute symbol reference. Other address spaces may have null as a
3852 // valid address for a global, so we can't assume anything.
3853 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3854 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
3855 GV->getType()->getAddressSpace() == 0)
3856 return true;
3857 }
3858
3859 // For constant expressions, fall through to the Operator code below.
3860 if (!isa<ConstantExpr>(V))
3861 return false;
3862 }
3863
3864 if (const auto *A = dyn_cast<Argument>(V))
3865 if (std::optional<ConstantRange> Range = A->getRange()) {
3866 const APInt ZeroValue(Range->getBitWidth(), 0);
3867 if (!Range->contains(ZeroValue))
3868 return true;
3869 }
3870
3871 if (!isa<Constant>(V) && isKnownNonZeroFromAssume(V, Q))
3872 return true;
3873
3874 // Some of the tests below are recursive, so bail out if we hit the limit.
3876 return false;
3877
3878 // Check for pointer simplifications.
3879
3880 if (PointerType *PtrTy = dyn_cast<PointerType>(Ty)) {
3881 // A byval, inalloca may not be null in a non-default addres space. A
3882 // nonnull argument is assumed never 0.
3883 if (const Argument *A = dyn_cast<Argument>(V)) {
3884 if (((A->hasPassPointeeByValueCopyAttr() &&
3885 !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
3886 A->hasNonNullAttr()))
3887 return true;
3888 }
3889 }
3890
3891 if (const auto *I = dyn_cast<Operator>(V))
3892 if (isKnownNonZeroFromOperator(I, DemandedElts, Q, Depth))
3893 return true;
3894
3895 if (!isa<Constant>(V) &&
3897 return true;
3898
3899 if (const Value *Stripped = stripNullTest(V))
3900 return isKnownNonZero(Stripped, DemandedElts, Q, Depth);
3901
3902 return false;
3903}
3904
3906 unsigned Depth) {
3907 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
3908 APInt DemandedElts =
3909 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
3910 return ::isKnownNonZero(V, DemandedElts, Q, Depth);
3911}
3912
3913/// If the pair of operators are the same invertible function, return the
3914/// the operands of the function corresponding to each input. Otherwise,
3915/// return std::nullopt. An invertible function is one that is 1-to-1 and maps
3916/// every input value to exactly one output value. This is equivalent to
3917/// saying that Op1 and Op2 are equal exactly when the specified pair of
3918/// operands are equal, (except that Op1 and Op2 may be poison more often.)
3919static std::optional<std::pair<Value*, Value*>>
3921 const Operator *Op2) {
3922 if (Op1->getOpcode() != Op2->getOpcode())
3923 return std::nullopt;
3924
3925 auto getOperands = [&](unsigned OpNum) -> auto {
3926 return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
3927 };
3928
3929 switch (Op1->getOpcode()) {
3930 default:
3931 break;
3932 case Instruction::Or:
3933 if (!cast<PossiblyDisjointInst>(Op1)->isDisjoint() ||
3934 !cast<PossiblyDisjointInst>(Op2)->isDisjoint())
3935 break;
3936 [[fallthrough]];
3937 case Instruction::Xor:
3938 case Instruction::Add: {
3939 Value *Other;
3940 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(0)), m_Value(Other))))
3941 return std::make_pair(Op1->getOperand(1), Other);
3942 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(1)), m_Value(Other))))
3943 return std::make_pair(Op1->getOperand(0), Other);
3944 break;
3945 }
3946 case Instruction::Sub:
3947 if (Op1->getOperand(0) == Op2->getOperand(0))
3948 return getOperands(1);
3949 if (Op1->getOperand(1) == Op2->getOperand(1))
3950 return getOperands(0);
3951 break;
3952 case Instruction::Mul: {
3953 // invertible if A * B == (A * B) mod 2^N where A, and B are integers
3954 // and N is the bitwdith. The nsw case is non-obvious, but proven by
3955 // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
3956 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3957 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3958 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3959 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3960 break;
3961
3962 // Assume operand order has been canonicalized
3963 if (Op1->getOperand(1) == Op2->getOperand(1) &&
3964 isa<ConstantInt>(Op1->getOperand(1)) &&
3965 !cast<ConstantInt>(Op1->getOperand(1))->isZero())
3966 return getOperands(0);
3967 break;
3968 }
3969 case Instruction::Shl: {
3970 // Same as multiplies, with the difference that we don't need to check
3971 // for a non-zero multiply. Shifts always multiply by non-zero.
3972 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3973 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3974 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3975 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3976 break;
3977
3978 if (Op1->getOperand(1) == Op2->getOperand(1))
3979 return getOperands(0);
3980 break;
3981 }
3982 case Instruction::AShr:
3983 case Instruction::LShr: {
3984 auto *PEO1 = cast<PossiblyExactOperator>(Op1);
3985 auto *PEO2 = cast<PossiblyExactOperator>(Op2);
3986 if (!PEO1->isExact() || !PEO2->isExact())
3987 break;
3988
3989 if (Op1->getOperand(1) == Op2->getOperand(1))
3990 return getOperands(0);
3991 break;
3992 }
3993 case Instruction::SExt:
3994 case Instruction::ZExt:
3995 if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
3996 return getOperands(0);
3997 break;
3998 case Instruction::PHI: {
3999 const PHINode *PN1 = cast<PHINode>(Op1);
4000 const PHINode *PN2 = cast<PHINode>(Op2);
4001
4002 // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
4003 // are a single invertible function of the start values? Note that repeated
4004 // application of an invertible function is also invertible
4005 BinaryOperator *BO1 = nullptr;
4006 Value *Start1 = nullptr, *Step1 = nullptr;
4007 BinaryOperator *BO2 = nullptr;
4008 Value *Start2 = nullptr, *Step2 = nullptr;
4009 if (PN1->getParent() != PN2->getParent() ||
4010 !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
4011 !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
4012 break;
4013
4015 cast<Operator>(BO2));
4016 if (!Values)
4017 break;
4018
4019 // We have to be careful of mutually defined recurrences here. Ex:
4020 // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
4021 // * X_i = Y_i = X_(i-1) OP Y_(i-1)
4022 // The invertibility of these is complicated, and not worth reasoning
4023 // about (yet?).
4024 if (Values->first != PN1 || Values->second != PN2)
4025 break;
4026
4027 return std::make_pair(Start1, Start2);
4028 }
4029 }
4030 return std::nullopt;
4031}
4032
4033/// Return true if V1 == (binop V2, X), where X is known non-zero.
4034/// Only handle a small subset of binops where (binop V2, X) with non-zero X
4035/// implies V2 != V1.
4036static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2,
4037 const APInt &DemandedElts,
4038 const SimplifyQuery &Q, unsigned Depth) {
4040 if (!BO)
4041 return false;
4042 switch (BO->getOpcode()) {
4043 default:
4044 break;
4045 case Instruction::Or:
4046 if (!cast<PossiblyDisjointInst>(V1)->isDisjoint())
4047 break;
4048 [[fallthrough]];
4049 case Instruction::Xor:
4050 case Instruction::Add:
4051 Value *Op = nullptr;
4052 if (V2 == BO->getOperand(0))
4053 Op = BO->getOperand(1);
4054 else if (V2 == BO->getOperand(1))
4055 Op = BO->getOperand(0);
4056 else
4057 return false;
4058 return isKnownNonZero(Op, DemandedElts, Q, Depth + 1);
4059 }
4060 return false;
4061}
4062
4063/// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
4064/// the multiplication is nuw or nsw.
4065static bool isNonEqualMul(const Value *V1, const Value *V2,
4066 const APInt &DemandedElts, const SimplifyQuery &Q,
4067 unsigned Depth) {
4068 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4069 const APInt *C;
4070 return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
4071 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4072 !C->isZero() && !C->isOne() &&
4073 isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4074 }
4075 return false;
4076}
4077
4078/// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
4079/// the shift is nuw or nsw.
4080static bool isNonEqualShl(const Value *V1, const Value *V2,
4081 const APInt &DemandedElts, const SimplifyQuery &Q,
4082 unsigned Depth) {
4083 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4084 const APInt *C;
4085 return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
4086 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4087 !C->isZero() && isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4088 }
4089 return false;
4090}
4091
4092static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
4093 const APInt &DemandedElts, const SimplifyQuery &Q,
4094 unsigned Depth) {
4095 // Check two PHIs are in same block.
4096 if (PN1->getParent() != PN2->getParent())
4097 return false;
4098
4100 bool UsedFullRecursion = false;
4101 for (const BasicBlock *IncomBB : PN1->blocks()) {
4102 if (!VisitedBBs.insert(IncomBB).second)
4103 continue; // Don't reprocess blocks that we have dealt with already.
4104 const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
4105 const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
4106 const APInt *C1, *C2;
4107 if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
4108 continue;
4109
4110 // Only one pair of phi operands is allowed for full recursion.
4111 if (UsedFullRecursion)
4112 return false;
4113
4115 RecQ.CxtI = IncomBB->getTerminator();
4116 if (!isKnownNonEqual(IV1, IV2, DemandedElts, RecQ, Depth + 1))
4117 return false;
4118 UsedFullRecursion = true;
4119 }
4120 return true;
4121}
4122
4123static bool isNonEqualSelect(const Value *V1, const Value *V2,
4124 const APInt &DemandedElts, const SimplifyQuery &Q,
4125 unsigned Depth) {
4126 const SelectInst *SI1 = dyn_cast<SelectInst>(V1);
4127 if (!SI1)
4128 return false;
4129
4130 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) {
4131 const Value *Cond1 = SI1->getCondition();
4132 const Value *Cond2 = SI2->getCondition();
4133 if (Cond1 == Cond2)
4134 return isKnownNonEqual(SI1->getTrueValue(), SI2->getTrueValue(),
4135 DemandedElts, Q, Depth + 1) &&
4136 isKnownNonEqual(SI1->getFalseValue(), SI2->getFalseValue(),
4137 DemandedElts, Q, Depth + 1);
4138 }
4139 return isKnownNonEqual(SI1->getTrueValue(), V2, DemandedElts, Q, Depth + 1) &&
4140 isKnownNonEqual(SI1->getFalseValue(), V2, DemandedElts, Q, Depth + 1);
4141}
4142
4143// Check to see if A is both a GEP and is the incoming value for a PHI in the
4144// loop, and B is either a ptr or another GEP. If the PHI has 2 incoming values,
4145// one of them being the recursive GEP A and the other a ptr at same base and at
4146// the same/higher offset than B we are only incrementing the pointer further in
4147// loop if offset of recursive GEP is greater than 0.
4149 const SimplifyQuery &Q) {
4150 if (!A->getType()->isPointerTy() || !B->getType()->isPointerTy())
4151 return false;
4152
4153 auto *GEPA = dyn_cast<GEPOperator>(A);
4154 if (!GEPA || GEPA->getNumIndices() != 1 || !isa<Constant>(GEPA->idx_begin()))
4155 return false;
4156
4157 // Handle 2 incoming PHI values with one being a recursive GEP.
4158 auto *PN = dyn_cast<PHINode>(GEPA->getPointerOperand());
4159 if (!PN || PN->getNumIncomingValues() != 2)
4160 return false;
4161
4162 // Search for the recursive GEP as an incoming operand, and record that as
4163 // Step.
4164 Value *Start = nullptr;
4165 Value *Step = const_cast<Value *>(A);
4166 if (PN->getIncomingValue(0) == Step)
4167 Start = PN->getIncomingValue(1);
4168 else if (PN->getIncomingValue(1) == Step)
4169 Start = PN->getIncomingValue(0);
4170 else
4171 return false;
4172
4173 // Other incoming node base should match the B base.
4174 // StartOffset >= OffsetB && StepOffset > 0?
4175 // StartOffset <= OffsetB && StepOffset < 0?
4176 // Is non-equal if above are true.
4177 // We use stripAndAccumulateInBoundsConstantOffsets to restrict the
4178 // optimisation to inbounds GEPs only.
4179 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(Start->getType());
4180 APInt StartOffset(IndexWidth, 0);
4181 Start = Start->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StartOffset);
4182 APInt StepOffset(IndexWidth, 0);
4183 Step = Step->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StepOffset);
4184
4185 // Check if Base Pointer of Step matches the PHI.
4186 if (Step != PN)
4187 return false;
4188 APInt OffsetB(IndexWidth, 0);
4189 B = B->stripAndAccumulateInBoundsConstantOffsets(Q.DL, OffsetB);
4190 return Start == B &&
4191 ((StartOffset.sge(OffsetB) && StepOffset.isStrictlyPositive()) ||
4192 (StartOffset.sle(OffsetB) && StepOffset.isNegative()));
4193}
4194
4195static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2,
4196 const SimplifyQuery &Q, unsigned Depth) {
4197 if (!Q.CxtI)
4198 return false;
4199
4200 // Try to infer NonEqual based on information from dominating conditions.
4201 if (Q.DC && Q.DT) {
4202 auto IsKnownNonEqualFromDominatingCondition = [&](const Value *V) {
4203 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4204 Value *Cond = BI->getCondition();
4205 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
4206 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()) &&
4208 /*LHSIsTrue=*/true, Depth)
4209 .value_or(false))
4210 return true;
4211
4212 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
4213 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()) &&
4215 /*LHSIsTrue=*/false, Depth)
4216 .value_or(false))
4217 return true;
4218 }
4219
4220 return false;
4221 };
4222
4223 if (IsKnownNonEqualFromDominatingCondition(V1) ||
4224 IsKnownNonEqualFromDominatingCondition(V2))
4225 return true;
4226 }
4227
4228 if (!Q.AC)
4229 return false;
4230
4231 // Try to infer NonEqual based on information from assumptions.
4232 for (auto &AssumeVH : Q.AC->assumptionsFor(V1)) {
4233 if (!AssumeVH)
4234 continue;
4235 CallInst *I = cast<CallInst>(AssumeVH);
4236
4237 assert(I->getFunction() == Q.CxtI->getFunction() &&
4238 "Got assumption for the wrong function!");
4239 assert(I->getIntrinsicID() == Intrinsic::assume &&
4240 "must be an assume intrinsic");
4241
4242 if (isImpliedCondition(I->getArgOperand(0), ICmpInst::ICMP_NE, V1, V2, Q.DL,
4243 /*LHSIsTrue=*/true, Depth)
4244 .value_or(false) &&
4246 return true;
4247 }
4248
4249 return false;
4250}
4251
4252static bool isNonEqualURem(const Value *X, const Value *Rem,
4253 const SimplifyQuery &Q) {
4254 const Value *Y;
4255 if (!match(Rem, m_URem(m_Specific(X), m_Value(Y))))
4256 return false;
4257
4258 // For a defined urem, X != X urem Y exactly when X u>= Y.
4259 // isTruePredicate does not handle UGE, so use the equivalent Y u<= X.
4261 return true;
4262
4263 std::optional<bool> Implied =
4265 return Implied && *Implied;
4266}
4267
4268/// Return true if it is known that V1 != V2.
4269static bool isKnownNonEqual(const Value *V1, const Value *V2,
4270 const APInt &DemandedElts, const SimplifyQuery &Q,
4271 unsigned Depth) {
4272 if (V1 == V2)
4273 return false;
4274 if (V1->getType() != V2->getType())
4275 // We can't look through casts yet.
4276 return false;
4277
4279 return false;
4280
4281 // See if we can recurse through (exactly one of) our operands. This
4282 // requires our operation be 1-to-1 and map every input value to exactly
4283 // one output value. Such an operation is invertible.
4284 auto *O1 = dyn_cast<Operator>(V1);
4285 auto *O2 = dyn_cast<Operator>(V2);
4286 if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
4287 if (auto Values = getInvertibleOperands(O1, O2))
4288 return isKnownNonEqual(Values->first, Values->second, DemandedElts, Q,
4289 Depth + 1);
4290
4291 if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
4292 const PHINode *PN2 = cast<PHINode>(V2);
4293 // FIXME: This is missing a generalization to handle the case where one is
4294 // a PHI and another one isn't.
4295 if (isNonEqualPHIs(PN1, PN2, DemandedElts, Q, Depth))
4296 return true;
4297 };
4298 }
4299
4300 if (isModifyingBinopOfNonZero(V1, V2, DemandedElts, Q, Depth) ||
4301 isModifyingBinopOfNonZero(V2, V1, DemandedElts, Q, Depth))
4302 return true;
4303
4304 if (isNonEqualMul(V1, V2, DemandedElts, Q, Depth) ||
4305 isNonEqualMul(V2, V1, DemandedElts, Q, Depth))
4306 return true;
4307
4308 if (isNonEqualShl(V1, V2, DemandedElts, Q, Depth) ||
4309 isNonEqualShl(V2, V1, DemandedElts, Q, Depth))
4310 return true;
4311
4312 if (V1->getType()->isIntOrIntVectorTy()) {
4313 // Are any known bits in V1 contradictory to known bits in V2? If V1
4314 // has a known zero where V2 has a known one, they must not be equal.
4315 KnownBits Known1 = computeKnownBits(V1, DemandedElts, Q, Depth);
4316 if (!Known1.isUnknown()) {
4317 KnownBits Known2 = computeKnownBits(V2, DemandedElts, Q, Depth);
4318 if (Known1.Zero.intersects(Known2.One) ||
4319 Known2.Zero.intersects(Known1.One))
4320 return true;
4321 }
4322 }
4323
4324 if (isNonEqualSelect(V1, V2, DemandedElts, Q, Depth) ||
4325 isNonEqualSelect(V2, V1, DemandedElts, Q, Depth))
4326 return true;
4327
4330 return true;
4331
4332 Value *A, *B;
4333 // PtrToInts are NonEqual if their Ptrs are NonEqual.
4334 // Check PtrToInt type matches the pointer size.
4335 if (match(V1, m_PtrToIntSameSize(Q.DL, m_Value(A))) &&
4337 return isKnownNonEqual(A, B, DemandedElts, Q, Depth + 1);
4338
4339 if (isNonEqualURem(V1, V2, Q) || isNonEqualURem(V2, V1, Q))
4340 return true;
4341
4342 if (isKnownNonEqualFromContext(V1, V2, Q, Depth))
4343 return true;
4344
4345 return false;
4346}
4347
4348/// For vector constants, loop over the elements and find the constant with the
4349/// minimum number of sign bits. Return 0 if the value is not a vector constant
4350/// or if any element was not analyzed; otherwise, return the count for the
4351/// element with the minimum number of sign bits.
4353 const APInt &DemandedElts,
4354 unsigned TyBits) {
4355 const auto *CV = dyn_cast<Constant>(V);
4356 if (!CV || !isa<FixedVectorType>(CV->getType()))
4357 return 0;
4358
4359 unsigned MinSignBits = TyBits;
4360 unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
4361 for (unsigned i = 0; i != NumElts; ++i) {
4362 if (!DemandedElts[i])
4363 continue;
4364 // If we find a non-ConstantInt, bail out.
4365 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
4366 if (!Elt)
4367 return 0;
4368
4369 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
4370 }
4371
4372 return MinSignBits;
4373}
4374
4375static unsigned ComputeNumSignBitsImpl(const Value *V,
4376 const APInt &DemandedElts,
4377 const SimplifyQuery &Q, unsigned Depth);
4378
4379static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
4380 const SimplifyQuery &Q, unsigned Depth) {
4381 unsigned Result = ComputeNumSignBitsImpl(V, DemandedElts, Q, Depth);
4382 assert(Result > 0 && "At least one sign bit needs to be present!");
4383 return Result;
4384}
4385
4386/// Return the number of times the sign bit of the register is replicated into
4387/// the other bits. We know that at least 1 bit is always equal to the sign bit
4388/// (itself), but other cases can give us information. For example, immediately
4389/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
4390/// other, so we return 3. For vectors, return the number of sign bits for the
4391/// vector element with the minimum number of known sign bits of the demanded
4392/// elements in the vector specified by DemandedElts.
4393static unsigned ComputeNumSignBitsImpl(const Value *V,
4394 const APInt &DemandedElts,
4395 const SimplifyQuery &Q, unsigned Depth) {
4396 Type *Ty = V->getType();
4397#ifndef NDEBUG
4398 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
4399
4400 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
4401 assert(
4402 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
4403 "DemandedElt width should equal the fixed vector number of elements");
4404 } else {
4405 assert(DemandedElts == APInt(1, 1) &&
4406 "DemandedElt width should be 1 for scalars");
4407 }
4408#endif
4409
4410 // We return the minimum number of sign bits that are guaranteed to be present
4411 // in V, so for undef we have to conservatively return 1. We don't have the
4412 // same behavior for poison though -- that's a FIXME today.
4413
4414 Type *ScalarTy = Ty->getScalarType();
4415 unsigned TyBits = ScalarTy->isPointerTy() ?
4416 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
4417 Q.DL.getTypeSizeInBits(ScalarTy);
4418
4419 unsigned Tmp, Tmp2;
4420 unsigned FirstAnswer = 1;
4421
4422 // Note that ConstantInt is handled by the general computeKnownBits case
4423 // below.
4424
4426 return 1;
4427
4428 if (auto *U = dyn_cast<Operator>(V)) {
4429 switch (Operator::getOpcode(V)) {
4430 default: break;
4431 case Instruction::BitCast: {
4432 Value *Src = U->getOperand(0);
4433 Type *SrcTy = Src->getType();
4434
4435 // Skip if the source type is not an integer or integer vector type
4436 // This ensures we only process integer-like types
4437 if (!SrcTy->isIntOrIntVectorTy())
4438 break;
4439
4440 unsigned SrcBits = SrcTy->getScalarSizeInBits();
4441
4442 // Bitcast 'large element' scalar/vector to 'small element' vector.
4443 if ((SrcBits % TyBits) != 0)
4444 break;
4445
4446 // Only proceed if the destination type is a fixed-size vector
4447 if (isa<FixedVectorType>(Ty)) {
4448 // Fast case - sign splat can be simply split across the small elements.
4449 // This works for both vector and scalar sources
4450 Tmp = ComputeNumSignBits(Src, Q, Depth + 1);
4451 if (Tmp == SrcBits)
4452 return TyBits;
4453 }
4454 break;
4455 }
4456 case Instruction::SExt:
4457 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
4458 return ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1) +
4459 Tmp;
4460
4461 case Instruction::SDiv: {
4462 const APInt *Denominator;
4463 // sdiv X, C -> adds log(C) sign bits.
4464 if (match(U->getOperand(1), m_APInt(Denominator))) {
4465
4466 // Ignore non-positive denominator.
4467 if (!Denominator->isStrictlyPositive())
4468 break;
4469
4470 // Calculate the incoming numerator bits.
4471 unsigned NumBits =
4472 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4473
4474 // Add floor(log(C)) bits to the numerator bits.
4475 return std::min(TyBits, NumBits + Denominator->logBase2());
4476 }
4477 break;
4478 }
4479
4480 case Instruction::SRem: {
4481 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4482
4483 const APInt *Denominator;
4484 // srem X, C -> we know that the result is within [-C+1,C) when C is a
4485 // positive constant. This let us put a lower bound on the number of sign
4486 // bits.
4487 if (match(U->getOperand(1), m_APInt(Denominator))) {
4488
4489 // Ignore non-positive denominator.
4490 if (Denominator->isStrictlyPositive()) {
4491 // Calculate the leading sign bit constraints by examining the
4492 // denominator. Given that the denominator is positive, there are two
4493 // cases:
4494 //
4495 // 1. The numerator is positive. The result range is [0,C) and
4496 // [0,C) u< (1 << ceilLogBase2(C)).
4497 //
4498 // 2. The numerator is negative. Then the result range is (-C,0] and
4499 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
4500 //
4501 // Thus a lower bound on the number of sign bits is `TyBits -
4502 // ceilLogBase2(C)`.
4503
4504 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
4505 Tmp = std::max(Tmp, ResBits);
4506 }
4507 }
4508 return Tmp;
4509 }
4510
4511 case Instruction::AShr: {
4512 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4513 // ashr X, C -> adds C sign bits. Vectors too.
4514 const APInt *ShAmt;
4515 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4516 if (ShAmt->uge(TyBits))
4517 break; // Bad shift.
4518 unsigned ShAmtLimited = ShAmt->getZExtValue();
4519 Tmp += ShAmtLimited;
4520 if (Tmp > TyBits) Tmp = TyBits;
4521 }
4522 return Tmp;
4523 }
4524 case Instruction::Shl: {
4525 const APInt *ShAmt;
4526 Value *X = nullptr;
4527 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4528 // shl destroys sign bits.
4529 if (ShAmt->uge(TyBits))
4530 break; // Bad shift.
4531 // We can look through a zext (more or less treating it as a sext) if
4532 // all extended bits are shifted out.
4533 if (match(U->getOperand(0), m_ZExt(m_Value(X))) &&
4534 ShAmt->uge(TyBits - X->getType()->getScalarSizeInBits())) {
4535 Tmp = ComputeNumSignBits(X, DemandedElts, Q, Depth + 1);
4536 Tmp += TyBits - X->getType()->getScalarSizeInBits();
4537 } else
4538 Tmp =
4539 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4540 if (ShAmt->uge(Tmp))
4541 break; // Shifted all sign bits out.
4542 Tmp2 = ShAmt->getZExtValue();
4543 return Tmp - Tmp2;
4544 }
4545 break;
4546 }
4547 case Instruction::And:
4548 case Instruction::Or:
4549 case Instruction::Xor: // NOT is handled here.
4550 // Logical binary ops preserve the number of sign bits at the worst.
4551 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4552 if (Tmp != 1) {
4553 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4554 FirstAnswer = std::min(Tmp, Tmp2);
4555 // We computed what we know about the sign bits as our first
4556 // answer. Now proceed to the generic code that uses
4557 // computeKnownBits, and pick whichever answer is better.
4558 }
4559 break;
4560
4561 case Instruction::Select: {
4562 // If we have a clamp pattern, we know that the number of sign bits will
4563 // be the minimum of the clamp min/max range.
4564 const Value *X;
4565 const APInt *CLow, *CHigh;
4566 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
4567 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4568
4569 Tmp = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4570 if (Tmp == 1)
4571 break;
4572 Tmp2 = ComputeNumSignBits(U->getOperand(2), DemandedElts, Q, Depth + 1);
4573 return std::min(Tmp, Tmp2);
4574 }
4575
4576 case Instruction::Add:
4577 // Add can have at most one carry bit. Thus we know that the output
4578 // is, at worst, one more bit than the inputs.
4579 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4580 if (Tmp == 1) break;
4581
4582 // Special case decrementing a value (ADD X, -1):
4583 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
4584 if (CRHS->isAllOnesValue()) {
4585 KnownBits Known(TyBits);
4586 computeKnownBits(U->getOperand(0), DemandedElts, Known, Q, Depth + 1);
4587
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 we are subtracting one from a positive number, there is no carry
4594 // out of the result.
4595 if (Known.isNonNegative())
4596 return Tmp;
4597 }
4598
4599 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4600 if (Tmp2 == 1)
4601 break;
4602 return std::min(Tmp, Tmp2) - 1;
4603
4604 case Instruction::Sub:
4605 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4606 if (Tmp2 == 1)
4607 break;
4608
4609 // Handle NEG.
4610 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
4611 if (CLHS->isNullValue()) {
4612 KnownBits Known(TyBits);
4613 computeKnownBits(U->getOperand(1), DemandedElts, Known, Q, Depth + 1);
4614 // If the input is known to be 0 or 1, the output is 0/-1, which is
4615 // all sign bits set.
4616 if ((Known.Zero | 1).isAllOnes())
4617 return TyBits;
4618
4619 // If the input is known to be positive (the sign bit is known clear),
4620 // the output of the NEG has the same number of sign bits as the
4621 // input.
4622 if (Known.isNonNegative())
4623 return Tmp2;
4624
4625 // Otherwise, we treat this like a SUB.
4626 }
4627
4628 // Sub can have at most one carry bit. Thus we know that the output
4629 // is, at worst, one more bit than the inputs.
4630 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4631 if (Tmp == 1)
4632 break;
4633 return std::min(Tmp, Tmp2) - 1;
4634
4635 case Instruction::Mul: {
4636 // The output of the Mul can be at most twice the valid bits in the
4637 // inputs.
4638 unsigned SignBitsOp0 =
4639 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4640 if (SignBitsOp0 == 1)
4641 break;
4642 unsigned SignBitsOp1 =
4643 ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4644 if (SignBitsOp1 == 1)
4645 break;
4646 unsigned OutValidBits =
4647 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
4648 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
4649 }
4650
4651 case Instruction::PHI: {
4652 const PHINode *PN = cast<PHINode>(U);
4653 unsigned NumIncomingValues = PN->getNumIncomingValues();
4654 // Don't analyze large in-degree PHIs.
4655 if (NumIncomingValues > 4) break;
4656 // Unreachable blocks may have zero-operand PHI nodes.
4657 if (NumIncomingValues == 0) break;
4658
4659 // Take the minimum of all incoming values. This can't infinitely loop
4660 // because of our depth threshold.
4662 Tmp = TyBits;
4663 for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
4664 if (Tmp == 1) return Tmp;
4665 RecQ.CxtI = PN->getIncomingBlock(i)->getTerminator();
4666 Tmp = std::min(Tmp, ComputeNumSignBits(PN->getIncomingValue(i),
4667 DemandedElts, RecQ, Depth + 1));
4668 }
4669 return Tmp;
4670 }
4671
4672 case Instruction::Trunc: {
4673 // If the input contained enough sign bits that some remain after the
4674 // truncation, then we can make use of that. Otherwise we don't know
4675 // anything.
4676 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4677 unsigned OperandTyBits = U->getOperand(0)->getType()->getScalarSizeInBits();
4678 if (Tmp > (OperandTyBits - TyBits))
4679 return Tmp - (OperandTyBits - TyBits);
4680
4681 return 1;
4682 }
4683
4684 case Instruction::ExtractElement:
4685 // Look through extract element. At the moment we keep this simple and
4686 // skip tracking the specific element. But at least we might find
4687 // information valid for all elements of the vector (for example if vector
4688 // is sign extended, shifted, etc).
4689 return ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4690
4691 case Instruction::ShuffleVector: {
4692 // Collect the minimum number of sign bits that are shared by every vector
4693 // element referenced by the shuffle.
4694 auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
4695 if (!Shuf) {
4696 // FIXME: Add support for shufflevector constant expressions.
4697 return 1;
4698 }
4699 APInt DemandedLHS, DemandedRHS;
4700 // For undef elements, we don't know anything about the common state of
4701 // the shuffle result.
4702 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
4703 return 1;
4704 Tmp = std::numeric_limits<unsigned>::max();
4705 if (!!DemandedLHS) {
4706 const Value *LHS = Shuf->getOperand(0);
4707 Tmp = ComputeNumSignBits(LHS, DemandedLHS, Q, Depth + 1);
4708 }
4709 // If we don't know anything, early out and try computeKnownBits
4710 // fall-back.
4711 if (Tmp == 1)
4712 break;
4713 if (!!DemandedRHS) {
4714 const Value *RHS = Shuf->getOperand(1);
4715 Tmp2 = ComputeNumSignBits(RHS, DemandedRHS, Q, Depth + 1);
4716 Tmp = std::min(Tmp, Tmp2);
4717 }
4718 // If we don't know anything, early out and try computeKnownBits
4719 // fall-back.
4720 if (Tmp == 1)
4721 break;
4722 assert(Tmp <= TyBits && "Failed to determine minimum sign bits");
4723 return Tmp;
4724 }
4725 case Instruction::Call: {
4726 if (const auto *II = dyn_cast<IntrinsicInst>(U)) {
4727 switch (II->getIntrinsicID()) {
4728 default:
4729 break;
4730 case Intrinsic::abs:
4731 Tmp =
4732 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4733 if (Tmp == 1)
4734 break;
4735
4736 // Absolute value reduces number of sign bits by at most 1.
4737 return Tmp - 1;
4738 case Intrinsic::smin:
4739 case Intrinsic::smax: {
4740 const APInt *CLow, *CHigh;
4741 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
4742 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4743 }
4744 }
4745 }
4746 }
4747 }
4748 }
4749
4750 // Finally, if we can prove that the top bits of the result are 0's or 1's,
4751 // use this information.
4752
4753 // If we can examine all elements of a vector constant successfully, we're
4754 // done (we can't do any better than that). If not, keep trying.
4755 if (unsigned VecSignBits =
4756 computeNumSignBitsVectorConstant(V, DemandedElts, TyBits))
4757 return VecSignBits;
4758
4759 KnownBits Known(TyBits);
4760 computeKnownBits(V, DemandedElts, Known, Q, Depth);
4761
4762 // If we know that the sign bit is either zero or one, determine the number of
4763 // identical bits in the top of the input value.
4764 return std::max(FirstAnswer, Known.countMinSignBits());
4765}
4766
4768 const TargetLibraryInfo *TLI) {
4769 const Function *F = CB.getCalledFunction();
4770 if (!F)
4772
4773 if (F->isIntrinsic())
4774 return F->getIntrinsicID();
4775
4776 // We are going to infer semantics of a library function based on mapping it
4777 // to an LLVM intrinsic. Check that the library function is available from
4778 // this callbase and in this environment.
4779 if (F->hasLocalLinkage() || !TLI || !CB.onlyReadsMemory())
4781
4782 LibFunc Func = TLI->getLibFunc(CB);
4783 if (Func == NotLibFunc)
4785
4786 switch (Func) {
4787 default:
4788 break;
4789 case LibFunc_sin:
4790 case LibFunc_sinf:
4791 case LibFunc_sinl:
4792 return Intrinsic::sin;
4793 case LibFunc_cos:
4794 case LibFunc_cosf:
4795 case LibFunc_cosl:
4796 return Intrinsic::cos;
4797 case LibFunc_tan:
4798 case LibFunc_tanf:
4799 case LibFunc_tanl:
4800 return Intrinsic::tan;
4801 case LibFunc_asin:
4802 case LibFunc_asinf:
4803 case LibFunc_asinl:
4804 return Intrinsic::asin;
4805 case LibFunc_acos:
4806 case LibFunc_acosf:
4807 case LibFunc_acosl:
4808 return Intrinsic::acos;
4809 case LibFunc_atan:
4810 case LibFunc_atanf:
4811 case LibFunc_atanl:
4812 return Intrinsic::atan;
4813 case LibFunc_atan2:
4814 case LibFunc_atan2f:
4815 case LibFunc_atan2l:
4816 return Intrinsic::atan2;
4817 case LibFunc_sinh:
4818 case LibFunc_sinhf:
4819 case LibFunc_sinhl:
4820 return Intrinsic::sinh;
4821 case LibFunc_cosh:
4822 case LibFunc_coshf:
4823 case LibFunc_coshl:
4824 return Intrinsic::cosh;
4825 case LibFunc_tanh:
4826 case LibFunc_tanhf:
4827 case LibFunc_tanhl:
4828 return Intrinsic::tanh;
4829 case LibFunc_exp:
4830 case LibFunc_expf:
4831 case LibFunc_expl:
4832 return Intrinsic::exp;
4833 case LibFunc_exp2:
4834 case LibFunc_exp2f:
4835 case LibFunc_exp2l:
4836 return Intrinsic::exp2;
4837 case LibFunc_exp10:
4838 case LibFunc_exp10f:
4839 case LibFunc_exp10l:
4840 return Intrinsic::exp10;
4841 case LibFunc_log:
4842 case LibFunc_logf:
4843 case LibFunc_logl:
4844 return Intrinsic::log;
4845 case LibFunc_log10:
4846 case LibFunc_log10f:
4847 case LibFunc_log10l:
4848 return Intrinsic::log10;
4849 case LibFunc_log2:
4850 case LibFunc_log2f:
4851 case LibFunc_log2l:
4852 return Intrinsic::log2;
4853 case LibFunc_fabs:
4854 case LibFunc_fabsf:
4855 case LibFunc_fabsl:
4856 return Intrinsic::fabs;
4857 case LibFunc_fmin:
4858 case LibFunc_fminf:
4859 case LibFunc_fminl:
4860 return Intrinsic::minnum;
4861 case LibFunc_fmax:
4862 case LibFunc_fmaxf:
4863 case LibFunc_fmaxl:
4864 return Intrinsic::maxnum;
4865 case LibFunc_copysign:
4866 case LibFunc_copysignf:
4867 case LibFunc_copysignl:
4868 return Intrinsic::copysign;
4869 case LibFunc_floor:
4870 case LibFunc_floorf:
4871 case LibFunc_floorl:
4872 return Intrinsic::floor;
4873 case LibFunc_ceil:
4874 case LibFunc_ceilf:
4875 case LibFunc_ceill:
4876 return Intrinsic::ceil;
4877 case LibFunc_trunc:
4878 case LibFunc_truncf:
4879 case LibFunc_truncl:
4880 return Intrinsic::trunc;
4881 case LibFunc_rint:
4882 case LibFunc_rintf:
4883 case LibFunc_rintl:
4884 return Intrinsic::rint;
4885 case LibFunc_nearbyint:
4886 case LibFunc_nearbyintf:
4887 case LibFunc_nearbyintl:
4888 return Intrinsic::nearbyint;
4889 case LibFunc_round:
4890 case LibFunc_roundf:
4891 case LibFunc_roundl:
4892 return Intrinsic::round;
4893 case LibFunc_roundeven:
4894 case LibFunc_roundevenf:
4895 case LibFunc_roundevenl:
4896 return Intrinsic::roundeven;
4897 case LibFunc_pow:
4898 case LibFunc_powf:
4899 case LibFunc_powl:
4900 return Intrinsic::pow;
4901 case LibFunc_sqrt:
4902 case LibFunc_sqrtf:
4903 case LibFunc_sqrtl:
4904 return Intrinsic::sqrt;
4905 }
4906
4908}
4909
4910/// Given an exploded icmp instruction, return true if the comparison only
4911/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if
4912/// the result of the comparison is true when the input value is signed.
4914 bool &TrueIfSigned) {
4915 switch (Pred) {
4916 case ICmpInst::ICMP_SLT: // True if LHS s< 0
4917 TrueIfSigned = true;
4918 return RHS.isZero();
4919 case ICmpInst::ICMP_SLE: // True if LHS s<= -1
4920 TrueIfSigned = true;
4921 return RHS.isAllOnes();
4922 case ICmpInst::ICMP_SGT: // True if LHS s> -1
4923 TrueIfSigned = false;
4924 return RHS.isAllOnes();
4925 case ICmpInst::ICMP_SGE: // True if LHS s>= 0
4926 TrueIfSigned = false;
4927 return RHS.isZero();
4928 case ICmpInst::ICMP_UGT:
4929 // True if LHS u> RHS and RHS == sign-bit-mask - 1
4930 TrueIfSigned = true;
4931 return RHS.isMaxSignedValue();
4932 case ICmpInst::ICMP_UGE:
4933 // True if LHS u>= RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4934 TrueIfSigned = true;
4935 return RHS.isMinSignedValue();
4936 case ICmpInst::ICMP_ULT:
4937 // True if LHS u< RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4938 TrueIfSigned = false;
4939 return RHS.isMinSignedValue();
4940 case ICmpInst::ICMP_ULE:
4941 // True if LHS u<= RHS and RHS == sign-bit-mask - 1
4942 TrueIfSigned = false;
4943 return RHS.isMaxSignedValue();
4944 default:
4945 return false;
4946 }
4947}
4948
4950 bool CondIsTrue,
4951 const Instruction *CxtI,
4952 KnownFPClass &KnownFromContext,
4953 unsigned Depth = 0) {
4954 Value *A, *B;
4956 (CondIsTrue ? match(Cond, m_LogicalAnd(m_Value(A), m_Value(B)))
4957 : match(Cond, m_LogicalOr(m_Value(A), m_Value(B))))) {
4958 computeKnownFPClassFromCond(V, A, CondIsTrue, CxtI, KnownFromContext,
4959 Depth + 1);
4960 computeKnownFPClassFromCond(V, B, CondIsTrue, CxtI, KnownFromContext,
4961 Depth + 1);
4962 return;
4963 }
4965 computeKnownFPClassFromCond(V, A, !CondIsTrue, CxtI, KnownFromContext,
4966 Depth + 1);
4967 return;
4968 }
4969 CmpPredicate Pred;
4970 Value *LHS;
4971 uint64_t ClassVal = 0;
4972 const APFloat *CRHS;
4973 const APInt *RHS;
4974 if (match(Cond, m_FCmp(Pred, m_Value(LHS), m_APFloat(CRHS)))) {
4975 auto [CmpVal, MaskIfTrue, MaskIfFalse] = fcmpImpliesClass(
4976 Pred, *cast<Instruction>(Cond)->getParent()->getParent(), LHS, *CRHS,
4977 LHS != V);
4978 if (CmpVal == V)
4979 KnownFromContext.knownNot(~(CondIsTrue ? MaskIfTrue : MaskIfFalse));
4981 m_Specific(V), m_ConstantInt(ClassVal)))) {
4982 FPClassTest Mask = static_cast<FPClassTest>(ClassVal);
4983 KnownFromContext.knownNot(CondIsTrue ? ~Mask : Mask);
4984 } else if (match(Cond, m_ICmp(Pred, m_ElementWiseBitCast(m_Specific(V)),
4985 m_APInt(RHS)))) {
4986 bool TrueIfSigned;
4987 if (!isSignBitCheck(Pred, *RHS, TrueIfSigned))
4988 return;
4989 if (TrueIfSigned == CondIsTrue)
4990 KnownFromContext.signBitMustBeOne();
4991 else
4992 KnownFromContext.signBitMustBeZero();
4993 }
4994}
4995
4996/// Compute the minimum and maximum values (inclusive) for the exponent of \p V,
4997/// assuming it is not nan. Returns {min, max, max-assuming-nonzero}. A value
4998/// frexp(0) = 0, so the tighter max-assuming-nonzero bound is only usable when
4999/// \p V is known not to be a logical zero (e.g., for fabs(x) < 0.25, the non-0
5000/// exponent range is [-149, -2], but the 0 edge case is above this range).
5001static std::tuple<int, int, int>
5003 if (!Q.CxtI || !Q.DC || !Q.DT)
5005
5006 // Intersect the bounds implied by every dominating condition, keeping the
5007 // tightest maximum. A value may participate in multiple compares
5008 // (e.g. fabs(x) < 2.0 and fabs(x) < 1.0), and the tighter one wins.
5009 int MaxExp = APFloat::IEK_Inf;
5010 int MaxExpNonZero = APFloat::IEK_Inf;
5011
5012 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5013 CmpPredicate Pred;
5014 const APFloat *LimitC;
5015 if (!match(BI->getCondition(),
5016 m_FCmp(Pred, m_FAbs(m_Specific(V)), m_Finite(LimitC))))
5017 continue;
5018
5019 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO ||
5020 Pred == FCmpInst::FCMP_TRUE || Pred == FCmpInst::FCMP_FALSE)
5021 continue;
5022
5023 // If fabs(x) <= K, implies the exponent min exp range.
5024 // if fabs(x) >= K, swap the successor
5025 bool IsLessEqual =
5026 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
5027 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE ||
5028 Pred == FCmpInst::FCMP_OEQ || Pred == FCmpInst::FCMP_UEQ;
5029
5030 bool KnownStrictlyLess =
5031 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT ||
5032 Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
5033
5034 BasicBlockEdge Edge1(BI->getParent(),
5035 BI->getSuccessor(IsLessEqual ? 0 : 1));
5036 if (Q.DT->dominates(Edge1, Q.CxtI->getParent())) {
5037 // frexp returns an exponent one greater than ilogb.
5038 int Exp = ilogb(*LimitC) + 1;
5039
5040 // A strict bound fabs(V) < 2^n forces ilogb(V) <= n - 1, so the max frexp
5041 // exponent drops by one when K is exact power of two.
5042 if (KnownStrictlyLess && LimitC->getExactLog2Abs() != INT_MIN)
5043 --Exp;
5044
5045 // frexp(0) = 0, which the bound above (assuming a normal nonzero value)
5046 // may exclude.
5047
5048 // TODO: Figure out lower bound to detect no-underflow.
5049 MaxExpNonZero = std::min(MaxExpNonZero, Exp);
5050 MaxExp = std::min(MaxExp, std::max(Exp, 0));
5051 }
5052 }
5053
5054 return {APFloat::IEK_NaN, MaxExp, MaxExpNonZero};
5055}
5056
5058 const SimplifyQuery &Q) {
5059 KnownFPClass KnownFromContext;
5060
5061 if (Q.CC && Q.CC->AffectedValues.contains(V))
5063 KnownFromContext);
5064
5065 if (!Q.CxtI)
5066 return KnownFromContext;
5067
5068 if (Q.DC && Q.DT) {
5069 // Handle dominating conditions.
5070 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5071 Value *Cond = BI->getCondition();
5072
5073 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
5074 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()))
5075 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/true, Q.CxtI,
5076 KnownFromContext);
5077
5078 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
5079 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()))
5080 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/false, Q.CxtI,
5081 KnownFromContext);
5082 }
5083 }
5084
5085 if (!Q.AC)
5086 return KnownFromContext;
5087
5088 // Try to restrict the floating-point classes based on information from
5089 // assumptions.
5090 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
5091 if (!AssumeVH)
5092 continue;
5093 CallInst *I = cast<CallInst>(AssumeVH);
5094
5095 assert(I->getFunction() == Q.CxtI->getParent()->getParent() &&
5096 "Got assumption for the wrong function!");
5097 assert(I->getIntrinsicID() == Intrinsic::assume &&
5098 "must be an assume intrinsic");
5099
5100 if (!isValidAssumeForContext(I, Q))
5101 continue;
5102
5103 computeKnownFPClassFromCond(V, I->getArgOperand(0),
5104 /*CondIsTrue=*/true, Q.CxtI, KnownFromContext);
5105 }
5106
5107 return KnownFromContext;
5108}
5109
5111 Value *Arm, bool Invert,
5112 const SimplifyQuery &SQ,
5113 unsigned Depth) {
5114
5115 KnownFPClass KnownSrc;
5117 /*CondIsTrue=*/!Invert, SQ.CxtI, KnownSrc,
5118 Depth + 1);
5119 KnownSrc = KnownSrc.unionWith(Known);
5120 if (KnownSrc.isUnknown())
5121 return;
5122
5123 if (isGuaranteedNotToBeUndef(Arm, SQ.AC, SQ.CxtI, SQ.DT, Depth + 1))
5124 Known = KnownSrc;
5125}
5126
5127void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5128 FPClassTest InterestedClasses, KnownFPClass &Known,
5129 const SimplifyQuery &Q, unsigned Depth);
5130
5132 FPClassTest InterestedClasses,
5133 const SimplifyQuery &Q, unsigned Depth) {
5134 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
5135 APInt DemandedElts =
5136 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
5137 computeKnownFPClass(V, DemandedElts, InterestedClasses, Known, Q, Depth);
5138}
5139
5141 const APInt &DemandedElts,
5142 FPClassTest InterestedClasses,
5144 const SimplifyQuery &Q,
5145 unsigned Depth) {
5146 if ((InterestedClasses &
5148 return;
5149
5150 KnownFPClass KnownSrc;
5151 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5152 KnownSrc, Q, Depth + 1);
5153 Known = KnownFPClass::fptrunc(KnownSrc);
5154}
5155
5157 switch (IID) {
5158 case Intrinsic::minimum:
5160 case Intrinsic::maximum:
5162 case Intrinsic::minimumnum:
5164 case Intrinsic::maximumnum:
5166 case Intrinsic::minnum:
5168 case Intrinsic::maxnum:
5170 default:
5171 llvm_unreachable("not a floating-point min-max intrinsic");
5172 }
5173}
5174
5175/// \return true if this is a floating point value that is known to have a
5176/// magnitude smaller than 1. i.e., fabs(X) <= 1.0 or is nan.
5177static bool isAbsoluteValueULEOne(const Value *V) {
5178 // TODO: Handle frexp
5179 // TODO: Other rounding intrinsics?
5180 // TODO: Try computeKnownExponentRangeFromContext
5181
5182 // fabs(x - floor(x)) <= 1
5183 const Value *SubFloorX;
5184 if (match(V, m_FSub(m_Value(SubFloorX),
5186 return true;
5187
5190}
5191
5192void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5193 FPClassTest InterestedClasses, KnownFPClass &Known,
5194 const SimplifyQuery &Q, unsigned Depth) {
5195 assert(Known.isUnknown() && "should not be called with known information");
5196
5197 if (!DemandedElts) {
5198 // No demanded elts, better to assume we don't know anything.
5199 Known.resetAll();
5200 return;
5201 }
5202
5203 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
5204
5205 if (auto *CFP = dyn_cast<ConstantFP>(V)) {
5206 Known = KnownFPClass(CFP->getValueAPF());
5207 return;
5208 }
5209
5211 Known.setKnownFPClasses(fcPosZero);
5212 Known.setSignBit(false);
5213 return;
5214 }
5215
5216 if (isa<PoisonValue>(V)) {
5217 Known.setKnownFPClasses(fcNone);
5218 Known.setSignBit(false);
5219 return;
5220 }
5221
5222 // Try to handle fixed width vector constants
5223 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
5224 const Constant *CV = dyn_cast<Constant>(V);
5225 if (VFVTy && CV) {
5226 Known.setKnownFPClasses(fcNone);
5227 bool SignBitAllZero = true;
5228 bool SignBitAllOne = true;
5229
5230 // For vectors, verify that each element is not NaN.
5231 unsigned NumElts = VFVTy->getNumElements();
5232 for (unsigned i = 0; i != NumElts; ++i) {
5233 if (!DemandedElts[i])
5234 continue;
5235
5236 Constant *Elt = CV->getAggregateElement(i);
5237 if (!Elt) {
5238 Known = KnownFPClass();
5239 return;
5240 }
5241 if (isa<PoisonValue>(Elt))
5242 continue;
5243 auto *CElt = dyn_cast<ConstantFP>(Elt);
5244 if (!CElt) {
5245 Known = KnownFPClass();
5246 return;
5247 }
5248
5249 const APFloat &C = CElt->getValueAPF();
5250 Known.setKnownFPClasses(Known.getKnownFPClasses() | C.classify());
5251 if (C.isNegative())
5252 SignBitAllZero = false;
5253 else
5254 SignBitAllOne = false;
5255 }
5256 if (SignBitAllOne != SignBitAllZero)
5257 Known.setSignBit(SignBitAllOne);
5258 return;
5259 }
5260
5261 if (const auto *CDS = dyn_cast<ConstantDataSequential>(V)) {
5262 Known.setKnownFPClasses(fcNone);
5263 for (size_t I = 0, E = CDS->getNumElements(); I != E; ++I)
5264 Known |= CDS->getElementAsAPFloat(I).classify();
5265 return;
5266 }
5267
5268 if (const auto *CA = dyn_cast<ConstantAggregate>(V)) {
5269 // TODO: Handle complex aggregates
5270 Known.setKnownFPClasses(fcNone);
5271 for (const Use &Op : CA->operands()) {
5272 auto *CFP = dyn_cast<ConstantFP>(Op.get());
5273 if (!CFP) {
5274 Known = KnownFPClass();
5275 return;
5276 }
5277
5278 Known |= CFP->getValueAPF().classify();
5279 }
5280
5281 return;
5282 }
5283
5284 FPClassTest KnownNotFromFlags = fcNone;
5285 if (const auto *CB = dyn_cast<CallBase>(V))
5286 KnownNotFromFlags |= CB->getRetNoFPClass();
5287 else if (const auto *Arg = dyn_cast<Argument>(V))
5288 KnownNotFromFlags |= Arg->getNoFPClass();
5289
5290 const Operator *Op = dyn_cast<Operator>(V);
5292 if (FPOp->hasNoNaNs())
5293 KnownNotFromFlags |= fcNan;
5294 if (FPOp->hasNoInfs())
5295 KnownNotFromFlags |= fcInf;
5296 }
5297
5298 KnownFPClass AssumedClasses = computeKnownFPClassFromContext(V, Q);
5299 KnownNotFromFlags |= ~AssumedClasses.getKnownFPClasses();
5300
5301 // We no longer need to find out about these bits from inputs if we can
5302 // assume this from flags/attributes.
5303 InterestedClasses &= ~KnownNotFromFlags;
5304
5305 llvm::scope_exit ClearClassesFromFlags([=, &Known] {
5306 Known.knownNot(KnownNotFromFlags);
5307 if (!Known.getSignBit() && AssumedClasses.getSignBit()) {
5308 if (*AssumedClasses.getSignBit())
5309 Known.signBitMustBeOne();
5310 else
5311 Known.signBitMustBeZero();
5312 }
5313 });
5314
5315 if (!Op)
5316 return;
5317
5318 // All recursive calls that increase depth must come after this.
5320 return;
5321
5322 const unsigned Opc = Op->getOpcode();
5323 switch (Opc) {
5324 case Instruction::FNeg: {
5325 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5326 Known, Q, Depth + 1);
5327 Known.fneg();
5328 break;
5329 }
5330 case Instruction::Select: {
5331 auto ComputeForArm = [&](Value *Arm, bool Invert) {
5332 KnownFPClass Res;
5333 computeKnownFPClass(Arm, DemandedElts, InterestedClasses, Res, Q,
5334 Depth + 1);
5335 adjustKnownFPClassForSelectArm(Res, Op->getOperand(0), Arm, Invert, Q,
5336 Depth);
5337 return Res;
5338 };
5339 // Only known if known in both the LHS and RHS.
5340 Known =
5341 ComputeForArm(Op->getOperand(1), /*Invert=*/false)
5342 .intersectWith(ComputeForArm(Op->getOperand(2), /*Invert=*/true));
5343 break;
5344 }
5345 case Instruction::Load: {
5346 const MDNode *NoFPClass =
5347 cast<LoadInst>(Op)->getMetadata(LLVMContext::MD_nofpclass);
5348 if (!NoFPClass)
5349 break;
5350
5351 ConstantInt *MaskVal =
5353 Known.knownNot(static_cast<FPClassTest>(MaskVal->getZExtValue()));
5354 break;
5355 }
5356 case Instruction::Call: {
5357 const CallInst *II = cast<CallInst>(Op);
5358 const Intrinsic::ID IID = II->getIntrinsicID();
5359 switch (IID) {
5360 case Intrinsic::fabs: {
5361 if ((InterestedClasses & (fcNan | fcPositive)) != fcNone) {
5362 // If we only care about the sign bit we don't need to inspect the
5363 // operand.
5364 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5365 InterestedClasses, Known, Q, Depth + 1);
5366 }
5367
5368 Known.fabs();
5369 break;
5370 }
5371 case Intrinsic::copysign: {
5372 KnownFPClass KnownSign;
5373
5374 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5375 Known, Q, Depth + 1);
5376 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5377 KnownSign, Q, Depth + 1);
5378 Known.copysign(KnownSign);
5379 break;
5380 }
5381 case Intrinsic::fma:
5382 case Intrinsic::fmuladd: {
5383 if ((InterestedClasses & fcNegative) == fcNone)
5384 break;
5385
5386 // FIXME: This should check isGuaranteedNotToBeUndef
5387 if (II->getArgOperand(0) == II->getArgOperand(1)) {
5388 KnownFPClass KnownSrc, KnownAddend;
5389 computeKnownFPClass(II->getArgOperand(2), DemandedElts,
5390 InterestedClasses, KnownAddend, Q, Depth + 1);
5391 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5392 InterestedClasses, KnownSrc, Q, Depth + 1);
5393
5394 const Function *F = II->getFunction();
5395 const fltSemantics &FltSem =
5396 II->getType()->getScalarType()->getFltSemantics();
5398 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5399
5400 if (KnownNotFromFlags & fcNan) {
5401 KnownSrc.knownNot(fcNan);
5402 KnownAddend.knownNot(fcNan);
5403 }
5404
5405 if (KnownNotFromFlags & fcInf) {
5406 KnownSrc.knownNot(fcInf);
5407 KnownAddend.knownNot(fcInf);
5408 }
5409
5410 Known = KnownFPClass::fma_square(KnownSrc, KnownAddend, Mode);
5411 break;
5412 }
5413
5414 KnownFPClass KnownSrc[3];
5415 for (int I = 0; I != 3; ++I) {
5416 computeKnownFPClass(II->getArgOperand(I), DemandedElts,
5417 InterestedClasses, KnownSrc[I], Q, Depth + 1);
5418 if (KnownSrc[I].isUnknown())
5419 return;
5420
5421 if (KnownNotFromFlags & fcNan)
5422 KnownSrc[I].knownNot(fcNan);
5423 if (KnownNotFromFlags & fcInf)
5424 KnownSrc[I].knownNot(fcInf);
5425 }
5426
5427 const Function *F = II->getFunction();
5428 const fltSemantics &FltSem =
5429 II->getType()->getScalarType()->getFltSemantics();
5431 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5432 Known = KnownFPClass::fma(KnownSrc[0], KnownSrc[1], KnownSrc[2], Mode);
5433 break;
5434 }
5435 case Intrinsic::sqrt:
5436 case Intrinsic::experimental_constrained_sqrt: {
5437 KnownFPClass KnownSrc;
5438 FPClassTest InterestedSrcs = InterestedClasses;
5439 if (InterestedClasses & fcNan)
5440 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5441
5442 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5443 KnownSrc, Q, Depth + 1);
5444
5446
5447 bool HasNSZ = Q.IIQ.hasNoSignedZeros(II);
5448 if (!HasNSZ) {
5449 const Function *F = II->getFunction();
5450 const fltSemantics &FltSem =
5451 II->getType()->getScalarType()->getFltSemantics();
5452 Mode = F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5453 }
5454
5455 Known = KnownFPClass::sqrt(KnownSrc, Mode);
5456 if (HasNSZ)
5457 Known.knownNot(fcNegZero);
5458
5459 break;
5460 }
5461 case Intrinsic::sin: {
5462 KnownFPClass KnownSrc;
5463 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5464 KnownSrc, Q, Depth + 1);
5465 Known = KnownFPClass::sin(KnownSrc);
5466 break;
5467 }
5468 case Intrinsic::cos: {
5469 KnownFPClass KnownSrc;
5470 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5471 KnownSrc, Q, Depth + 1);
5472 Known = KnownFPClass::cos(KnownSrc);
5473 break;
5474 }
5475 case Intrinsic::tan: {
5476 KnownFPClass KnownSrc;
5477 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5478 KnownSrc, Q, Depth + 1);
5479 Known = KnownFPClass::tan(KnownSrc);
5480 break;
5481 }
5482 case Intrinsic::sinh: {
5483 KnownFPClass KnownSrc;
5484 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5485 KnownSrc, Q, Depth + 1);
5486 Known = KnownFPClass::sinh(KnownSrc);
5487 break;
5488 }
5489 case Intrinsic::cosh: {
5490 KnownFPClass KnownSrc;
5491 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5492 KnownSrc, Q, Depth + 1);
5493 Known = KnownFPClass::cosh(KnownSrc);
5494 break;
5495 }
5496 case Intrinsic::tanh: {
5497 KnownFPClass KnownSrc;
5498 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5499 KnownSrc, Q, Depth + 1);
5500 Known = KnownFPClass::tanh(KnownSrc);
5501 break;
5502 }
5503 case Intrinsic::asin: {
5504 KnownFPClass KnownSrc;
5505 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5506 KnownSrc, Q, Depth + 1);
5507 Known = KnownFPClass::asin(KnownSrc);
5508 break;
5509 }
5510 case Intrinsic::acos: {
5511 KnownFPClass KnownSrc;
5512 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5513 KnownSrc, Q, Depth + 1);
5514 Known = KnownFPClass::acos(KnownSrc);
5515 break;
5516 }
5517 case Intrinsic::atan: {
5518 KnownFPClass KnownSrc;
5519 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5520 KnownSrc, Q, Depth + 1);
5521 Known = KnownFPClass::atan(KnownSrc);
5522 break;
5523 }
5524 case Intrinsic::atan2: {
5525 FPClassTest InterestedY = InterestedClasses;
5526 FPClassTest InterestedX = InterestedClasses;
5527
5528 // We can rule out negative values if y cannot have a negative value.
5529 if ((InterestedClasses & fcNegFinite) != fcNone)
5530 InterestedY |= fcNegative;
5531
5532 // We can rule out positive values if y cannot have a positive value.
5533 if ((InterestedClasses & fcPosFinite) != fcNone)
5534 InterestedY |= fcPositive | fcNegSubnormal;
5535
5536 // We can rule out zero and subnormal if x cannot have a positive value.
5537 if ((InterestedClasses & (fcZero | fcSubnormal)) != fcNone)
5538 InterestedX |= fcPositive | fcNegSubnormal;
5539
5540 KnownFPClass KnownY, KnownX;
5541 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedY,
5542 KnownY, Q, Depth + 1);
5543 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedX,
5544 KnownX, Q, Depth + 1);
5545
5546 const Function *F = II->getFunction();
5548 F ? F->getDenormalMode(
5549 II->getType()->getScalarType()->getFltSemantics())
5551 Known = KnownFPClass::atan2(KnownY, KnownX, Mode);
5552 break;
5553 }
5554 case Intrinsic::maxnum:
5555 case Intrinsic::minnum:
5556 case Intrinsic::minimum:
5557 case Intrinsic::maximum:
5558 case Intrinsic::minimumnum:
5559 case Intrinsic::maximumnum: {
5560 KnownFPClass KnownLHS, KnownRHS;
5561 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5562 KnownLHS, Q, Depth + 1);
5563 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5564 KnownRHS, Q, Depth + 1);
5565
5566 const Function *F = II->getFunction();
5567
5569 F ? F->getDenormalMode(
5570 II->getType()->getScalarType()->getFltSemantics())
5572
5573 Known = KnownFPClass::minMaxLike(KnownLHS, KnownRHS, getMinMaxKind(IID),
5574 Mode);
5575 break;
5576 }
5577 case Intrinsic::canonicalize: {
5578 KnownFPClass KnownSrc;
5579 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5580 KnownSrc, Q, Depth + 1);
5581
5582 const Function *F = II->getFunction();
5583 DenormalMode DenormMode =
5584 F ? F->getDenormalMode(
5585 II->getType()->getScalarType()->getFltSemantics())
5587 Known = KnownFPClass::canonicalize(KnownSrc, DenormMode);
5588 break;
5589 }
5590 case Intrinsic::vector_reduce_fmax:
5591 case Intrinsic::vector_reduce_fmin:
5592 case Intrinsic::vector_reduce_fmaximum:
5593 case Intrinsic::vector_reduce_fminimum:
5594 case Intrinsic::vector_reduce_fmaximumnum:
5595 case Intrinsic::vector_reduce_fminimumnum: {
5596 // reduce min/max will choose an element from one of the vector elements,
5597 // so we can infer and class information that is common to all elements.
5598 Known = computeKnownFPClass(II->getArgOperand(0), II->getFastMathFlags(),
5599 InterestedClasses, Q, Depth + 1);
5600 // Can only propagate sign if output is never NaN.
5601 if (!Known.isKnownNeverNaN())
5602 Known.setSignBit(std::nullopt);
5603 break;
5604 }
5605 // reverse preserves all characteristics of the input vec's element.
5606 case Intrinsic::vector_reverse:
5608 II->getArgOperand(0), DemandedElts.reverseBits(),
5609 II->getFastMathFlags(), InterestedClasses, Q, Depth + 1);
5610 break;
5611 case Intrinsic::trunc:
5612 case Intrinsic::floor:
5613 case Intrinsic::ceil:
5614 case Intrinsic::rint:
5615 case Intrinsic::nearbyint:
5616 case Intrinsic::round:
5617 case Intrinsic::roundeven: {
5618 KnownFPClass KnownSrc;
5619 FPClassTest InterestedSrcs = InterestedClasses;
5620 if (InterestedSrcs & fcPosFinite)
5621 InterestedSrcs |= fcPosFinite;
5622 if (InterestedSrcs & fcNegFinite)
5623 InterestedSrcs |= fcNegFinite;
5624 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5625 KnownSrc, Q, Depth + 1);
5626
5628 KnownSrc, IID == Intrinsic::trunc,
5629 V->getType()->getScalarType()->isMultiUnitFPType());
5630 break;
5631 }
5632 case Intrinsic::exp:
5633 case Intrinsic::exp2:
5634 case Intrinsic::exp10:
5635 case Intrinsic::amdgcn_exp2: {
5636 KnownFPClass KnownSrc;
5637 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5638 KnownSrc, Q, Depth + 1);
5639
5640 Known = KnownFPClass::exp(KnownSrc);
5641
5642 Type *EltTy = II->getType()->getScalarType();
5643 if (IID == Intrinsic::amdgcn_exp2 && EltTy->isFloatTy())
5644 Known.knownNot(fcSubnormal);
5645
5646 break;
5647 }
5648 case Intrinsic::fptrunc_round: {
5649 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known,
5650 Q, Depth);
5651 break;
5652 }
5653 case Intrinsic::log:
5654 case Intrinsic::log10:
5655 case Intrinsic::log2:
5656 case Intrinsic::experimental_constrained_log:
5657 case Intrinsic::experimental_constrained_log10:
5658 case Intrinsic::experimental_constrained_log2:
5659 case Intrinsic::amdgcn_log: {
5660 FPClassTest InterestedSrcs = fcNone;
5661
5662 // log(negative) produces NaN.
5663 if ((InterestedClasses & fcNan) != fcNone)
5664 InterestedSrcs |= fcNan | fcNegative;
5665
5666 // log(logical-zero) produces negative infinity.
5667 if ((InterestedClasses & fcNegInf) != fcNone)
5668 InterestedSrcs |= fcZero | fcSubnormal;
5669
5670 // log(x) < -0.0 if x < +1.0
5671 if ((InterestedClasses & fcNegNormal) != fcNone)
5672 InterestedSrcs |= fcPosSubnormal | fcPosNormal;
5673
5674 // log(x) >= +0.0 if x >= +1.0
5675 if ((InterestedClasses & (fcPosZero | fcPosNormal)) != fcNone)
5676 InterestedSrcs |= fcPosNormal;
5677
5678 // log(x) is positive infinity iff x is positive infinity.
5679 if ((InterestedClasses & fcPosInf) != fcNone)
5680 InterestedSrcs |= fcPosInf;
5681
5682 KnownFPClass KnownSrc;
5683 if (InterestedSrcs != fcNone)
5684 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5685 KnownSrc, Q, Depth + 1);
5686 const Function *F = II->getFunction();
5688 F ? F->getDenormalMode(
5689 II->getType()->getScalarType()->getFltSemantics())
5691 Known = KnownFPClass::log(KnownSrc, Mode);
5692 break;
5693 }
5694 case Intrinsic::pow: {
5695 const bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5696 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
5697 if (!WantNaN && !WantNegative)
5698 break;
5699
5700 FPClassTest InterestedLHS = fcNone;
5701 FPClassTest InterestedRHS = fcNone;
5702 if (WantNaN) {
5703 // pow may return NaN if one of the arguments is NaN. NaN may also be
5704 // produced from a negative, non-zero finite base and a non-integer
5705 // exponent.
5706 InterestedLHS |= fcNan | fcNegNormal | fcNegSubnormal;
5707 InterestedRHS |= fcNan;
5708 }
5709 if (WantNegative) {
5710 // A negative value is returned when a negative base is raised to an odd
5711 // integer power. Only normal values can be odd integers.
5712 InterestedLHS |= fcNegative;
5713 InterestedRHS |= fcNormal;
5714 }
5715
5716 KnownFPClass KnownLHS;
5717 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedLHS,
5718 KnownLHS, Q, Depth + 1);
5719
5720 // If the LHS is unknown, then querying the RHS is only useful for rare
5721 // edge cases.
5722 if (KnownLHS.isUnknown())
5723 break;
5724
5725 KnownFPClass KnownRHS;
5726 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedRHS,
5727 KnownRHS, Q, Depth + 1);
5728 Known = KnownFPClass::pow(KnownLHS, KnownRHS);
5729 break;
5730 }
5731 case Intrinsic::powi: {
5732 if ((InterestedClasses & (fcNan | fcInf | fcNegative)) == fcNone)
5733 break;
5734
5735 // The exponent is always a scalar, even when raising a vector to a power.
5736 const Value *Exp = II->getArgOperand(1);
5737 unsigned BitWidth = Exp->getType()->getIntegerBitWidth();
5738 KnownBits ExponentKnownBits(BitWidth);
5739 computeKnownBits(Exp, APInt(1, 1), ExponentKnownBits, Q, Depth + 1);
5740
5741 FPClassTest InterestedSrcs = fcNone;
5742 if (InterestedClasses & fcNan)
5743 InterestedSrcs |= fcNan;
5744 if (!ExponentKnownBits.isZero()) {
5745 if (InterestedClasses & fcInf)
5746 InterestedSrcs |= fcFinite | fcInf;
5747 if ((InterestedClasses & fcNegative) && !ExponentKnownBits.isEven())
5748 InterestedSrcs |= fcNegative;
5749 }
5750
5751 KnownFPClass KnownSrc;
5752 if (InterestedSrcs != fcNone)
5753 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5754 KnownSrc, Q, Depth + 1);
5755
5756 Known = KnownFPClass::powi(KnownSrc, ExponentKnownBits);
5757 break;
5758 }
5759 case Intrinsic::ldexp: {
5760 KnownFPClass KnownSrc;
5761 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5762 KnownSrc, Q, Depth + 1);
5763 // Can refine inf/zero handling based on the exponent operand.
5764 const FPClassTest ExpInfoMask = fcZero | fcSubnormal | fcInf;
5765
5766 const Value *ExpArg = II->getArgOperand(1);
5767 ConstantRange ExpKnownRange =
5768 ((KnownSrc.getKnownFPClasses() & ExpInfoMask) != fcNone)
5769 ? computeConstantRange(ExpArg, /*ForSigned=*/true, Q, Depth + 1)
5770 : ConstantRange::getFull(
5771 ExpArg->getType()->getScalarSizeInBits());
5772
5773 const fltSemantics &Flt =
5774 II->getType()->getScalarType()->getFltSemantics();
5775
5776 const Function *F = II->getFunction();
5778 F ? F->getDenormalMode(Flt) : DenormalMode::getDynamic();
5779
5780 Known = KnownFPClass::ldexp(KnownSrc, ExpKnownRange.getSignedMin(),
5781 ExpKnownRange.getSignedMax(), Flt, Mode);
5782 break;
5783 }
5784 case Intrinsic::arithmetic_fence: {
5785 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5786 Known, Q, Depth + 1);
5787 break;
5788 }
5789 case Intrinsic::experimental_constrained_sitofp:
5790 case Intrinsic::experimental_constrained_uitofp:
5791 // Cannot produce nan
5792 Known.knownNot(fcNan);
5793
5794 // sitofp and uitofp turn into +0.0 for zero.
5795 Known.knownNot(fcNegZero);
5796
5797 // Integers cannot be subnormal
5798 Known.knownNot(fcSubnormal);
5799
5800 if (IID == Intrinsic::experimental_constrained_uitofp)
5801 Known.signBitMustBeZero();
5802
5803 // TODO: Copy inf handling from instructions
5804 break;
5805
5806 case Intrinsic::amdgcn_fract: {
5807 Known.knownNot(fcInf);
5808
5809 if (InterestedClasses & fcNan) {
5810 KnownFPClass KnownSrc;
5811 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5812 InterestedClasses, KnownSrc, Q, Depth + 1);
5813
5814 if (KnownSrc.isKnownNeverInfOrNaN())
5815 Known.knownNot(fcNan);
5816 else if (KnownSrc.isKnownNever(fcSNan))
5817 Known.knownNot(fcSNan);
5818 }
5819
5820 break;
5821 }
5822 case Intrinsic::amdgcn_rcp: {
5823 KnownFPClass KnownSrc;
5824 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5825 KnownSrc, Q, Depth + 1);
5826
5827 Known.propagateNonNaN(KnownSrc);
5828
5829 Type *EltTy = II->getType()->getScalarType();
5830
5831 // f32 denormal always flushed.
5832 if (EltTy->isFloatTy()) {
5833 Known.knownNot(fcSubnormal);
5834 KnownSrc.knownNot(fcSubnormal);
5835 }
5836
5837 if (KnownSrc.isKnownNever(fcNegative))
5838 Known.knownNot(fcNegative);
5839 if (KnownSrc.isKnownNever(fcPositive))
5840 Known.knownNot(fcPositive);
5841
5842 if (const Function *F = II->getFunction()) {
5843 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5844 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5845 Known.knownNot(fcPosInf);
5846 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5847 Known.knownNot(fcNegInf);
5848 }
5849
5850 break;
5851 }
5852 case Intrinsic::amdgcn_rsq: {
5853 KnownFPClass KnownSrc;
5854 // The only negative value that can be returned is -inf for -0 inputs.
5856
5857 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5858 KnownSrc, Q, Depth + 1);
5859
5860 // Negative -> nan
5861 if (KnownSrc.isKnownNeverNaN() && KnownSrc.cannotBeOrderedLessThanZero())
5862 Known.knownNot(fcNan);
5863 else if (KnownSrc.isKnownNever(fcSNan))
5864 Known.knownNot(fcSNan);
5865
5866 // +inf -> +0
5867 if (KnownSrc.isKnownNeverPosInfinity())
5868 Known.knownNot(fcPosZero);
5869
5870 Type *EltTy = II->getType()->getScalarType();
5871
5872 // f32 denormal always flushed.
5873 if (EltTy->isFloatTy())
5874 Known.knownNot(fcPosSubnormal);
5875
5876 if (const Function *F = II->getFunction()) {
5877 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5878
5879 // -0 -> -inf
5880 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5881 Known.knownNot(fcNegInf);
5882
5883 // +0 -> +inf
5884 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5885 Known.knownNot(fcPosInf);
5886 }
5887
5888 break;
5889 }
5890 case Intrinsic::amdgcn_trig_preop: {
5891 // Always returns a value [0, 1)
5892 Known.knownNot(fcNan | fcInf | fcNegative);
5893 break;
5894 }
5895 case Intrinsic::convert_from_arbitrary_fp: {
5896 auto *MD = cast<MetadataAsValue>(II->getArgOperand(1))->getMetadata();
5897 StringRef FormatStr = cast<MDString>(MD)->getString();
5898
5899 const fltSemantics *SrcSemantics =
5901 if (!SrcSemantics)
5902 break;
5903
5904 const fltSemantics DstSemantics =
5905 II->getType()->getScalarType()->getFltSemantics();
5906
5907 if (!APFloat::semanticsHasNaN(*SrcSemantics))
5908 Known.knownNot(fcNan);
5909
5910 // fcInf can only be cleared if the source format has no Inf encoding
5911 // and the dst max exp can accommodate src max exp.
5912 if (!APFloat::semanticsHasInf(*SrcSemantics) &&
5913 APFloat::semanticsMaxExponent(*SrcSemantics) <=
5914 APFloat::semanticsMaxExponent(DstSemantics))
5915 Known.knownNot(fcInf);
5916
5917 // Check and clear all neg flags for formats that do not have signed
5918 // representation.
5919 if (!APFloat::semanticsHasSignedRepr(*SrcSemantics))
5920 Known.knownNot(fcNegative);
5921
5922 // Check if format has no zero at all (Float8E8M0FNU), or no negative
5923 // zero.
5924 if (!APFloat::semanticsHasZero(*SrcSemantics))
5925 Known.knownNot(fcZero);
5926 else if (SrcSemantics->nanEncoding == fltNanEncoding::NegativeZero)
5927 Known.knownNot(fcNegZero);
5928
5929 // If src lands normally in dest, the result can never be subnormal.
5930 if (APFloat::isRepresentableAsNormalIn(*SrcSemantics, DstSemantics))
5931 Known.knownNot(fcSubnormal);
5932 break;
5933 }
5934 default:
5935 break;
5936 }
5937
5938 break;
5939 }
5940 case Instruction::FAdd:
5941 case Instruction::FSub: {
5942 KnownFPClass KnownLHS, KnownRHS;
5943 bool WantNegative =
5944 Op->getOpcode() == Instruction::FAdd &&
5945 (InterestedClasses & KnownFPClass::OrderedLessThanZeroMask) != fcNone;
5946 bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5947 bool WantNegZero = (InterestedClasses & fcNegZero) != fcNone;
5948
5949 if (!WantNaN && !WantNegative && !WantNegZero)
5950 break;
5951
5952 FPClassTest InterestedSrcs = InterestedClasses;
5953 if (WantNegative)
5954 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5955 if (InterestedClasses & fcNan)
5956 InterestedSrcs |= fcInf;
5957 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedSrcs,
5958 KnownRHS, Q, Depth + 1);
5959
5960 // Special case fadd x, x, which is the canonical form of fmul x, 2.
5961 bool Self = Op->getOperand(0) == Op->getOperand(1) &&
5962 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT,
5963 Depth + 1);
5964 if (Self)
5965 KnownLHS = KnownRHS;
5966
5967 if ((WantNaN && KnownRHS.isKnownNeverNaN()) ||
5968 (WantNegative && KnownRHS.cannotBeOrderedLessThanZero()) ||
5969 WantNegZero || Opc == Instruction::FSub) {
5970
5971 // FIXME: Context function should always be passed in separately
5972 const Function *F = cast<Instruction>(Op)->getFunction();
5973 const fltSemantics &FltSem =
5974 Op->getType()->getScalarType()->getFltSemantics();
5976 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5977
5978 if (Self && Opc == Instruction::FAdd) {
5979 Known = KnownFPClass::fadd_self(KnownLHS, Mode);
5980 } else {
5981 // RHS is canonically cheaper to compute. Skip inspecting the LHS if
5982 // there's no point.
5983
5984 if (!Self) {
5985 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
5986 KnownLHS, Q, Depth + 1);
5987 }
5988
5989 Known = Opc == Instruction::FAdd
5990 ? KnownFPClass::fadd(KnownLHS, KnownRHS, Mode)
5991 : KnownFPClass::fsub(KnownLHS, KnownRHS, Mode);
5992 }
5993 }
5994
5995 break;
5996 }
5997 case Instruction::FMul: {
5998 const Function *F = cast<Instruction>(Op)->getFunction();
6000 F ? F->getDenormalMode(
6001 Op->getType()->getScalarType()->getFltSemantics())
6003
6004 Value *LHS = Op->getOperand(0);
6005 Value *RHS = Op->getOperand(1);
6006 // X * X is always non-negative or a NaN.
6007 // FIXME: Should check isGuaranteedNotToBeUndef
6008 if (LHS == RHS) {
6009 KnownFPClass KnownSrc;
6010 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownSrc, Q,
6011 Depth + 1);
6012 Known = KnownFPClass::square(KnownSrc, Mode);
6013 break;
6014 }
6015
6016 KnownFPClass KnownLHS, KnownRHS;
6017
6018 const APFloat *CRHS;
6019 if (match(RHS, m_APFloat(CRHS))) {
6020 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
6021 Depth + 1);
6022 Known = KnownFPClass::fmul(KnownLHS, *CRHS, Mode);
6023 } else {
6024 computeKnownFPClass(RHS, DemandedElts, fcAllFlags, KnownRHS, Q,
6025 Depth + 1);
6026 // TODO: Improve accuracy in unfused FMA pattern. We can prove an
6027 // additional not-nan if the addend is known-not negative infinity if the
6028 // multiply is known-not infinity.
6029
6030 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
6031 Depth + 1);
6032 Known = KnownFPClass::fmul(KnownLHS, KnownRHS, Mode);
6033 }
6034
6035 /// Propgate no-infs if the other source is known smaller than one, such
6036 /// that this cannot introduce overflow.
6037 if (KnownLHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(RHS))
6038 Known.knownNot(fcInf);
6039 else if (KnownRHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(LHS))
6040 Known.knownNot(fcInf);
6041
6042 break;
6043 }
6044 case Instruction::FDiv: {
6045 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
6046
6047 const Function *F = cast<Instruction>(Op)->getFunction();
6048 const fltSemantics &FltSem =
6049 Op->getType()->getScalarType()->getFltSemantics();
6051 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6052
6053 if (Op->getOperand(0) == Op->getOperand(1) &&
6054 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT)) {
6055 // X / X is always exactly 1.0 or a NaN.
6056 Known.setKnownFPClasses(fcNan | fcPosNormal);
6057
6058 if (!WantNan)
6059 break;
6060
6061 KnownFPClass KnownSrc;
6062 computeKnownFPClass(Op->getOperand(0), DemandedElts,
6063 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
6064 Depth + 1);
6065
6066 Known = KnownFPClass::fdiv_self(KnownSrc, Mode);
6067 break;
6068 }
6069
6070 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
6071 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
6072 if (!WantNan && !WantNegative && !WantPositive)
6073 break;
6074
6075 KnownFPClass KnownLHS, KnownRHS;
6076 computeKnownFPClass(Op->getOperand(1), DemandedElts, fcAllFlags, KnownRHS,
6077 Q, Depth + 1);
6078
6079 bool KnowSomethingUseful =
6080 KnownRHS.isKnownNeverNaN() ||
6083
6084 if (KnowSomethingUseful)
6085 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
6086 Q, Depth + 1);
6087
6088 Known = KnownFPClass::fdiv(KnownLHS, KnownRHS, Mode);
6089 break;
6090 }
6091 case Instruction::FRem: {
6092 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
6093
6094 Known.knownNot(fcInf);
6095
6096 const Function *F = cast<Instruction>(Op)->getFunction();
6098 F ? F->getDenormalMode(
6099 Op->getType()->getScalarType()->getFltSemantics())
6101
6102 if (Op->getOperand(0) == Op->getOperand(1) &&
6103 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT)) {
6104 // X % X is always exactly [+-]0.0 or a NaN.
6105 Known.setKnownFPClasses(fcNan | fcZero);
6106
6107 if (!WantNan)
6108 break;
6109
6110 KnownFPClass KnownSrc;
6111 computeKnownFPClass(Op->getOperand(0), DemandedElts,
6112 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
6113 Depth + 1);
6114
6115 Known = KnownFPClass::frem_self(KnownSrc, Mode);
6116 break;
6117 }
6118
6119 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
6120 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
6121 if (!WantNan && !WantNegative && !WantPositive)
6122 break;
6123
6124 KnownFPClass KnownLHS, KnownRHS;
6125 computeKnownFPClass(Op->getOperand(1), DemandedElts,
6126 fcNan | fcInf | fcZero | fcNegative, KnownRHS, Q,
6127 Depth + 1);
6128
6129 bool KnowSomethingUseful = KnownRHS.isKnownNeverNaN() ||
6130 KnownRHS.isKnownNever(fcNegative) ||
6131 KnownRHS.isKnownNever(fcPositive);
6132
6133 if (KnowSomethingUseful || WantPositive)
6134 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
6135 Q, Depth + 1);
6136
6137 Known = KnownFPClass::frem(KnownLHS, KnownRHS, Mode);
6138
6139 break;
6140 }
6141 case Instruction::FPExt: {
6142 KnownFPClass KnownSrc;
6143 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
6144 KnownSrc, Q, Depth + 1);
6145
6146 const fltSemantics &DstTy =
6147 Op->getType()->getScalarType()->getFltSemantics();
6148 const fltSemantics &SrcTy =
6149 Op->getOperand(0)->getType()->getScalarType()->getFltSemantics();
6150
6151 Known = KnownFPClass::fpext(KnownSrc, DstTy, SrcTy);
6152 break;
6153 }
6154 case Instruction::FPTrunc: {
6155 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known, Q,
6156 Depth);
6157 break;
6158 }
6159 case Instruction::SIToFP:
6160 case Instruction::UIToFP: {
6161 // Cannot produce nan
6162 Known.knownNot(fcNan);
6163
6164 // Integers cannot be subnormal
6165 Known.knownNot(fcSubnormal);
6166
6167 // sitofp and uitofp turn into +0.0 for zero.
6168 Known.knownNot(fcNegZero);
6169
6170 // UIToFP is always non-negative regardless of known bits.
6171 if (Op->getOpcode() == Instruction::UIToFP)
6172 Known.signBitMustBeZero();
6173
6174 // Only compute known bits if we can learn something useful from them.
6175 if (!(InterestedClasses & (fcPosZero | fcNormal | fcInf)))
6176 break;
6177
6178 KnownBits IntKnown =
6179 computeKnownBits(Op->getOperand(0), DemandedElts, Q, Depth + 1);
6180
6181 // If the integer is non-zero, the result cannot be +0.0
6182 if (IntKnown.isNonZero())
6183 Known.knownNot(fcPosZero);
6184
6185 if (Op->getOpcode() == Instruction::SIToFP) {
6186 // If the signed integer is known non-negative, the result is
6187 // non-negative. If the signed integer is known negative, the result is
6188 // negative.
6189 if (IntKnown.isNonNegative()) {
6190 Known.signBitMustBeZero();
6191 } else if (IntKnown.isNegative()) {
6192 Known.signBitMustBeOne();
6193 }
6194 }
6195
6196 // Guard kept for ilogb()
6197 if (InterestedClasses & fcInf) {
6198 // Get width of largest magnitude integer known.
6199 // This still works for a signed minimum value because the largest FP
6200 // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx).
6201 int IntSize = IntKnown.getBitWidth();
6202 if (Op->getOpcode() == Instruction::UIToFP)
6203 IntSize -= IntKnown.countMinLeadingZeros();
6204 else if (Op->getOpcode() == Instruction::SIToFP)
6205 IntSize -= IntKnown.countMinSignBits();
6206
6207 // If the exponent of the largest finite FP value can hold the largest
6208 // integer, the result of the cast must be finite.
6209 Type *FPTy = Op->getType()->getScalarType();
6210 if (ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize)
6211 Known.knownNot(fcInf);
6212 }
6213
6214 break;
6215 }
6216 case Instruction::ExtractElement: {
6217 // Look through extract element. If the index is non-constant or
6218 // out-of-range demand all elements, otherwise just the extracted element.
6219 const Value *Vec = Op->getOperand(0);
6220
6221 APInt DemandedVecElts;
6222 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
6223 unsigned NumElts = VecTy->getNumElements();
6224 DemandedVecElts = APInt::getAllOnes(NumElts);
6225 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(1));
6226 if (CIdx && CIdx->getValue().ult(NumElts))
6227 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
6228 } else {
6229 DemandedVecElts = APInt(1, 1);
6230 }
6231
6232 return computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known,
6233 Q, Depth + 1);
6234 }
6235 case Instruction::InsertElement: {
6236 if (isa<ScalableVectorType>(Op->getType()))
6237 return;
6238
6239 const Value *Vec = Op->getOperand(0);
6240 const Value *Elt = Op->getOperand(1);
6241 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(2));
6242 unsigned NumElts = DemandedElts.getBitWidth();
6243 APInt DemandedVecElts = DemandedElts;
6244 bool NeedsElt = true;
6245 // If we know the index we are inserting to, clear it from Vec check.
6246 if (CIdx && CIdx->getValue().ult(NumElts)) {
6247 DemandedVecElts.clearBit(CIdx->getZExtValue());
6248 NeedsElt = DemandedElts[CIdx->getZExtValue()];
6249 }
6250
6251 // Do we demand the inserted element?
6252 if (NeedsElt) {
6253 computeKnownFPClass(Elt, Known, InterestedClasses, Q, Depth + 1);
6254 // If we don't know any bits, early out.
6255 if (Known.isUnknown())
6256 break;
6257 } else {
6258 Known.setKnownFPClasses(fcNone);
6259 }
6260
6261 // Do we need anymore elements from Vec?
6262 if (!DemandedVecElts.isZero()) {
6263 KnownFPClass Known2;
6264 computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known2, Q,
6265 Depth + 1);
6266 Known |= Known2;
6267 }
6268
6269 break;
6270 }
6271 case Instruction::ShuffleVector: {
6272 // Handle vector splat idiom
6273 if (Value *Splat = getSplatValue(V)) {
6274 computeKnownFPClass(Splat, Known, InterestedClasses, Q, Depth + 1);
6275 break;
6276 }
6277
6278 // For undef elements, we don't know anything about the common state of
6279 // the shuffle result.
6280 APInt DemandedLHS, DemandedRHS;
6281 auto *Shuf = dyn_cast<ShuffleVectorInst>(Op);
6282 if (!Shuf || !getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
6283 return;
6284
6285 if (!!DemandedLHS) {
6286 const Value *LHS = Shuf->getOperand(0);
6287 computeKnownFPClass(LHS, DemandedLHS, InterestedClasses, Known, Q,
6288 Depth + 1);
6289
6290 // If we don't know any bits, early out.
6291 if (Known.isUnknown())
6292 break;
6293 } else {
6294 Known.setKnownFPClasses(fcNone);
6295 }
6296
6297 if (!!DemandedRHS) {
6298 KnownFPClass Known2;
6299 const Value *RHS = Shuf->getOperand(1);
6300 computeKnownFPClass(RHS, DemandedRHS, InterestedClasses, Known2, Q,
6301 Depth + 1);
6302 Known |= Known2;
6303 }
6304
6305 break;
6306 }
6307 case Instruction::ExtractValue: {
6308 const ExtractValueInst *Extract = cast<ExtractValueInst>(Op);
6309 ArrayRef<unsigned> Indices = Extract->getIndices();
6310 const Value *Src = Extract->getAggregateOperand();
6311 if (isa<StructType>(Src->getType()) && Indices.size() == 1 &&
6312 Indices[0] == 0) {
6313 if (const auto *II = dyn_cast<IntrinsicInst>(Src)) {
6314 switch (II->getIntrinsicID()) {
6315 case Intrinsic::frexp: {
6316 Known.knownNot(fcSubnormal);
6317
6318 KnownFPClass KnownSrc;
6319 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
6320 InterestedClasses, KnownSrc, Q, Depth + 1);
6321
6322 const Function *F = cast<Instruction>(Op)->getFunction();
6323 const fltSemantics &FltSem =
6324 Op->getType()->getScalarType()->getFltSemantics();
6325
6327 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6328 Known = KnownFPClass::frexp_mant(KnownSrc, Mode);
6329 return;
6330 }
6331 default:
6332 break;
6333 }
6334 }
6335 }
6336
6337 computeKnownFPClass(Src, DemandedElts, InterestedClasses, Known, Q,
6338 Depth + 1);
6339 break;
6340 }
6341 case Instruction::PHI: {
6342 const PHINode *P = cast<PHINode>(Op);
6343 // Unreachable blocks may have zero-operand PHI nodes.
6344 if (P->getNumIncomingValues() == 0)
6345 break;
6346
6347 // Otherwise take the unions of the known bit sets of the operands,
6348 // taking conservative care to avoid excessive recursion.
6349 const unsigned PhiRecursionLimit = MaxAnalysisRecursionDepth - 2;
6350
6351 if (Depth < PhiRecursionLimit) {
6352 // Skip if every incoming value references to ourself.
6353 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
6354 break;
6355
6356 bool First = true;
6357
6358 for (const Use &U : P->operands()) {
6359 Value *IncValue;
6360 Instruction *CxtI;
6361 breakSelfRecursivePHI(&U, P, IncValue, CxtI);
6362 // Skip direct self references.
6363 if (IncValue == P)
6364 continue;
6365
6366 KnownFPClass KnownSrc;
6367 // Recurse, but cap the recursion to two levels, because we don't want
6368 // to waste time spinning around in loops. We need at least depth 2 to
6369 // detect known sign bits.
6370 computeKnownFPClass(IncValue, DemandedElts, InterestedClasses, KnownSrc,
6372 PhiRecursionLimit);
6373
6374 if (First) {
6375 Known = KnownSrc;
6376 First = false;
6377 } else {
6378 Known |= KnownSrc;
6379 }
6380
6381 if (Known.getKnownFPClasses() == fcAllFlags)
6382 break;
6383 }
6384 }
6385
6386 // Look for the case of a for loop which has a positive
6387 // initial value and is incremented by a squared value.
6388 // This will propagate sign information out of such loops.
6389 if (P->getNumIncomingValues() != 2 || Known.cannotBeOrderedLessThanZero())
6390 break;
6391 for (unsigned I = 0; I < 2; I++) {
6392 Value *RecurValue = P->getIncomingValue(1 - I);
6394 if (!II)
6395 continue;
6396 Value *R, *L, *Init;
6397 PHINode *PN;
6399 PN == P) {
6400 switch (II->getIntrinsicID()) {
6401 case Intrinsic::fma:
6402 case Intrinsic::fmuladd: {
6403 KnownFPClass KnownStart;
6404 computeKnownFPClass(Init, DemandedElts, InterestedClasses, KnownStart,
6405 Q, Depth + 1);
6406 if (KnownStart.cannotBeOrderedLessThanZero() && L == R &&
6407 isGuaranteedNotToBeUndef(L, Q.AC, Q.CxtI, Q.DT, Depth + 1))
6409 break;
6410 }
6411 }
6412 }
6413 }
6414 break;
6415 }
6416 case Instruction::BitCast: {
6417 const Value *Src;
6418 if (!match(Op, m_ElementWiseBitCast(m_Value(Src))) ||
6419 !Src->getType()->isIntOrIntVectorTy())
6420 break;
6421
6422 const Type *Ty = Op->getType();
6423
6424 Value *CastLHS, *CastRHS;
6425
6426 // Match bitcast(umax(bitcast(a), bitcast(b)))
6427 if (match(Src, m_c_MaxOrMin(m_BitCast(m_Value(CastLHS)),
6428 m_BitCast(m_Value(CastRHS)))) &&
6429 CastLHS->getType() == Ty && CastRHS->getType() == Ty) {
6430 KnownFPClass KnownLHS, KnownRHS;
6431 computeKnownFPClass(CastRHS, DemandedElts, InterestedClasses, KnownRHS, Q,
6432 Depth + 1);
6433 if (!KnownRHS.isUnknown()) {
6434 computeKnownFPClass(CastLHS, DemandedElts, InterestedClasses, KnownLHS,
6435 Q, Depth + 1);
6436 Known = KnownLHS | KnownRHS;
6437 }
6438
6439 return;
6440 }
6441
6442 const Type *EltTy = Ty->getScalarType();
6443 KnownBits Bits(EltTy->getPrimitiveSizeInBits());
6444 computeKnownBits(Src, DemandedElts, Bits, Q, Depth + 1);
6445
6447 break;
6448 }
6449 default:
6450 break;
6451 }
6452}
6453
6455 const APInt &DemandedElts,
6456 FPClassTest InterestedClasses,
6457 const SimplifyQuery &SQ,
6458 unsigned Depth) {
6459 KnownFPClass KnownClasses;
6460 ::computeKnownFPClass(V, DemandedElts, InterestedClasses, KnownClasses, SQ,
6461 Depth);
6462 return KnownClasses;
6463}
6464
6466 FPClassTest InterestedClasses,
6467 const SimplifyQuery &SQ,
6468 unsigned Depth) {
6470 ::computeKnownFPClass(V, Known, InterestedClasses, SQ, Depth);
6471 return Known;
6472}
6473
6475 const Value *V, const DataLayout &DL, FPClassTest InterestedClasses,
6476 const TargetLibraryInfo *TLI, AssumptionCache *AC, const Instruction *CxtI,
6477 const DominatorTree *DT, bool UseInstrInfo, unsigned Depth) {
6478 return computeKnownFPClass(V, InterestedClasses,
6479 SimplifyQuery(DL, TLI, DT, AC, CxtI, UseInstrInfo),
6480 Depth);
6481}
6482
6484llvm::computeKnownFPClass(const Value *V, const APInt &DemandedElts,
6485 FastMathFlags FMF, FPClassTest InterestedClasses,
6486 const SimplifyQuery &SQ, unsigned Depth) {
6487 if (FMF.noNaNs())
6488 InterestedClasses &= ~fcNan;
6489 if (FMF.noInfs())
6490 InterestedClasses &= ~fcInf;
6491
6492 KnownFPClass Result =
6493 computeKnownFPClass(V, DemandedElts, InterestedClasses, SQ, Depth);
6494
6495 if (FMF.noNaNs())
6496 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcNan);
6497 if (FMF.noInfs())
6498 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcInf);
6499 return Result;
6500}
6501
6503 FPClassTest InterestedClasses,
6504 const SimplifyQuery &SQ,
6505 unsigned Depth) {
6506 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
6507 APInt DemandedElts =
6508 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
6509 return computeKnownFPClass(V, DemandedElts, FMF, InterestedClasses, SQ,
6510 Depth);
6511}
6512
6514 unsigned Depth) {
6516 return Known.isKnownNeverNegZero();
6517}
6518
6520 unsigned Depth) {
6523 return Known.cannotBeOrderedLessThanZero();
6524}
6525
6527 unsigned Depth) {
6529 return Known.isKnownNeverInfinity();
6530}
6531
6532/// Return true if the floating-point value can never contain a NaN or infinity.
6534 unsigned Depth) {
6536 return Known.isKnownNeverNaN() && Known.isKnownNeverInfinity();
6537}
6538
6539/// Return true if the floating-point scalar value is not a NaN or if the
6540/// floating-point vector value has no NaN elements. Return false if a value
6541/// could ever be NaN.
6543 unsigned Depth) {
6545 return Known.isKnownNeverNaN();
6546}
6547
6548/// Return false if we can prove that the specified FP value's sign bit is 0.
6549/// Return true if we can prove that the specified FP value's sign bit is 1.
6550/// Otherwise return std::nullopt.
6551std::optional<bool> llvm::computeKnownFPSignBit(const Value *V,
6552 const SimplifyQuery &SQ,
6553 unsigned Depth) {
6555 return Known.getSignBit();
6556}
6557
6559 auto *User = cast<Instruction>(U.getUser());
6560 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6561 if (FPOp->hasNoSignedZeros())
6562 return true;
6563 }
6564
6565 switch (User->getOpcode()) {
6566 case Instruction::FPToSI:
6567 case Instruction::FPToUI:
6568 return true;
6569 case Instruction::FCmp:
6570 // fcmp treats both positive and negative zero as equal.
6571 return true;
6572 case Instruction::Call:
6573 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6574 switch (II->getIntrinsicID()) {
6575 case Intrinsic::fabs:
6576 return true;
6577 case Intrinsic::copysign:
6578 return U.getOperandNo() == 0;
6579 case Intrinsic::is_fpclass: {
6580 auto Test =
6581 static_cast<FPClassTest>(
6582 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue()) &
6585 }
6586 default:
6587 return false;
6588 }
6589 }
6590 return false;
6591 default:
6592 return false;
6593 }
6594}
6595
6597 auto *User = cast<Instruction>(U.getUser());
6598 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6599 if (FPOp->hasNoNaNs())
6600 return true;
6601 }
6602
6603 switch (User->getOpcode()) {
6604 case Instruction::FPToSI:
6605 case Instruction::FPToUI:
6606 return true;
6607 // Proper FP math operations ignore the sign bit of NaN.
6608 case Instruction::FAdd:
6609 case Instruction::FSub:
6610 case Instruction::FMul:
6611 case Instruction::FDiv:
6612 case Instruction::FRem:
6613 case Instruction::FPTrunc:
6614 case Instruction::FPExt:
6615 case Instruction::FCmp:
6616 return true;
6617 // Bitwise FP operations should preserve the sign bit of NaN.
6618 case Instruction::FNeg:
6619 case Instruction::Select:
6620 case Instruction::PHI:
6621 return false;
6622 case Instruction::Ret:
6623 return User->getFunction()->getAttributes().getRetNoFPClass() &
6625 case Instruction::Call:
6626 case Instruction::Invoke: {
6627 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6628 switch (II->getIntrinsicID()) {
6629 case Intrinsic::fabs:
6630 return true;
6631 case Intrinsic::copysign:
6632 return U.getOperandNo() == 0;
6633 // Other proper FP math intrinsics ignore the sign bit of NaN.
6634 case Intrinsic::maxnum:
6635 case Intrinsic::minnum:
6636 case Intrinsic::maximum:
6637 case Intrinsic::minimum:
6638 case Intrinsic::maximumnum:
6639 case Intrinsic::minimumnum:
6640 case Intrinsic::canonicalize:
6641 case Intrinsic::fma:
6642 case Intrinsic::fmuladd:
6643 case Intrinsic::sqrt:
6644 case Intrinsic::pow:
6645 case Intrinsic::powi:
6646 case Intrinsic::fptoui_sat:
6647 case Intrinsic::fptosi_sat:
6648 case Intrinsic::is_fpclass:
6649 return true;
6650 default:
6651 return false;
6652 }
6653 }
6654
6655 FPClassTest NoFPClass =
6656 cast<CallBase>(User)->getParamNoFPClass(U.getOperandNo());
6657 return NoFPClass & FPClassTest::fcNan;
6658 }
6659 default:
6660 return false;
6661 }
6662}
6663
6665 FastMathFlags FMF) {
6666 if (isa<PoisonValue>(V))
6667 return true;
6668 if (isa<UndefValue>(V))
6669 return false;
6670
6671 if (match(V, m_CheckedFp([](const APFloat &Val) { return Val.isInteger(); })))
6672 return true;
6673
6675 if (!I)
6676 return false;
6677
6678 switch (I->getOpcode()) {
6679 case Instruction::SIToFP:
6680 case Instruction::UIToFP:
6681 // TODO: Could check nofpclass(inf) on incoming argument
6682 if (FMF.noInfs())
6683 return true;
6684
6685 // Need to check int size cannot produce infinity, which computeKnownFPClass
6686 // knows how to do already.
6687 return isKnownNeverInfinity(I, SQ);
6688 case Instruction::Call: {
6689 const CallInst *CI = cast<CallInst>(I);
6690 switch (CI->getIntrinsicID()) {
6691 case Intrinsic::trunc:
6692 case Intrinsic::floor:
6693 case Intrinsic::ceil:
6694 case Intrinsic::rint:
6695 case Intrinsic::nearbyint:
6696 case Intrinsic::round:
6697 case Intrinsic::roundeven:
6698 return (FMF.noInfs() && FMF.noNaNs()) || isKnownNeverInfOrNaN(I, SQ);
6699 default:
6700 break;
6701 }
6702
6703 break;
6704 }
6705 default:
6706 break;
6707 }
6708
6709 return false;
6710}
6711
6713
6714 // All byte-wide stores are splatable, even of arbitrary variables.
6715 if (V->getType()->isIntegerTy(8))
6716 return V;
6717
6718 LLVMContext &Ctx = V->getContext();
6719
6720 // Undef don't care.
6721 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
6722 if (isa<UndefValue>(V))
6723 return UndefInt8;
6724
6725 // Return poison for zero-sized type.
6726 if (DL.getTypeStoreSize(V->getType()).isZero())
6727 return PoisonValue::get(Type::getInt8Ty(Ctx));
6728
6730 if (!C) {
6731 // Conceptually, we could handle things like:
6732 // %a = zext i8 %X to i16
6733 // %b = shl i16 %a, 8
6734 // %c = or i16 %a, %b
6735 // but until there is an example that actually needs this, it doesn't seem
6736 // worth worrying about.
6737 return nullptr;
6738 }
6739
6740 // Handle 'null' ConstantArrayZero etc.
6741 if (C->isNullValue())
6743
6744 // Constant floating-point values can be handled as integer values if the
6745 // corresponding integer value is "byteable". An important case is 0.0.
6746 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
6747 Type *ScalarTy = CFP->getType()->getScalarType();
6748 if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
6749 return isBytewiseValue(
6750 ConstantInt::get(Ctx, CFP->getValue().bitcastToAPInt()), DL);
6751
6752 // Don't handle long double formats, which have strange constraints.
6753 return nullptr;
6754 }
6755
6756 // We can handle constant integers that are multiple of 8 bits.
6757 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
6758 if (CI->getBitWidth() % 8 == 0) {
6759 if (!CI->getValue().isSplat(8))
6760 return nullptr;
6761 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
6762 }
6763 }
6764
6765 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
6766 if (CE->getOpcode() == Instruction::IntToPtr) {
6767 if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
6768 unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
6770 CE->getOperand(0), Type::getIntNTy(Ctx, BitWidth), false, DL))
6771 return isBytewiseValue(Op, DL);
6772 }
6773 }
6774 }
6775
6776 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
6777 if (LHS == RHS)
6778 return LHS;
6779 if (!LHS || !RHS)
6780 return nullptr;
6781 if (LHS == UndefInt8)
6782 return RHS;
6783 if (RHS == UndefInt8)
6784 return LHS;
6785 return nullptr;
6786 };
6787
6789 Value *Val = UndefInt8;
6790 for (uint64_t I = 0, E = CA->getNumElements(); I != E; ++I)
6791 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
6792 return nullptr;
6793 return Val;
6794 }
6795
6797 Value *Val = UndefInt8;
6798 for (Value *Op : C->operands())
6799 if (!(Val = Merge(Val, isBytewiseValue(Op, DL))))
6800 return nullptr;
6801 return Val;
6802 }
6803
6804 // Don't try to handle the handful of other constants.
6805 return nullptr;
6806}
6807
6808// This is the recursive version of BuildSubAggregate. It takes a few different
6809// arguments. Idxs is the index within the nested struct From that we are
6810// looking at now (which is of type IndexedType). IdxSkip is the number of
6811// indices from Idxs that should be left out when inserting into the resulting
6812// struct. To is the result struct built so far, new insertvalue instructions
6813// build on that.
6814static Value *BuildSubAggregate(Value *From, Value *To, Type *IndexedType,
6816 unsigned IdxSkip,
6817 BasicBlock::iterator InsertBefore) {
6818 StructType *STy = dyn_cast<StructType>(IndexedType);
6819 if (STy) {
6820 // Save the original To argument so we can modify it
6821 Value *OrigTo = To;
6822 // General case, the type indexed by Idxs is a struct
6823 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
6824 // Process each struct element recursively
6825 Idxs.push_back(i);
6826 Value *PrevTo = To;
6827 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
6828 InsertBefore);
6829 Idxs.pop_back();
6830 if (!To) {
6831 // Couldn't find any inserted value for this index? Cleanup
6832 while (PrevTo != OrigTo) {
6834 PrevTo = Del->getAggregateOperand();
6835 Del->eraseFromParent();
6836 }
6837 // Stop processing elements
6838 break;
6839 }
6840 }
6841 // If we successfully found a value for each of our subaggregates
6842 if (To)
6843 return To;
6844 }
6845 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
6846 // the struct's elements had a value that was inserted directly. In the latter
6847 // case, perhaps we can't determine each of the subelements individually, but
6848 // we might be able to find the complete struct somewhere.
6849
6850 // Find the value that is at that particular spot
6851 Value *V = FindInsertedValue(From, Idxs);
6852
6853 if (!V)
6854 return nullptr;
6855
6856 // Insert the value in the new (sub) aggregate
6857 return InsertValueInst::Create(To, V, ArrayRef(Idxs).slice(IdxSkip), "tmp",
6858 InsertBefore);
6859}
6860
6861// This helper takes a nested struct and extracts a part of it (which is again a
6862// struct) into a new value. For example, given the struct:
6863// { a, { b, { c, d }, e } }
6864// and the indices "1, 1" this returns
6865// { c, d }.
6866//
6867// It does this by inserting an insertvalue for each element in the resulting
6868// struct, as opposed to just inserting a single struct. This will only work if
6869// each of the elements of the substruct are known (ie, inserted into From by an
6870// insertvalue instruction somewhere).
6871//
6872// All inserted insertvalue instructions are inserted before InsertBefore
6874 BasicBlock::iterator InsertBefore) {
6875 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
6876 idx_range);
6877 Value *To = PoisonValue::get(IndexedType);
6878 SmallVector<unsigned, 10> Idxs(idx_range);
6879 unsigned IdxSkip = Idxs.size();
6880
6881 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
6882}
6883
6884/// Given an aggregate and a sequence of indices, see if the scalar value
6885/// indexed is already around as a register, for example if it was inserted
6886/// directly into the aggregate.
6887///
6888/// If InsertBefore is not null, this function will duplicate (modified)
6889/// insertvalues when a part of a nested struct is extracted.
6890Value *
6892 std::optional<BasicBlock::iterator> InsertBefore) {
6893 // Nothing to index? Just return V then (this is useful at the end of our
6894 // recursion).
6895 if (idx_range.empty())
6896 return V;
6897 // We have indices, so V should have an indexable type.
6898 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
6899 "Not looking at a struct or array?");
6900 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
6901 "Invalid indices for type?");
6902
6903 if (Constant *C = dyn_cast<Constant>(V)) {
6904 C = C->getAggregateElement(idx_range[0]);
6905 if (!C) return nullptr;
6906 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
6907 }
6908
6910 // Loop the indices for the insertvalue instruction in parallel with the
6911 // requested indices
6912 const unsigned *req_idx = idx_range.begin();
6913 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
6914 i != e; ++i, ++req_idx) {
6915 if (req_idx == idx_range.end()) {
6916 // We can't handle this without inserting insertvalues
6917 if (!InsertBefore)
6918 return nullptr;
6919
6920 // The requested index identifies a part of a nested aggregate. Handle
6921 // this specially. For example,
6922 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
6923 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
6924 // %C = extractvalue {i32, { i32, i32 } } %B, 1
6925 // This can be changed into
6926 // %A = insertvalue {i32, i32 } undef, i32 10, 0
6927 // %C = insertvalue {i32, i32 } %A, i32 11, 1
6928 // which allows the unused 0,0 element from the nested struct to be
6929 // removed.
6930 return BuildSubAggregate(V, ArrayRef(idx_range.begin(), req_idx),
6931 *InsertBefore);
6932 }
6933
6934 // This insert value inserts something else than what we are looking for.
6935 // See if the (aggregate) value inserted into has the value we are
6936 // looking for, then.
6937 if (*req_idx != *i)
6938 return FindInsertedValue(I->getAggregateOperand(), idx_range,
6939 InsertBefore);
6940 }
6941 // If we end up here, the indices of the insertvalue match with those
6942 // requested (though possibly only partially). Now we recursively look at
6943 // the inserted value, passing any remaining indices.
6944 return FindInsertedValue(I->getInsertedValueOperand(),
6945 ArrayRef(req_idx, idx_range.end()), InsertBefore);
6946 }
6947
6949 // If we're extracting a value from an aggregate that was extracted from
6950 // something else, we can extract from that something else directly instead.
6951 // However, we will need to chain I's indices with the requested indices.
6952
6953 // Calculate the number of indices required
6954 unsigned size = I->getNumIndices() + idx_range.size();
6955 // Allocate some space to put the new indices in
6957 Idxs.reserve(size);
6958 // Add indices from the extract value instruction
6959 Idxs.append(I->idx_begin(), I->idx_end());
6960
6961 // Add requested indices
6962 Idxs.append(idx_range.begin(), idx_range.end());
6963
6964 assert(Idxs.size() == size
6965 && "Number of indices added not correct?");
6966
6967 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
6968 }
6969 // Otherwise, we don't know (such as, extracting from a function return value
6970 // or load instruction)
6971 return nullptr;
6972}
6973
6974// If V refers to an initialized global constant, set Slice either to
6975// its initializer if the size of its elements equals ElementSize, or,
6976// for ElementSize == 8, to its representation as an array of unsiged
6977// char. Return true on success.
6978// Offset is in the unit "nr of ElementSize sized elements".
6981 unsigned ElementSize, uint64_t Offset) {
6982 assert(V && "V should not be null.");
6983 assert((ElementSize % 8) == 0 &&
6984 "ElementSize expected to be a multiple of the size of a byte.");
6985 unsigned ElementSizeInBytes = ElementSize / 8;
6986
6987 // Drill down into the pointer expression V, ignoring any intervening
6988 // casts, and determine the identity of the object it references along
6989 // with the cumulative byte offset into it.
6990 const GlobalVariable *GV =
6992 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
6993 // Fail if V is not based on constant global object.
6994 return false;
6995
6996 const DataLayout &DL = GV->getDataLayout();
6997 APInt Off(DL.getIndexTypeSizeInBits(V->getType()), 0);
6998
6999 if (GV != V->stripAndAccumulateConstantOffsets(DL, Off,
7000 /*AllowNonInbounds*/ true))
7001 // Fail if a constant offset could not be determined.
7002 return false;
7003
7004 uint64_t StartIdx = Off.getLimitedValue();
7005 if (StartIdx == UINT64_MAX)
7006 // Fail if the constant offset is excessive.
7007 return false;
7008
7009 // Off/StartIdx is in the unit of bytes. So we need to convert to number of
7010 // elements. Simply bail out if that isn't possible.
7011 if ((StartIdx % ElementSizeInBytes) != 0)
7012 return false;
7013
7014 Offset += StartIdx / ElementSizeInBytes;
7015 ConstantDataArray *Array = nullptr;
7016 ArrayType *ArrayTy = nullptr;
7017
7018 if (GV->getInitializer()->isNullValue()) {
7019 Type *GVTy = GV->getValueType();
7020 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedValue();
7021 uint64_t Length = SizeInBytes / ElementSizeInBytes;
7022
7023 Slice.Array = nullptr;
7024 Slice.Offset = 0;
7025 // Return an empty Slice for undersized constants to let callers
7026 // transform even undefined library calls into simpler, well-defined
7027 // expressions. This is preferable to making the calls although it
7028 // prevents sanitizers from detecting such calls.
7029 Slice.Length = Length < Offset ? 0 : Length - Offset;
7030 return true;
7031 }
7032
7033 auto *Init = const_cast<Constant *>(GV->getInitializer());
7034 if (auto *ArrayInit = dyn_cast<ConstantDataArray>(Init)) {
7035 Type *InitElTy = ArrayInit->getElementType();
7036 if (InitElTy->isIntegerTy(ElementSize)) {
7037 // If Init is an initializer for an array of the expected type
7038 // and size, use it as is.
7039 Array = ArrayInit;
7040 ArrayTy = ArrayInit->getType();
7041 }
7042 }
7043
7044 if (!Array) {
7045 if (ElementSize != 8)
7046 // TODO: Handle conversions to larger integral types.
7047 return false;
7048
7049 // Otherwise extract the portion of the initializer starting
7050 // at Offset as an array of bytes, and reset Offset.
7052 if (!Init)
7053 return false;
7054
7055 Offset = 0;
7057 ArrayTy = dyn_cast<ArrayType>(Init->getType());
7058 }
7059
7060 uint64_t NumElts = ArrayTy->getArrayNumElements();
7061 if (Offset > NumElts)
7062 return false;
7063
7064 Slice.Array = Array;
7065 Slice.Offset = Offset;
7066 Slice.Length = NumElts - Offset;
7067 return true;
7068}
7069
7070/// Extract bytes from the initializer of the constant array V, which need
7071/// not be a nul-terminated string. On success, store the bytes in Str and
7072/// return true. When TrimAtNul is set, Str will contain only the bytes up
7073/// to but not including the first nul. Return false on failure.
7075 bool TrimAtNul) {
7077 if (!getConstantDataArrayInfo(V, Slice, 8))
7078 return false;
7079
7080 if (Slice.Array == nullptr) {
7081 if (TrimAtNul) {
7082 // Return a nul-terminated string even for an empty Slice. This is
7083 // safe because all existing SimplifyLibcalls callers require string
7084 // arguments and the behavior of the functions they fold is undefined
7085 // otherwise. Folding the calls this way is preferable to making
7086 // the undefined library calls, even though it prevents sanitizers
7087 // from reporting such calls.
7088 Str = StringRef();
7089 return true;
7090 }
7091 if (Slice.Length == 1) {
7092 Str = StringRef("", 1);
7093 return true;
7094 }
7095 // We cannot instantiate a StringRef as we do not have an appropriate string
7096 // of 0s at hand.
7097 return false;
7098 }
7099
7100 // Start out with the entire array in the StringRef.
7101 Str = Slice.Array->getAsString();
7102 // Skip over 'offset' bytes.
7103 Str = Str.substr(Slice.Offset);
7104
7105 if (TrimAtNul) {
7106 // Trim off the \0 and anything after it. If the array is not nul
7107 // terminated, we just return the whole end of string. The client may know
7108 // some other way that the string is length-bound.
7109 Str = Str.substr(0, Str.find('\0'));
7110 }
7111 return true;
7112}
7113
7114// These next two are very similar to the above, but also look through PHI
7115// nodes.
7116// TODO: See if we can integrate these two together.
7117
7118/// If we can compute the length of the string pointed to by
7119/// the specified pointer, return 'len+1'. If we can't, return 0.
7122 unsigned CharSize) {
7123 // Look through noop bitcast instructions.
7124 V = V->stripPointerCasts();
7125
7126 // If this is a PHI node, there are two cases: either we have already seen it
7127 // or we haven't.
7128 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
7129 if (!PHIs.insert(PN).second)
7130 return ~0ULL; // already in the set.
7131
7132 // If it was new, see if all the input strings are the same length.
7133 uint64_t LenSoFar = ~0ULL;
7134 for (Value *IncValue : PN->incoming_values()) {
7135 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
7136 if (Len == 0) return 0; // Unknown length -> unknown.
7137
7138 if (Len == ~0ULL) continue;
7139
7140 if (Len != LenSoFar && LenSoFar != ~0ULL)
7141 return 0; // Disagree -> unknown.
7142 LenSoFar = Len;
7143 }
7144
7145 // Success, all agree.
7146 return LenSoFar;
7147 }
7148
7149 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
7150 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
7151 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
7152 if (Len1 == 0) return 0;
7153 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
7154 if (Len2 == 0) return 0;
7155 if (Len1 == ~0ULL) return Len2;
7156 if (Len2 == ~0ULL) return Len1;
7157 if (Len1 != Len2) return 0;
7158 return Len1;
7159 }
7160
7161 // Otherwise, see if we can read the string.
7163 if (!getConstantDataArrayInfo(V, Slice, CharSize))
7164 return 0;
7165
7166 if (Slice.Array == nullptr)
7167 // Zeroinitializer (including an empty one).
7168 return 1;
7169
7170 // Search for the first nul character. Return a conservative result even
7171 // when there is no nul. This is safe since otherwise the string function
7172 // being folded such as strlen is undefined, and can be preferable to
7173 // making the undefined library call.
7174 unsigned NullIndex = 0;
7175 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
7176 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
7177 break;
7178 }
7179
7180 return NullIndex + 1;
7181}
7182
7183/// If we can compute the length of the string pointed to by
7184/// the specified pointer, return 'len+1'. If we can't, return 0.
7185uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
7186 if (!V->getType()->isPointerTy())
7187 return 0;
7188
7190 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
7191 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
7192 // an empty string as a length.
7193 return Len == ~0ULL ? 1 : Len;
7194}
7195
7196const Value *
7198 bool MustPreserveOffset) {
7199 assert(Call &&
7200 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
7201 if (const Value *RV = Call->getReturnedArgOperand())
7202 return RV;
7203 // This can be used only as a aliasing property.
7205 Call, MustPreserveOffset))
7206 return Call->getArgOperand(0);
7207 return nullptr;
7208}
7209
7211 const CallBase *Call, bool MustPreserveOffset) {
7212 switch (Call->getIntrinsicID()) {
7213 case Intrinsic::launder_invariant_group:
7214 case Intrinsic::strip_invariant_group:
7215 case Intrinsic::aarch64_irg:
7216 case Intrinsic::aarch64_tagp:
7217 // The amdgcn_make_buffer_rsrc function does not alter the address of the
7218 // input pointer (and thus preserves the byte offset, which is the property
7219 // the MustPreserveOffset flag selects). However, it will not necessarily
7220 // map ptr addrspace(N) null to ptr addrspace(8) null, aka the "null
7221 // descriptor", which has "all loads return 0, all stores are dropped"
7222 // semantics. Given the context of this intrinsic list, no one should be
7223 // relying on such a strict bit-exact null mapping (and, at time of
7224 // writing, they are not), but we document this fact out of an abundance
7225 // of caution.
7226 case Intrinsic::amdgcn_make_buffer_rsrc:
7227 return true;
7228 case Intrinsic::ptrmask:
7229 return !MustPreserveOffset;
7230 case Intrinsic::threadlocal_address:
7231 // The underlying variable changes with thread ID. The Thread ID may change
7232 // at coroutine suspend points.
7233 return !Call->getParent()->getParent()->isPresplitCoroutine();
7234 default:
7235 return false;
7236 }
7237}
7238
7239/// \p PN defines a loop-variant pointer to an object. Check if the
7240/// previous iteration of the loop was referring to the same object as \p PN.
7242 const LoopInfo *LI) {
7243 // Find the loop-defined value.
7244 Loop *L = LI->getLoopFor(PN->getParent());
7245 if (PN->getNumIncomingValues() != 2)
7246 return true;
7247
7248 // Find the value from previous iteration.
7249 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
7250 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7251 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
7252 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7253 return true;
7254
7255 // If a new pointer is loaded in the loop, the pointer references a different
7256 // object in every iteration. E.g.:
7257 // for (i)
7258 // int *p = a[i];
7259 // ...
7260 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
7261 if (!L->isLoopInvariant(Load->getPointerOperand()))
7262 return false;
7263 return true;
7264}
7265
7266const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup) {
7267 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
7268 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
7269 const Value *PtrOp = GEP->getPointerOperand();
7270 if (!PtrOp->getType()->isPointerTy()) // Only handle scalar pointer base.
7271 return V;
7272 V = PtrOp;
7273 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
7274 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
7275 Value *NewV = cast<Operator>(V)->getOperand(0);
7276 if (!NewV->getType()->isPointerTy())
7277 return V;
7278 V = NewV;
7279 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
7280 if (GA->isInterposable())
7281 return V;
7282 V = GA->getAliasee();
7283 } else {
7284 if (auto *PHI = dyn_cast<PHINode>(V)) {
7285 // Look through single-arg phi nodes created by LCSSA.
7286 if (PHI->getNumIncomingValues() == 1) {
7287 V = PHI->getIncomingValue(0);
7288 continue;
7289 }
7290 } else if (auto *Call = dyn_cast<CallBase>(V)) {
7291 // CaptureTracking can know about special capturing properties of some
7292 // intrinsics like launder.invariant.group, that can't be expressed with
7293 // the attributes, but have properties like returning aliasing pointer.
7294 // Because some analysis may assume that nocaptured pointer is not
7295 // returned from some special intrinsic (because function would have to
7296 // be marked with returns attribute), it is crucial to use this function
7297 // because it should be in sync with CaptureTracking. Not using it may
7298 // cause weird miscompilations where 2 aliasing pointers are assumed to
7299 // noalias.
7301 Call, /*MustPreserveOffset=*/false)) {
7302 V = RP;
7303 continue;
7304 }
7305 }
7306
7307 return V;
7308 }
7309 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
7310 }
7311 return V;
7312}
7313
7316 const LoopInfo *LI, unsigned MaxLookup) {
7319 Worklist.push_back(V);
7320 do {
7321 const Value *P = Worklist.pop_back_val();
7322 P = getUnderlyingObject(P, MaxLookup);
7323
7324 if (!Visited.insert(P).second)
7325 continue;
7326
7327 if (auto *SI = dyn_cast<SelectInst>(P)) {
7328 Worklist.push_back(SI->getTrueValue());
7329 Worklist.push_back(SI->getFalseValue());
7330 continue;
7331 }
7332
7333 if (auto *PN = dyn_cast<PHINode>(P)) {
7334 // If this PHI changes the underlying object in every iteration of the
7335 // loop, don't look through it. Consider:
7336 // int **A;
7337 // for (i) {
7338 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
7339 // Curr = A[i];
7340 // *Prev, *Curr;
7341 //
7342 // Prev is tracking Curr one iteration behind so they refer to different
7343 // underlying objects.
7344 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
7346 append_range(Worklist, PN->incoming_values());
7347 else
7348 Objects.push_back(P);
7349 continue;
7350 }
7351
7352 Objects.push_back(P);
7353 } while (!Worklist.empty());
7354}
7355
7357 const unsigned MaxVisited = 8;
7358
7361 Worklist.push_back(V);
7362 const Value *Object = nullptr;
7363 // Used as fallback if we can't find a common underlying object through
7364 // recursion.
7365 bool First = true;
7366 const Value *FirstObject = getUnderlyingObject(V);
7367 do {
7368 const Value *P = Worklist.pop_back_val();
7369 P = First ? FirstObject : getUnderlyingObject(P);
7370 First = false;
7371
7372 if (!Visited.insert(P).second)
7373 continue;
7374
7375 if (Visited.size() == MaxVisited)
7376 return FirstObject;
7377
7378 if (auto *SI = dyn_cast<SelectInst>(P)) {
7379 Worklist.push_back(SI->getTrueValue());
7380 Worklist.push_back(SI->getFalseValue());
7381 continue;
7382 }
7383
7384 if (auto *PN = dyn_cast<PHINode>(P)) {
7385 append_range(Worklist, PN->incoming_values());
7386 continue;
7387 }
7388
7389 if (!Object)
7390 Object = P;
7391 else if (Object != P)
7392 return FirstObject;
7393 } while (!Worklist.empty());
7394
7395 return Object ? Object : FirstObject;
7396}
7397
7398/// This is the function that does the work of looking through basic
7399/// ptrtoint+arithmetic+inttoptr sequences.
7400static const Value *getUnderlyingObjectFromInt(const Value *V) {
7401 do {
7402 if (const Operator *U = dyn_cast<Operator>(V)) {
7403 // If we find a ptrtoint, we can transfer control back to the
7404 // regular getUnderlyingObjectFromInt.
7405 if (U->getOpcode() == Instruction::PtrToInt)
7406 return U->getOperand(0);
7407 // If we find an add of a constant, a multiplied value, or a phi, it's
7408 // likely that the other operand will lead us to the base
7409 // object. We don't have to worry about the case where the
7410 // object address is somehow being computed by the multiply,
7411 // because our callers only care when the result is an
7412 // identifiable object.
7413 if (U->getOpcode() != Instruction::Add ||
7414 (!isa<ConstantInt>(U->getOperand(1)) &&
7415 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
7416 !isa<PHINode>(U->getOperand(1))))
7417 return V;
7418 V = U->getOperand(0);
7419 } else {
7420 return V;
7421 }
7422 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
7423 } while (true);
7424}
7425
7426/// This is a wrapper around getUnderlyingObjects and adds support for basic
7427/// ptrtoint+arithmetic+inttoptr sequences.
7428/// It returns false if unidentified object is found in getUnderlyingObjects.
7430 SmallVectorImpl<Value *> &Objects) {
7432 SmallVector<const Value *, 4> Working(1, V);
7433 do {
7434 V = Working.pop_back_val();
7435
7437 getUnderlyingObjects(V, Objs);
7438
7439 for (const Value *V : Objs) {
7440 if (!Visited.insert(V).second)
7441 continue;
7442 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
7443 const Value *O =
7444 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
7445 if (O->getType()->isPointerTy()) {
7446 Working.push_back(O);
7447 continue;
7448 }
7449 }
7450 // If getUnderlyingObjects fails to find an identifiable object,
7451 // getUnderlyingObjectsForCodeGen also fails for safety.
7452 if (!isIdentifiedObject(V)) {
7453 Objects.clear();
7454 return false;
7455 }
7456 Objects.push_back(const_cast<Value *>(V));
7457 }
7458 } while (!Working.empty());
7459 return true;
7460}
7461
7463 AllocaInst *Result = nullptr;
7465 SmallVector<Value *, 4> Worklist;
7466
7467 auto AddWork = [&](Value *V) {
7468 if (Visited.insert(V).second)
7469 Worklist.push_back(V);
7470 };
7471
7472 AddWork(V);
7473 do {
7474 V = Worklist.pop_back_val();
7475 assert(Visited.count(V));
7476
7477 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
7478 if (Result && Result != AI)
7479 return nullptr;
7480 Result = AI;
7481 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
7482 AddWork(CI->getOperand(0));
7483 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
7484 for (Value *IncValue : PN->incoming_values())
7485 AddWork(IncValue);
7486 } else if (auto *SI = dyn_cast<SelectInst>(V)) {
7487 AddWork(SI->getTrueValue());
7488 AddWork(SI->getFalseValue());
7490 if (OffsetZero && !GEP->hasAllZeroIndices())
7491 return nullptr;
7492 AddWork(GEP->getPointerOperand());
7493 } else if (CallBase *CB = dyn_cast<CallBase>(V)) {
7494 Value *Returned = CB->getReturnedArgOperand();
7495 if (Returned)
7496 AddWork(Returned);
7497 else
7498 return nullptr;
7499 } else {
7500 return nullptr;
7501 }
7502 } while (!Worklist.empty());
7503
7504 return Result;
7505}
7506
7508 const Value *V, bool AllowLifetime, bool AllowDroppable) {
7509 for (const User *U : V->users()) {
7511 if (!II)
7512 return false;
7513
7514 if (AllowLifetime && II->isLifetimeStartOrEnd())
7515 continue;
7516
7517 if (AllowDroppable && II->isDroppable())
7518 continue;
7519
7520 return false;
7521 }
7522 return true;
7523}
7524
7527 V, /* AllowLifetime */ true, /* AllowDroppable */ false);
7528}
7531 V, /* AllowLifetime */ true, /* AllowDroppable */ true);
7532}
7533
7535 if (auto *II = dyn_cast<IntrinsicInst>(I))
7536 return isTriviallyVectorizable(II->getIntrinsicID());
7537 auto *Shuffle = dyn_cast<ShuffleVectorInst>(I);
7538 return (!Shuffle || Shuffle->isSelect()) &&
7540}
7541
7543 const Instruction *Inst, const Instruction *CtxI, AssumptionCache *AC,
7544 const DominatorTree *DT, const TargetLibraryInfo *TLI, bool UseVariableInfo,
7545 bool IgnoreUBImplyingAttrs) {
7546 return isSafeToSpeculativelyExecuteWithOpcode(Inst->getOpcode(), Inst, CtxI,
7547 AC, DT, TLI, UseVariableInfo,
7548 IgnoreUBImplyingAttrs);
7549}
7550
7552 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI,
7553 AssumptionCache *AC, const DominatorTree *DT, const TargetLibraryInfo *TLI,
7554 bool UseVariableInfo, bool IgnoreUBImplyingAttrs) {
7555#ifndef NDEBUG
7556 if (Inst->getOpcode() != Opcode) {
7557 // Check that the operands are actually compatible with the Opcode override.
7558 auto hasEqualReturnAndLeadingOperandTypes =
7559 [](const Instruction *Inst, unsigned NumLeadingOperands) {
7560 if (Inst->getNumOperands() < NumLeadingOperands)
7561 return false;
7562 const Type *ExpectedType = Inst->getType();
7563 for (unsigned ItOp = 0; ItOp < NumLeadingOperands; ++ItOp)
7564 if (Inst->getOperand(ItOp)->getType() != ExpectedType)
7565 return false;
7566 return true;
7567 };
7569 hasEqualReturnAndLeadingOperandTypes(Inst, 2));
7570 assert(!Instruction::isUnaryOp(Opcode) ||
7571 hasEqualReturnAndLeadingOperandTypes(Inst, 1));
7572 }
7573#endif
7574
7575 switch (Opcode) {
7576 default:
7577 return true;
7578 case Instruction::UDiv:
7579 case Instruction::URem: {
7580 // x / y is undefined if y == 0.
7581 const APInt *V;
7582 if (match(Inst->getOperand(1), m_APInt(V)))
7583 return *V != 0;
7584 return false;
7585 }
7586 case Instruction::SDiv:
7587 case Instruction::SRem: {
7588 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
7589 const APInt *Numerator, *Denominator;
7590 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
7591 return false;
7592 // We cannot hoist this division if the denominator is 0.
7593 if (*Denominator == 0)
7594 return false;
7595 // It's safe to hoist if the denominator is not 0 or -1.
7596 if (!Denominator->isAllOnes())
7597 return true;
7598 // At this point we know that the denominator is -1. It is safe to hoist as
7599 // long we know that the numerator is not INT_MIN.
7600 if (match(Inst->getOperand(0), m_APInt(Numerator)))
7601 return !Numerator->isMinSignedValue();
7602 // The numerator *might* be MinSignedValue.
7603 return false;
7604 }
7605 case Instruction::Load: {
7606 if (!UseVariableInfo)
7607 return false;
7608
7609 const LoadInst *LI = dyn_cast<LoadInst>(Inst);
7610 if (!LI)
7611 return false;
7612 if (mustSuppressSpeculation(*LI))
7613 return false;
7614 const DataLayout &DL = LI->getDataLayout();
7616 LI->getPointerOperand(), LI->getType(), LI->getAlign(),
7617 SimplifyQuery(DL, TLI, DT, AC, CtxI));
7618 }
7619 case Instruction::Call: {
7620 auto *CI = dyn_cast<const CallInst>(Inst);
7621 if (!CI)
7622 return false;
7623 const Function *Callee = CI->getCalledFunction();
7624
7625 // The called function could have undefined behavior or side-effects, even
7626 // if marked readnone nounwind.
7627 if (!Callee || !Callee->isSpeculatable())
7628 return false;
7629 // Since the operands may be changed after hoisting, undefined behavior may
7630 // be triggered by some UB-implying attributes.
7631 return IgnoreUBImplyingAttrs || !CI->hasUBImplyingAttrs();
7632 }
7633 case Instruction::VAArg:
7634 case Instruction::Alloca:
7635 case Instruction::Invoke:
7636 case Instruction::CallBr:
7637 case Instruction::PHI:
7638 case Instruction::Store:
7639 case Instruction::Ret:
7640 case Instruction::UncondBr:
7641 case Instruction::CondBr:
7642 case Instruction::IndirectBr:
7643 case Instruction::Switch:
7644 case Instruction::Unreachable:
7645 case Instruction::Fence:
7646 case Instruction::AtomicRMW:
7647 case Instruction::AtomicCmpXchg:
7648 case Instruction::LandingPad:
7649 case Instruction::Resume:
7650 case Instruction::CatchSwitch:
7651 case Instruction::CatchPad:
7652 case Instruction::CatchRet:
7653 case Instruction::CleanupPad:
7654 case Instruction::CleanupRet:
7655 return false; // Misc instructions which have effects
7656 }
7657}
7658
7660 if (I.mayReadOrWriteMemory())
7661 // Memory dependency possible
7662 return true;
7664 // Can't move above a maythrow call or infinite loop. Or if an
7665 // inalloca alloca, above a stacksave call.
7666 return true;
7668 // 1) Can't reorder two inf-loop calls, even if readonly
7669 // 2) Also can't reorder an inf-loop call below a instruction which isn't
7670 // safe to speculative execute. (Inverse of above)
7671 return true;
7672 return false;
7673}
7674
7675/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
7689
7690/// Combine constant ranges from computeConstantRange() and computeKnownBits().
7693 bool ForSigned,
7694 const SimplifyQuery &SQ) {
7695 ConstantRange CR1 =
7696 ConstantRange::fromKnownBits(V.getKnownBits(SQ), ForSigned);
7697 ConstantRange CR2 = computeConstantRange(V, ForSigned, SQ);
7700 return CR1.intersectWith(CR2, RangeType);
7701}
7702
7704 const Value *RHS,
7705 const SimplifyQuery &SQ,
7706 bool IsNSW) {
7707 ConstantRange LHSRange =
7708 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7709 ConstantRange RHSRange =
7710 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7711
7712 // mul nsw of two non-negative numbers is also nuw.
7713 if (IsNSW && LHSRange.isAllNonNegative() && RHSRange.isAllNonNegative())
7715
7716 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
7717}
7718
7720 const Value *RHS,
7721 const SimplifyQuery &SQ) {
7722 // Multiplying n * m significant bits yields a result of n + m significant
7723 // bits. If the total number of significant bits does not exceed the
7724 // result bit width (minus 1), there is no overflow.
7725 // This means if we have enough leading sign bits in the operands
7726 // we can guarantee that the result does not overflow.
7727 // Ref: "Hacker's Delight" by Henry Warren
7728 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
7729
7730 // Note that underestimating the number of sign bits gives a more
7731 // conservative answer.
7732 unsigned SignBits =
7733 ::ComputeNumSignBits(LHS, SQ) + ::ComputeNumSignBits(RHS, SQ);
7734
7735 // First handle the easy case: if we have enough sign bits there's
7736 // definitely no overflow.
7737 if (SignBits > BitWidth + 1)
7739
7740 // There are two ambiguous cases where there can be no overflow:
7741 // SignBits == BitWidth + 1 and
7742 // SignBits == BitWidth
7743 // The second case is difficult to check, therefore we only handle the
7744 // first case.
7745 if (SignBits == BitWidth + 1) {
7746 // It overflows only when both arguments are negative and the true
7747 // product is exactly the minimum negative number.
7748 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
7749 // For simplicity we just check if at least one side is not negative.
7750 KnownBits LHSKnown = computeKnownBits(LHS, SQ);
7751 KnownBits RHSKnown = computeKnownBits(RHS, SQ);
7752 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
7754 }
7756}
7757
7760 const WithCache<const Value *> &RHS,
7761 const SimplifyQuery &SQ) {
7762 ConstantRange LHSRange =
7763 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7764 ConstantRange RHSRange =
7765 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7766 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
7767}
7768
7769static OverflowResult
7772 const AddOperator *Add, const SimplifyQuery &SQ) {
7773 if (Add && Add->hasNoSignedWrap()) {
7775 }
7776
7777 // If LHS and RHS each have at least two sign bits, the addition will look
7778 // like
7779 //
7780 // XX..... +
7781 // YY.....
7782 //
7783 // If the carry into the most significant position is 0, X and Y can't both
7784 // be 1 and therefore the carry out of the addition is also 0.
7785 //
7786 // If the carry into the most significant position is 1, X and Y can't both
7787 // be 0 and therefore the carry out of the addition is also 1.
7788 //
7789 // Since the carry into the most significant position is always equal to
7790 // the carry out of the addition, there is no signed overflow.
7791 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7793
7794 ConstantRange LHSRange =
7795 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7796 ConstantRange RHSRange =
7797 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7798 OverflowResult OR =
7799 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
7801 return OR;
7802
7803 // The remaining code needs Add to be available. Early returns if not so.
7804 if (!Add)
7806
7807 // If the sign of Add is the same as at least one of the operands, this add
7808 // CANNOT overflow. If this can be determined from the known bits of the
7809 // operands the above signedAddMayOverflow() check will have already done so.
7810 // The only other way to improve on the known bits is from an assumption, so
7811 // call computeKnownBitsFromContext() directly.
7812 bool LHSOrRHSKnownNonNegative =
7813 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
7814 bool LHSOrRHSKnownNegative =
7815 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
7816 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
7817 KnownBits AddKnown(LHSRange.getBitWidth());
7818 computeKnownBitsFromContext(Add, AddKnown, SQ);
7819 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
7820 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
7822 }
7823
7825}
7826
7828 const Value *RHS,
7829 const SimplifyQuery &SQ) {
7830 // X - (X % ?)
7831 // The remainder of a value can't have greater magnitude than itself,
7832 // so the subtraction can't overflow.
7833
7834 // X - (X -nuw ?)
7835 // In the minimal case, this would simplify to "?", so there's no subtract
7836 // at all. But if this analysis is used to peek through casts, for example,
7837 // then determining no-overflow may allow other transforms.
7838
7839 // TODO: There are other patterns like this.
7840 // See simplifyICmpWithBinOpOnLHS() for candidates.
7841 if (match(RHS, m_URem(m_Specific(LHS), m_Value())) ||
7842 match(RHS, m_NUWSub(m_Specific(LHS), m_Value())))
7843 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT))
7845
7846 if (auto C = isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, SQ.CxtI,
7847 SQ.DL)) {
7848 if (*C)
7851 }
7852
7853 ConstantRange LHSRange =
7854 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7855 ConstantRange RHSRange =
7856 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7857 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
7858}
7859
7861 const Value *RHS,
7862 const SimplifyQuery &SQ) {
7863 // X - (X % ?)
7864 // The remainder of a value can't have greater magnitude than itself,
7865 // so the subtraction can't overflow.
7866
7867 // X - (X -nsw ?)
7868 // In the minimal case, this would simplify to "?", so there's no subtract
7869 // at all. But if this analysis is used to peek through casts, for example,
7870 // then determining no-overflow may allow other transforms.
7871 if (match(RHS, m_SRem(m_Specific(LHS), m_Value())) ||
7872 match(RHS, m_NSWSub(m_Specific(LHS), m_Value())))
7873 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT))
7875
7876 // If LHS and RHS each have at least two sign bits, the subtraction
7877 // cannot overflow.
7878 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7880
7881 ConstantRange LHSRange =
7882 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7883 ConstantRange RHSRange =
7884 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7885 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
7886}
7887
7889 const DominatorTree &DT) {
7890 SmallVector<const CondBrInst *, 2> GuardingBranches;
7892
7893 for (const User *U : WO->users()) {
7894 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
7895 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
7896
7897 if (EVI->getIndices()[0] == 0)
7898 Results.push_back(EVI);
7899 else {
7900 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
7901
7902 for (const auto *U : EVI->users())
7903 if (const auto *B = dyn_cast<CondBrInst>(U))
7904 GuardingBranches.push_back(B);
7905 }
7906 } else {
7907 // We are using the aggregate directly in a way we don't want to analyze
7908 // here (storing it to a global, say).
7909 return false;
7910 }
7911 }
7912
7913 auto AllUsesGuardedByBranch = [&](const CondBrInst *BI) {
7914 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
7915
7916 // Check if all users of the add are provably no-wrap.
7917 for (const auto *Result : Results) {
7918 // If the extractvalue itself is not executed on overflow, the we don't
7919 // need to check each use separately, since domination is transitive.
7920 if (DT.dominates(NoWrapEdge, Result->getParent()))
7921 continue;
7922
7923 for (const auto &RU : Result->uses())
7924 if (!DT.dominates(NoWrapEdge, RU))
7925 return false;
7926 }
7927
7928 return true;
7929 };
7930
7931 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
7932}
7933
7934/// Shifts return poison if shiftwidth is larger than the bitwidth.
7935static bool shiftAmountKnownInRange(const Value *ShiftAmount) {
7936 auto *C = dyn_cast<Constant>(ShiftAmount);
7937 if (!C)
7938 return false;
7939
7940 // Shifts return poison if shiftwidth is larger than the bitwidth.
7942 if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
7943 unsigned NumElts = FVTy->getNumElements();
7944 for (unsigned i = 0; i < NumElts; ++i)
7945 ShiftAmounts.push_back(C->getAggregateElement(i));
7946 } else if (isa<ScalableVectorType>(C->getType()))
7947 return false; // Can't tell, just return false to be safe
7948 else
7949 ShiftAmounts.push_back(C);
7950
7951 bool Safe = llvm::all_of(ShiftAmounts, [](const Constant *C) {
7952 auto *CI = dyn_cast_or_null<ConstantInt>(C);
7953 return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
7954 });
7955
7956 return Safe;
7957}
7958
7960 bool ConsiderFlagsAndMetadata) {
7961
7962 if (ConsiderFlagsAndMetadata && includesPoison(Kind) &&
7963 Op->hasPoisonGeneratingAnnotations())
7964 return true;
7965
7966 unsigned Opcode = Op->getOpcode();
7967
7968 // Check whether opcode is a poison/undef-generating operation
7969 switch (Opcode) {
7970 case Instruction::Shl:
7971 case Instruction::AShr:
7972 case Instruction::LShr:
7973 return includesPoison(Kind) && !shiftAmountKnownInRange(Op->getOperand(1));
7974 case Instruction::FPToSI:
7975 case Instruction::FPToUI:
7976 // fptosi/ui yields poison if the resulting value does not fit in the
7977 // destination type.
7978 return true;
7979 case Instruction::Call:
7980 if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
7981 switch (II->getIntrinsicID()) {
7982 // NOTE: Use IntrNoCreateUndefOrPoison when possible.
7983 case Intrinsic::ctlz:
7984 case Intrinsic::cttz:
7985 case Intrinsic::abs:
7986 // We're not considering flags so it is safe to just return false.
7987 return false;
7988 case Intrinsic::sshl_sat:
7989 case Intrinsic::ushl_sat:
7990 if (!includesPoison(Kind) ||
7991 shiftAmountKnownInRange(II->getArgOperand(1)))
7992 return false;
7993 break;
7994 }
7995 }
7996 [[fallthrough]];
7997 case Instruction::CallBr:
7998 case Instruction::Invoke: {
7999 const auto *CB = cast<CallBase>(Op);
8000 return !CB->hasRetAttr(Attribute::NoUndef) &&
8001 !CB->hasFnAttr(Attribute::NoCreateUndefOrPoison);
8002 }
8003 case Instruction::InsertElement:
8004 case Instruction::ExtractElement: {
8005 // If index exceeds the length of the vector, it returns poison
8006 auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
8007 unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
8008 auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
8009 if (includesPoison(Kind))
8010 return !Idx ||
8011 Idx->getValue().uge(VTy->getElementCount().getKnownMinValue());
8012 return false;
8013 }
8014 case Instruction::ShuffleVector: {
8016 ? cast<ConstantExpr>(Op)->getShuffleMask()
8017 : cast<ShuffleVectorInst>(Op)->getShuffleMask();
8018 return includesPoison(Kind) && is_contained(Mask, PoisonMaskElem);
8019 }
8020 case Instruction::FNeg:
8021 case Instruction::PHI:
8022 case Instruction::Select:
8023 case Instruction::ExtractValue:
8024 case Instruction::InsertValue:
8025 case Instruction::Freeze:
8026 case Instruction::ICmp:
8027 case Instruction::FCmp:
8028 case Instruction::GetElementPtr:
8029 return false;
8030 case Instruction::AddrSpaceCast:
8031 return true;
8032 default: {
8033 const auto *CE = dyn_cast<ConstantExpr>(Op);
8034 if (isa<CastInst>(Op) || (CE && CE->isCast()))
8035 return false;
8036 else if (Instruction::isBinaryOp(Opcode))
8037 return false;
8038 // Be conservative and return true.
8039 return true;
8040 }
8041 }
8042}
8043
8045 bool ConsiderFlagsAndMetadata) {
8046 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::UndefOrPoison,
8047 ConsiderFlagsAndMetadata);
8048}
8049
8050bool llvm::canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata) {
8051 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::PoisonOnly,
8052 ConsiderFlagsAndMetadata);
8053}
8054
8055static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V,
8056 unsigned Depth) {
8057 if (ValAssumedPoison == V)
8058 return true;
8059
8060 const unsigned MaxDepth = 2;
8061 if (Depth >= MaxDepth)
8062 return false;
8063
8064 if (const auto *I = dyn_cast<Instruction>(V)) {
8065 if (any_of(I->operands(), [=](const Use &Op) {
8066 return propagatesPoison(Op) &&
8067 directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
8068 }))
8069 return true;
8070
8071 // V = extractvalue V0, idx
8072 // V2 = extractvalue V0, idx2
8073 // V0's elements are all poison or not. (e.g., add_with_overflow)
8074 const WithOverflowInst *II;
8076 (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
8077 llvm::is_contained(II->args(), ValAssumedPoison)))
8078 return true;
8079 }
8080 return false;
8081}
8082
8083static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
8084 unsigned Depth) {
8085 if (isGuaranteedNotToBePoison(ValAssumedPoison))
8086 return true;
8087
8088 if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
8089 return true;
8090
8091 const unsigned MaxDepth = 2;
8092 if (Depth >= MaxDepth)
8093 return false;
8094
8095 const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
8096 if (I && !canCreatePoison(cast<Operator>(I))) {
8097 return all_of(I->operands(), [=](const Value *Op) {
8098 return impliesPoison(Op, V, Depth + 1);
8099 });
8100 }
8101 return false;
8102}
8103
8104bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
8105 return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
8106}
8107
8108static bool programUndefinedIfUndefOrPoison(const Value *V, bool PoisonOnly);
8109
8111 const Value *V, AssumptionCache *AC, const Instruction *CtxI,
8112 const DominatorTree *DT, unsigned Depth, UndefPoisonKind Kind) {
8114 return false;
8115
8116 if (isa<MetadataAsValue>(V))
8117 return false;
8118
8119 if (const auto *A = dyn_cast<Argument>(V)) {
8120 if (A->hasAttribute(Attribute::NoUndef) ||
8121 A->hasAttribute(Attribute::Dereferenceable) ||
8122 A->hasAttribute(Attribute::DereferenceableOrNull))
8123 return true;
8124 }
8125
8126 if (auto *C = dyn_cast<Constant>(V)) {
8127 if (isa<PoisonValue>(C))
8128 return !includesPoison(Kind);
8129
8130 if (isa<UndefValue>(C))
8131 return !includesUndef(Kind);
8132
8135 return true;
8136
8137 if (C->getType()->isVectorTy()) {
8138 if (isa<ConstantExpr>(C)) {
8139 // Scalable vectors can use a ConstantExpr to build a splat.
8140 if (Constant *SplatC = C->getSplatValue())
8141 if (isa<ConstantInt>(SplatC) || isa<ConstantFP>(SplatC))
8142 return true;
8143 } else {
8144 if (includesUndef(Kind) && C->containsUndefElement())
8145 return false;
8146 if (includesPoison(Kind) && C->containsPoisonElement())
8147 return false;
8148 return !C->containsConstantExpression();
8149 }
8150 }
8151 }
8152
8153 // Strip cast operations from a pointer value.
8154 // Note that stripPointerCastsSameRepresentation can strip off getelementptr
8155 // inbounds with zero offset. To guarantee that the result isn't poison, the
8156 // stripped pointer is checked as it has to be pointing into an allocated
8157 // object or be null `null` to ensure `inbounds` getelement pointers with a
8158 // zero offset could not produce poison.
8159 // It can strip off addrspacecast that do not change bit representation as
8160 // well. We believe that such addrspacecast is equivalent to no-op.
8161 auto *StrippedV = V->stripPointerCastsSameRepresentation();
8162 if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
8163 isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
8164 return true;
8165
8166 auto OpCheck = [&](const Value *V) {
8167 return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1, Kind);
8168 };
8169
8170 if (auto *Opr = dyn_cast<Operator>(V)) {
8171 // If the value is a freeze instruction, then it can never
8172 // be undef or poison.
8173 if (isa<FreezeInst>(V))
8174 return true;
8175
8176 if (const auto *CB = dyn_cast<CallBase>(V)) {
8177 if (CB->hasRetAttr(Attribute::NoUndef) ||
8178 CB->hasRetAttr(Attribute::Dereferenceable) ||
8179 CB->hasRetAttr(Attribute::DereferenceableOrNull))
8180 return true;
8181 }
8182
8183 if (!::canCreateUndefOrPoison(Opr, Kind,
8184 /*ConsiderFlagsAndMetadata=*/true)) {
8185 if (const auto *PN = dyn_cast<PHINode>(V)) {
8186 unsigned Num = PN->getNumIncomingValues();
8187 bool IsWellDefined = true;
8188 for (unsigned i = 0; i < Num; ++i) {
8189 if (PN == PN->getIncomingValue(i))
8190 continue;
8191 auto *TI = PN->getIncomingBlock(i)->getTerminator();
8192 if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
8193 DT, Depth + 1, Kind)) {
8194 IsWellDefined = false;
8195 break;
8196 }
8197 }
8198 if (IsWellDefined)
8199 return true;
8200 } else if (auto *Splat = isa<ShuffleVectorInst>(Opr) ? getSplatValue(Opr)
8201 : nullptr) {
8202 // For splats we only need to check the value being splatted.
8203 if (OpCheck(Splat))
8204 return true;
8205 } else if (all_of(Opr->operands(), OpCheck))
8206 return true;
8207 }
8208 }
8209
8210 if (auto *I = dyn_cast<LoadInst>(V))
8211 if (I->hasMetadata(LLVMContext::MD_noundef) ||
8212 I->hasMetadata(LLVMContext::MD_dereferenceable) ||
8213 I->hasMetadata(LLVMContext::MD_dereferenceable_or_null))
8214 return true;
8215
8217 return true;
8218
8219 // CxtI may be null or a cloned instruction.
8220 if (!CtxI || !CtxI->getParent() || !DT)
8221 return false;
8222
8223 auto *DNode = DT->getNode(CtxI->getParent());
8224 if (!DNode)
8225 // Unreachable block
8226 return false;
8227
8228 // If V is used as a branch condition before reaching CtxI, V cannot be
8229 // undef or poison.
8230 // br V, BB1, BB2
8231 // BB1:
8232 // CtxI ; V cannot be undef or poison here
8233 auto *Dominator = DNode->getIDom();
8234 // This check is purely for compile time reasons: we can skip the IDom walk
8235 // if what we are checking for includes undef and the value is not an integer.
8236 if (!includesUndef(Kind) || V->getType()->isIntegerTy())
8237 while (Dominator) {
8238 auto *TI = Dominator->getBlock()->getTerminatorOrNull();
8239
8240 Value *Cond = nullptr;
8241 if (auto BI = dyn_cast_or_null<CondBrInst>(TI)) {
8242 Cond = BI->getCondition();
8243 } else if (auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
8244 Cond = SI->getCondition();
8245 }
8246
8247 if (Cond) {
8248 if (Cond == V)
8249 return true;
8250 else if (!includesUndef(Kind) && isa<Operator>(Cond)) {
8251 // For poison, we can analyze further
8252 auto *Opr = cast<Operator>(Cond);
8253 if (any_of(Opr->operands(), [V](const Use &U) {
8254 return V == U && propagatesPoison(U);
8255 }))
8256 return true;
8257 }
8258 }
8259
8260 Dominator = Dominator->getIDom();
8261 }
8262
8263 if (AC && getKnowledgeValidInContext(V, {Attribute::NoUndef}, *AC, CtxI, DT))
8264 return true;
8265
8266 return false;
8267}
8268
8270 const Instruction *CtxI,
8271 const DominatorTree *DT,
8272 unsigned Depth) {
8273 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8275}
8276
8278 const Instruction *CtxI,
8279 const DominatorTree *DT, unsigned Depth) {
8280 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8282}
8283
8285 const Instruction *CtxI,
8286 const DominatorTree *DT, unsigned Depth) {
8287 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8289}
8290
8291/// Return true if undefined behavior would provably be executed on the path to
8292/// OnPathTo if Root produced a posion result. Note that this doesn't say
8293/// anything about whether OnPathTo is actually executed or whether Root is
8294/// actually poison. This can be used to assess whether a new use of Root can
8295/// be added at a location which is control equivalent with OnPathTo (such as
8296/// immediately before it) without introducing UB which didn't previously
8297/// exist. Note that a false result conveys no information.
8299 Instruction *OnPathTo,
8300 DominatorTree *DT) {
8301 // Basic approach is to assume Root is poison, propagate poison forward
8302 // through all users we can easily track, and then check whether any of those
8303 // users are provable UB and must execute before out exiting block might
8304 // exit.
8305
8306 // The set of all recursive users we've visited (which are assumed to all be
8307 // poison because of said visit)
8310 Worklist.push_back(Root);
8311 while (!Worklist.empty()) {
8312 const Instruction *I = Worklist.pop_back_val();
8313
8314 // If we know this must trigger UB on a path leading our target.
8315 if (mustTriggerUB(I, KnownPoison) && DT->dominates(I, OnPathTo))
8316 return true;
8317
8318 // If we can't analyze propagation through this instruction, just skip it
8319 // and transitive users. Safe as false is a conservative result.
8320 if (I != Root && !any_of(I->operands(), [&KnownPoison](const Use &U) {
8321 return KnownPoison.contains(U) && propagatesPoison(U);
8322 }))
8323 continue;
8324
8325 if (KnownPoison.insert(I).second)
8326 for (const User *User : I->users())
8327 Worklist.push_back(cast<Instruction>(User));
8328 }
8329
8330 // Might be non-UB, or might have a path we couldn't prove must execute on
8331 // way to exiting bb.
8332 return false;
8333}
8334
8336 const SimplifyQuery &SQ) {
8337 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
8338 Add, SQ);
8339}
8340
8343 const WithCache<const Value *> &RHS,
8344 const SimplifyQuery &SQ) {
8345 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, SQ);
8346}
8347
8349 // Note: An atomic operation isn't guaranteed to return in a reasonable amount
8350 // of time because it's possible for another thread to interfere with it for an
8351 // arbitrary length of time, but programs aren't allowed to rely on that.
8352
8353 // If there is no successor, then execution can't transfer to it.
8354 if (isa<ReturnInst>(I))
8355 return false;
8357 return false;
8358
8359 // Note: Do not add new checks here; instead, change Instruction::mayThrow or
8360 // Instruction::willReturn.
8361 //
8362 // FIXME: Move this check into Instruction::willReturn.
8363 if (isa<CatchPadInst>(I)) {
8364 switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) {
8365 default:
8366 // A catchpad may invoke exception object constructors and such, which
8367 // in some languages can be arbitrary code, so be conservative by default.
8368 return false;
8370 // For CoreCLR, it just involves a type test.
8371 return true;
8372 }
8373 }
8374
8375 // An instruction that returns without throwing must transfer control flow
8376 // to a successor.
8377 return !I->mayThrow() && I->willReturn();
8378}
8379
8381 // TODO: This is slightly conservative for invoke instruction since exiting
8382 // via an exception *is* normal control for them.
8383 for (const Instruction &I : *BB)
8385 return false;
8386 return true;
8387}
8388
8395
8398 assert(ScanLimit && "scan limit must be non-zero");
8399 for (const Instruction &I : Range) {
8400 if (--ScanLimit == 0)
8401 return false;
8403 return false;
8404 }
8405 return true;
8406}
8407
8409 const Loop *L) {
8410 // The loop header is guaranteed to be executed for every iteration.
8411 //
8412 // FIXME: Relax this constraint to cover all basic blocks that are
8413 // guaranteed to be executed at every iteration.
8414 if (I->getParent() != L->getHeader()) return false;
8415
8416 for (const Instruction &LI : *L->getHeader()) {
8417 if (&LI == I) return true;
8418 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
8419 }
8420 llvm_unreachable("Instruction not contained in its own parent basic block.");
8421}
8422
8424 switch (IID) {
8425 // TODO: Add more intrinsics.
8426 case Intrinsic::sadd_with_overflow:
8427 case Intrinsic::ssub_with_overflow:
8428 case Intrinsic::smul_with_overflow:
8429 case Intrinsic::uadd_with_overflow:
8430 case Intrinsic::usub_with_overflow:
8431 case Intrinsic::umul_with_overflow:
8432 // If an input is a vector containing a poison element, the
8433 // two output vectors (calculated results, overflow bits)'
8434 // corresponding lanes are poison.
8435 return true;
8436 case Intrinsic::ctpop:
8437 case Intrinsic::ctlz:
8438 case Intrinsic::cttz:
8439 case Intrinsic::abs:
8440 case Intrinsic::smax:
8441 case Intrinsic::smin:
8442 case Intrinsic::umax:
8443 case Intrinsic::umin:
8444 case Intrinsic::scmp:
8445 case Intrinsic::is_fpclass:
8446 case Intrinsic::ptrmask:
8447 case Intrinsic::ucmp:
8448 case Intrinsic::bitreverse:
8449 case Intrinsic::bswap:
8450 case Intrinsic::sadd_sat:
8451 case Intrinsic::ssub_sat:
8452 case Intrinsic::sshl_sat:
8453 case Intrinsic::uadd_sat:
8454 case Intrinsic::usub_sat:
8455 case Intrinsic::ushl_sat:
8456 case Intrinsic::smul_fix:
8457 case Intrinsic::smul_fix_sat:
8458 case Intrinsic::umul_fix:
8459 case Intrinsic::umul_fix_sat:
8460 case Intrinsic::pow:
8461 case Intrinsic::powi:
8462 case Intrinsic::sin:
8463 case Intrinsic::sinh:
8464 case Intrinsic::cos:
8465 case Intrinsic::cosh:
8466 case Intrinsic::sincos:
8467 case Intrinsic::sincospi:
8468 case Intrinsic::tan:
8469 case Intrinsic::tanh:
8470 case Intrinsic::asin:
8471 case Intrinsic::acos:
8472 case Intrinsic::atan:
8473 case Intrinsic::atan2:
8474 case Intrinsic::canonicalize:
8475 case Intrinsic::sqrt:
8476 case Intrinsic::exp:
8477 case Intrinsic::exp2:
8478 case Intrinsic::exp10:
8479 case Intrinsic::log:
8480 case Intrinsic::log2:
8481 case Intrinsic::log10:
8482 case Intrinsic::modf:
8483 case Intrinsic::floor:
8484 case Intrinsic::ceil:
8485 case Intrinsic::trunc:
8486 case Intrinsic::rint:
8487 case Intrinsic::nearbyint:
8488 case Intrinsic::round:
8489 case Intrinsic::roundeven:
8490 case Intrinsic::lrint:
8491 case Intrinsic::llrint:
8492 case Intrinsic::fshl:
8493 case Intrinsic::fshr:
8494 case Intrinsic::frexp:
8495 case Intrinsic::get_active_lane_mask:
8496 return true;
8497 default:
8498 return false;
8499 }
8500}
8501
8502bool llvm::propagatesPoison(const Use &PoisonOp) {
8503 const Operator *I = cast<Operator>(PoisonOp.getUser());
8504 switch (I->getOpcode()) {
8505 case Instruction::Freeze:
8506 case Instruction::PHI:
8507 case Instruction::Invoke:
8508 return false;
8509 case Instruction::Select:
8510 return PoisonOp.getOperandNo() == 0;
8511 case Instruction::Call:
8512 if (auto *II = dyn_cast<IntrinsicInst>(I))
8513 return intrinsicPropagatesPoison(II->getIntrinsicID());
8514 return false;
8515 case Instruction::ICmp:
8516 case Instruction::FCmp:
8517 case Instruction::GetElementPtr:
8518 return true;
8519 default:
8521 return true;
8522
8523 // Be conservative and return false.
8524 return false;
8525 }
8526}
8527
8528/// Enumerates all operands of \p I that are guaranteed to not be undef or
8529/// poison. If the callback \p Handle returns true, stop processing and return
8530/// true. Otherwise, return false.
8531template <typename CallableT>
8533 const CallableT &Handle) {
8534 switch (I->getOpcode()) {
8535 case Instruction::Store:
8536 if (Handle(cast<StoreInst>(I)->getPointerOperand()))
8537 return true;
8538 break;
8539
8540 case Instruction::Load:
8541 if (Handle(cast<LoadInst>(I)->getPointerOperand()))
8542 return true;
8543 break;
8544
8545 // Since dereferenceable attribute imply noundef, atomic operations
8546 // also implicitly have noundef pointers too
8547 case Instruction::AtomicCmpXchg:
8549 return true;
8550 break;
8551
8552 case Instruction::AtomicRMW:
8553 if (Handle(cast<AtomicRMWInst>(I)->getPointerOperand()))
8554 return true;
8555 break;
8556
8557 case Instruction::Call:
8558 case Instruction::Invoke: {
8559 const CallBase *CB = cast<CallBase>(I);
8560 if (CB->isIndirectCall() && Handle(CB->getCalledOperand()))
8561 return true;
8562 for (unsigned i = 0; i < CB->arg_size(); ++i)
8563 if ((CB->paramHasAttr(i, Attribute::NoUndef) ||
8564 CB->paramHasAttr(i, Attribute::Dereferenceable) ||
8565 CB->paramHasAttr(i, Attribute::DereferenceableOrNull)) &&
8566 Handle(CB->getArgOperand(i)))
8567 return true;
8568 break;
8569 }
8570 case Instruction::Ret:
8571 if (I->getFunction()->hasRetAttribute(Attribute::NoUndef) &&
8572 Handle(I->getOperand(0)))
8573 return true;
8574 break;
8575 case Instruction::Switch:
8576 if (Handle(cast<SwitchInst>(I)->getCondition()))
8577 return true;
8578 break;
8579 case Instruction::CondBr:
8580 if (Handle(cast<CondBrInst>(I)->getCondition()))
8581 return true;
8582 break;
8583 default:
8584 break;
8585 }
8586
8587 return false;
8588}
8589
8590/// Enumerates all operands of \p I that are guaranteed to not be poison.
8591template <typename CallableT>
8593 const CallableT &Handle) {
8594 if (handleGuaranteedWellDefinedOps(I, Handle))
8595 return true;
8596 switch (I->getOpcode()) {
8597 // Divisors of these operations are allowed to be partially undef.
8598 case Instruction::UDiv:
8599 case Instruction::SDiv:
8600 case Instruction::URem:
8601 case Instruction::SRem:
8602 return Handle(I->getOperand(1));
8603 default:
8604 return false;
8605 }
8606}
8607
8609 const SmallPtrSetImpl<const Value *> &KnownPoison) {
8611 I, [&](const Value *V) { return KnownPoison.count(V); });
8612}
8613
8615 bool PoisonOnly) {
8616 // We currently only look for uses of values within the same basic
8617 // block, as that makes it easier to guarantee that the uses will be
8618 // executed given that Inst is executed.
8619 //
8620 // FIXME: Expand this to consider uses beyond the same basic block. To do
8621 // this, look out for the distinction between post-dominance and strong
8622 // post-dominance.
8623 const BasicBlock *BB = nullptr;
8625 if (const auto *Inst = dyn_cast<Instruction>(V)) {
8626 BB = Inst->getParent();
8627 Begin = Inst->getIterator();
8628 Begin++;
8629 } else if (const auto *Arg = dyn_cast<Argument>(V)) {
8630 if (Arg->getParent()->isDeclaration())
8631 return false;
8632 BB = &Arg->getParent()->getEntryBlock();
8633 Begin = BB->begin();
8634 } else {
8635 return false;
8636 }
8637
8638 // Limit number of instructions we look at, to avoid scanning through large
8639 // blocks. The current limit is chosen arbitrarily.
8640 unsigned ScanLimit = 32;
8641 BasicBlock::const_iterator End = BB->end();
8642
8643 if (!PoisonOnly) {
8644 // Since undef does not propagate eagerly, be conservative & just check
8645 // whether a value is directly passed to an instruction that must take
8646 // well-defined operands.
8647
8648 for (const auto &I : make_range(Begin, End)) {
8649 if (--ScanLimit == 0)
8650 break;
8651
8652 if (handleGuaranteedWellDefinedOps(&I, [V](const Value *WellDefinedOp) {
8653 return WellDefinedOp == V;
8654 }))
8655 return true;
8656
8658 break;
8659 }
8660 return false;
8661 }
8662
8663 // Set of instructions that we have proved will yield poison if Inst
8664 // does.
8665 SmallPtrSet<const Value *, 16> YieldsPoison;
8667
8668 YieldsPoison.insert(V);
8669 Visited.insert(BB);
8670
8671 while (true) {
8672 for (const auto &I : make_range(Begin, End)) {
8673 if (--ScanLimit == 0)
8674 return false;
8675 if (mustTriggerUB(&I, YieldsPoison))
8676 return true;
8678 return false;
8679
8680 // If an operand is poison and propagates it, mark I as yielding poison.
8681 for (const Use &Op : I.operands()) {
8682 if (YieldsPoison.count(Op) && propagatesPoison(Op)) {
8683 YieldsPoison.insert(&I);
8684 break;
8685 }
8686 }
8687
8688 // Special handling for select, which returns poison if its operand 0 is
8689 // poison (handled in the loop above) *or* if both its true/false operands
8690 // are poison (handled here).
8691 if (I.getOpcode() == Instruction::Select &&
8692 YieldsPoison.count(I.getOperand(1)) &&
8693 YieldsPoison.count(I.getOperand(2))) {
8694 YieldsPoison.insert(&I);
8695 }
8696 }
8697
8698 BB = BB->getSingleSuccessor();
8699 if (!BB || !Visited.insert(BB).second)
8700 break;
8701
8702 Begin = BB->getFirstNonPHIIt();
8703 End = BB->end();
8704 }
8705 return false;
8706}
8707
8709 return ::programUndefinedIfUndefOrPoison(Inst, false);
8710}
8711
8713 return ::programUndefinedIfUndefOrPoison(Inst, true);
8714}
8715
8716static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
8717 if (FMF.noNaNs())
8718 return true;
8719
8720 if (auto *C = dyn_cast<ConstantFP>(V))
8721 return !C->isNaN();
8722
8723 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8724 if (!C->getElementType()->isFloatingPointTy())
8725 return false;
8726 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8727 if (C->getElementAsAPFloat(I).isNaN())
8728 return false;
8729 }
8730 return true;
8731 }
8732
8734 return true;
8735
8736 return false;
8737}
8738
8739static bool isKnownNonZero(const Value *V) {
8740 if (auto *C = dyn_cast<ConstantFP>(V))
8741 return !C->isZero();
8742
8743 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8744 if (!C->getElementType()->isFloatingPointTy())
8745 return false;
8746 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8747 if (C->getElementAsAPFloat(I).isZero())
8748 return false;
8749 }
8750 return true;
8751 }
8752
8753 return false;
8754}
8755
8756/// Match clamp pattern for float types without care about NaNs or signed zeros.
8757/// Given non-min/max outer cmp/select from the clamp pattern this
8758/// function recognizes if it can be substitued by a "canonical" min/max
8759/// pattern.
8761 Value *CmpLHS, Value *CmpRHS,
8762 Value *TrueVal, Value *FalseVal,
8763 Value *&LHS, Value *&RHS) {
8764 // Try to match
8765 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
8766 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
8767 // and return description of the outer Max/Min.
8768
8769 // First, check if select has inverse order:
8770 if (CmpRHS == FalseVal) {
8771 std::swap(TrueVal, FalseVal);
8772 Pred = CmpInst::getInversePredicate(Pred);
8773 }
8774
8775 // Assume success now. If there's no match, callers should not use these anyway.
8776 LHS = TrueVal;
8777 RHS = FalseVal;
8778
8779 const APFloat *FC1;
8780 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
8781 return {SPF_UNKNOWN, SPNB_NA, false};
8782
8783 const APFloat *FC2;
8784 switch (Pred) {
8785 case CmpInst::FCMP_OLT:
8786 case CmpInst::FCMP_OLE:
8787 case CmpInst::FCMP_ULT:
8788 case CmpInst::FCMP_ULE:
8789 if (match(FalseVal, m_OrdOrUnordFMin(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8790 *FC1 < *FC2)
8791 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8792 if (match(FalseVal, m_FMinNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8793 *FC1 < *FC2)
8794 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8795 break;
8796 case CmpInst::FCMP_OGT:
8797 case CmpInst::FCMP_OGE:
8798 case CmpInst::FCMP_UGT:
8799 case CmpInst::FCMP_UGE:
8800 if (match(FalseVal, m_OrdOrUnordFMax(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8801 *FC1 > *FC2)
8802 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8803 if (match(FalseVal, m_FMaxNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8804 *FC1 > *FC2)
8805 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8806 break;
8807 default:
8808 break;
8809 }
8810
8811 return {SPF_UNKNOWN, SPNB_NA, false};
8812}
8813
8814/// Recognize variations of:
8815/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
8817 Value *CmpLHS, Value *CmpRHS,
8818 Value *TrueVal, Value *FalseVal) {
8819 // Swap the select operands and predicate to match the patterns below.
8820 if (CmpRHS != TrueVal) {
8821 Pred = ICmpInst::getSwappedPredicate(Pred);
8822 std::swap(TrueVal, FalseVal);
8823 }
8824 const APInt *C1;
8825 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
8826 const APInt *C2;
8827 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
8828 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8829 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
8830 return {SPF_SMAX, SPNB_NA, false};
8831
8832 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
8833 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8834 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
8835 return {SPF_SMIN, SPNB_NA, false};
8836
8837 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
8838 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8839 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
8840 return {SPF_UMAX, SPNB_NA, false};
8841
8842 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
8843 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8844 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
8845 return {SPF_UMIN, SPNB_NA, false};
8846 }
8847 return {SPF_UNKNOWN, SPNB_NA, false};
8848}
8849
8850/// Recognize variations of:
8851/// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
8853 Value *CmpLHS, Value *CmpRHS,
8854 Value *TVal, Value *FVal,
8855 unsigned Depth) {
8856 // TODO: Allow FP min/max with nnan/nsz.
8857 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
8858
8859 Value *A = nullptr, *B = nullptr;
8860 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
8861 if (!SelectPatternResult::isMinOrMax(L.Flavor))
8862 return {SPF_UNKNOWN, SPNB_NA, false};
8863
8864 Value *C = nullptr, *D = nullptr;
8865 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
8866 if (L.Flavor != R.Flavor)
8867 return {SPF_UNKNOWN, SPNB_NA, false};
8868
8869 // We have something like: x Pred y ? min(a, b) : min(c, d).
8870 // Try to match the compare to the min/max operations of the select operands.
8871 // First, make sure we have the right compare predicate.
8872 switch (L.Flavor) {
8873 case SPF_SMIN:
8874 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
8875 Pred = ICmpInst::getSwappedPredicate(Pred);
8876 std::swap(CmpLHS, CmpRHS);
8877 }
8878 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
8879 break;
8880 return {SPF_UNKNOWN, SPNB_NA, false};
8881 case SPF_SMAX:
8882 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
8883 Pred = ICmpInst::getSwappedPredicate(Pred);
8884 std::swap(CmpLHS, CmpRHS);
8885 }
8886 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
8887 break;
8888 return {SPF_UNKNOWN, SPNB_NA, false};
8889 case SPF_UMIN:
8890 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
8891 Pred = ICmpInst::getSwappedPredicate(Pred);
8892 std::swap(CmpLHS, CmpRHS);
8893 }
8894 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
8895 break;
8896 return {SPF_UNKNOWN, SPNB_NA, false};
8897 case SPF_UMAX:
8898 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
8899 Pred = ICmpInst::getSwappedPredicate(Pred);
8900 std::swap(CmpLHS, CmpRHS);
8901 }
8902 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
8903 break;
8904 return {SPF_UNKNOWN, SPNB_NA, false};
8905 default:
8906 return {SPF_UNKNOWN, SPNB_NA, false};
8907 }
8908
8909 // If there is a common operand in the already matched min/max and the other
8910 // min/max operands match the compare operands (either directly or inverted),
8911 // then this is min/max of the same flavor.
8912
8913 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8914 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8915 if (D == B) {
8916 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8917 match(A, m_Not(m_Specific(CmpRHS)))))
8918 return {L.Flavor, SPNB_NA, false};
8919 }
8920 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8921 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8922 if (C == B) {
8923 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8924 match(A, m_Not(m_Specific(CmpRHS)))))
8925 return {L.Flavor, SPNB_NA, false};
8926 }
8927 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8928 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8929 if (D == A) {
8930 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8931 match(B, m_Not(m_Specific(CmpRHS)))))
8932 return {L.Flavor, SPNB_NA, false};
8933 }
8934 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8935 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8936 if (C == A) {
8937 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8938 match(B, m_Not(m_Specific(CmpRHS)))))
8939 return {L.Flavor, SPNB_NA, false};
8940 }
8941
8942 return {SPF_UNKNOWN, SPNB_NA, false};
8943}
8944
8945/// If the input value is the result of a 'not' op, constant integer, or vector
8946/// splat of a constant integer, return the bitwise-not source value.
8947/// TODO: This could be extended to handle non-splat vector integer constants.
8949 Value *NotV;
8950 if (match(V, m_Not(m_Value(NotV))))
8951 return NotV;
8952
8953 const APInt *C;
8954 if (match(V, m_APInt(C)))
8955 return ConstantInt::get(V->getType(), ~(*C));
8956
8957 return nullptr;
8958}
8959
8960/// Match non-obvious integer minimum and maximum sequences.
8962 Value *CmpLHS, Value *CmpRHS,
8963 Value *TrueVal, Value *FalseVal,
8964 Value *&LHS, Value *&RHS,
8965 unsigned Depth) {
8966 // Assume success. If there's no match, callers should not use these anyway.
8967 LHS = TrueVal;
8968 RHS = FalseVal;
8969
8970 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
8972 return SPR;
8973
8974 SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
8976 return SPR;
8977
8978 // Look through 'not' ops to find disguised min/max.
8979 // (X > Y) ? ~X : ~Y ==> (~X < ~Y) ? ~X : ~Y ==> MIN(~X, ~Y)
8980 // (X < Y) ? ~X : ~Y ==> (~X > ~Y) ? ~X : ~Y ==> MAX(~X, ~Y)
8981 if (CmpLHS == getNotValue(TrueVal) && CmpRHS == getNotValue(FalseVal)) {
8982 switch (Pred) {
8983 case CmpInst::ICMP_SGT: return {SPF_SMIN, SPNB_NA, false};
8984 case CmpInst::ICMP_SLT: return {SPF_SMAX, SPNB_NA, false};
8985 case CmpInst::ICMP_UGT: return {SPF_UMIN, SPNB_NA, false};
8986 case CmpInst::ICMP_ULT: return {SPF_UMAX, SPNB_NA, false};
8987 default: break;
8988 }
8989 }
8990
8991 // (X > Y) ? ~Y : ~X ==> (~X < ~Y) ? ~Y : ~X ==> MAX(~Y, ~X)
8992 // (X < Y) ? ~Y : ~X ==> (~X > ~Y) ? ~Y : ~X ==> MIN(~Y, ~X)
8993 if (CmpLHS == getNotValue(FalseVal) && CmpRHS == getNotValue(TrueVal)) {
8994 switch (Pred) {
8995 case CmpInst::ICMP_SGT: return {SPF_SMAX, SPNB_NA, false};
8996 case CmpInst::ICMP_SLT: return {SPF_SMIN, SPNB_NA, false};
8997 case CmpInst::ICMP_UGT: return {SPF_UMAX, SPNB_NA, false};
8998 case CmpInst::ICMP_ULT: return {SPF_UMIN, SPNB_NA, false};
8999 default: break;
9000 }
9001 }
9002
9003 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
9004 return {SPF_UNKNOWN, SPNB_NA, false};
9005
9006 const APInt *C1;
9007 if (!match(CmpRHS, m_APInt(C1)))
9008 return {SPF_UNKNOWN, SPNB_NA, false};
9009
9010 // An unsigned min/max can be written with a signed compare.
9011 const APInt *C2;
9012 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
9013 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
9014 // Is the sign bit set?
9015 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
9016 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
9017 if (Pred == CmpInst::ICMP_SLT && C1->isZero() && C2->isMaxSignedValue())
9018 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
9019
9020 // Is the sign bit clear?
9021 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
9022 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
9023 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnes() && C2->isMinSignedValue())
9024 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
9025 }
9026
9027 return {SPF_UNKNOWN, SPNB_NA, false};
9028}
9029
9030bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW,
9031 bool AllowPoison) {
9032 assert(X && Y && "Invalid operand");
9033
9034 auto IsNegationOf = [&](const Value *X, const Value *Y) {
9035 if (!match(X, m_Neg(m_Specific(Y))))
9036 return false;
9037
9038 auto *BO = cast<BinaryOperator>(X);
9039 if (NeedNSW && !BO->hasNoSignedWrap())
9040 return false;
9041
9042 auto *Zero = cast<Constant>(BO->getOperand(0));
9043 if (!AllowPoison && !Zero->isNullValue())
9044 return false;
9045
9046 return true;
9047 };
9048
9049 // X = -Y or Y = -X
9050 if (IsNegationOf(X, Y) || IsNegationOf(Y, X))
9051 return true;
9052
9053 // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
9054 Value *A, *B;
9055 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
9056 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
9057 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
9059}
9060
9061bool llvm::isKnownInversion(const Value *X, const Value *Y) {
9062 // Handle X = icmp pred A, B, Y = icmp pred A, C.
9063 Value *A, *B, *C;
9064 CmpPredicate Pred1, Pred2;
9065 if (!match(X, m_ICmp(Pred1, m_Value(A), m_Value(B))) ||
9066 !match(Y, m_c_ICmp(Pred2, m_Specific(A), m_Value(C))))
9067 return false;
9068
9069 // They must both have samesign flag or not.
9070 if (Pred1.hasSameSign() != Pred2.hasSameSign())
9071 return false;
9072
9073 if (B == C)
9074 return Pred1 == ICmpInst::getInversePredicate(Pred2);
9075
9076 // Try to infer the relationship from constant ranges.
9077 const APInt *RHSC1, *RHSC2;
9078 if (!match(B, m_APInt(RHSC1)) || !match(C, m_APInt(RHSC2)))
9079 return false;
9080
9081 // Sign bits of two RHSCs should match.
9082 if (Pred1.hasSameSign() && RHSC1->isNonNegative() != RHSC2->isNonNegative())
9083 return false;
9084
9085 const auto CR1 = ConstantRange::makeExactICmpRegion(Pred1, *RHSC1);
9086 const auto CR2 = ConstantRange::makeExactICmpRegion(Pred2, *RHSC2);
9087
9088 return CR1.inverse() == CR2;
9089}
9090
9092 SelectPatternNaNBehavior NaNBehavior,
9093 bool Ordered) {
9094 switch (Pred) {
9095 default:
9096 return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
9097 case ICmpInst::ICMP_UGT:
9098 case ICmpInst::ICMP_UGE:
9099 return {SPF_UMAX, SPNB_NA, false};
9100 case ICmpInst::ICMP_SGT:
9101 case ICmpInst::ICMP_SGE:
9102 return {SPF_SMAX, SPNB_NA, false};
9103 case ICmpInst::ICMP_ULT:
9104 case ICmpInst::ICMP_ULE:
9105 return {SPF_UMIN, SPNB_NA, false};
9106 case ICmpInst::ICMP_SLT:
9107 case ICmpInst::ICMP_SLE:
9108 return {SPF_SMIN, SPNB_NA, false};
9109 case FCmpInst::FCMP_UGT:
9110 case FCmpInst::FCMP_UGE:
9111 case FCmpInst::FCMP_OGT:
9112 case FCmpInst::FCMP_OGE:
9113 return {SPF_FMAXNUM, NaNBehavior, Ordered};
9114 case FCmpInst::FCMP_ULT:
9115 case FCmpInst::FCMP_ULE:
9116 case FCmpInst::FCMP_OLT:
9117 case FCmpInst::FCMP_OLE:
9118 return {SPF_FMINNUM, NaNBehavior, Ordered};
9119 }
9120}
9121
9122std::optional<std::pair<CmpPredicate, Constant *>>
9125 "Only for relational integer predicates.");
9126 if (isa<UndefValue>(C))
9127 return std::nullopt;
9128
9129 Type *Type = C->getType();
9130 bool IsSigned = ICmpInst::isSigned(Pred);
9131
9133 bool WillIncrement =
9134 UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
9135
9136 // Check if the constant operand can be safely incremented/decremented
9137 // without overflowing/underflowing.
9138 auto ConstantIsOk = [Pred, WillIncrement, IsSigned](ConstantInt *C) {
9139 if (WillIncrement ? C->isMaxValue(IsSigned) : C->isMinValue(IsSigned))
9140 return false;
9141
9142 if (!Pred.hasSameSign())
9143 return true;
9144
9145 // Crossing the corresponding boundary in the other ordering changes the
9146 // sign bit, and therefore changes the poison domain.
9147 return WillIncrement ? !C->isMaxValue(!IsSigned)
9148 : !C->isMinValue(!IsSigned);
9149 };
9150
9151 Constant *SafeReplacementConstant = nullptr;
9152 if (auto *CI = dyn_cast<ConstantInt>(C)) {
9153 // Bail out if the constant can't be safely incremented/decremented.
9154 if (!ConstantIsOk(CI))
9155 return std::nullopt;
9156 } else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) {
9157 unsigned NumElts = FVTy->getNumElements();
9158 for (unsigned i = 0; i != NumElts; ++i) {
9159 Constant *Elt = C->getAggregateElement(i);
9160 if (!Elt)
9161 return std::nullopt;
9162
9163 if (isa<UndefValue>(Elt))
9164 continue;
9165
9166 // Bail out if we can't determine if this constant is min/max or if we
9167 // know that this constant is min/max.
9168 auto *CI = dyn_cast<ConstantInt>(Elt);
9169 if (!CI || !ConstantIsOk(CI))
9170 return std::nullopt;
9171
9172 if (!SafeReplacementConstant)
9173 SafeReplacementConstant = CI;
9174 }
9175 } else if (isa<VectorType>(C->getType())) {
9176 // Handle scalable splat
9177 Value *SplatC = C->getSplatValue();
9178 auto *CI = dyn_cast_or_null<ConstantInt>(SplatC);
9179 // Bail out if the constant can't be safely incremented/decremented.
9180 if (!CI || !ConstantIsOk(CI))
9181 return std::nullopt;
9182 } else {
9183 // ConstantExpr?
9184 return std::nullopt;
9185 }
9186
9187 // It may not be safe to change a compare predicate in the presence of
9188 // undefined elements, so replace those elements with the first safe constant
9189 // that we found.
9190 // TODO: in case of poison, it is safe; let's replace undefs only.
9191 if (C->containsUndefOrPoisonElement()) {
9192 assert(SafeReplacementConstant && "Replacement constant not set");
9193 C = Constant::replaceUndefsWith(C, SafeReplacementConstant);
9194 }
9195
9197 Pred.hasSameSign());
9198
9199 // Increment or decrement the constant.
9200 Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
9201 Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
9202
9203 return std::make_pair(NewPred, NewC);
9204}
9205
9207 FastMathFlags FMF,
9208 Value *CmpLHS, Value *CmpRHS,
9209 Value *TrueVal, Value *FalseVal,
9210 Value *&LHS, Value *&RHS,
9211 unsigned Depth) {
9212 if (CmpInst::isFPPredicate(Pred)) {
9213 // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
9214 // 0.0 operand, set the compare's 0.0 operands to that same value for the
9215 // purpose of identifying min/max. Disregard vector constants with undefined
9216 // elements because those can not be back-propagated for analysis.
9217 Value *OutputZeroVal = nullptr;
9218 if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
9219 !cast<Constant>(TrueVal)->containsUndefOrPoisonElement())
9220 OutputZeroVal = TrueVal;
9221 else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
9222 !cast<Constant>(FalseVal)->containsUndefOrPoisonElement())
9223 OutputZeroVal = FalseVal;
9224
9225 if (OutputZeroVal) {
9226 if (match(CmpLHS, m_AnyZeroFP()) && CmpLHS != OutputZeroVal)
9227 CmpLHS = OutputZeroVal;
9228 if (match(CmpRHS, m_AnyZeroFP()) && CmpRHS != OutputZeroVal)
9229 CmpRHS = OutputZeroVal;
9230 }
9231 }
9232
9233 LHS = CmpLHS;
9234 RHS = CmpRHS;
9235
9236 // Signed zero may return inconsistent results between implementations.
9237 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
9238 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
9239 // Therefore, we behave conservatively and only proceed if at least one of the
9240 // operands is known to not be zero or if we don't care about signed zero.
9241 if (CmpInst::isFPPredicate(Pred)) {
9242 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9243 !isKnownNonZero(CmpRHS))
9244 return {SPF_UNKNOWN, SPNB_NA, false};
9245 }
9246
9247 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
9248 bool Ordered = false;
9249
9250 // When given one NaN and one non-NaN input:
9251 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
9252 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
9253 // ordered comparison fails), which could be NaN or non-NaN.
9254 // so here we discover exactly what NaN behavior is required/accepted.
9255 if (CmpInst::isFPPredicate(Pred)) {
9256 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
9257 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
9258
9259 if (LHSSafe && RHSSafe) {
9260 // Both operands are known non-NaN.
9261 NaNBehavior = SPNB_RETURNS_ANY;
9262 Ordered = CmpInst::isOrdered(Pred);
9263 } else if (CmpInst::isOrdered(Pred)) {
9264 // An ordered comparison will return false when given a NaN, so it
9265 // returns the RHS.
9266 Ordered = true;
9267 if (LHSSafe)
9268 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
9269 NaNBehavior = SPNB_RETURNS_NAN;
9270 else if (RHSSafe)
9271 NaNBehavior = SPNB_RETURNS_OTHER;
9272 else
9273 // Completely unsafe.
9274 return {SPF_UNKNOWN, SPNB_NA, false};
9275 } else {
9276 Ordered = false;
9277 // An unordered comparison will return true when given a NaN, so it
9278 // returns the LHS.
9279 if (LHSSafe)
9280 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
9281 NaNBehavior = SPNB_RETURNS_OTHER;
9282 else if (RHSSafe)
9283 NaNBehavior = SPNB_RETURNS_NAN;
9284 else
9285 // Completely unsafe.
9286 return {SPF_UNKNOWN, SPNB_NA, false};
9287 }
9288 }
9289
9290 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
9291 std::swap(CmpLHS, CmpRHS);
9292 Pred = CmpInst::getSwappedPredicate(Pred);
9293 if (NaNBehavior == SPNB_RETURNS_NAN)
9294 NaNBehavior = SPNB_RETURNS_OTHER;
9295 else if (NaNBehavior == SPNB_RETURNS_OTHER)
9296 NaNBehavior = SPNB_RETURNS_NAN;
9297 Ordered = !Ordered;
9298 }
9299
9300 // ([if]cmp X, Y) ? X : Y
9301 if (TrueVal == CmpLHS && FalseVal == CmpRHS)
9302 return getSelectPattern(Pred, NaNBehavior, Ordered);
9303
9304 if (isKnownNegation(TrueVal, FalseVal)) {
9305 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
9306 // match against either LHS or sign-preserving operations on LHS, like
9307 // sext(LHS), or binary ops that do not wrap in signed sense.
9308 auto CmpLHSOrSExt =
9309 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
9310 auto MaybeSExtOrMulCmpLHS =
9311 m_CombineOr(CmpLHSOrSExt, m_NSWMul(CmpLHSOrSExt, m_StrictlyPositive()),
9312 m_NSWShl(CmpLHSOrSExt, m_Value()));
9313 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
9314 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
9315 if (match(TrueVal, MaybeSExtOrMulCmpLHS)) {
9316 // Set the return values. If the compare uses the negated value (-X >s 0),
9317 // swap the return values because the negated value is always 'RHS'.
9318 LHS = TrueVal;
9319 RHS = FalseVal;
9320 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
9321 std::swap(LHS, RHS);
9322
9323 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
9324 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
9325 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9326 return {SPF_ABS, SPNB_NA, false};
9327
9328 // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
9329 if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
9330 return {SPF_ABS, SPNB_NA, false};
9331
9332 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
9333 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
9334 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9335 return {SPF_NABS, SPNB_NA, false};
9336 } else if (match(FalseVal, MaybeSExtOrMulCmpLHS)) {
9337 // Set the return values. If the compare uses the negated value (-X >s 0),
9338 // swap the return values because the negated value is always 'RHS'.
9339 LHS = FalseVal;
9340 RHS = TrueVal;
9341 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
9342 std::swap(LHS, RHS);
9343
9344 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
9345 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
9346 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9347 return {SPF_NABS, SPNB_NA, false};
9348
9349 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
9350 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
9351 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9352 return {SPF_ABS, SPNB_NA, false};
9353 }
9354 }
9355
9356 if (CmpInst::isIntPredicate(Pred))
9357 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
9358
9359 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
9360 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
9361 // semantics than minNum. Be conservative in such case.
9362 if (NaNBehavior != SPNB_RETURNS_ANY ||
9363 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9364 !isKnownNonZero(CmpRHS)))
9365 return {SPF_UNKNOWN, SPNB_NA, false};
9366
9367 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
9368}
9369
9371 Instruction::CastOps *CastOp) {
9372 const DataLayout &DL = CmpI->getDataLayout();
9373
9374 Constant *CastedTo = nullptr;
9375 switch (*CastOp) {
9376 case Instruction::ZExt:
9377 if (CmpI->isUnsigned())
9378 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
9379 break;
9380 case Instruction::SExt:
9381 if (CmpI->isSigned())
9382 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
9383 break;
9384 case Instruction::Trunc:
9385 Constant *CmpConst;
9386 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
9387 CmpConst->getType() == SrcTy) {
9388 // Here we have the following case:
9389 //
9390 // %cond = cmp iN %x, CmpConst
9391 // %tr = trunc iN %x to iK
9392 // %narrowsel = select i1 %cond, iK %t, iK C
9393 //
9394 // We can always move trunc after select operation:
9395 //
9396 // %cond = cmp iN %x, CmpConst
9397 // %widesel = select i1 %cond, iN %x, iN CmpConst
9398 // %tr = trunc iN %widesel to iK
9399 //
9400 // Note that C could be extended in any way because we don't care about
9401 // upper bits after truncation. It can't be abs pattern, because it would
9402 // look like:
9403 //
9404 // select i1 %cond, x, -x.
9405 //
9406 // So only min/max pattern could be matched. Such match requires widened C
9407 // == CmpConst. That is why set widened C = CmpConst, condition trunc
9408 // CmpConst == C is checked below.
9409 CastedTo = CmpConst;
9410 } else {
9411 unsigned ExtOp = CmpI->isSigned() ? Instruction::SExt : Instruction::ZExt;
9412 CastedTo = ConstantFoldCastOperand(ExtOp, C, SrcTy, DL);
9413 }
9414 break;
9415 case Instruction::FPTrunc:
9416 CastedTo = ConstantFoldCastOperand(Instruction::FPExt, C, SrcTy, DL);
9417 break;
9418 case Instruction::FPExt:
9419 CastedTo = ConstantFoldCastOperand(Instruction::FPTrunc, C, SrcTy, DL);
9420 break;
9421 case Instruction::FPToUI:
9422 CastedTo = ConstantFoldCastOperand(Instruction::UIToFP, C, SrcTy, DL);
9423 break;
9424 case Instruction::FPToSI:
9425 CastedTo = ConstantFoldCastOperand(Instruction::SIToFP, C, SrcTy, DL);
9426 break;
9427 case Instruction::UIToFP:
9428 CastedTo = ConstantFoldCastOperand(Instruction::FPToUI, C, SrcTy, DL);
9429 break;
9430 case Instruction::SIToFP:
9431 CastedTo = ConstantFoldCastOperand(Instruction::FPToSI, C, SrcTy, DL);
9432 break;
9433 default:
9434 break;
9435 }
9436
9437 if (!CastedTo)
9438 return nullptr;
9439
9440 // Make sure the cast doesn't lose any information.
9441 Constant *CastedBack =
9442 ConstantFoldCastOperand(*CastOp, CastedTo, C->getType(), DL);
9443 if (CastedBack && CastedBack != C)
9444 return nullptr;
9445
9446 return CastedTo;
9447}
9448
9449/// Helps to match a select pattern in case of a type mismatch.
9450///
9451/// The function processes the case when type of true and false values of a
9452/// select instruction differs from type of the cmp instruction operands because
9453/// of a cast instruction. The function checks if it is legal to move the cast
9454/// operation after "select". If yes, it returns the new second value of
9455/// "select" (with the assumption that cast is moved):
9456/// 1. As operand of cast instruction when both values of "select" are same cast
9457/// instructions.
9458/// 2. As restored constant (by applying reverse cast operation) when the first
9459/// value of the "select" is a cast operation and the second value is a
9460/// constant. It is implemented in lookThroughCastConst().
9461/// 3. As one operand is cast instruction and the other is not. The operands in
9462/// sel(cmp) are in different type integer.
9463/// NOTE: We return only the new second value because the first value could be
9464/// accessed as operand of cast instruction.
9466 Instruction::CastOps *CastOp) {
9467 auto *Cast1 = dyn_cast<CastInst>(V1);
9468 if (!Cast1)
9469 return nullptr;
9470
9471 *CastOp = Cast1->getOpcode();
9472 Type *SrcTy = Cast1->getSrcTy();
9473 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
9474 // If V1 and V2 are both the same cast from the same type, look through V1.
9475 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
9476 return Cast2->getOperand(0);
9477 return nullptr;
9478 }
9479
9480 auto *C = dyn_cast<Constant>(V2);
9481 if (C)
9482 return lookThroughCastConst(CmpI, SrcTy, C, CastOp);
9483
9484 Value *CastedTo = nullptr;
9485 if (*CastOp == Instruction::Trunc) {
9486 if (match(CmpI->getOperand(1), m_ZExtOrSExt(m_Specific(V2)))) {
9487 // Here we have the following case:
9488 // %y_ext = sext iK %y to iN
9489 // %cond = cmp iN %x, %y_ext
9490 // %tr = trunc iN %x to iK
9491 // %narrowsel = select i1 %cond, iK %tr, iK %y
9492 //
9493 // We can always move trunc after select operation:
9494 // %y_ext = sext iK %y to iN
9495 // %cond = cmp iN %x, %y_ext
9496 // %widesel = select i1 %cond, iN %x, iN %y_ext
9497 // %tr = trunc iN %widesel to iK
9498 assert(V2->getType() == Cast1->getType() &&
9499 "V2 and Cast1 should be the same type.");
9500 CastedTo = CmpI->getOperand(1);
9501 }
9502 }
9503
9504 return CastedTo;
9505}
9507 Instruction::CastOps *CastOp,
9508 unsigned Depth) {
9510 return {SPF_UNKNOWN, SPNB_NA, false};
9511
9513 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
9514
9515 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
9516 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
9517
9518 Value *TrueVal = SI->getTrueValue();
9519 Value *FalseVal = SI->getFalseValue();
9520
9521 return llvm::matchDecomposedSelectPattern(CmpI, TrueVal, FalseVal, LHS, RHS,
9522 SI->getFastMathFlagsOrNone(),
9523 CastOp, Depth);
9524}
9525
9527 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
9528 FastMathFlags FMF, Instruction::CastOps *CastOp, unsigned Depth) {
9529 CmpInst::Predicate Pred = CmpI->getPredicate();
9530 Value *CmpLHS = CmpI->getOperand(0);
9531 Value *CmpRHS = CmpI->getOperand(1);
9532 if (isa<FPMathOperator>(CmpI) && CmpI->hasNoNaNs())
9533 FMF.setNoNaNs();
9534
9535 // Bail out early.
9536 if (CmpI->isEquality())
9537 return {SPF_UNKNOWN, SPNB_NA, false};
9538
9539 // Deal with type mismatches.
9540 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
9541 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
9542 // If this is a potential fmin/fmax with a cast to integer, then ignore
9543 // -0.0 because there is no corresponding integer value.
9544 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9545 FMF.setNoSignedZeros();
9546 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9547 cast<CastInst>(TrueVal)->getOperand(0), C,
9548 LHS, RHS, Depth);
9549 }
9550 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
9551 // If this is a potential fmin/fmax with a cast to integer, then ignore
9552 // -0.0 because there is no corresponding integer value.
9553 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9554 FMF.setNoSignedZeros();
9555 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9556 C, cast<CastInst>(FalseVal)->getOperand(0),
9557 LHS, RHS, Depth);
9558 }
9559 }
9560 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
9561 LHS, RHS, Depth);
9562}
9563
9565 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
9566 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
9567 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
9568 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
9569 if (SPF == SPF_FMINNUM)
9570 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
9571 if (SPF == SPF_FMAXNUM)
9572 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
9573 llvm_unreachable("unhandled!");
9574}
9575
9577 switch (SPF) {
9579 return Intrinsic::umin;
9581 return Intrinsic::umax;
9583 return Intrinsic::smin;
9585 return Intrinsic::smax;
9586 default:
9587 llvm_unreachable("Unexpected SPF");
9588 }
9589}
9590
9592 if (SPF == SPF_SMIN) return SPF_SMAX;
9593 if (SPF == SPF_UMIN) return SPF_UMAX;
9594 if (SPF == SPF_SMAX) return SPF_SMIN;
9595 if (SPF == SPF_UMAX) return SPF_UMIN;
9596 llvm_unreachable("unhandled!");
9597}
9598
9600 switch (MinMaxID) {
9601 case Intrinsic::smax: return Intrinsic::smin;
9602 case Intrinsic::smin: return Intrinsic::smax;
9603 case Intrinsic::umax: return Intrinsic::umin;
9604 case Intrinsic::umin: return Intrinsic::umax;
9605 // Please note that next four intrinsics may produce the same result for
9606 // original and inverted case even if X != Y due to NaN is handled specially.
9607 case Intrinsic::maximum: return Intrinsic::minimum;
9608 case Intrinsic::minimum: return Intrinsic::maximum;
9609 case Intrinsic::maxnum: return Intrinsic::minnum;
9610 case Intrinsic::minnum: return Intrinsic::maxnum;
9611 case Intrinsic::maximumnum:
9612 return Intrinsic::minimumnum;
9613 case Intrinsic::minimumnum:
9614 return Intrinsic::maximumnum;
9615 default: llvm_unreachable("Unexpected intrinsic");
9616 }
9617}
9618
9620 switch (SPF) {
9623 case SPF_UMAX: return APInt::getMaxValue(BitWidth);
9624 case SPF_UMIN: return APInt::getMinValue(BitWidth);
9625 default: llvm_unreachable("Unexpected flavor");
9626 }
9627}
9628
9629std::pair<Intrinsic::ID, bool>
9631 // Check if VL contains select instructions that can be folded into a min/max
9632 // vector intrinsic and return the intrinsic if it is possible.
9633 // TODO: Support floating point min/max.
9634 bool AllCmpSingleUse = true;
9635 SelectPatternResult SelectPattern;
9636 SelectPattern.Flavor = SPF_UNKNOWN;
9637 if (all_of(VL, [&SelectPattern, &AllCmpSingleUse](Value *I) {
9638 Value *LHS, *RHS;
9639 auto CurrentPattern = matchSelectPattern(I, LHS, RHS);
9640 if (!SelectPatternResult::isMinOrMax(CurrentPattern.Flavor))
9641 return false;
9642 if (SelectPattern.Flavor != SPF_UNKNOWN &&
9643 SelectPattern.Flavor != CurrentPattern.Flavor)
9644 return false;
9645 SelectPattern = CurrentPattern;
9646 AllCmpSingleUse &=
9648 return true;
9649 })) {
9650 switch (SelectPattern.Flavor) {
9651 case SPF_SMIN:
9652 return {Intrinsic::smin, AllCmpSingleUse};
9653 case SPF_UMIN:
9654 return {Intrinsic::umin, AllCmpSingleUse};
9655 case SPF_SMAX:
9656 return {Intrinsic::smax, AllCmpSingleUse};
9657 case SPF_UMAX:
9658 return {Intrinsic::umax, AllCmpSingleUse};
9659 case SPF_FMAXNUM:
9660 return {Intrinsic::maxnum, AllCmpSingleUse};
9661 case SPF_FMINNUM:
9662 return {Intrinsic::minnum, AllCmpSingleUse};
9663 default:
9664 llvm_unreachable("unexpected select pattern flavor");
9665 }
9666 }
9667 return {Intrinsic::not_intrinsic, false};
9668}
9669
9670template <typename InstTy>
9671static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst,
9672 Value *&Init, Value *&OtherOp) {
9673 // Handle the case of a simple two-predecessor recurrence PHI.
9674 // There's a lot more that could theoretically be done here, but
9675 // this is sufficient to catch some interesting cases.
9676 // TODO: Expand list -- gep, uadd.sat etc.
9677 if (PN->getNumIncomingValues() != 2)
9678 return false;
9679
9680 for (unsigned I = 0; I != 2; ++I) {
9681 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9682 Operation && Operation->getNumOperands() >= 2) {
9683 Value *LHS = Operation->getOperand(0);
9684 Value *RHS = Operation->getOperand(1);
9685 if (LHS != PN && RHS != PN)
9686 continue;
9687
9688 Inst = Operation;
9689 Init = PN->getIncomingValue(!I);
9690 OtherOp = (LHS == PN) ? RHS : LHS;
9691 return true;
9692 }
9693 }
9694 return false;
9695}
9696
9697template <typename InstTy>
9698static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst,
9699 Value *&Init, Value *&OtherOp0,
9700 Value *&OtherOp1) {
9701 if (PN->getNumIncomingValues() != 2)
9702 return false;
9703
9704 for (unsigned I = 0; I != 2; ++I) {
9705 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9706 Operation && Operation->getNumOperands() >= 3) {
9707 Value *Op0 = Operation->getOperand(0);
9708 Value *Op1 = Operation->getOperand(1);
9709 Value *Op2 = Operation->getOperand(2);
9710
9711 if (Op0 != PN && Op1 != PN && Op2 != PN)
9712 continue;
9713
9714 Inst = Operation;
9715 Init = PN->getIncomingValue(!I);
9716 if (Op0 == PN) {
9717 OtherOp0 = Op1;
9718 OtherOp1 = Op2;
9719 } else if (Op1 == PN) {
9720 OtherOp0 = Op0;
9721 OtherOp1 = Op2;
9722 } else {
9723 OtherOp0 = Op0;
9724 OtherOp1 = Op1;
9725 }
9726 return true;
9727 }
9728 }
9729 return false;
9730}
9732 Value *&Start, Value *&Step) {
9733 // We try to match a recurrence of the form:
9734 // %iv = [Start, %entry], [%iv.next, %backedge]
9735 // %iv.next = binop %iv, Step
9736 // Or:
9737 // %iv = [Start, %entry], [%iv.next, %backedge]
9738 // %iv.next = binop Step, %iv
9739 return matchTwoInputRecurrence(P, BO, Start, Step);
9740}
9741
9743 Value *&Start, Value *&Step) {
9744 BinaryOperator *BO = nullptr;
9745 return match(I, m_c_BinOp(m_Phi(P), m_Value())) &&
9746 matchSimpleRecurrence(P, BO, Start, Step) && BO == I;
9747}
9748
9750 PHINode *&P, Value *&Init,
9751 Value *&OtherOp) {
9752 // Binary intrinsics only supported for now.
9753 if (I->arg_size() != 2 || I->getType() != I->getArgOperand(0)->getType() ||
9754 I->getType() != I->getArgOperand(1)->getType())
9755 return false;
9756
9757 IntrinsicInst *II = nullptr;
9758 P = dyn_cast<PHINode>(I->getArgOperand(0));
9759 if (!P)
9760 P = dyn_cast<PHINode>(I->getArgOperand(1));
9761
9762 return P && matchTwoInputRecurrence(P, II, Init, OtherOp) && II == I;
9763}
9764
9766 PHINode *&P, Value *&Init,
9767 Value *&OtherOp0,
9768 Value *&OtherOp1) {
9769 if (I->arg_size() != 3 || I->getType() != I->getArgOperand(0)->getType() ||
9770 I->getType() != I->getArgOperand(1)->getType() ||
9771 I->getType() != I->getArgOperand(2)->getType())
9772 return false;
9773 IntrinsicInst *II = nullptr;
9774 P = dyn_cast<PHINode>(I->getArgOperand(0));
9775 if (!P) {
9776 P = dyn_cast<PHINode>(I->getArgOperand(1));
9777 if (!P)
9778 P = dyn_cast<PHINode>(I->getArgOperand(2));
9779 }
9780 return P && matchThreeInputRecurrence(P, II, Init, OtherOp0, OtherOp1) &&
9781 II == I;
9782}
9783
9784/// Return true if "icmp Pred LHS RHS" is always true.
9786 const Value *RHS) {
9787 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
9788 return true;
9789
9790 switch (Pred) {
9791 default:
9792 return false;
9793
9794 case CmpInst::ICMP_SLE: {
9795 const APInt *C;
9796
9797 // LHS s<= LHS +_{nsw} C if C >= 0
9798 // LHS s<= LHS | C if C >= 0
9799 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))) ||
9801 return !C->isNegative();
9802
9803 // LHS s<= smax(LHS, V) for any V
9805 return true;
9806
9807 // smin(RHS, V) s<= RHS for any V
9809 return true;
9810
9811 // Match A to (X +_{nsw} CA) and B to (X +_{nsw} CB)
9812 const Value *X;
9813 const APInt *CLHS, *CRHS;
9814 if (match(LHS, m_NSWAddLike(m_Value(X), m_APInt(CLHS))) &&
9816 return CLHS->sle(*CRHS);
9817
9818 return false;
9819 }
9820
9821 case CmpInst::ICMP_ULE: {
9822 // LHS u<= LHS +_{nuw} V for any V
9823 if (match(RHS, m_c_Add(m_Specific(LHS), m_Value())) &&
9825 return true;
9826
9827 // LHS u<= LHS | V for any V
9828 if (match(RHS, m_c_Or(m_Specific(LHS), m_Value())))
9829 return true;
9830
9831 // LHS u<= umax(LHS, V) for any V
9833 return true;
9834
9835 // RHS >> V u<= RHS for any V
9836 if (match(LHS, m_LShr(m_Specific(RHS), m_Value())))
9837 return true;
9838
9839 // RHS u/ C_ugt_1 u<= RHS
9840 const APInt *C;
9841 if (match(LHS, m_UDiv(m_Specific(RHS), m_APInt(C))) && C->ugt(1))
9842 return true;
9843
9844 // RHS & V u<= RHS for any V
9846 return true;
9847
9848 // umin(RHS, V) u<= RHS for any V
9850 return true;
9851
9852 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
9853 const Value *X;
9854 const APInt *CLHS, *CRHS;
9855 if (match(LHS, m_NUWAddLike(m_Value(X), m_APInt(CLHS))) &&
9857 return CLHS->ule(*CRHS);
9858
9859 return false;
9860 }
9861 }
9862}
9863
9864/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
9865/// ALHS ARHS" is true. Otherwise, return std::nullopt.
9866static std::optional<bool>
9868 const Value *ARHS, const Value *BLHS, const Value *BRHS) {
9869 switch (Pred) {
9870 default:
9871 return std::nullopt;
9872
9873 case CmpInst::ICMP_SLT:
9874 case CmpInst::ICMP_SLE:
9875 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS) &&
9877 return true;
9878 return std::nullopt;
9879
9880 case CmpInst::ICMP_SGT:
9881 case CmpInst::ICMP_SGE:
9882 if (isTruePredicate(CmpInst::ICMP_SLE, ALHS, BLHS) &&
9884 return true;
9885 return std::nullopt;
9886
9887 case CmpInst::ICMP_ULT:
9888 case CmpInst::ICMP_ULE:
9889 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS) &&
9891 return true;
9892 return std::nullopt;
9893
9894 case CmpInst::ICMP_UGT:
9895 case CmpInst::ICMP_UGE:
9896 if (isTruePredicate(CmpInst::ICMP_ULE, ALHS, BLHS) &&
9898 return true;
9899 return std::nullopt;
9900 }
9901}
9902
9903/// Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
9904/// Return false if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is false.
9905/// Otherwise, return std::nullopt if we can't infer anything.
9906static std::optional<bool>
9908 CmpPredicate RPred, const ConstantRange &RCR) {
9909 auto CRImpliesPred = [&](ConstantRange CR,
9910 CmpInst::Predicate Pred) -> std::optional<bool> {
9911 // If all true values for lhs and true for rhs, lhs implies rhs
9912 if (CR.icmp(Pred, RCR))
9913 return true;
9914
9915 // If there is no overlap, lhs implies not rhs
9916 if (CR.icmp(CmpInst::getInversePredicate(Pred), RCR))
9917 return false;
9918
9919 return std::nullopt;
9920 };
9921 if (auto Res = CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9922 RPred))
9923 return Res;
9924 if (LPred.hasSameSign() ^ RPred.hasSameSign()) {
9926 : LPred.dropSameSign();
9928 : RPred.dropSameSign();
9929 return CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9930 RPred);
9931 }
9932 return std::nullopt;
9933}
9934
9935/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
9936/// is true. Return false if LHS implies RHS is false. Otherwise, return
9937/// std::nullopt if we can't infer anything.
9938static std::optional<bool>
9939isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1,
9940 CmpPredicate RPred, const Value *R0, const Value *R1,
9941 const DataLayout &DL, bool LHSIsTrue) {
9942 // The rest of the logic assumes the LHS condition is true. If that's not the
9943 // case, invert the predicate to make it so.
9944 if (!LHSIsTrue)
9945 LPred = ICmpInst::getInverseCmpPredicate(LPred);
9946
9947 // We can have non-canonical operands, so try to normalize any common operand
9948 // to L0/R0.
9949 if (L0 == R1) {
9950 std::swap(R0, R1);
9951 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9952 }
9953 if (R0 == L1) {
9954 std::swap(L0, L1);
9955 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9956 }
9957 if (L1 == R1) {
9958 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
9959 if (L0 != R0 || match(L0, m_ImmConstant())) {
9960 std::swap(L0, L1);
9961 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9962 std::swap(R0, R1);
9963 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9964 }
9965 }
9966
9967 // See if we can infer anything if operand-0 matches and we have at least one
9968 // constant.
9969 const APInt *Unused;
9970 if (L0 == R0 && (match(L1, m_APInt(Unused)) || match(R1, m_APInt(Unused)))) {
9971 // Potential TODO: We could also further use the constant range of L0/R0 to
9972 // further constraint the constant ranges. At the moment this leads to
9973 // several regressions related to not transforming `multi_use(A + C0) eq/ne
9974 // C1` (see discussion: D58633).
9975 SimplifyQuery SQ(DL);
9980
9981 // Even if L1/R1 are not both constant, we can still sometimes deduce
9982 // relationship from a single constant. For example X u> Y implies X != 0.
9983 if (auto R = isImpliedCondCommonOperandWithCR(LPred, LCR, RPred, RCR))
9984 return R;
9985 // If both L1/R1 were exact constant ranges and we didn't get anything
9986 // here, we won't be able to deduce this.
9987 if (match(L1, m_APInt(Unused)) && match(R1, m_APInt(Unused)))
9988 return std::nullopt;
9989 }
9990
9991 // Can we infer anything when the two compares have matching operands?
9992 if (L0 == R0 && L1 == R1)
9993 return ICmpInst::isImpliedByMatchingCmp(LPred, RPred);
9994
9995 // It only really makes sense in the context of signed comparison for "X - Y
9996 // must be positive if X >= Y and no overflow".
9997 // Take SGT as an example: L0:x > L1:y and C >= 0
9998 // ==> R0:(x -nsw y) < R1:(-C) is false
9999 CmpInst::Predicate SignedLPred = LPred.getPreferredSignedPredicate();
10000 if ((SignedLPred == ICmpInst::ICMP_SGT ||
10001 SignedLPred == ICmpInst::ICMP_SGE) &&
10002 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
10003 if (match(R1, m_NonPositive()) &&
10004 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == false)
10005 return false;
10006 }
10007
10008 // Take SLT as an example: L0:x < L1:y and C <= 0
10009 // ==> R0:(x -nsw y) < R1:(-C) is true
10010 if ((SignedLPred == ICmpInst::ICMP_SLT ||
10011 SignedLPred == ICmpInst::ICMP_SLE) &&
10012 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
10013 if (match(R1, m_NonNegative()) &&
10014 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == true)
10015 return true;
10016 }
10017
10018 // a - b == NonZero -> a != b
10019 // ptrtoint(a) - ptrtoint(b) == NonZero -> a != b
10020 const APInt *L1C;
10021 Value *A, *B;
10022 if (LPred == ICmpInst::ICMP_EQ && ICmpInst::isEquality(RPred) &&
10023 match(L1, m_APInt(L1C)) && !L1C->isZero() &&
10024 match(L0, m_Sub(m_Value(A), m_Value(B))) &&
10025 ((A == R0 && B == R1) || (A == R1 && B == R0) ||
10030 return RPred.dropSameSign() == ICmpInst::ICMP_NE;
10031 }
10032
10033 // L0 = R0 = L1 + R1, L0 >=u L1 implies R0 >=u R1, L0 <u L1 implies R0 <u R1
10034 if (L0 == R0 &&
10035 (LPred == ICmpInst::ICMP_ULT || LPred == ICmpInst::ICMP_UGE) &&
10036 (RPred == ICmpInst::ICMP_ULT || RPred == ICmpInst::ICMP_UGE) &&
10037 match(L0, m_c_Add(m_Specific(L1), m_Specific(R1))))
10038 return CmpPredicate::getMatching(LPred, RPred).has_value();
10039
10040 if (auto P = CmpPredicate::getMatching(LPred, RPred))
10041 return isImpliedCondOperands(*P, L0, L1, R0, R1);
10042
10043 // L0 u< C sets limits to L0's bits which may imply (L0 & Mask) pred RC
10044 // Example: L0 u< 13 => (L0 & 16) == 0
10045 const APInt *LC, *RC, *MaskC;
10046 if (match(L1, m_APInt(LC)) && match(R1, m_APInt(RC)) &&
10047 match(R0, m_And(m_Specific(L0), m_APInt(MaskC)))) {
10049 ConstantRange MaskedCRange = LCRange.binaryAnd(*MaskC);
10050 if (MaskedCRange.icmp(RPred, ConstantRange(*RC)))
10051 return true;
10052 if (MaskedCRange.icmp(ICmpInst::getInversePredicate(RPred),
10053 ConstantRange(*RC)))
10054 return false;
10055 }
10056
10057 return std::nullopt;
10058}
10059
10060/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
10061/// is true. Return false if LHS implies RHS is false. Otherwise, return
10062/// std::nullopt if we can't infer anything.
10063static std::optional<bool>
10065 FCmpInst::Predicate RPred, const Value *R0, const Value *R1,
10066 const DataLayout &DL, bool LHSIsTrue) {
10067 // The rest of the logic assumes the LHS condition is true. If that's not the
10068 // case, invert the predicate to make it so.
10069 if (!LHSIsTrue)
10070 LPred = FCmpInst::getInversePredicate(LPred);
10071
10072 // We can have non-canonical operands, so try to normalize any common operand
10073 // to L0/R0.
10074 if (L0 == R1) {
10075 std::swap(R0, R1);
10076 RPred = FCmpInst::getSwappedPredicate(RPred);
10077 }
10078 if (R0 == L1) {
10079 std::swap(L0, L1);
10080 LPred = FCmpInst::getSwappedPredicate(LPred);
10081 }
10082 if (L1 == R1) {
10083 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
10084 if (L0 != R0 || match(L0, m_ImmConstant())) {
10085 std::swap(L0, L1);
10086 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10087 std::swap(R0, R1);
10088 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10089 }
10090 }
10091
10092 // Can we infer anything when the two compares have matching operands?
10093 if (L0 == R0 && L1 == R1) {
10094 if ((LPred & RPred) == LPred)
10095 return true;
10096 if ((LPred & ~RPred) == LPred)
10097 return false;
10098 }
10099
10100 // See if we can infer anything if operand-0 matches and we have at least one
10101 // constant.
10102 const APFloat *L1C, *R1C;
10103 if (L0 == R0 && match(L1, m_APFloat(L1C)) && match(R1, m_APFloat(R1C))) {
10104 if (std::optional<ConstantFPRange> DomCR =
10106 if (std::optional<ConstantFPRange> ImpliedCR =
10108 if (ImpliedCR->contains(*DomCR))
10109 return true;
10110 }
10111 if (std::optional<ConstantFPRange> ImpliedCR =
10113 FCmpInst::getInversePredicate(RPred), *R1C)) {
10114 if (ImpliedCR->contains(*DomCR))
10115 return false;
10116 }
10117 }
10118 }
10119
10120 return std::nullopt;
10121}
10122
10123/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
10124/// false. Otherwise, return std::nullopt if we can't infer anything. We
10125/// expect the RHS to be an icmp and the LHS to be an 'and', 'or', or a 'select'
10126/// instruction.
10127static std::optional<bool>
10129 const Value *RHSOp0, const Value *RHSOp1,
10130 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10131 // The LHS must be an 'or', 'and', or a 'select' instruction.
10132 assert((LHS->getOpcode() == Instruction::And ||
10133 LHS->getOpcode() == Instruction::Or ||
10134 LHS->getOpcode() == Instruction::Select) &&
10135 "Expected LHS to be 'and', 'or', or 'select'.");
10136
10137 assert(Depth <= MaxAnalysisRecursionDepth && "Hit recursion limit");
10138
10139 // If the result of an 'or' is false, then we know both legs of the 'or' are
10140 // false. Similarly, if the result of an 'and' is true, then we know both
10141 // legs of the 'and' are true.
10142 const Value *ALHS, *ARHS;
10143 if ((!LHSIsTrue && match(LHS, m_LogicalOr(m_Value(ALHS), m_Value(ARHS)))) ||
10144 (LHSIsTrue && match(LHS, m_LogicalAnd(m_Value(ALHS), m_Value(ARHS))))) {
10145 // FIXME: Make this non-recursion.
10146 if (std::optional<bool> Implication = isImpliedCondition(
10147 ALHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10148 return Implication;
10149 if (std::optional<bool> Implication = isImpliedCondition(
10150 ARHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10151 return Implication;
10152 return std::nullopt;
10153 }
10154 return std::nullopt;
10155}
10156
10157std::optional<bool>
10159 const Value *RHSOp0, const Value *RHSOp1,
10160 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10161 // Bail out when we hit the limit.
10163 return std::nullopt;
10164
10165 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
10166 // example.
10167 if (RHSOp0->getType()->isVectorTy() != LHS->getType()->isVectorTy())
10168 return std::nullopt;
10169
10170 assert(LHS->getType()->isIntOrIntVectorTy(1) &&
10171 "Expected integer type only!");
10172
10173 // Match not
10174 if (match(LHS, m_Not(m_Value(LHS))))
10175 LHSIsTrue = !LHSIsTrue;
10176
10177 // Both LHS and RHS are icmps.
10178 if (RHSOp0->getType()->getScalarType()->isIntOrPtrTy()) {
10179 CmpPredicate LHSPred;
10180 Value *LHSOp0, *LHSOp1;
10181 if (match(LHS, m_ICmpLike(LHSPred, m_Value(LHSOp0), m_Value(LHSOp1))))
10182 return isImpliedCondICmps(LHSPred, LHSOp0, LHSOp1, RHSPred, RHSOp0,
10183 RHSOp1, DL, LHSIsTrue);
10184 } else {
10185 assert(RHSOp0->getType()->isFPOrFPVectorTy() &&
10186 "Expected floating point type only!");
10187 if (const auto *LHSCmp = dyn_cast<FCmpInst>(LHS))
10188 return isImpliedCondFCmps(LHSCmp->getPredicate(), LHSCmp->getOperand(0),
10189 LHSCmp->getOperand(1), RHSPred, RHSOp0, RHSOp1,
10190 DL, LHSIsTrue);
10191 }
10192
10193 /// The LHS should be an 'or', 'and', or a 'select' instruction. We expect
10194 /// the RHS to be an icmp.
10195 /// FIXME: Add support for and/or/select on the RHS.
10196 if (const Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
10197 if ((LHSI->getOpcode() == Instruction::And ||
10198 LHSI->getOpcode() == Instruction::Or ||
10199 LHSI->getOpcode() == Instruction::Select))
10200 return isImpliedCondAndOr(LHSI, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue,
10201 Depth);
10202 }
10203 return std::nullopt;
10204}
10205
10206std::optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
10207 const DataLayout &DL,
10208 bool LHSIsTrue, unsigned Depth) {
10209 // LHS ==> RHS by definition
10210 if (LHS == RHS)
10211 return LHSIsTrue;
10212
10213 // Match not
10214 bool InvertRHS = false;
10215 if (match(RHS, m_Not(m_Value(RHS)))) {
10216 if (LHS == RHS)
10217 return !LHSIsTrue;
10218 InvertRHS = true;
10219 }
10220
10221 CmpPredicate RHSPred;
10222 Value *RHSOp0, *RHSOp1;
10223 if (match(RHS, m_ICmpLike(RHSPred, m_Value(RHSOp0), m_Value(RHSOp1)))) {
10224 if (auto Implied = isImpliedCondition(LHS, RHSPred, RHSOp0, RHSOp1, DL,
10225 LHSIsTrue, Depth))
10226 return InvertRHS ? !*Implied : *Implied;
10227 return std::nullopt;
10228 }
10229 if (const FCmpInst *RHSCmp = dyn_cast<FCmpInst>(RHS)) {
10230 if (auto Implied = isImpliedCondition(
10231 LHS, RHSCmp->getPredicate(), RHSCmp->getOperand(0),
10232 RHSCmp->getOperand(1), DL, LHSIsTrue, Depth))
10233 return InvertRHS ? !*Implied : *Implied;
10234 return std::nullopt;
10235 }
10236
10238 return std::nullopt;
10239
10240 // LHS ==> (RHS1 || RHS2) if LHS ==> RHS1 or LHS ==> RHS2
10241 // LHS ==> !(RHS1 && RHS2) if LHS ==> !RHS1 or LHS ==> !RHS2
10242 const Value *RHS1, *RHS2;
10243 if (match(RHS, m_LogicalOr(m_Value(RHS1), m_Value(RHS2)))) {
10244 if (std::optional<bool> Imp =
10245 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10246 if (*Imp == true)
10247 return !InvertRHS;
10248 if (std::optional<bool> Imp =
10249 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10250 if (*Imp == true)
10251 return !InvertRHS;
10252 }
10253 if (match(RHS, m_LogicalAnd(m_Value(RHS1), m_Value(RHS2)))) {
10254 if (std::optional<bool> Imp =
10255 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10256 if (*Imp == false)
10257 return InvertRHS;
10258 if (std::optional<bool> Imp =
10259 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10260 if (*Imp == false)
10261 return InvertRHS;
10262 }
10263
10264 return std::nullopt;
10265}
10266
10267// Returns a pair (Condition, ConditionIsTrue), where Condition is a branch
10268// condition dominating ContextI or nullptr, if no condition is found.
10269static std::pair<Value *, bool>
10271 if (!ContextI || !ContextI->getParent())
10272 return {nullptr, false};
10273
10274 // TODO: This is a poor/cheap way to determine dominance. Should we use a
10275 // dominator tree (eg, from a SimplifyQuery) instead?
10276 const BasicBlock *ContextBB = ContextI->getParent();
10277 const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
10278 if (!PredBB)
10279 return {nullptr, false};
10280
10281 // We need a conditional branch in the predecessor.
10282 Value *PredCond;
10283 BasicBlock *TrueBB, *FalseBB;
10284 if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
10285 return {nullptr, false};
10286
10287 // The branch should get simplified. Don't bother simplifying this condition.
10288 if (TrueBB == FalseBB)
10289 return {nullptr, false};
10290
10291 assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
10292 "Predecessor block does not point to successor?");
10293
10294 // Is this condition implied by the predecessor condition?
10295 return {PredCond, TrueBB == ContextBB};
10296}
10297
10298std::optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
10299 const Instruction *ContextI,
10300 const DataLayout &DL) {
10301 assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
10302 auto PredCond = getDomPredecessorCondition(ContextI);
10303 if (PredCond.first)
10304 return isImpliedCondition(PredCond.first, Cond, DL, PredCond.second);
10305 return std::nullopt;
10306}
10307
10309 const Value *LHS,
10310 const Value *RHS,
10311 const Instruction *ContextI,
10312 const DataLayout &DL) {
10313 auto PredCond = getDomPredecessorCondition(ContextI);
10314 if (PredCond.first)
10315 return isImpliedCondition(PredCond.first, Pred, LHS, RHS, DL,
10316 PredCond.second);
10317 return std::nullopt;
10318}
10319
10321 APInt &Upper, const InstrInfoQuery &IIQ,
10322 bool PreferSignedRange) {
10323 unsigned Width = Lower.getBitWidth();
10324 const APInt *C;
10325 switch (BO.getOpcode()) {
10326 case Instruction::Sub:
10327 if (match(BO.getOperand(0), m_APInt(C))) {
10328 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10329 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10330
10331 // If the caller expects a signed compare, then try to use a signed range.
10332 // Otherwise if both no-wraps are set, use the unsigned range because it
10333 // is never larger than the signed range. Example:
10334 // "sub nuw nsw i8 -2, x" is unsigned [0, 254] vs. signed [-128, 126].
10335 // "sub nuw nsw i8 2, x" is unsigned [0, 2] vs. signed [-125, 127].
10336 if (PreferSignedRange && HasNSW && HasNUW)
10337 HasNUW = false;
10338
10339 if (HasNUW) {
10340 // 'sub nuw c, x' produces [0, C].
10341 Upper = *C + 1;
10342 } else if (HasNSW) {
10343 if (C->isNegative()) {
10344 // 'sub nsw -C, x' produces [SINT_MIN, -C - SINT_MIN].
10346 Upper = *C - APInt::getSignedMaxValue(Width);
10347 } else {
10348 // Note that sub 0, INT_MIN is not NSW. It techically is a signed wrap
10349 // 'sub nsw C, x' produces [C - SINT_MAX, SINT_MAX].
10350 Lower = *C - APInt::getSignedMaxValue(Width);
10352 }
10353 }
10354 }
10355 break;
10356 case Instruction::Add:
10357 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10358 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10359 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10360
10361 // If the caller expects a signed compare, then try to use a signed
10362 // range. Otherwise if both no-wraps are set, use the unsigned range
10363 // because it is never larger than the signed range. Example: "add nuw
10364 // nsw i8 X, -2" is unsigned [254,255] vs. signed [-128, 125].
10365 if (PreferSignedRange && HasNSW && HasNUW)
10366 HasNUW = false;
10367
10368 if (HasNUW) {
10369 // 'add nuw x, C' produces [C, UINT_MAX].
10370 Lower = *C;
10371 } else if (HasNSW) {
10372 if (C->isNegative()) {
10373 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
10375 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
10376 } else {
10377 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
10378 Lower = APInt::getSignedMinValue(Width) + *C;
10379 Upper = APInt::getSignedMaxValue(Width) + 1;
10380 }
10381 }
10382 }
10383 break;
10384
10385 case Instruction::And:
10386 if (match(BO.getOperand(1), m_APInt(C)))
10387 // 'and x, C' produces [0, C].
10388 Upper = *C + 1;
10389 // X & -X is a power of two or zero. So we can cap the value at max power of
10390 // two.
10391 if (match(BO.getOperand(0), m_Neg(m_Specific(BO.getOperand(1)))) ||
10392 match(BO.getOperand(1), m_Neg(m_Specific(BO.getOperand(0)))))
10393 Upper = APInt::getSignedMinValue(Width) + 1;
10394 break;
10395
10396 case Instruction::Or:
10397 if (match(BO.getOperand(1), m_APInt(C)))
10398 // 'or x, C' produces [C, UINT_MAX].
10399 Lower = *C;
10400 break;
10401
10402 case Instruction::AShr:
10403 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10404 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
10406 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
10407 } else if (match(BO.getOperand(0), m_APInt(C))) {
10408 unsigned ShiftAmount = Width - 1;
10409 if (!C->isZero() && IIQ.isExact(&BO))
10410 ShiftAmount = C->countr_zero();
10411 if (C->isNegative()) {
10412 // 'ashr C, x' produces [C, C >> (Width-1)]
10413 Lower = *C;
10414 Upper = C->ashr(ShiftAmount) + 1;
10415 } else {
10416 // 'ashr C, x' produces [C >> (Width-1), C]
10417 Lower = C->ashr(ShiftAmount);
10418 Upper = *C + 1;
10419 }
10420 }
10421 break;
10422
10423 case Instruction::LShr:
10424 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10425 // 'lshr x, C' produces [0, UINT_MAX >> C].
10426 Upper = APInt::getAllOnes(Width).lshr(*C) + 1;
10427 } else if (match(BO.getOperand(0), m_APInt(C))) {
10428 // 'lshr C, x' produces [C >> (Width-1), C].
10429 unsigned ShiftAmount = Width - 1;
10430 if (!C->isZero() && IIQ.isExact(&BO))
10431 ShiftAmount = C->countr_zero();
10432 Lower = C->lshr(ShiftAmount);
10433 Upper = *C + 1;
10434 }
10435 break;
10436
10437 case Instruction::Shl:
10438 if (match(BO.getOperand(0), m_APInt(C))) {
10439 if (IIQ.hasNoUnsignedWrap(&BO)) {
10440 // 'shl nuw C, x' produces [C, C << CLZ(C)]
10441 Lower = *C;
10442 Upper = Lower.shl(Lower.countl_zero()) + 1;
10443 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
10444 if (C->isNegative()) {
10445 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
10446 unsigned ShiftAmount = C->countl_one() - 1;
10447 Lower = C->shl(ShiftAmount);
10448 Upper = *C + 1;
10449 } else {
10450 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
10451 unsigned ShiftAmount = C->countl_zero() - 1;
10452 Lower = *C;
10453 Upper = C->shl(ShiftAmount) + 1;
10454 }
10455 } else {
10456 // If lowbit is set, value can never be zero.
10457 if ((*C)[0])
10458 Lower = APInt::getOneBitSet(Width, 0);
10459 // If we are shifting a constant the largest it can be is if the longest
10460 // sequence of consecutive ones is shifted to the highbits (breaking
10461 // ties for which sequence is higher). At the moment we take a liberal
10462 // upper bound on this by just popcounting the constant.
10463 // TODO: There may be a bitwise trick for it longest/highest
10464 // consecutative sequence of ones (naive method is O(Width) loop).
10465 Upper = APInt::getHighBitsSet(Width, C->popcount()) + 1;
10466 }
10467 } else if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10468 Upper = APInt::getBitsSetFrom(Width, C->getZExtValue()) + 1;
10469 }
10470 break;
10471
10472 case Instruction::SDiv:
10473 if (match(BO.getOperand(1), m_APInt(C))) {
10474 APInt IntMin = APInt::getSignedMinValue(Width);
10475 APInt IntMax = APInt::getSignedMaxValue(Width);
10476 if (C->isAllOnes()) {
10477 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
10478 // where C != -1 and C != 0 and C != 1
10479 Lower = IntMin + 1;
10480 Upper = IntMax + 1;
10481 } else if (C->countl_zero() < Width - 1) {
10482 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
10483 // where C != -1 and C != 0 and C != 1
10484 Lower = IntMin.sdiv(*C);
10485 Upper = IntMax.sdiv(*C);
10486 if (Lower.sgt(Upper))
10488 Upper = Upper + 1;
10489 assert(Upper != Lower && "Upper part of range has wrapped!");
10490 }
10491 } else if (match(BO.getOperand(0), m_APInt(C))) {
10492 if (C->isMinSignedValue()) {
10493 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
10494 Lower = *C;
10495 Upper = Lower.lshr(1) + 1;
10496 } else {
10497 // 'sdiv C, x' produces [-|C|, |C|].
10498 Upper = C->abs() + 1;
10499 Lower = (-Upper) + 1;
10500 }
10501 }
10502 break;
10503
10504 case Instruction::UDiv:
10505 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10506 // 'udiv x, C' produces [0, UINT_MAX / C].
10507 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
10508 } else if (match(BO.getOperand(0), m_APInt(C))) {
10509 // 'udiv C, x' produces [0, C].
10510 Upper = *C + 1;
10511 }
10512 break;
10513
10514 case Instruction::SRem:
10515 if (match(BO.getOperand(1), m_APInt(C))) {
10516 // 'srem x, C' produces (-|C|, |C|).
10517 Upper = C->abs();
10518 Lower = (-Upper) + 1;
10519 } else if (match(BO.getOperand(0), m_APInt(C))) {
10520 if (C->isNegative()) {
10521 // 'srem -|C|, x' produces [-|C|, 0].
10522 Upper = 1;
10523 Lower = *C;
10524 } else {
10525 // 'srem |C|, x' produces [0, |C|].
10526 Upper = *C + 1;
10527 }
10528 }
10529 break;
10530
10531 case Instruction::URem:
10532 if (match(BO.getOperand(1), m_APInt(C)))
10533 // 'urem x, C' produces [0, C).
10534 Upper = *C;
10535 else if (match(BO.getOperand(0), m_APInt(C)))
10536 // 'urem C, x' produces [0, C].
10537 Upper = *C + 1;
10538 break;
10539
10540 default:
10541 break;
10542 }
10543}
10544
10546 bool UseInstrInfo) {
10547 unsigned Width = II.getType()->getScalarSizeInBits();
10548 const APInt *C;
10549 switch (II.getIntrinsicID()) {
10550 case Intrinsic::ctlz:
10551 case Intrinsic::cttz: {
10552 APInt Upper(Width, Width);
10553 if (!UseInstrInfo || !match(II.getArgOperand(1), m_One()))
10554 Upper += 1;
10555 // Maximum of set/clear bits is the bit width.
10557 }
10558 case Intrinsic::ctpop:
10559 // Maximum of set/clear bits is the bit width.
10561 APInt(Width, Width) + 1);
10562 case Intrinsic::uadd_sat:
10563 // uadd.sat(x, C) produces [C, UINT_MAX].
10564 if (match(II.getOperand(0), m_APInt(C)) ||
10565 match(II.getOperand(1), m_APInt(C)))
10567 break;
10568 case Intrinsic::sadd_sat:
10569 if (match(II.getOperand(0), m_APInt(C)) ||
10570 match(II.getOperand(1), m_APInt(C))) {
10571 if (C->isNegative())
10572 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
10574 APInt::getSignedMaxValue(Width) + *C +
10575 1);
10576
10577 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
10579 APInt::getSignedMaxValue(Width) + 1);
10580 }
10581 break;
10582 case Intrinsic::usub_sat:
10583 // usub.sat(C, x) produces [0, C].
10584 if (match(II.getOperand(0), m_APInt(C)))
10585 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10586
10587 // usub.sat(x, C) produces [0, UINT_MAX - C].
10588 if (match(II.getOperand(1), m_APInt(C)))
10590 APInt::getMaxValue(Width) - *C + 1);
10591 break;
10592 case Intrinsic::ssub_sat:
10593 if (match(II.getOperand(0), m_APInt(C))) {
10594 if (C->isNegative())
10595 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
10597 *C - APInt::getSignedMinValue(Width) +
10598 1);
10599
10600 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
10602 APInt::getSignedMaxValue(Width) + 1);
10603 } else if (match(II.getOperand(1), m_APInt(C))) {
10604 if (C->isNegative())
10605 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
10607 APInt::getSignedMaxValue(Width) + 1);
10608
10609 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
10611 APInt::getSignedMaxValue(Width) - *C +
10612 1);
10613 }
10614 break;
10615 case Intrinsic::umin:
10616 case Intrinsic::umax:
10617 case Intrinsic::smin:
10618 case Intrinsic::smax:
10619 if (!match(II.getOperand(0), m_APInt(C)) &&
10620 !match(II.getOperand(1), m_APInt(C)))
10621 break;
10622
10623 switch (II.getIntrinsicID()) {
10624 case Intrinsic::umin:
10625 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10626 case Intrinsic::umax:
10628 case Intrinsic::smin:
10630 *C + 1);
10631 case Intrinsic::smax:
10633 APInt::getSignedMaxValue(Width) + 1);
10634 default:
10635 llvm_unreachable("Must be min/max intrinsic");
10636 }
10637 break;
10638 case Intrinsic::abs:
10639 // If abs of SIGNED_MIN is poison, then the result is [0..SIGNED_MAX],
10640 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10641 if (match(II.getOperand(1), m_One()))
10643 APInt::getSignedMaxValue(Width) + 1);
10644
10646 APInt::getSignedMinValue(Width) + 1);
10647 case Intrinsic::vscale:
10648 if (!II.getParent() || !II.getFunction())
10649 break;
10650 return getVScaleRange(II.getFunction(), Width);
10651 case Intrinsic::read_register:
10652 case Intrinsic::read_volatile_register: {
10653 const Module *M = II.getModule();
10654 if (!M || !M->getTargetTriple().isRISCV())
10655 break;
10656 if (II.getFunction() && isReadVLENB(II))
10657 return getRISCVVLENBRange(II, Width);
10658 break;
10659 }
10660 default:
10661 break;
10662 }
10663
10664 return ConstantRange::getFull(Width);
10665}
10666
10668 const InstrInfoQuery &IIQ) {
10669 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
10670 const Value *LHS = nullptr, *RHS = nullptr;
10672 if (R.Flavor == SPF_UNKNOWN)
10673 return ConstantRange::getFull(BitWidth);
10674
10675 if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
10676 // If the negation part of the abs (in RHS) has the NSW flag,
10677 // then the result of abs(X) is [0..SIGNED_MAX],
10678 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10679 if (match(RHS, m_Neg(m_Specific(LHS))) &&
10683
10686 }
10687
10688 if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
10689 // The result of -abs(X) is <= 0.
10691 APInt(BitWidth, 1));
10692 }
10693
10694 const APInt *C;
10695 if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
10696 return ConstantRange::getFull(BitWidth);
10697
10698 switch (R.Flavor) {
10699 case SPF_UMIN:
10701 case SPF_UMAX:
10703 case SPF_SMIN:
10705 *C + 1);
10706 case SPF_SMAX:
10709 default:
10710 return ConstantRange::getFull(BitWidth);
10711 }
10712}
10713
10715 // The maximum representable value of a half is 65504. For floats the maximum
10716 // value is 3.4e38 which requires roughly 129 bits.
10717 unsigned BitWidth = I->getType()->getScalarSizeInBits();
10718 if (!I->getOperand(0)->getType()->getScalarType()->isHalfTy())
10719 return;
10720 if (isa<FPToSIInst>(I) && BitWidth >= 17) {
10721 Lower = APInt(BitWidth, -65504, true);
10722 Upper = APInt(BitWidth, 65505);
10723 }
10724
10725 if (isa<FPToUIInst>(I) && BitWidth >= 16) {
10726 // For a fptoui the lower limit is left as 0.
10727 Upper = APInt(BitWidth, 65505);
10728 }
10729}
10730
10732 const SimplifyQuery &SQ,
10733 unsigned Depth) {
10734 assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
10735
10737 return ConstantRange::getFull(V->getType()->getScalarSizeInBits());
10738
10739 if (auto *C = dyn_cast<Constant>(V))
10740 return C->toConstantRange();
10741
10742 unsigned BitWidth = V->getType()->getScalarSizeInBits();
10743 ConstantRange CR = ConstantRange::getFull(BitWidth);
10744 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
10745 APInt Lower = APInt(BitWidth, 0);
10746 APInt Upper = APInt(BitWidth, 0);
10747 // TODO: Return ConstantRange.
10748 setLimitsForBinOp(*BO, Lower, Upper, SQ.IIQ, ForSigned);
10750 } else if (auto *II = dyn_cast<IntrinsicInst>(V))
10752 else if (auto *SI = dyn_cast<SelectInst>(V)) {
10753 ConstantRange CRTrue =
10754 computeConstantRange(SI->getTrueValue(), ForSigned, SQ, Depth + 1);
10755 ConstantRange CRFalse =
10756 computeConstantRange(SI->getFalseValue(), ForSigned, SQ, Depth + 1);
10757 CR = CRTrue.unionWith(CRFalse);
10759 } else if (auto *TI = dyn_cast<TruncInst>(V)) {
10760 ConstantRange SrcCR =
10761 computeConstantRange(TI->getOperand(0), ForSigned, SQ, Depth + 1);
10762 CR = SrcCR.truncate(BitWidth);
10763 } else if (isa<FPToUIInst>(V) || isa<FPToSIInst>(V)) {
10764 APInt Lower = APInt(BitWidth, 0);
10765 APInt Upper = APInt(BitWidth, 0);
10766 // TODO: Return ConstantRange.
10769 } else if (const auto *A = dyn_cast<Argument>(V))
10770 if (std::optional<ConstantRange> Range = A->getRange())
10771 CR = *Range;
10772
10773 if (auto *I = dyn_cast<Instruction>(V)) {
10774 if (auto *Range = SQ.IIQ.getMetadata(I, LLVMContext::MD_range))
10776
10777 Value *FrexpSrc;
10778 if (const auto *CB = dyn_cast<CallBase>(V)) {
10779 if (std::optional<ConstantRange> Range = CB->getRange())
10780 CR = CR.intersectWith(*Range);
10782 m_Value(FrexpSrc))))) {
10783 const fltSemantics &FltSem =
10784 FrexpSrc->getType()->getScalarType()->getFltSemantics();
10785 // It should be possible to implement this for any type, but this logic
10786 // only computes the range assuming standard subnormal handling.
10787 if (APFloat::isIEEELikeFP(FltSem)) {
10789 FrexpSrc, fcSubnormal | fcZero | fcNan | fcInf, SQ, Depth + 1);
10790
10791 // The exponent of frexp(NaN) and frexp(Inf) is unspecified. Only
10792 // constrain its range when the source can be neither.
10793 if (KnownSrc.isKnownNeverInfOrNaN()) {
10794 int MinExp = APFloat::semanticsMinExponent(FltSem) + 1;
10795
10796 // Offset to find the true minimum exponent value for a denormal.
10797 if (!KnownSrc.isKnownNeverSubnormal())
10798 MinExp -= (APFloat::semanticsPrecision(FltSem) - 1);
10799
10800 int MaxExp = APFloat::semanticsMaxExponent(FltSem) + 1;
10801
10802 auto [AdjustedMin, AdjustedMax, AdjustedMaxNonZero] =
10804
10805 DenormalMode Mode = I->getFunction()->getDenormalMode(FltSem);
10806 bool NeverLogicalZero = KnownSrc.isKnownNeverLogicalZero(Mode);
10807
10808 MinExp = std::max(AdjustedMin, MinExp);
10809 MaxExp = std::min(NeverLogicalZero ? AdjustedMaxNonZero : AdjustedMax,
10810 MaxExp);
10811
10813 APInt(BitWidth, static_cast<int64_t>(MinExp), /*isSigned=*/true),
10814 APInt(BitWidth, static_cast<int64_t>(MaxExp) + 1,
10815 /*isSigned=*/true));
10816 }
10817 }
10818 }
10819 }
10820
10821 if (SQ.CxtI && SQ.AC) {
10822 // Try to restrict the range based on information from assumptions.
10823 for (auto &AssumeVH : SQ.AC->assumptionsFor(V)) {
10824 if (!AssumeVH)
10825 continue;
10826 CallInst *I = cast<CallInst>(AssumeVH);
10827 assert(I->getParent()->getParent() == SQ.CxtI->getParent()->getParent() &&
10828 "Got assumption for the wrong function!");
10829 assert(I->getIntrinsicID() == Intrinsic::assume &&
10830 "must be an assume intrinsic");
10831
10832 if (!isValidAssumeForContext(I, SQ))
10833 continue;
10834 Value *Arg = I->getArgOperand(0);
10835 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
10836 // Currently we just use information from comparisons.
10837 if (!Cmp || Cmp->getOperand(0) != V)
10838 continue;
10839 // TODO: Set "ForSigned" parameter via Cmp->isSigned()?
10840 ConstantRange RHS =
10841 computeConstantRange(Cmp->getOperand(1), /*ForSigned=*/false,
10842 SQ.getWithInstruction(I), Depth + 1);
10843 CR = CR.intersectWith(
10844 ConstantRange::makeAllowedICmpRegion(Cmp->getCmpPredicate(), RHS));
10845 }
10846 }
10847
10848 return CR;
10849}
10850
10851static void
10853 function_ref<void(Value *)> InsertAffected) {
10854 assert(V != nullptr);
10855 if (isa<Argument>(V) || isa<GlobalValue>(V)) {
10856 InsertAffected(V);
10857 } else if (auto *I = dyn_cast<Instruction>(V)) {
10858 InsertAffected(V);
10859
10860 // Peek through unary operators to find the source of the condition.
10861 Value *Op;
10863 m_Trunc(m_Value(Op))))) {
10865 InsertAffected(Op);
10866 }
10867 }
10868}
10869
10871 Value *Cond, bool IsAssume, function_ref<void(Value *)> InsertAffected) {
10872 auto AddAffected = [&InsertAffected](Value *V) {
10873 addValueAffectedByCondition(V, InsertAffected);
10874 };
10875
10876 auto AddCmpOperands = [&AddAffected, IsAssume](Value *LHS, Value *RHS) {
10877 if (IsAssume) {
10878 AddAffected(LHS);
10879 AddAffected(RHS);
10880 } else if (match(RHS, m_Constant()))
10881 AddAffected(LHS);
10882 };
10883
10884 SmallVector<Value *, 8> Worklist;
10886 Worklist.push_back(Cond);
10887 while (!Worklist.empty()) {
10888 Value *V = Worklist.pop_back_val();
10889 if (!Visited.insert(V).second)
10890 continue;
10891
10892 CmpPredicate Pred;
10893 Value *A, *B, *X;
10894
10895 if (IsAssume) {
10896 AddAffected(V);
10897 if (match(V, m_Not(m_Value(X))))
10898 AddAffected(X);
10899 }
10900
10901 if (match(V, m_LogicalOp(m_Value(A), m_Value(B)))) {
10902 // assume(A && B) is split to -> assume(A); assume(B);
10903 // assume(!(A || B)) is split to -> assume(!A); assume(!B);
10904 // Finally, assume(A || B) / assume(!(A && B)) generally don't provide
10905 // enough information to be worth handling (intersection of information as
10906 // opposed to union).
10907 if (!IsAssume) {
10908 Worklist.push_back(A);
10909 Worklist.push_back(B);
10910 }
10911 } else if (match(V, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
10912 bool HasRHSC = match(B, m_ConstantInt());
10913 if (ICmpInst::isEquality(Pred)) {
10914 AddAffected(A);
10915 if (IsAssume)
10916 AddAffected(B);
10917 if (HasRHSC) {
10918 Value *Y;
10919 // (X << C) or (X >>_s C) or (X >>_u C).
10920 if (match(A, m_Shift(m_Value(X), m_ConstantInt())))
10921 AddAffected(X);
10922 // (X & C) or (X | C).
10923 else if (match(A, m_And(m_Value(X), m_Value(Y))) ||
10924 match(A, m_Or(m_Value(X), m_Value(Y)))) {
10925 AddAffected(X);
10926 AddAffected(Y);
10927 }
10928 // X - Y
10929 else if (match(A, m_Sub(m_Value(X), m_Value(Y)))) {
10930 AddAffected(X);
10931 AddAffected(Y);
10932 }
10933 }
10934 } else {
10935 AddCmpOperands(A, B);
10936 if (HasRHSC) {
10937 // Handle (A + C1) u< C2, which is the canonical form of
10938 // A > C3 && A < C4.
10940 AddAffected(X);
10941
10942 if (ICmpInst::isUnsigned(Pred)) {
10943 Value *Y;
10944 // X & Y u> C -> X >u C && Y >u C
10945 // X | Y u< C -> X u< C && Y u< C
10946 // X nuw+ Y u< C -> X u< C && Y u< C
10947 if (match(A, m_And(m_Value(X), m_Value(Y))) ||
10948 match(A, m_Or(m_Value(X), m_Value(Y))) ||
10949 match(A, m_NUWAdd(m_Value(X), m_Value(Y)))) {
10950 AddAffected(X);
10951 AddAffected(Y);
10952 }
10953 // X nuw- Y u> C -> X u> C
10954 if (match(A, m_NUWSub(m_Value(X), m_Value())))
10955 AddAffected(X);
10956 }
10957 }
10958
10959 // Handle icmp slt/sgt (bitcast X to int), 0/-1, which is supported
10960 // by computeKnownFPClass().
10962 if (Pred == ICmpInst::ICMP_SLT && match(B, m_Zero()))
10963 InsertAffected(X);
10964 else if (Pred == ICmpInst::ICMP_SGT && match(B, m_AllOnes()))
10965 InsertAffected(X);
10966 }
10967 }
10968
10969 auto AddNuwSquareOperand = [&AddAffected](Value *Op) {
10970 Value *SquareOp = nullptr;
10971 if (match(Op, m_NUWMul(m_Value(SquareOp), m_Deferred(SquareOp))))
10972 AddAffected(SquareOp);
10973 };
10974 AddNuwSquareOperand(A);
10975 AddNuwSquareOperand(B);
10976
10977 if (HasRHSC && match(A, m_Ctpop(m_Value(X))))
10978 AddAffected(X);
10979 } else if (match(V, m_FCmp(Pred, m_Value(A), m_Value(B)))) {
10980 AddCmpOperands(A, B);
10981
10982 // fcmp fneg(x), y
10983 // fcmp fabs(x), y
10984 // fcmp fneg(fabs(x)), y
10985 if (match(A, m_FNeg(m_Value(A))))
10986 AddAffected(A);
10987 if (match(A, m_FAbs(m_Value(A))))
10988 AddAffected(A);
10989
10991 m_Value()))) {
10992 // Handle patterns that computeKnownFPClass() support.
10993 AddAffected(A);
10994 } else if (!IsAssume && match(V, m_Trunc(m_Value(X)))) {
10995 // Assume is checked here as X is already added above for assumes in
10996 // addValueAffectedByCondition
10997 AddAffected(X);
10998 } else if (!IsAssume && match(V, m_Not(m_Value(X)))) {
10999 // Assume is checked here to avoid issues with ephemeral values
11000 Worklist.push_back(X);
11001 }
11002 }
11003}
11004
11006 // (X >> C) or/add (X & mask(C) != 0)
11007 if (const auto *BO = dyn_cast<BinaryOperator>(V)) {
11008 if (BO->getOpcode() == Instruction::Add ||
11009 BO->getOpcode() == Instruction::Or) {
11010 const Value *X;
11011 const APInt *C1, *C2;
11012 if (match(BO, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C1)),
11016 m_Zero())))) &&
11017 C2->popcount() == C1->getZExtValue())
11018 return X;
11019 }
11020 }
11021 return nullptr;
11022}
11023
11025 return const_cast<Value *>(stripNullTest(const_cast<const Value *>(V)));
11026}
11027
11030 unsigned MaxCount, bool AllowUndefOrPoison) {
11033 auto Push = [&](const Value *V) -> bool {
11034 Constant *C;
11035 if (match(const_cast<Value *>(V), m_ImmConstant(C))) {
11036 if (!AllowUndefOrPoison && !isGuaranteedNotToBeUndefOrPoison(C))
11037 return false;
11038 // Check existence first to avoid unnecessary allocations.
11039 if (Constants.contains(C))
11040 return true;
11041 if (Constants.size() == MaxCount)
11042 return false;
11043 Constants.insert(C);
11044 return true;
11045 }
11046
11047 if (auto *Inst = dyn_cast<Instruction>(V)) {
11048 if (Visited.insert(Inst).second)
11049 Worklist.push_back(Inst);
11050 return true;
11051 }
11052 return false;
11053 };
11054 if (!Push(V))
11055 return false;
11056 while (!Worklist.empty()) {
11057 const Instruction *CurInst = Worklist.pop_back_val();
11058 switch (CurInst->getOpcode()) {
11059 case Instruction::Select:
11060 if (!Push(CurInst->getOperand(1)))
11061 return false;
11062 if (!Push(CurInst->getOperand(2)))
11063 return false;
11064 break;
11065 case Instruction::PHI:
11066 for (Value *IncomingValue : cast<PHINode>(CurInst)->incoming_values()) {
11067 // Fast path for recurrence PHI.
11068 if (IncomingValue == CurInst)
11069 continue;
11070 if (!Push(IncomingValue))
11071 return false;
11072 }
11073 break;
11074 default:
11075 return false;
11076 }
11077 }
11078 return true;
11079}
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:362
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:337
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
Definition APFloat.cpp:358
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:333
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:329
static LLVM_ABI bool semanticsHasNaN(const fltSemantics &)
Definition APFloat.cpp:366
static LLVM_ABI bool semanticsHasZero(const fltSemantics &)
Definition APFloat.cpp:354
static LLVM_ABI bool isRepresentableAsNormalIn(const fltSemantics &Src, const fltSemantics &Dst)
Definition APFloat.cpp:379
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:370
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:6153
LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.h:1639
bool isFinite() const
Definition APFloat.h:1588
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1242
bool isInteger() const
Definition APFloat.h:1600
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2009
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:231
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1427
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:420
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1561
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition APInt.h:1412
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1691
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:203
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1351
unsigned ceilLogBase2() const
Definition APInt.h:1785
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1206
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:368
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1187
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:377
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1509
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1116
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:206
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:213
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:326
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
Definition APInt.h:1254
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1673
LLVM_ABI APInt reverseBits() const
Definition APInt.cpp:786
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1171
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition APInt.h:1649
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1619
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:216
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1086
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:353
unsigned logBase2() const
Definition APInt.h:1782
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:830
bool getBoolValue() const
Convert APInt to a boolean value.
Definition APInt.h:468
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:402
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:331
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1155
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:876
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1262
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1135
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:293
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:197
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Definition APInt.h:1409
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1242
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:283
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:236
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:854
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1226
an instruction to allocate memory on the stack
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
Class to represent array types.
This represents the llvm.assume intrinsic.
A cache of @llvm.assume calls within a function.
MutableArrayRef< ResultElem > assumptionsFor(const Value *V)
Access the list of assumptions which affect this value.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
LLVM_ABI std::optional< unsigned > getVScaleRangeMax() const
Returns the maximum value for the vscale_range attribute or std::nullopt when unknown.
LLVM_ABI unsigned getVScaleRangeMin() const
Returns the minimum value for the vscale_range attribute.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:266
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
unsigned arg_size() const
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
static LLVM_ABI Predicate getFlippedStrictnessPredicate(Predicate pred)
This is a static version that you can use without an instruction available.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
bool isSigned() const
Definition InstrTypes.h:993
static LLVM_ABI bool isEquality(Predicate pred)
Determine if this is an equals/not equals predicate.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
static bool isFPPredicate(Predicate P)
Definition InstrTypes.h:833
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
static LLVM_ABI bool isOrdered(Predicate predicate)
Determine if the predicate is an ordered operation.
bool isUnsigned() const
Definition InstrTypes.h:999
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
LLVM_ABI CmpInst::Predicate getPreferredSignedPredicate() const
Attempts to return a signed CmpInst::Predicate from the CmpPredicate.
CmpInst::Predicate dropSameSign() const
Drops samesign information.
bool hasSameSign() const
Query samesign information, for optimizations.
Conditional Branch instruction.
An array constant whose element type is a simple 1/2/4/8-byte integer, bytes or float/double,...
Definition Constants.h:865
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition Constants.h:755
StringRef getAsString() const
If this array is isString(), then this method returns the array as a StringRef.
Definition Constants.h:831
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition Constants.h:951
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI std::optional< ConstantFPRange > makeExactFCmpRegion(FCmpInst::Predicate Pred, const APFloat &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
This class represents a range of values.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
static LLVM_ABI ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
LLVM_ABI OverflowResult unsignedSubMayOverflow(const ConstantRange &Other) const
Return whether unsigned sub of the two ranges always/never overflows.
LLVM_ABI bool isAllNegative() const
Return true if all values in this range are negative.
LLVM_ABI OverflowResult unsignedAddMayOverflow(const ConstantRange &Other) const
Return whether unsigned add of the two ranges always/never overflows.
LLVM_ABI KnownBits toKnownBits() const
Return known bits for values in this range.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
LLVM_ABI APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI OverflowResult unsignedMulMayOverflow(const ConstantRange &Other) const
Return whether unsigned mul of the two ranges always/never overflows.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI bool isAllNonNegative() const
Return true if all values in this range are non-negative.
static LLVM_ABI ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
LLVM_ABI ConstantRange multiply(const ConstantRange &Other, unsigned NoWrapKind=0) const
Return a new range representing the possible values resulting from a multiplication of a value in thi...
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI ConstantRange binaryAnd(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a binary-and of a value in this ra...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
LLVM_ABI OverflowResult signedAddMayOverflow(const ConstantRange &Other) const
Return whether signed add of the two ranges always/never overflows.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
OverflowResult
Represents whether an operation on the given constant range is known to always or never overflow.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
LLVM_ABI OverflowResult signedSubMayOverflow(const ConstantRange &Other) const
Return whether signed sub of the two ranges always/never overflows.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * replaceUndefsWith(Constant *C, Constant *Replacement)
Try to replace undefined constant C or undefined elements in C with Replacement.
LLVM_ABI Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:217
unsigned getAddressSizeInBits(unsigned AS) const
The size in bits of an address in for the given AS.
Definition DataLayout.h:518
LLVM_ABI const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
LLVM_ABI unsigned getPointerTypeSizeInBits(Type *) const
The pointer representation size in bits for this type.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:791
ArrayRef< CondBrInst * > conditionsFor(const Value *V) const
Access the list of branches which affect this value.
DomTreeNodeBase * getIDom() const
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction extracts a struct member or array element value from an aggregate value.
ArrayRef< unsigned > getIndices() const
unsigned getNumIndices() const
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
This instruction compares its operands according to the predicate given to the constructor.
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition Operator.h:202
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
bool noSignedZeros() const
Definition FMF.h:67
bool noInfs() const
Definition FMF.h:66
void setNoSignedZeros(bool B=true)
Definition FMF.h:84
void setNoNaNs(bool B=true)
Definition FMF.h:78
bool noNaNs() const
Definition FMF.h:65
const BasicBlock & getEntryBlock() const
Definition Function.h:794
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
PointerType * getType() const
Global values are always pointers.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
This instruction compares its operands according to the predicate given to the constructor.
CmpPredicate getSwappedCmpPredicate() const
CmpPredicate getInverseCmpPredicate() const
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
static LLVM_ABI std::optional< bool > isImpliedByMatchingCmp(CmpPredicate Pred1, CmpPredicate Pred2)
Determine if Pred1 implies Pred2 is true, false, or if nothing can be inferred about the implication,...
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
This instruction inserts a struct field of array element value into an aggregate value.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI bool hasNoNaNs() const LLVM_READONLY
Determine whether the no-NaNs flag is set.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
bool isBinaryOp() const
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
iterator_range< user_iterator > users()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isUnaryOp() const
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
An instruction for reading from memory.
Value * getPointerOperand()
Align getAlign() const
Return the alignment of the access that is being performed.
bool isLoopHeader(const BlockT *BB) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
This is a utility class that provides an abstraction for the common functionality between Instruction...
Definition Operator.h:33
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
iterator_range< const_block_iterator > blocks() const
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A udiv, sdiv, lshr, or ashr instruction, which can be marked as "exact", indicating that no bits are ...
Definition Operator.h:156
bool isExact() const
Test whether this division is known to be exact, with zero remainder.
Definition Operator.h:175
This class represents the LLVM 'select' instruction.
const Value * getFalseValue() const
const Value * getCondition() const
const Value * getTrueValue() const
This instruction constructs a fixed permutation of two input vectors.
VectorType * getType() const
Overload to return most specific vector type.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:743
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
Class to represent struct types.
unsigned getNumElements() const
Random access to the elements.
Type * getElementType(unsigned N) const
Provides information about what library functions are available for the current target.
LibFunc getLibFunc(StringRef funcName) const
Searches for a particular function name.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI uint64_t getArrayNumElements() const
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
This is a wrapper around stripAndAccumulateConstantOffsets with the in-bounds requirement set to fals...
Definition Value.h:729
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
const KnownBits & getKnownBits(const SimplifyQuery &Q) const
Definition WithCache.h:59
PointerType getValue() const
Definition WithCache.h:57
Represents an op.with.overflow intrinsic.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
An efficient, type-erasing, non-owning reference to a callable.
TypeSize getSequentialElementStride(const DataLayout &DL) const
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
A range adaptor for a pair of iterators.
CallInst * Call
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt ScaleBitMask(const APInt &A, unsigned NewBitWidth, bool MatchAllBits=false)
Splat/Merge neighboring bits to widen/narrow the bitmask represented by.
Definition APInt.cpp:3043
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2290
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
match_bind< PHINode > m_Phi(PHINode *&PN)
Match a PHI node, capturing it if we match.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
PtrToIntSameSize_match< OpTy > m_PtrToIntSameSize(const DataLayout &DL, const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, FCmpInst > m_FCmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_c_UMax(const LHS &L, const RHS &R)
Matches a UMax with LHS and RHS in either order.
cst_pred_ty< is_sign_mask > m_SignMask()
Match an integer or vector with only the sign bit(s) set.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
auto m_PtrToIntOrAddr(const OpTy &Op)
Matches PtrToInt or PtrToAddr.
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
auto m_LogicalOp()
Matches either L && R or L || R where L and R are arbitrary values.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
cst_pred_ty< is_power2_or_zero > m_Power2OrZero()
Match an integer or vector of 0 or power-of-2 values.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_idiv_op > m_IDiv(const LHS &L, const RHS &R)
Matches integer division operations.
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
auto m_UMin(const Opnd0 &Op0, const Opnd1 &Op1)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
auto match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true > m_c_NUWAdd(const LHS &L, const RHS &R)
cstfp_pred_ty< is_finite > m_Finite()
Match a finite FP constant, i.e.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
auto m_SMax(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
ICmpLike_match< LHS, RHS > m_ICmpLike(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
auto m_Ctpop(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
cst_pred_ty< is_strictlypositive > m_StrictlyPositive()
Match an integer or vector of strictly positive values.
auto m_VScale()
Matches a call to llvm.vscale().
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
auto m_Ctlz(const Opnd0 &Op0, const Opnd1 &Op1)
match_combine_or< FMaxMin_match< LHS, RHS, ofmin_pred_ty >, FMaxMin_match< LHS, RHS, ufmin_pred_ty > > m_OrdOrUnordFMin(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point minimum function.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_c_MaxOrMin(const LHS &L, const RHS &R)
cstfp_pred_ty< custom_checkfn< APFloat > > m_CheckedFp(function_ref< bool(const APFloat &)> CheckFn)
Match a float or vector where CheckFn(ele) for each element is true.
auto m_FMinNum(const Opnd0 &Op0, const Opnd1 &Op1)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
auto m_SMin(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_FAbs(const Opnd0 &Op0)
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
match_combine_or< FMaxMin_match< LHS, RHS, ofmax_pred_ty >, FMaxMin_match< LHS, RHS, ufmax_pred_ty > > m_OrdOrUnordFMax(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point maximum function.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
BinOpPred_match< LHS, RHS, is_shift_op > m_Shift(const LHS &L, const RHS &R)
Matches shift operations.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinOpPred_match< LHS, RHS, is_irem_op > m_IRem(const LHS &L, const RHS &R)
Matches integer remainder operations.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
auto m_c_UMin(const LHS &L, const RHS &R)
Matches a UMin with LHS and RHS in either order.
auto m_c_SMax(const LHS &L, const RHS &R)
Matches an SMax with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
auto m_FMaxNum(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_nonpositive > m_NonPositive()
Match an integer or vector of non-positive values.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
auto m_c_SMin(const LHS &L, const RHS &R)
Matches an SMin with LHS and RHS in either order.
ElementWiseBitCast_match< OpTy > m_ElementWiseBitCast(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap > m_NSWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
static unsigned decodeVSEW(unsigned VSEW)
LLVM_ABI unsigned getSEWLMULRatio(unsigned SEW, VLMUL VLMul)
static constexpr unsigned RVVBitsPerBlock
static constexpr unsigned RVVBytesPerBlock
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
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:1755
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:1685
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:2224
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:1762
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:1963
LLVM_ABI bool isKnownIntegral(const Value *V, const SimplifyQuery &SQ, FastMathFlags FMF)
Return true if the floating-point value V is known to be an integer value.
LLVM_ABI AssumeAlignInfo getAssumeAlignInfo(OperandBundleUse)
LLVM_ABI OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:197
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
LLVM_ABI std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known)
Compute known bits from the range metadata.
LLVM_ABI Value * FindInsertedValue(Value *V, ArrayRef< unsigned > idx_range, std::optional< BasicBlock::iterator > InsertBefore=std::nullopt)
Given an aggregate and an sequence of indices, see if the scalar value indexed is already around as a...
LLVM_ABI bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false, bool AllowPoison=true)
Return true if the two given values are negation.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI bool isKnownPositive(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
LLVM_ABI Constant * ConstantFoldIntegerCast(Constant *C, Type *DestTy, bool IsSigned, const DataLayout &DL)
Constant fold a zext, sext or trunc, depending on IsSigned and whether the DestTy is wider or narrowe...
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI bool cannotBeOrderedLessThanZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is either NaN or never less than -0....
LLVM_ABI void getUnderlyingObjects(const Value *V, SmallVectorImpl< const Value * > &Objects, const LoopInfo *LI=nullptr, unsigned MaxLookup=MaxLookupSearchDepth)
This method is similar to getUnderlyingObject except that it can look through phi and select instruct...
LLVM_ABI bool mayHaveNonDefUseDependency(const Instruction &I)
Returns true if the result or effects of the given instructions I depend values not reachable through...
LLVM_ABI bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
LLVM_ABI std::optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
LLVM_ABI std::optional< bool > computeKnownFPSignBit(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return false if we can prove that the specified FP value's sign bit is 0.
LLVM_ABI bool canIgnoreSignBitOfNaN(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is NaN.
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
LLVM_ABI void findValuesAffectedByCondition(Value *Cond, bool IsAssume, function_ref< void(Value *)> InsertAffected)
Call InsertAffected on all Values whose known bits / value may be affected by the condition Cond.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
SmallPtrSet< Value *, 4 > AffectedValues
Represents offset+length into a ConstantDataArray.
const ConstantDataArray * Array
ConstantDataArray pointer.
Represent subnormal handling kind for floating point instruction inputs and outputs.
static constexpr DenormalMode getDynamic()
InstrInfoQuery provides an interface to query additional information for instructions like metadata o...
bool isExact(const BinaryOperator *Op) const
MDNode * getMetadata(const Instruction *I, unsigned KindID) const
bool hasNoSignedZeros(const InstT *Op) const
bool hasNoSignedWrap(const InstT *Op) const
bool hasNoUnsignedWrap(const InstT *Op) const
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits sadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.sadd.sat(LHS, RHS)
KnownBits anyextOrTrunc(unsigned BitWidth) const
Return known bits for an "any" extension or truncation of the value we're tracking.
Definition KnownBits.h:190
static LLVM_ABI KnownBits mulhu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from zero-extended multiply-hi.
unsigned countMinSignBits() const
Returns the number of times the sign bit is replicated into the other bits.
Definition KnownBits.h:269
static LLVM_ABI KnownBits smax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smax(LHS, RHS).
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
bool isZero() const
Returns true if value is all zero.
Definition KnownBits.h:78
LLVM_ABI KnownBits blsi() const
Compute known bits for X & -X, which has only the lowest bit set of X set.
void makeNonNegative()
Make this value non-negative.
Definition KnownBits.h:125
static LLVM_ABI KnownBits usub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.usub.sat(LHS, RHS)
unsigned countMinLeadingOnes() const
Returns the minimum number of leading one bits.
Definition KnownBits.h:265
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:256
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits ssub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.ssub.sat(LHS, RHS)
static LLVM_ABI KnownBits urem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for urem(LHS, RHS).
bool isUnknown() const
Returns true if we don't know any bits.
Definition KnownBits.h:64
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:288
LLVM_ABI KnownBits blsmsk() const
Compute known bits for X ^ (X - 1), which has all bits up to and including the lowest set bit of X se...
KnownBits byteSwap() const
Definition KnownBits.h:559
bool hasConflict() const
Returns true if there is conflicting information.
Definition KnownBits.h:51
static LLVM_ABI KnownBits fshl(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshl(LHS, RHS, Amt).
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
void setAllZero()
Make all bits known to be zero and discard any previous information.
Definition KnownBits.h:84
KnownBits reverseBits() const
Definition KnownBits.h:563
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
static LLVM_ABI KnownBits umax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umax(LHS, RHS).
KnownBits zext(unsigned BitWidth) const
Return known bits for a zero extension of the value we're tracking.
Definition KnownBits.h:176
bool isConstant() const
Returns true if we know the value of all bits.
Definition KnownBits.h:54
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
KnownBits unionWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for either this or RHS or both.
Definition KnownBits.h:335
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
bool isNonZero() const
Returns true if this value is known to be non-zero.
Definition KnownBits.h:109
bool isEven() const
Return if the value is known even (the low bit is 0).
Definition KnownBits.h:162
KnownBits extractBits(unsigned NumBits, unsigned BitPosition) const
Return a subset of the known bits from [bitPosition,bitPosition+numBits).
Definition KnownBits.h:239
static LLVM_ABI KnownBits pdep(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pdep(Val, Mask).
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
Definition KnownBits.h:325
unsigned countMinTrailingOnes() const
Returns the minimum number of trailing one bits.
Definition KnownBits.h:259
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
static LLVM_ABI KnownBits fshr(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshr(LHS, RHS, Amt).
static LLVM_ABI KnownBits smin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smin(LHS, RHS).
static LLVM_ABI KnownBits mulhs(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from sign-extended multiply-hi.
static LLVM_ABI KnownBits srem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for srem(LHS, RHS).
static LLVM_ABI KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
Definition KnownBits.h:130
static LLVM_ABI KnownBits computeForAddSub(bool Add, bool NSW, bool NUW, const KnownBits &LHS, const KnownBits &RHS)
Compute known bits resulting from adding LHS and RHS.
Definition KnownBits.cpp:61
static LLVM_ABI KnownBits sdiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for sdiv(LHS, RHS).
static bool haveNoCommonBitsSet(const KnownBits &LHS, const KnownBits &RHS)
Return true if LHS and RHS have no common bits set.
Definition KnownBits.h:340
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static KnownBits sub(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from subtraction of LHS and RHS.
Definition KnownBits.h:376
unsigned countMaxLeadingZeros() const
Returns the maximum number of leading zero bits possible.
Definition KnownBits.h:294
void setAllOnes()
Make all bits known to be one and discard any previous information.
Definition KnownBits.h:90
static LLVM_ABI KnownBits uadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.uadd.sat(LHS, RHS)
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
KnownBits anyext(unsigned BitWidth) const
Return known bits for an "any" extension of the value we're tracking, where we don't know anything ab...
Definition KnownBits.h:171
static LLVM_ABI KnownBits clmul(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for clmul(LHS, RHS).
LLVM_ABI KnownBits abs(bool IntMinIsPoison=false) const
Compute known bits for the absolute value.
static LLVM_ABI std::optional< bool > sgt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGT result.
static LLVM_ABI std::optional< bool > uge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGE result.
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
static LLVM_ABI KnownBits umin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umin(LHS, RHS).
static LLVM_ABI KnownBits pext(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pext(Val, Mask).
KnownBits sextOrTrunc(unsigned BitWidth) const
Return known bits for a sign extension or truncation of the value we're tracking.
Definition KnownBits.h:210
bool isKnownNeverInfOrNaN() const
Return true if it's known this can never be an infinity or nan.
static LLVM_ABI KnownFPClass sin(const KnownFPClass &Src)
Report known values for sin.
static LLVM_ABI KnownFPClass frem(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for frem.
static LLVM_ABI KnownFPClass fdiv_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv x, x.
static constexpr FPClassTest OrderedLessThanZeroMask
void knownNot(FPClassTest RuleOut)
static LLVM_ABI KnownFPClass fmul(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fmul.
static LLVM_ABI KnownFPClass fadd_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd x, x.
static KnownFPClass square(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
static LLVM_ABI KnownFPClass fsub(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fsub.
bool isKnownNeverSubnormal() const
Return true if it's known this can never be a subnormal.
KnownFPClass unionWith(const KnownFPClass &RHS) const
static LLVM_ABI KnownFPClass canonicalize(const KnownFPClass &Src, DenormalMode DenormMode=DenormalMode::getDynamic())
Apply the canonicalize intrinsic to this value.
LLVM_ABI bool isKnownNeverLogicalZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a zero.
static LLVM_ABI KnownFPClass log(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for log/log2/log10.
static LLVM_ABI KnownFPClass atan2(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for atan2.
static LLVM_ABI KnownFPClass atan(const KnownFPClass &Src)
Report known values for atan.
static LLVM_ABI KnownFPClass fdiv(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv.
static LLVM_ABI KnownFPClass roundToIntegral(const KnownFPClass &Src, bool IsTrunc, bool IsMultiUnitFPType)
Propagate known class for rounding intrinsics (trunc, floor, ceil, rint, nearbyint,...
static LLVM_ABI KnownFPClass cos(const KnownFPClass &Src)
Report known values for cos.
static LLVM_ABI KnownFPClass cosh(const KnownFPClass &Src)
Report known values for cosh.
static LLVM_ABI KnownFPClass minMaxLike(const KnownFPClass &LHS, const KnownFPClass &RHS, MinMaxKind Kind, DenormalMode DenormMode=DenormalMode::getDynamic())
bool isUnknown() const
static LLVM_ABI KnownFPClass exp(const KnownFPClass &Src)
Report known values for exp, exp2 and exp10.
static LLVM_ABI KnownFPClass frexp_mant(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for mantissa component of frexp.
static LLVM_ABI KnownFPClass asin(const KnownFPClass &Src)
Report known values for asin.
bool isKnownNeverNaN() const
Return true if it's known this can never be a nan.
bool isKnownNever(FPClassTest Mask) const
Return true if it's known this can never be one of the mask entries.
std::optional< bool > getSignBit() const
std::nullopt if the sign bit is unknown, true if the sign bit is definitely set or false if the sign ...
static LLVM_ABI KnownFPClass fpext(const KnownFPClass &KnownSrc, const fltSemantics &DstTy, const fltSemantics &SrcTy)
Propagate known class for fpext.
FPClassTest getKnownFPClasses() const
Floating-point classes the value could be one of.
static LLVM_ABI KnownFPClass fma(const KnownFPClass &LHS, const KnownFPClass &RHS, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma.
static LLVM_ABI KnownFPClass tan(const KnownFPClass &Src)
Report known values for tan.
static LLVM_ABI KnownFPClass fptrunc(const KnownFPClass &KnownSrc)
Propagate known class for fptrunc.
bool cannotBeOrderedLessThanZero() const
Return true if we can prove that the analyzed floating-point value is either NaN or never less than -...
void signBitMustBeOne()
Assume the sign bit is one.
void signBitMustBeZero()
Assume the sign bit is zero.
static LLVM_ABI KnownFPClass sqrt(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for sqrt.
LLVM_ABI bool isKnownNeverLogicalPosZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a positive zero.
bool isKnownNeverPosInfinity() const
Return true if it's known this can never be +infinity.
static LLVM_ABI KnownFPClass fadd(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd.
LLVM_ABI bool isKnownNeverLogicalNegZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a negative zero.
static LLVM_ABI KnownFPClass bitcast(const fltSemantics &FltSemantics, const KnownBits &Bits)
Report known values for a bitcast into a float with provided semantics.
static LLVM_ABI KnownFPClass fma_square(const KnownFPClass &Squared, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma squared, squared, addend.
static LLVM_ABI KnownFPClass acos(const KnownFPClass &Src)
Report known values for acos.
static LLVM_ABI KnownFPClass frem_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for frem x, x.
static LLVM_ABI KnownFPClass powi(const KnownFPClass &Src, const KnownBits &N)
Propagate known class for powi.
static LLVM_ABI KnownFPClass pow(const KnownFPClass &LHS, const KnownFPClass &RHS)
Propagate known class for pow.
static LLVM_ABI KnownFPClass ldexp(const KnownFPClass &Src, const APInt &ConstantRangeMin, const APInt &ConstantRangeMax, const fltSemantics &Flt, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for ldexp, assuming the exponent is known to be within [ConstantRangeMin,...
static LLVM_ABI KnownFPClass sinh(const KnownFPClass &Src)
Report known values for sinh.
static LLVM_ABI KnownFPClass tanh(const KnownFPClass &Src)
Report known values for tanh.
SelectPatternFlavor Flavor
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?
const DataLayout & DL
SimplifyQuery getWithoutCondContext() const
const Instruction * CxtI
const DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
const DomConditionCache * DC
const InstrInfoQuery IIQ
const CondContext * CC
fltNanEncoding nanEncoding
Definition APFloat.h:1041